14 // logKinds holds the logKinds that a message can have.
15 var logKinds = map[string]bool{
24 // openLog locks the chat in root and indexes its new lines. The clock gives the
25 // date of each new message.
26 func openLog(ctx context.Context, root string, clock func() time.Time) (*Log, error) {
27 for _, dir := range []string{"main", "index"} {
28 err := os.MkdirAll(filepath.Join(root, dir), 0o700)
30 return nil, fmt.Errorf("create %s directory: %w", dir, err)
34 lock, err := lockFile(filepath.Join(root, "lock"))
43 dir: filepath.Join(root, "main"),
47 l.index, err = openRecords(filepath.Join(root, "index", "main.idx"), positionBytes)
49 return nil, errors.Join(err, l.Close())
54 return nil, errors.Join(fmt.Errorf("index message log: %w", err), l.Close())
60 // Log is the append-only message log of one chat. It writes one JSON line for
61 // each message to main/YYYY-MM-DD.jsonl, named for the local day of the
62 // message. It never edits or deletes a line. Each line goes to the operating
63 // system before Append returns, so a crash of the process loses no message. An
64 // exclusive lock on the lock file makes sure that only one process writes the
65 // log. After a failed write, the end of the file is not known, so the log
66 // refuses all writes until it is opened again. The caller serializes all calls.
68 // The log keeps no message in memory. The index index/main.idx holds the
69 // position of message i in record i, so a read of a message is one read of the
70 // index and one of its day file. At open the log indexes the lines after the
71 // last indexed one, so a missing index is built again from the day files.
73 clock func() time.Time
80 // Close releases the lock. The log refuses all calls after Close.
81 func (l *Log) Close() error {
82 err := l.journal.Close()
84 err = errors.Join(err, l.index.Close())
89 err = errors.Join(err, l.lock.Close())
96 // Append writes a new message to the log and returns it with its ID, size, and
98 func (l *Log) Append(kind, text string) (Message, error) {
99 return l.AppendDated(kind, text, "")
102 // AppendDated writes a message with date in RFC 3339 format. An empty date uses
103 // the clock. The day file uses the local day of the given date.
104 func (l *Log) AppendDated(kind, text, date string) (Message, error) {
106 return Message{}, fmt.Errorf("append dated message: %w", os.ErrClosed)
109 if l.failure != nil {
110 return Message{}, fmt.Errorf("log needs a reopen after a failed write: %w", l.failure)
116 date = now.Format(time.RFC3339Nano)
118 now, err = time.Parse(time.RFC3339Nano, date)
120 return Message{}, fmt.Errorf("parse message date: %w", err)
123 now = now.In(time.Local)
134 err = logValidateMessage(message)
136 return Message{}, fmt.Errorf("validate dated message: %w", err)
139 line, err := json.Marshal(message)
141 return Message{}, fmt.Errorf("encode message: %w", err)
144 place, err := l.journal.Write(now.Format(time.DateOnly), append(line, '\n'))
146 err = l.addIndex(place)
151 return Message{}, fmt.Errorf("write message %d: %w", message.ID, err)
157 // Len returns the number of messages in the log.
158 func (l *Log) Len() int {
162 // Message reads the message with the given ID from its day file.
163 func (l *Log) Message(id int) (Message, error) {
164 record, found, err := l.index.Read(id)
166 return Message{}, err
170 return Message{}, fmt.Errorf("no message %d", id)
173 line, err := l.journal.Read(decodePosition(record))
175 return Message{}, fmt.Errorf("read message %d: %w", id, err)
179 err = json.Unmarshal(line, &message)
181 return Message{}, fmt.Errorf("decode message %d: %w", id, err)
184 if message.ID != id {
185 return Message{}, fmt.Errorf("index of message %d points to message %d", id, message.ID)
191 // catchUp indexes the lines after the last indexed line.
192 func (l *Log) catchUp(ctx context.Context) error {
194 if l.index.count > 0 {
195 record, _, err := l.index.Read(l.index.count - 1)
200 last := decodePosition(record)
203 offset: last.offset + uint64(last.length),
207 return l.journal.Scan(ctx, start, func(line []byte, place Position) error {
209 err := json.Unmarshal(line, &message)
214 if message.ID != l.index.count {
215 return fmt.Errorf("expected message %d, found %d", l.index.count, message.ID)
218 err = logValidateMessage(message)
220 return fmt.Errorf("message %d: %w", message.ID, err)
223 return l.addIndex(place)
227 func (l *Log) addIndex(place Position) error {
228 record := make([]byte, positionBytes)
229 encodePosition(record, place)
231 return l.index.Append(record)
234 // Message is one entry of the chat log. ID is its position in the log, from 0.
235 // A rebuild assigns positions in the merged log. Size is the UTF-8 byte length
236 // of Text. Date is the message time in RFC 3339 format, supplied at append or
237 // taken from the clock.
238 type Message struct {
240 Kind string `json:"kind"`
241 Text string `json:"text"`
242 Size int `json:"size"`
243 Date string `json:"date"`
246 // logValidateMessage makes sure that a message has a known kind, valid UTF-8
247 // text, the size of its text, and a valid date.
248 func logValidateMessage(message Message) error {
249 if !logKinds[message.Kind] {
250 return fmt.Errorf("unknown message kind %q", message.Kind)
253 if !utf8.ValidString(message.Text) {
254 return errors.New("message text is not valid UTF-8")
257 if message.Size != len(message.Text) {
258 return fmt.Errorf("message size %d is not the text size %d", message.Size, len(message.Text))
261 _, err := time.Parse(time.RFC3339Nano, message.Date)
263 return fmt.Errorf("parse message date: %w", err)