]> git.giacomolli.uk - onechat/blob - log.go
Name private helpers for their owning feature
[onechat] / log.go
1 package main
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "os"
9 "path/filepath"
10 "time"
11 "unicode/utf8"
12 )
13
14 // logKinds holds the logKinds that a message can have.
15 var logKinds = map[string]bool{
16 "user": true,
17 "reply": true,
18 "tool": true,
19 "echo": true,
20 "work": true,
21 "note": true,
22 }
23
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.
31 //
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.
36 type Log struct {
37 clock func() time.Time
38 lock *os.File
39 journal Journal
40 index *Records
41 failure error
42 }
43
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.
48 type Message struct {
49 ID int `json:"i"`
50 Kind string `json:"kind"`
51 Text string `json:"text"`
52 Size int `json:"size"`
53 Date string `json:"date"`
54 }
55
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)
61 if err != nil {
62 return nil, fmt.Errorf("create %s directory: %w", dir, err)
63 }
64 }
65
66 lock, err := lockFile(filepath.Join(root, "lock"))
67 if err != nil {
68 return nil, err
69 }
70
71 l := &Log{
72 clock: clock,
73 lock: lock,
74 journal: Journal{
75 dir: filepath.Join(root, "main"),
76 },
77 }
78
79 l.index, err = openRecords(filepath.Join(root, "index", "main.idx"), positionBytes)
80 if err != nil {
81 return nil, errors.Join(err, l.Close())
82 }
83
84 err = l.catchUp(ctx)
85 if err != nil {
86 return nil, errors.Join(fmt.Errorf("index message log: %w", err), l.Close())
87 }
88
89 return l, nil
90 }
91
92 // Close releases the lock. The log refuses all calls after Close.
93 func (l *Log) Close() error {
94 err := l.journal.Close()
95 if l.index != nil {
96 err = errors.Join(err, l.index.Close())
97 l.index = nil
98 }
99
100 if l.lock != nil {
101 err = errors.Join(err, l.lock.Close())
102 l.lock = nil
103 }
104
105 return err
106 }
107
108 // catchUp indexes the lines after the last indexed line.
109 func (l *Log) catchUp(ctx context.Context) error {
110 start := Position{}
111 if l.index.count > 0 {
112 record, _, err := l.index.Read(l.index.count - 1)
113 if err != nil {
114 return err
115 }
116
117 last := decodePosition(record)
118 start = Position{
119 day: last.day,
120 offset: last.offset + uint64(last.length),
121 }
122 }
123
124 return l.journal.Scan(ctx, start, func(line []byte, place Position) error {
125 var message Message
126
127 err := json.Unmarshal(line, &message)
128 if err != nil {
129 return fmt.Errorf("decode log message: %w", err)
130 }
131
132 if message.ID != l.index.count {
133 return fmt.Errorf("expected message %d, found %d", l.index.count, message.ID)
134 }
135
136 err = logValidateMessage(message)
137 if err != nil {
138 return fmt.Errorf("message %d: %w", message.ID, err)
139 }
140
141 return l.addIndex(place)
142 })
143 }
144
145 func (l *Log) addIndex(place Position) error {
146 record := make([]byte, positionBytes)
147 encodePosition(record, place)
148
149 return l.index.Append(record)
150 }
151
152 // Append writes a new message to the log and returns it with its ID, size, and
153 // date.
154 func (l *Log) Append(kind, text string) (Message, error) {
155 return l.AppendDated(kind, text, "")
156 }
157
158 // AppendDated writes a message with date in RFC 3339 format. An empty date uses
159 // the clock. The day file uses the local day of the given date.
160 func (l *Log) AppendDated(kind, text, date string) (Message, error) {
161 if l.lock == nil {
162 return Message{}, fmt.Errorf("append dated message: %w", os.ErrClosed)
163 }
164
165 if l.failure != nil {
166 return Message{}, fmt.Errorf("log needs a reopen after a failed write: %w", l.failure)
167 }
168
169 var err error
170
171 now := l.clock()
172 if date == "" {
173 date = now.Format(time.RFC3339Nano)
174 } else {
175 now, err = time.Parse(time.RFC3339Nano, date)
176 if err != nil {
177 return Message{}, fmt.Errorf("parse message date: %w", err)
178 }
179
180 now = now.In(time.Local)
181 }
182
183 message := Message{
184 ID: l.index.count,
185 Kind: kind,
186 Text: text,
187 Size: len(text),
188 Date: date,
189 }
190
191 err = logValidateMessage(message)
192 if err != nil {
193 return Message{}, fmt.Errorf("validate dated message: %w", err)
194 }
195
196 line, err := json.Marshal(message)
197 if err != nil {
198 return Message{}, fmt.Errorf("encode message: %w", err)
199 }
200
201 place, err := l.journal.Write(now.Format(time.DateOnly), append(line, '\n'))
202 if err == nil {
203 err = l.addIndex(place)
204 }
205
206 if err != nil {
207 l.failure = err
208 return Message{}, fmt.Errorf("write message %d: %w", message.ID, err)
209 }
210
211 return message, nil
212 }
213
214 // Len returns the number of messages in the log.
215 func (l *Log) Len() int {
216 return l.index.count
217 }
218
219 // Message reads the message with the given ID from its day file.
220 func (l *Log) Message(id int) (Message, error) {
221 record, found, err := l.index.Read(id)
222 if err != nil {
223 return Message{}, err
224 }
225
226 if !found {
227 return Message{}, fmt.Errorf("no message %d", id)
228 }
229
230 line, err := l.journal.Read(decodePosition(record))
231 if err != nil {
232 return Message{}, fmt.Errorf("read message %d: %w", id, err)
233 }
234
235 var message Message
236
237 err = json.Unmarshal(line, &message)
238 if err != nil {
239 return Message{}, fmt.Errorf("decode message %d: %w", id, err)
240 }
241
242 if message.ID != id {
243 return Message{}, fmt.Errorf("index of message %d points to message %d", id, message.ID)
244 }
245
246 return message, nil
247 }
248
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)
254 }
255
256 if !utf8.ValidString(message.Text) {
257 return errors.New("message text is not valid UTF-8")
258 }
259
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))
262 }
263
264 _, err := time.Parse(time.RFC3339Nano, message.Date)
265 if err != nil {
266 return fmt.Errorf("parse message date: %w", err)
267 }
268
269 return nil
270 }