17 // scheduleFileName is the file of the schedules in the directory of the
19 scheduleFileName = "schedules.json"
21 // scheduleTextBytes is the most bytes of the text of a schedule.
22 scheduleTextBytes = 4096
24 // scheduleAtLayout is the layout of the time of a one-time schedule.
25 scheduleAtLayout = "2006-01-02 15:04"
27 // scheduleTimeLayout is the layout of the times in the answers of the
28 // tools and in the log.
29 scheduleTimeLayout = "Monday 2006-01-02 15:04 -07:00"
31 // scheduleLate is how long after its time a run is late.
32 scheduleLate = time.Minute
34 // scheduleEmptyReply is the last line of the message of a run.
35 scheduleEmptyReply = "If nothing in this task needs the user, end your turn with an empty reply."
37 // scheduleLateLine tells the agent that a run is late.
38 scheduleLateLine = "This run is late: the daemon was stopped at that time."
41 // openSchedules reads the schedules of the file at path. A missing file holds
42 // none. The clock gives the time and the time zone of the schedules.
43 func openSchedules(path string, clock func() time.Time) (*Schedules, error) {
49 data, err := os.ReadFile(path)
50 if errors.Is(err, os.ErrNotExist) {
55 return nil, fmt.Errorf("read schedules: %w", err)
58 err = json.Unmarshal(data, &s.file)
60 return nil, fmt.Errorf("%s: %w", path, err)
63 for _, schedule := range s.file.Schedules {
64 if schedule.Cron == "" {
68 _, err = scheduleParseCron(schedule.Cron)
70 return nil, fmt.Errorf("%s: schedule %d: %w", path, schedule.ID, err)
77 // Schedules holds the schedules of the agent: tasks that start a turn at one
78 // time or at the times of a cron expression. Each change writes the file whole
79 // before it returns, so a schedule survives a restart. The mutex protects the
80 // schedules, because the tools change them from a turn while the runs read
82 type Schedules struct {
84 clock func() time.Time
90 // Set adds a schedule with text and returns the answer of the tool. Exactly one
91 // of at and cron is not nil. at is a local time in scheduleAtLayout after now,
92 // and it goes through scheduleWallTime, so a time in the hour that the clock
93 // repeats is its first occurrence. cron is an expression of scheduleParseCron.
94 func (s *Schedules) Set(text string, at, cron *string) (string, error) {
95 text = strings.TrimSpace(text)
96 if text == "" || len(text) > scheduleTextBytes {
97 return "", fmt.Errorf("the text must have 1 to %d bytes", scheduleTextBytes)
101 schedule := Schedule{
106 case (at == nil) == (cron == nil):
107 return "", errors.New("give either at or cron, and null for the other")
109 parsed, err := time.Parse(scheduleAtLayout, *at)
111 return "", fmt.Errorf("at must be a local time such as %s", now.Format(scheduleAtLayout))
114 schedule.Due = scheduleWallTime(parsed.Year(), parsed.Month(), parsed.Day(), parsed.Hour(), parsed.Minute(), now.Location())
115 if !schedule.Due.After(now) {
116 return "", fmt.Errorf("the time %s is not after now, %s", schedule.Due.Format(scheduleTimeLayout), now.Format(scheduleTimeLayout))
119 parsed, err := scheduleParseCron(*cron)
124 next, found := parsed.Next(now)
126 return "", fmt.Errorf("the cron expression %q matches no time in %d years", *cron, scheduleCronYears)
129 schedule.Cron = parsed.String()
134 defer s.mutex.Unlock()
137 schedule.ID = s.file.Next
138 s.file.Schedules = append(s.file.Schedules, schedule)
144 return fmt.Sprintf("Schedule %d set. Next: %s.", schedule.ID, schedule.Due.In(now.Location()).Format(scheduleTimeLayout)), nil
147 // List returns the answer of the tool: one line for each schedule, by due time,
148 // with its ID, its next time, its cron expression or once, and its text on one
150 func (s *Schedules) List() string {
151 location := s.clock().Location()
152 schedules := s.sorted()
153 if len(schedules) == 0 {
154 return "No schedules."
157 lines := make([]string, 0, len(schedules))
158 for _, schedule := range schedules {
159 lines = append(lines, strconv.Itoa(schedule.ID)+" | "+schedule.Due.In(location).Format(scheduleTimeLayout)+" | "+cmp.Or(schedule.Cron, "once")+" | "+strings.Join(strings.Fields(schedule.Text), " "))
162 return strings.Join(lines, "\n")
165 // Remove removes the schedule id and returns the answer of the tool.
166 func (s *Schedules) Remove(id int) (string, error) {
168 defer s.mutex.Unlock()
170 index := slices.IndexFunc(s.file.Schedules, func(schedule Schedule) bool {
171 return schedule.ID == id
175 return "", fmt.Errorf("no schedule %d", id)
178 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
184 return fmt.Sprintf("Schedule %d removed.", id), nil
187 // Due returns the schedules whose time is not after now, by due time.
188 func (s *Schedules) Due(now time.Time) []Schedule {
190 for _, schedule := range s.sorted() {
191 if !schedule.Due.After(now) {
192 due = append(due, schedule)
199 // Done ends the run of schedule at now: a one-time schedule goes, and a
200 // repeating schedule gets the next time after now. So a repeating schedule that
201 // missed several times runs once. When a remove took the schedule first, Done
203 func (s *Schedules) Done(schedule Schedule, now time.Time) error {
205 defer s.mutex.Unlock()
207 index := slices.IndexFunc(s.file.Schedules, func(held Schedule) bool {
208 return held.ID == schedule.ID
215 if schedule.Cron == "" {
216 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
221 cron, err := scheduleParseCron(schedule.Cron)
223 return fmt.Errorf("schedule %d: %w", schedule.ID, err)
226 next, found := cron.Next(now)
228 s.file.Schedules = slices.Delete(s.file.Schedules, index, index+1)
233 s.file.Schedules[index].Due = next
238 // Wait returns how long after now the first schedule is due, or false when
239 // there is no schedule.
240 func (s *Schedules) Wait(now time.Time) (time.Duration, bool) {
241 schedules := s.sorted()
242 if len(schedules) == 0 {
246 return max(schedules[0].Due.Sub(now), 0), true
249 // sorted returns a copy of the schedules by due time, then by ID.
250 func (s *Schedules) sorted() []Schedule {
252 schedules := slices.Clone(s.file.Schedules)
255 slices.SortFunc(schedules, func(a, b Schedule) int {
256 return cmp.Or(a.Due.Compare(b.Due), cmp.Compare(a.ID, b.ID))
262 // save writes the file whole, with mode 0600. The caller holds the mutex.
263 func (s *Schedules) save() error {
264 data, err := json.Marshal(s.file)
266 err = writeFileAtomic(s.path, append(data, '\n'))
270 return fmt.Errorf("save schedules: %w", err)
276 // ScheduleFile is the content of the file of the schedules: the ID of the last
277 // schedule, so that an ID is never used again, and the schedules.
278 type ScheduleFile struct {
279 Next int `json:"next"`
280 Schedules []Schedule `json:"schedules"`
283 // Schedule is one schedule: its ID, the task for the agent, the cron expression
284 // of a repeating schedule, empty for a one-time schedule, and its next time.
285 type Schedule struct {
287 Text string `json:"text"`
288 Cron string `json:"cron"`
289 Due time.Time `json:"due"`
292 // Message returns the text of a run at now for the log, with the times in the
293 // location of now. The first line starts with [Schedule ID] and gives the due
294 // time and once or the cron expression. Then come the text, the line about a
295 // late run when now is more than scheduleLate after the due time, and the line
296 // about the empty reply.
297 func (s Schedule) Message(now time.Time) string {
299 "[Schedule " + strconv.Itoa(s.ID) + "] " + s.Due.In(now.Location()).Format(scheduleTimeLayout) + ", " + s.repeats(),
303 if now.Sub(s.Due) > scheduleLate {
304 lines = append(lines, scheduleLateLine)
307 return strings.Join(append(lines, scheduleEmptyReply), "\n")
310 // repeats returns once for a one-time schedule, or else repeats and the cron
312 func (s Schedule) repeats() string {
317 return "repeats " + s.Cron