]> git.giacomolli.uk - onechat/blob - log.go
Order model and chat declarations
[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 // Append writes a new message to the log and returns it with its ID, size, and
109 // date.
110 func (l *Log) Append(kind, text string) (Message, error) {
111 return l.AppendDated(kind, text, "")
112 }
113
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) {
117 if l.lock == nil {
118 return Message{}, fmt.Errorf("append dated message: %w", os.ErrClosed)
119 }
120
121 if l.failure != nil {
122 return Message{}, fmt.Errorf("log needs a reopen after a failed write: %w", l.failure)
123 }
124
125 var err error
126
127 now := l.clock()
128 if date == "" {
129 date = now.Format(time.RFC3339Nano)
130 } else {
131 now, err = time.Parse(time.RFC3339Nano, date)
132 if err != nil {
133 return Message{}, fmt.Errorf("parse message date: %w", err)
134 }
135
136 now = now.In(time.Local)
137 }
138
139 message := Message{
140 ID: l.index.count,
141 Kind: kind,
142 Text: text,
143 Size: len(text),
144 Date: date,
145 }
146
147 err = logValidateMessage(message)
148 if err != nil {
149 return Message{}, fmt.Errorf("validate dated message: %w", err)
150 }
151
152 line, err := json.Marshal(message)
153 if err != nil {
154 return Message{}, fmt.Errorf("encode message: %w", err)
155 }
156
157 place, err := l.journal.Write(now.Format(time.DateOnly), append(line, '\n'))
158 if err == nil {
159 err = l.addIndex(place)
160 }
161
162 if err != nil {
163 l.failure = err
164 return Message{}, fmt.Errorf("write message %d: %w", message.ID, err)
165 }
166
167 return message, nil
168 }
169
170 // Len returns the number of messages in the log.
171 func (l *Log) Len() int {
172 return l.index.count
173 }
174
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)
178 if err != nil {
179 return Message{}, err
180 }
181
182 if !found {
183 return Message{}, fmt.Errorf("no message %d", id)
184 }
185
186 line, err := l.journal.Read(decodePosition(record))
187 if err != nil {
188 return Message{}, fmt.Errorf("read message %d: %w", id, err)
189 }
190
191 var message Message
192
193 err = json.Unmarshal(line, &message)
194 if err != nil {
195 return Message{}, fmt.Errorf("decode message %d: %w", id, err)
196 }
197
198 if message.ID != id {
199 return Message{}, fmt.Errorf("index of message %d points to message %d", id, message.ID)
200 }
201
202 return message, nil
203 }
204
205 // catchUp indexes the lines after the last indexed line.
206 func (l *Log) catchUp(ctx context.Context) error {
207 start := Position{}
208 if l.index.count > 0 {
209 record, _, err := l.index.Read(l.index.count - 1)
210 if err != nil {
211 return err
212 }
213
214 last := decodePosition(record)
215 start = Position{
216 day: last.day,
217 offset: last.offset + uint64(last.length),
218 }
219 }
220
221 return l.journal.Scan(ctx, start, func(line []byte, place Position) error {
222 var message Message
223
224 err := json.Unmarshal(line, &message)
225 if err != nil {
226 return fmt.Errorf("decode log message: %w", err)
227 }
228
229 if message.ID != l.index.count {
230 return fmt.Errorf("expected message %d, found %d", l.index.count, message.ID)
231 }
232
233 err = logValidateMessage(message)
234 if err != nil {
235 return fmt.Errorf("message %d: %w", message.ID, err)
236 }
237
238 return l.addIndex(place)
239 })
240 }
241
242 func (l *Log) addIndex(place Position) error {
243 record := make([]byte, positionBytes)
244 encodePosition(record, place)
245
246 return l.index.Append(record)
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 }