]> git.giacomolli.uk - onechat/blob - schedule.go
Order daemon and storage declarations
[onechat] / schedule.go
1 package main
2
3 import (
4 "cmp"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "log/slog"
10 "os"
11 "slices"
12 "strconv"
13 "strings"
14 "sync"
15 "time"
16 )
17
18 const (
19 // scheduleFileName is the file of the schedules in the directory of the
20 // agent.
21 scheduleFileName = "schedules.json"
22
23 // scheduleTextBytes is the most bytes of the text of a schedule.
24 scheduleTextBytes = 4096
25
26 // scheduleAtLayout is the layout of the time of a one-time schedule.
27 scheduleAtLayout = "2006-01-02 15:04"
28
29 // scheduleTimeLayout is the layout of the times in the answers of the
30 // tools and in the log.
31 scheduleTimeLayout = "Monday 2006-01-02 15:04 -07:00"
32
33 // scheduleSource is the source of the work events of the runs.
34 scheduleSource = "schedule"
35
36 // scheduleClockWaitTimeout is the longest wait of Run before it looks
37 // at the times again, so that it sees a suspend of the machine or a
38 // change of the clock.
39 scheduleClockWaitTimeout = time.Minute
40
41 // scheduleLate is how long after its time a run is late.
42 scheduleLate = time.Minute
43
44 // scheduleEmptyReply is the last line of the message of a run.
45 scheduleEmptyReply = "If nothing in this task needs the user, end your turn with an empty reply."
46
47 // scheduleLateLine tells the agent that a run is late.
48 scheduleLateLine = "This run is late: the daemon was stopped at that time."
49 )
50
51 // Schedules holds the schedules of the agent: tasks that start a turn at one
52 // time or at the times of a cron expression. Each change writes the file whole
53 // before it returns, so a schedule survives a restart. The mutex protects the
54 // schedules, because the tools change them from a turn while Run reads them.
55 // changed tells Run that a set or a remove changed the times.
56 type Schedules struct {
57 path string
58 owner string
59 clock func() time.Time
60 logger *slog.Logger
61 changed chan struct{}
62
63 mutex sync.Mutex
64 file ScheduleFile
65 }
66
67 // ScheduleFile is the content of the file of the schedules: the ID of the last
68 // schedule, so that an ID is never used again, and the schedules.
69 type ScheduleFile struct {
70 Next int `json:"next"`
71 Schedules []Schedule `json:"schedules"`
72 }
73
74 // Schedule is one schedule: its owner, its ID, the task for the agent, the cron
75 // expression of a repeating schedule, empty for a one-time schedule, and its
76 // next time.
77 type Schedule struct {
78 Owner string `json:"owner"`
79 ID int `json:"id"`
80 Text string `json:"text"`
81 Cron string `json:"cron"`
82 Due time.Time `json:"due"`
83 }
84
85 // openSchedules reads the schedules of the file at path. A missing file holds
86 // none. The owner names its agent. Schedules without an owner take this name. A
87 // different stored owner is an error. The clock gives the time and the time
88 // zone of the schedules, and logger gets one line for each run.
89 func openSchedules(path, owner string, clock func() time.Time, logger *slog.Logger) (*Schedules, error) {
90 s := &Schedules{
91 path: path,
92 owner: owner,
93 clock: clock,
94 logger: logger,
95 changed: make(chan struct{}, 1),
96 }
97
98 data, err := os.ReadFile(path)
99 if errors.Is(err, os.ErrNotExist) {
100 return s, nil
101 }
102
103 if err != nil {
104 return nil, fmt.Errorf("read schedules: %w", err)
105 }
106
107 err = json.Unmarshal(data, &s.file)
108 if err != nil {
109 return nil, fmt.Errorf("%s: %w", path, err)
110 }
111
112 changed := false
113 for i := range s.file.Schedules {
114 schedule := &s.file.Schedules[i]
115 if schedule.Owner == "" {
116 schedule.Owner = owner
117 changed = true
118 }
119
120 if schedule.Owner != owner {
121 return nil, fmt.Errorf("schedule %d belongs to %q, not %q", schedule.ID, schedule.Owner, owner)
122 }
123
124 if schedule.Cron == "" {
125 continue
126 }
127
128 _, err = scheduleParseCron(schedule.Cron)
129 if err != nil {
130 return nil, fmt.Errorf("%s: schedule %d: %w", path, schedule.ID, err)
131 }
132 }
133
134 if changed {
135 err = s.save()
136 if err != nil {
137 return nil, fmt.Errorf("record schedule owner: %w", err)
138 }
139 }
140
141 return s, nil
142 }
143
144 // Run starts the runs of the due schedules in l until ctx ends. It waits until
145 // the first due time, at most scheduleClockWaitTimeout at a time, and also
146 // wakes at a set or a remove. So a schedule that came due while the daemon was
147 // stopped runs at the start. It returns the error of a write of the log or of
148 // the file.
149 func (s *Schedules) Run(ctx context.Context, l *TurnLoop) error {
150 for {
151 err := s.deliver(ctx, l)
152 if err != nil {
153 return err
154 }
155
156 var (
157 timer *time.Timer
158 timeout <-chan time.Time
159 )
160
161 wait, found := s.Wait(s.clock())
162 if found {
163 timer = time.NewTimer(min(wait, scheduleClockWaitTimeout))
164 timeout = timer.C
165 }
166
167 select {
168 case <-ctx.Done():
169 return nil
170 case <-s.changed:
171 case <-timeout:
172 }
173
174 if timer != nil {
175 timer.Stop()
176 }
177 }
178 }
179
180 // Set adds a schedule with text and returns the answer of the tool. Exactly one
181 // of at and cron is not nil. at is a local time in scheduleAtLayout after now,
182 // and it goes through scheduleWallTime, so a time in the hour that the clock
183 // repeats is its first occurrence. cron is an expression of scheduleParseCron.
184 func (s *Schedules) Set(text string, at, cron *string) (string, error) {
185 text = strings.TrimSpace(text)
186 if text == "" || len(text) > scheduleTextBytes {
187 return "", fmt.Errorf("the text must have 1 to %d bytes", scheduleTextBytes)
188 }
189
190 now := s.clock()
191 schedule := Schedule{
192 Text: text,
193 Owner: s.owner,
194 }
195
196 switch {
197 case (at == nil) == (cron == nil):
198 return "", errors.New("give either at or cron, and null for the other")
199 case at != nil:
200 parsed, err := time.Parse(scheduleAtLayout, *at)
201 if err != nil {
202 return "", fmt.Errorf("at must be a local time such as %s", now.Format(scheduleAtLayout))
203 }
204
205 schedule.Due = scheduleWallTime(parsed.Year(), parsed.Month(), parsed.Day(), parsed.Hour(), parsed.Minute(), now.Location())
206 if !schedule.Due.After(now) {
207 return "", fmt.Errorf("the time %s is not after now, %s", schedule.Due.Format(scheduleTimeLayout), now.Format(scheduleTimeLayout))
208 }
209 default:
210 parsed, err := scheduleParseCron(*cron)
211 if err != nil {
212 return "", err
213 }
214
215 next, found := parsed.Next(now)
216 if !found {
217 return "", fmt.Errorf("the cron expression %q matches no time in %d years", *cron, scheduleCronYears)
218 }
219
220 schedule.Cron = parsed.String()
221 schedule.Due = next
222 }
223
224 s.mutex.Lock()
225 defer s.mutex.Unlock()
226
227 s.file.Next++
228 schedule.ID = s.file.Next
229 s.file.Schedules = append(s.file.Schedules, schedule)
230 err := s.save()
231 if err != nil {
232 return "", err
233 }
234
235 s.change()
236
237 return fmt.Sprintf("Schedule %d set. Next: %s.", schedule.ID, schedule.Due.In(now.Location()).Format(scheduleTimeLayout)), nil
238 }
239
240 // List returns the answer of the tool: one line for each schedule, by due time,
241 // with its ID, its next time, its cron expression or once, and its text on one
242 // line.
243 func (s *Schedules) List() string {
244 location := s.clock().Location()
245 schedules := s.sorted()
246 if len(schedules) == 0 {
247 return "No schedules."
248 }
249
250 lines := make([]string, 0, len(schedules))
251 for _, schedule := range schedules {
252 lines = append(lines, strconv.Itoa(schedule.ID)+" | "+schedule.Due.In(location).Format(scheduleTimeLayout)+" | "+cmp.Or(schedule.Cron, "once")+" | "+strings.Join(strings.Fields(schedule.Text), " "))
253 }
254
255 return strings.Join(lines, "\n")
256 }
257
258 // Len returns the number of schedules.
259 func (s *Schedules) Len() int {
260 s.mutex.Lock()
261 defer s.mutex.Unlock()
262
263 return len(s.file.Schedules)
264 }
265
266 // Remove removes the schedule id and returns the answer of the tool.
267 func (s *Schedules) Remove(id int) (string, error) {
268 s.mutex.Lock()
269 defer s.mutex.Unlock()
270
271 index := slices.IndexFunc(s.file.Schedules, func(schedule Schedule) bool {
272 return schedule.ID == id
273 })
274
275 if index < 0 {
276 return "", fmt.Errorf("no schedule %d", id)
277 }
278
279 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
280 err := s.save()
281 if err != nil {
282 return "", err
283 }
284
285 s.change()
286
287 return fmt.Sprintf("Schedule %d removed.", id), nil
288 }
289
290 // deliver logs the message of each due schedule in l, in due order, as a work
291 // message of scheduleSource, and wakes the loop once with all of them. A
292 // schedule ends its run with Done after its message is durable in the log. A
293 // crash between the two makes the run repeat once. Each run logs one line with
294 // the ID of the schedule and, for a late run, how late it is. The line holds no
295 // text of the schedule.
296 func (s *Schedules) deliver(ctx context.Context, l *TurnLoop) error {
297 if l.agent.config.Name != s.owner {
298 return fmt.Errorf("schedule owner %q does not match agent %q", s.owner, l.agent.config.Name)
299 }
300
301 now := s.clock()
302
303 var turns []Message
304
305 for _, schedule := range s.Due(now) {
306 message, err := l.Work(scheduleSource, schedule.Message(now), "")
307 if err != nil {
308 return fmt.Errorf("log a schedule: %w", err)
309 }
310
311 // A stop of the daemon during the flush is no failure: the
312 // schedule stays due and runs at the next start.
313 err = l.Flush(ctx)
314 if ctx.Err() != nil {
315 return nil
316 }
317
318 if err != nil {
319 return fmt.Errorf("log a schedule: %w", err)
320 }
321
322 err = s.Done(schedule, now)
323 if err != nil {
324 return err
325 }
326
327 attrs := []any{"id", schedule.ID}
328 if schedule.late(now) {
329 attrs = append(attrs, "late", now.Sub(schedule.Due))
330 }
331
332 s.logger.Info("schedule ran", attrs...)
333
334 turns = append(turns, message)
335 }
336
337 l.Wake(turns...)
338
339 return nil
340 }
341
342 // Due returns the schedules whose time is not after now, by due time.
343 func (s *Schedules) Due(now time.Time) []Schedule {
344 var due []Schedule
345
346 for _, schedule := range s.sorted() {
347 if !schedule.Due.After(now) {
348 due = append(due, schedule)
349 }
350 }
351
352 return due
353 }
354
355 // Done ends the run of schedule at now: a one-time schedule goes, and a
356 // repeating schedule gets the next time after now. So a repeating schedule that
357 // missed several times runs once. When a remove took the schedule first, Done
358 // changes nothing.
359 func (s *Schedules) Done(schedule Schedule, now time.Time) error {
360 s.mutex.Lock()
361 defer s.mutex.Unlock()
362
363 index := slices.IndexFunc(s.file.Schedules, func(held Schedule) bool {
364 return held.ID == schedule.ID
365 })
366
367 if index < 0 {
368 return nil
369 }
370
371 if schedule.Cron == "" {
372 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
373
374 return s.save()
375 }
376
377 cron, err := scheduleParseCron(schedule.Cron)
378 if err != nil {
379 return fmt.Errorf("schedule %d: %w", schedule.ID, err)
380 }
381
382 next, found := cron.Next(now)
383 if !found {
384 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
385
386 return s.save()
387 }
388
389 s.file.Schedules[index].Due = next
390
391 return s.save()
392 }
393
394 // Wait returns how long after now the first schedule is due, or false when
395 // there is no schedule.
396 func (s *Schedules) Wait(now time.Time) (time.Duration, bool) {
397 schedules := s.sorted()
398 if len(schedules) == 0 {
399 return 0, false
400 }
401
402 return max(schedules[0].Due.Sub(now), 0), true
403 }
404
405 // change wakes Run after a set or a remove.
406 func (s *Schedules) change() {
407 select {
408 case s.changed <- struct{}{}:
409 default:
410 }
411 }
412
413 // sorted returns a copy of the schedules by due time, then by ID.
414 func (s *Schedules) sorted() []Schedule {
415 s.mutex.Lock()
416
417 schedules := slices.Clone(s.file.Schedules)
418 s.mutex.Unlock()
419
420 slices.SortFunc(schedules, func(a, b Schedule) int {
421 return cmp.Or(a.Due.Compare(b.Due), cmp.Compare(a.ID, b.ID))
422 })
423
424 return schedules
425 }
426
427 // save writes the file whole, with mode 0600. The caller holds the mutex.
428 func (s *Schedules) save() error {
429 data, err := json.Marshal(s.file)
430 if err == nil {
431 err = writeFileAtomic(s.path, append(data, '\n'))
432 }
433
434 if err != nil {
435 return fmt.Errorf("save schedules: %w", err)
436 }
437
438 return nil
439 }
440
441 // Message returns the text of a run at now for the log, with the times in the
442 // location of now. The first line starts with [Schedule ID] and gives the due
443 // time and once or the cron expression. Then come the text, the line about a
444 // late run when now is more than scheduleLate after the due time, and the line
445 // about the empty reply.
446 func (s Schedule) Message(now time.Time) string {
447 lines := []string{
448 "[Schedule " + strconv.Itoa(s.ID) + "] " + s.Due.In(now.Location()).Format(scheduleTimeLayout) + ", " + s.repeats(),
449 s.Text,
450 }
451
452 if s.late(now) {
453 lines = append(lines, scheduleLateLine)
454 }
455
456 return strings.Join(append(lines, scheduleEmptyReply), "\n")
457 }
458
459 // late tells if a run at now is late: more than scheduleLate after the due
460 // time.
461 func (s Schedule) late(now time.Time) bool {
462 return now.Sub(s.Due) > scheduleLate
463 }
464
465 // repeats returns once for a one-time schedule, or else repeats and the cron
466 // expression.
467 func (s Schedule) repeats() string {
468 if s.Cron == "" {
469 return "once"
470 }
471
472 return "repeats " + s.Cron
473 }