14 // kinds holds the kinds that a message can have.
15 var kinds = map[string]bool{
24 // Message is one entry of the chat log. ID is the permanent position of the
25 // message in the chat, from 0. Size is the UTF-8 byte length of Text. Date is
26 // the time of the write in RFC 3339 format.
29 Kind string `json:"kind"`
30 Text string `json:"text"`
31 Size int `json:"size"`
32 Date string `json:"date"`
35 // Log is the append-only message log of one chat. It writes one JSON line for
36 // each message to main/YYYY-MM-DD.jsonl, named for the local day of the write.
37 // It never edits or deletes a line. Each line goes to the operating system
38 // before Append returns, so a crash of the process loses no message. An
39 // exclusive lock on the lock file makes sure that only one process writes the
40 // log. After a failed write, the end of the file is not known, so the log
41 // refuses all writes until it is opened again. The caller serializes all calls.
43 // The log keeps no message in memory. The index index/main.idx holds the
44 // position of message i in record i, so a read of a message is one read of the
45 // index and one of its day file. At open the log indexes the lines after the
46 // last indexed one, so a missing index is built again from the day files.
48 clock func() time.Time
55 // openLog locks the chat in root and indexes its new lines. The clock gives the
56 // date of each new message.
57 func openLog(ctx context.Context, root string, clock func() time.Time) (*Log, error) {
58 for _, dir := range []string{"main", "index"} {
59 err := os.MkdirAll(filepath.Join(root, dir), 0o700)
61 return nil, fmt.Errorf("create %s directory: %w", dir, err)
65 lock, err := lockFile(filepath.Join(root, "lock"))
74 dir: filepath.Join(root, "main"),
78 l.index, err = openRecords(filepath.Join(root, "index", "main.idx"), positionBytes)
80 return nil, errors.Join(err, l.Close())
85 return nil, errors.Join(fmt.Errorf("index message log: %w", err), l.Close())
91 // catchUp indexes the lines after the last indexed line.
92 func (l *Log) catchUp(ctx context.Context) error {
94 if l.index.count > 0 {
95 record, _, err := l.index.Read(l.index.count - 1)
100 last := decodePosition(record)
103 offset: last.offset + uint64(last.length),
107 return l.journal.Scan(ctx, start, func(line []byte, place position) error {
109 err := json.Unmarshal(line, &message)
114 if message.ID != l.index.count {
115 return fmt.Errorf("expected message %d, found %d", l.index.count, message.ID)
118 err = validateMessage(message)
120 return fmt.Errorf("message %d: %w", message.ID, err)
123 return l.addIndex(place)
127 func (l *Log) addIndex(place position) error {
128 record := make([]byte, positionBytes)
129 encodePosition(record, place)
131 return l.index.Append(record)
134 // Close releases the lock. The log refuses all calls after Close.
135 func (l *Log) Close() error {
136 err := l.journal.Close()
138 err = errors.Join(err, l.index.Close())
143 err = errors.Join(err, l.lock.Close())
150 // Append writes a new message to the log and returns it with its ID, size, and
152 func (l *Log) Append(kind, text string) (Message, error) {
154 return Message{}, os.ErrClosed
157 if l.failure != nil {
158 return Message{}, fmt.Errorf("log needs a reopen after a failed write: %w", l.failure)
167 Date: now.Format(time.RFC3339Nano),
170 err := validateMessage(message)
172 return Message{}, err
175 line, err := json.Marshal(message)
177 return Message{}, fmt.Errorf("encode message: %w", err)
180 place, err := l.journal.Write(now.Format(time.DateOnly), append(line, '\n'))
182 err = l.addIndex(place)
187 return Message{}, fmt.Errorf("write message %d: %w", message.ID, err)
193 // Len returns the number of messages in the log.
194 func (l *Log) Len() int {
198 // Message reads the message with the given ID from its day file.
199 func (l *Log) Message(id int) (Message, error) {
200 record, found, err := l.index.Read(id)
202 return Message{}, err
206 return Message{}, fmt.Errorf("no message %d", id)
209 line, err := l.journal.Read(decodePosition(record))
211 return Message{}, fmt.Errorf("read message %d: %w", id, err)
215 err = json.Unmarshal(line, &message)
217 return Message{}, fmt.Errorf("decode message %d: %w", id, err)
220 if message.ID != id {
221 return Message{}, fmt.Errorf("index of message %d points to message %d", id, message.ID)
227 // validateMessage makes sure that a message has a known kind, valid UTF-8 text,
228 // the size of its text, and a valid date.
229 func validateMessage(message Message) error {
230 if !kinds[message.Kind] {
231 return fmt.Errorf("unknown message kind %q", message.Kind)
234 if !utf8.ValidString(message.Text) {
235 return errors.New("message text is not valid UTF-8")
238 if message.Size != len(message.Text) {
239 return fmt.Errorf("message size %d is not the text size %d", message.Size, len(message.Text))
242 _, err := time.Parse(time.RFC3339Nano, message.Date)
244 return fmt.Errorf("parse message date: %w", err)