19 // scheduleFileName is the file of the schedules in the directory of the
21 scheduleFileName = "schedules.json"
23 // scheduleTextBytes is the most bytes of the text of a schedule.
24 scheduleTextBytes = 4096
26 // scheduleAtLayout is the layout of the time of a one-time schedule.
27 scheduleAtLayout = "2006-01-02 15:04"
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"
33 // scheduleSource is the source of the work events of the runs.
34 scheduleSource = "schedule"
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
41 // scheduleLate is how long after its time a run is late.
42 scheduleLate = time.Minute
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."
47 // scheduleLateLine tells the agent that a run is late.
48 scheduleLateLine = "This run is late: the daemon was stopped at that time."
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 {
59 clock func() time.Time
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"`
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
77 type Schedule struct {
78 Owner string `json:"owner"`
80 Text string `json:"text"`
81 Cron string `json:"cron"`
82 Due time.Time `json:"due"`
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) {
95 changed: make(chan struct{}, 1),
98 data, err := os.ReadFile(path)
99 if errors.Is(err, os.ErrNotExist) {
104 return nil, fmt.Errorf("read schedules: %w", err)
107 err = json.Unmarshal(data, &s.file)
109 return nil, fmt.Errorf("%s: %w", path, err)
113 for i := range s.file.Schedules {
114 schedule := &s.file.Schedules[i]
115 if schedule.Owner == "" {
116 schedule.Owner = owner
120 if schedule.Owner != owner {
121 return nil, fmt.Errorf("schedule %d belongs to %q, not %q", schedule.ID, schedule.Owner, owner)
124 if schedule.Cron == "" {
128 _, err = scheduleParseCron(schedule.Cron)
130 return nil, fmt.Errorf("%s: schedule %d: %w", path, schedule.ID, err)
137 return nil, fmt.Errorf("record schedule owner: %w", err)
144 // save writes the file whole, with mode 0600. The caller holds the mutex.
145 func (s *Schedules) save() error {
146 data, err := json.Marshal(s.file)
148 err = writeFileAtomic(s.path, append(data, '\n'))
152 return fmt.Errorf("save schedules: %w", err)
158 // Run starts the runs of the due schedules in l until ctx ends. It waits until
159 // the first due time, at most scheduleClockWaitTimeout at a time, and also
160 // wakes at a set or a remove. So a schedule that came due while the daemon was
161 // stopped runs at the start. It returns the error of a write of the log or of
163 func (s *Schedules) Run(ctx context.Context, l *TurnLoop) error {
165 err := s.deliver(ctx, l)
172 timeout <-chan time.Time
175 wait, found := s.Wait(s.clock())
177 timer = time.NewTimer(min(wait, scheduleClockWaitTimeout))
194 // deliver logs the message of each due schedule in l, in due order, as a work
195 // message of scheduleSource, and wakes the loop once with all of them. A
196 // schedule ends its run with Done after its message is durable in the log. A
197 // crash between the two makes the run repeat once. Each run logs one line with
198 // the ID of the schedule and, for a late run, how late it is. The line holds no
199 // text of the schedule.
200 func (s *Schedules) deliver(ctx context.Context, l *TurnLoop) error {
201 if l.agent.config.Name != s.owner {
202 return fmt.Errorf("schedule owner %q does not match agent %q", s.owner, l.agent.config.Name)
209 for _, schedule := range s.Due(now) {
210 message, err := l.Work(scheduleSource, schedule.Message(now), "")
212 return fmt.Errorf("log a schedule: %w", err)
215 // A stop of the daemon during the flush is no failure: the
216 // schedule stays due and runs at the next start.
218 if ctx.Err() != nil {
223 return fmt.Errorf("log a schedule: %w", err)
226 err = s.Done(schedule, now)
228 return fmt.Errorf("acknowledge schedule run: %w", err)
231 attrs := []any{"id", schedule.ID}
232 if schedule.late(now) {
233 attrs = append(attrs, "late", now.Sub(schedule.Due))
236 s.logger.Info("schedule ran", attrs...)
238 turns = append(turns, message)
246 // Wait returns how long after now the first schedule is due, or false when
247 // there is no schedule.
248 func (s *Schedules) Wait(now time.Time) (time.Duration, bool) {
249 schedules := s.sorted()
250 if len(schedules) == 0 {
254 return max(schedules[0].Due.Sub(now), 0), true
257 // Due returns the schedules whose time is not after now, by due time.
258 func (s *Schedules) Due(now time.Time) []Schedule {
261 for _, schedule := range s.sorted() {
262 if !schedule.Due.After(now) {
263 due = append(due, schedule)
270 // Done ends the run of schedule at now: a one-time schedule goes, and a
271 // repeating schedule gets the next time after now. So a repeating schedule that
272 // missed several times runs once. When a remove took the schedule first, Done
274 func (s *Schedules) Done(schedule Schedule, now time.Time) error {
276 defer s.mutex.Unlock()
278 index := slices.IndexFunc(s.file.Schedules, func(held Schedule) bool {
279 return held.ID == schedule.ID
286 if schedule.Cron == "" {
287 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
292 cron, err := scheduleParseCron(schedule.Cron)
294 return fmt.Errorf("schedule %d: %w", schedule.ID, err)
297 next, found := cron.Next(now)
299 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
304 s.file.Schedules[index].Due = next
309 // sorted returns a copy of the schedules by due time, then by ID.
310 func (s *Schedules) sorted() []Schedule {
313 schedules := slices.Clone(s.file.Schedules)
316 slices.SortFunc(schedules, func(a, b Schedule) int {
317 return cmp.Or(a.Due.Compare(b.Due), cmp.Compare(a.ID, b.ID))
323 // Set adds a schedule with text and returns the answer of the tool. Exactly one
324 // of at and cron is not nil. at is a local time in scheduleAtLayout after now,
325 // and it goes through scheduleWallTime, so a time in the hour that the clock
326 // repeats is its first occurrence. cron is an expression of scheduleParseCron.
327 func (s *Schedules) Set(text string, at, cron *string) (string, error) {
328 text = strings.TrimSpace(text)
329 if text == "" || len(text) > scheduleTextBytes {
330 return "", fmt.Errorf("the text must have 1 to %d bytes", scheduleTextBytes)
334 schedule := Schedule{
340 case (at == nil) == (cron == nil):
341 return "", errors.New("give either at or cron, and null for the other")
343 parsed, err := time.Parse(scheduleAtLayout, *at)
345 return "", fmt.Errorf("at must be a local time such as %s", now.Format(scheduleAtLayout))
348 schedule.Due = scheduleWallTime(parsed.Year(), parsed.Month(), parsed.Day(), parsed.Hour(), parsed.Minute(), now.Location())
349 if !schedule.Due.After(now) {
350 return "", fmt.Errorf("the time %s is not after now, %s", schedule.Due.Format(scheduleTimeLayout), now.Format(scheduleTimeLayout))
353 parsed, err := scheduleParseCron(*cron)
355 return "", fmt.Errorf("parse schedule expression: %w", err)
358 next, found := parsed.Next(now)
360 return "", fmt.Errorf("the cron expression %q matches no time in %d years", *cron, scheduleCronYears)
363 schedule.Cron = parsed.String()
368 defer s.mutex.Unlock()
371 schedule.ID = s.file.Next
372 s.file.Schedules = append(s.file.Schedules, schedule)
375 return "", fmt.Errorf("save new schedule: %w", err)
380 return fmt.Sprintf("Schedule %d set. Next: %s.", schedule.ID, schedule.Due.In(now.Location()).Format(scheduleTimeLayout)), nil
383 // change wakes Run after a set or a remove.
384 func (s *Schedules) change() {
386 case s.changed <- struct{}{}:
391 // List returns the answer of the tool: one line for each schedule, by due time,
392 // with its ID, its next time, its cron expression or once, and its text on one
394 func (s *Schedules) List() string {
395 location := s.clock().Location()
396 schedules := s.sorted()
397 if len(schedules) == 0 {
398 return "No schedules."
401 lines := make([]string, 0, len(schedules))
402 for _, schedule := range schedules {
403 lines = append(lines, strconv.Itoa(schedule.ID)+" | "+schedule.Due.In(location).Format(scheduleTimeLayout)+" | "+cmp.Or(schedule.Cron, "once")+" | "+strings.Join(strings.Fields(schedule.Text), " "))
406 return strings.Join(lines, "\n")
409 // Len returns the number of schedules.
410 func (s *Schedules) Len() int {
412 defer s.mutex.Unlock()
414 return len(s.file.Schedules)
417 // Remove removes the schedule id and returns the answer of the tool.
418 func (s *Schedules) Remove(id int) (string, error) {
420 defer s.mutex.Unlock()
422 index := slices.IndexFunc(s.file.Schedules, func(schedule Schedule) bool {
423 return schedule.ID == id
427 return "", fmt.Errorf("no schedule %d", id)
430 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
433 return "", fmt.Errorf("save removed schedule: %w", err)
438 return fmt.Sprintf("Schedule %d removed.", id), nil
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 {
448 "[Schedule " + strconv.Itoa(s.ID) + "] " + s.Due.In(now.Location()).Format(scheduleTimeLayout) + ", " + s.repeats(),
453 lines = append(lines, scheduleLateLine)
456 return strings.Join(append(lines, scheduleEmptyReply), "\n")
459 // late tells if a run at now is late: more than scheduleLate after the due
461 func (s Schedule) late(now time.Time) bool {
462 return now.Sub(s.Due) > scheduleLate
465 // repeats returns once for a one-time schedule, or else repeats and the cron
467 func (s Schedule) repeats() string {
472 return "repeats " + s.Cron