14 // logKinds holds the logKinds that a message can have.
15 var logKinds = map[string]bool{
24 // Log is the append-only message log of one chat. It writes one JSON line for
25 // each message to main/YYYY-MM-DD.jsonl, named for the local day of the
26 // message. It never edits or deletes a line. Each line goes to the operating
27 // system before Append returns, so a crash of the process loses no message. An
28 // exclusive lock on the lock file makes sure that only one process writes the
29 // log. After a failed write, the end of the file is not known, so the log
30 // refuses all writes until it is opened again. The caller serializes all calls.
32 // The log keeps no message in memory. The index index/main.idx holds the
33 // position of message i in record i, so a read of a message is one read of the
34 // index and one of its day file. At open the log indexes the lines after the
35 // last indexed one, so a missing index is built again from the day files.
37 clock func() time.Time
44 // Message is one entry of the chat log. ID is its position in the log, from 0.
45 // A rebuild assigns positions in the merged log. Size is the UTF-8 byte length
46 // of Text. Date is the message time in RFC 3339 format, supplied at append or
47 // taken from the clock.
50 Kind string `json:"kind"`
51 Text string `json:"text"`
52 Size int `json:"size"`
53 Date string `json:"date"`
56 // openLog locks the chat in root and indexes its new lines. The clock gives the
57 // date of each new message.
58 func openLog(ctx context.Context, root string, clock func() time.Time) (*Log, error) {
59 for _, dir := range []string{"main", "index"} {
60 err := os.MkdirAll(filepath.Join(root, dir), 0o700)
62 return nil, fmt.Errorf("create %s directory: %w", dir, err)
66 lock, err := lockFile(filepath.Join(root, "lock"))
75 dir: filepath.Join(root, "main"),
79 l.index, err = openRecords(filepath.Join(root, "index", "main.idx"), positionBytes)
81 return nil, errors.Join(err, l.Close())
86 return nil, errors.Join(fmt.Errorf("index message log: %w", err), l.Close())
92 // Close releases the lock. The log refuses all calls after Close.
93 func (l *Log) Close() error {
94 err := l.journal.Close()
96 err = errors.Join(err, l.index.Close())
101 err = errors.Join(err, l.lock.Close())
108 // Append writes a new message to the log and returns it with its ID, size, and
110 func (l *Log) Append(kind, text string) (Message, error) {
111 return l.AppendDated(kind, text, "")
114 // AppendDated writes a message with date in RFC 3339 format. An empty date uses
115 // the clock. The day file uses the local day of the given date.
116 func (l *Log) AppendDated(kind, text, date string) (Message, error) {
118 return Message{}, fmt.Errorf("append dated message: %w", os.ErrClosed)
121 if l.failure != nil {
122 return Message{}, fmt.Errorf("log needs a reopen after a failed write: %w", l.failure)
129 date = now.Format(time.RFC3339Nano)
131 now, err = time.Parse(time.RFC3339Nano, date)
133 return Message{}, fmt.Errorf("parse message date: %w", err)
136 now = now.In(time.Local)
147 err = logValidateMessage(message)
149 return Message{}, fmt.Errorf("validate dated message: %w", err)
152 line, err := json.Marshal(message)
154 return Message{}, fmt.Errorf("encode message: %w", err)
157 place, err := l.journal.Write(now.Format(time.DateOnly), append(line, '\n'))
159 err = l.addIndex(place)
164 return Message{}, fmt.Errorf("write message %d: %w", message.ID, err)
170 // Len returns the number of messages in the log.
171 func (l *Log) Len() int {
175 // Message reads the message with the given ID from its day file.
176 func (l *Log) Message(id int) (Message, error) {
177 record, found, err := l.index.Read(id)
179 return Message{}, err
183 return Message{}, fmt.Errorf("no message %d", id)
186 line, err := l.journal.Read(decodePosition(record))
188 return Message{}, fmt.Errorf("read message %d: %w", id, err)
193 err = json.Unmarshal(line, &message)
195 return Message{}, fmt.Errorf("decode message %d: %w", id, err)
198 if message.ID != id {
199 return Message{}, fmt.Errorf("index of message %d points to message %d", id, message.ID)
205 // catchUp indexes the lines after the last indexed line.
206 func (l *Log) catchUp(ctx context.Context) error {
208 if l.index.count > 0 {
209 record, _, err := l.index.Read(l.index.count - 1)
214 last := decodePosition(record)
217 offset: last.offset + uint64(last.length),
221 return l.journal.Scan(ctx, start, func(line []byte, place Position) error {
224 err := json.Unmarshal(line, &message)
226 return fmt.Errorf("decode log message: %w", err)
229 if message.ID != l.index.count {
230 return fmt.Errorf("expected message %d, found %d", l.index.count, message.ID)
233 err = logValidateMessage(message)
235 return fmt.Errorf("message %d: %w", message.ID, err)
238 return l.addIndex(place)
242 func (l *Log) addIndex(place Position) error {
243 record := make([]byte, positionBytes)
244 encodePosition(record, place)
246 return l.index.Append(record)
249 // logValidateMessage makes sure that a message has a known kind, valid UTF-8
250 // text, the size of its text, and a valid date.
251 func logValidateMessage(message Message) error {
252 if !logKinds[message.Kind] {
253 return fmt.Errorf("unknown message kind %q", message.Kind)
256 if !utf8.ValidString(message.Text) {
257 return errors.New("message text is not valid UTF-8")
260 if message.Size != len(message.Text) {
261 return fmt.Errorf("message size %d is not the text size %d", message.Size, len(message.Text))
264 _, err := time.Parse(time.RFC3339Nano, message.Date)
266 return fmt.Errorf("parse message date: %w", err)