]> git.giacomolli.uk - onechat/blob - log.go
Record the subagent name in the usage records
[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 // 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)
29 if err != nil {
30 return nil, fmt.Errorf("create %s directory: %w", dir, err)
31 }
32 }
33
34 lock, err := lockFile(filepath.Join(root, "lock"))
35 if err != nil {
36 return nil, err
37 }
38
39 l := &Log{
40 clock: clock,
41 lock: lock,
42 journal: Journal{
43 dir: filepath.Join(root, "main"),
44 },
45 }
46
47 l.index, err = openRecords(filepath.Join(root, "index", "main.idx"), positionBytes)
48 if err != nil {
49 return nil, errors.Join(err, l.Close())
50 }
51
52 err = l.catchUp(ctx)
53 if err != nil {
54 return nil, errors.Join(fmt.Errorf("index message log: %w", err), l.Close())
55 }
56
57 return l, nil
58 }
59
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 write.
62 // It never edits or deletes a line. Each line goes to the operating system
63 // 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.
67 //
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.
72 type Log struct {
73 clock func() time.Time
74 lock *os.File
75 journal Journal
76 index *Records
77 failure error
78 }
79
80 // Close releases the lock. The log refuses all calls after Close.
81 func (l *Log) Close() error {
82 err := l.journal.Close()
83 if l.index != nil {
84 err = errors.Join(err, l.index.Close())
85 l.index = nil
86 }
87
88 if l.lock != nil {
89 err = errors.Join(err, l.lock.Close())
90 l.lock = nil
91 }
92
93 return err
94 }
95
96 // Append writes a new message to the log and returns it with its ID, size, and
97 // date.
98 func (l *Log) Append(kind, text string) (Message, error) {
99 if l.lock == nil {
100 return Message{}, os.ErrClosed
101 }
102
103 if l.failure != nil {
104 return Message{}, fmt.Errorf("log needs a reopen after a failed write: %w", l.failure)
105 }
106
107 now := l.clock()
108 message := Message{
109 ID: l.index.count,
110 Kind: kind,
111 Text: text,
112 Size: len(text),
113 Date: now.Format(time.RFC3339Nano),
114 }
115
116 err := logValidateMessage(message)
117 if err != nil {
118 return Message{}, err
119 }
120
121 line, err := json.Marshal(message)
122 if err != nil {
123 return Message{}, fmt.Errorf("encode message: %w", err)
124 }
125
126 place, err := l.journal.Write(now.Format(time.DateOnly), append(line, '\n'))
127 if err == nil {
128 err = l.addIndex(place)
129 }
130
131 if err != nil {
132 l.failure = err
133 return Message{}, fmt.Errorf("write message %d: %w", message.ID, err)
134 }
135
136 return message, nil
137 }
138
139 // Len returns the number of messages in the log.
140 func (l *Log) Len() int {
141 return l.index.count
142 }
143
144 // Message reads the message with the given ID from its day file.
145 func (l *Log) Message(id int) (Message, error) {
146 record, found, err := l.index.Read(id)
147 if err != nil {
148 return Message{}, err
149 }
150
151 if !found {
152 return Message{}, fmt.Errorf("no message %d", id)
153 }
154
155 line, err := l.journal.Read(decodePosition(record))
156 if err != nil {
157 return Message{}, fmt.Errorf("read message %d: %w", id, err)
158 }
159
160 var message Message
161 err = json.Unmarshal(line, &message)
162 if err != nil {
163 return Message{}, fmt.Errorf("decode message %d: %w", id, err)
164 }
165
166 if message.ID != id {
167 return Message{}, fmt.Errorf("index of message %d points to message %d", id, message.ID)
168 }
169
170 return message, nil
171 }
172
173 // catchUp indexes the lines after the last indexed line.
174 func (l *Log) catchUp(ctx context.Context) error {
175 start := Position{}
176 if l.index.count > 0 {
177 record, _, err := l.index.Read(l.index.count - 1)
178 if err != nil {
179 return err
180 }
181
182 last := decodePosition(record)
183 start = Position{
184 day: last.day,
185 offset: last.offset + uint64(last.length),
186 }
187 }
188
189 return l.journal.Scan(ctx, start, func(line []byte, place Position) error {
190 var message Message
191 err := json.Unmarshal(line, &message)
192 if err != nil {
193 return err
194 }
195
196 if message.ID != l.index.count {
197 return fmt.Errorf("expected message %d, found %d", l.index.count, message.ID)
198 }
199
200 err = logValidateMessage(message)
201 if err != nil {
202 return fmt.Errorf("message %d: %w", message.ID, err)
203 }
204
205 return l.addIndex(place)
206 })
207 }
208
209 func (l *Log) addIndex(place Position) error {
210 record := make([]byte, positionBytes)
211 encodePosition(record, place)
212
213 return l.index.Append(record)
214 }
215
216 // Message is one entry of the chat log. ID is the permanent position of the
217 // message in the chat, from 0. Size is the UTF-8 byte length of Text. Date is
218 // the time of the write in RFC 3339 format.
219 type Message struct {
220 ID int `json:"i"`
221 Kind string `json:"kind"`
222 Text string `json:"text"`
223 Size int `json:"size"`
224 Date string `json:"date"`
225 }
226
227 // logValidateMessage makes sure that a message has a known kind, valid UTF-8
228 // text, the size of its text, and a valid date.
229 func logValidateMessage(message Message) error {
230 if !logKinds[message.Kind] {
231 return fmt.Errorf("unknown message kind %q", message.Kind)
232 }
233
234 if !utf8.ValidString(message.Text) {
235 return errors.New("message text is not valid UTF-8")
236 }
237
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))
240 }
241
242 _, err := time.Parse(time.RFC3339Nano, message.Date)
243 if err != nil {
244 return fmt.Errorf("parse message date: %w", err)
245 }
246
247 return nil
248 }