]> git.giacomolli.uk - onechat/blob - schedule_cron.go
Keep retries after a rejected pair request
[onechat] / schedule_cron.go
1 package main
2
3 import (
4         "errors"
5         "fmt"
6         "strconv"
7         "strings"
8         "time"
9 )
10
11 const (
12         // scheduleCronGap is the shortest time between two runs of a cron
13         // expression. Each run is a full turn, so shorter gaps use the quota
14         // too fast.
15         scheduleCronGap = 5
16
17         // scheduleCronYears is how many years the search for the next time
18         // covers.
19         scheduleCronYears = 8
20 )
21
22 // scheduleCronFields are the fields of a cron expression, in order, with their
23 // lowest and highest values.
24 var scheduleCronFields = []struct {
25         name string
26         low  int
27         high int
28 }{
29         {
30                 name: "minute",
31                 low:  0,
32                 high: 59,
33         },
34         {
35                 name: "hour",
36                 low:  0,
37                 high: 23,
38         },
39         {
40                 name: "day of month",
41                 low:  1,
42                 high: 31,
43         },
44         {
45                 name: "month",
46                 low:  1,
47                 high: 12,
48         },
49         {
50                 name: "day of week",
51                 low:  0,
52                 high: 7,
53         },
54 }
55
56 // scheduleParseCron parses a cron expression of five fields: minute, hour, day
57 // of month, month, and day of week, where 0 and 7 are Sunday. A field is a
58 // comma list of items, and an item is *, N, or N-M, where * and N-M can have a
59 // step /S. Names, macros, the characters ? L W #, and N/S are errors.
60 //
61 // It refuses an expression whose runs can be less than scheduleCronGap minutes
62 // apart. The check takes the wall times of one day from the hour and the minute
63 // fields, and the gap across midnight as if the next day matches too. It also
64 // refuses an expression that matches no day in scheduleCronYears years, such as
65 // one on February 30.
66 func scheduleParseCron(expression string) (ScheduleCron, error) {
67         fields := strings.Fields(expression)
68         if len(fields) != len(scheduleCronFields) {
69                 return ScheduleCron{}, fmt.Errorf("the cron expression %q has %d fields, not 5: minute, hour, day of month, month, day of week", expression, len(fields))
70         }
71
72         var sets [5]uint64
73         for index, field := range fields {
74                 set, err := scheduleCronField(field, scheduleCronFields[index].low, scheduleCronFields[index].high)
75                 if err != nil {
76                         return ScheduleCron{}, fmt.Errorf("the %s field of %q: %w", scheduleCronFields[index].name, expression, err)
77                 }
78
79                 sets[index] = set
80         }
81
82         c := ScheduleCron{
83                 minutes:     sets[0],
84                 hours:       sets[1],
85                 days:        sets[2],
86                 months:      sets[3],
87                 weekdays:    sets[4],
88                 anyDay:      strings.HasPrefix(fields[2], "*"),
89                 anyWeekday:  strings.HasPrefix(fields[4], "*"),
90                 description: strings.Join(fields, " "),
91         }
92
93         if c.weekdays&(1<<7) != 0 {
94                 c.weekdays |= 1
95         }
96
97         if c.gap() < scheduleCronGap {
98                 return ScheduleCron{}, fmt.Errorf("the runs of %q can be less than %d minutes apart: the runs of a schedule must be at least %d minutes apart", expression, scheduleCronGap, scheduleCronGap)
99         }
100
101         start := time.Date(2024, time.January, 1, 0, 0, 0, 0, time.UTC)
102         _, found := c.Next(start)
103         if !found {
104                 return ScheduleCron{}, fmt.Errorf("the cron expression %q matches no day in %d years", expression, scheduleCronYears)
105         }
106
107         return c, nil
108 }
109
110 // ScheduleCron is a parsed cron expression. Each set holds a bit for each value
111 // of its field. anyDay and anyWeekday tell that the day field or the weekday
112 // field starts with *. When neither does, a day matches when either field
113 // matches, as in classic cron. Otherwise both fields must match.
114 type ScheduleCron struct {
115         minutes     uint64
116         hours       uint64
117         days        uint64
118         months      uint64
119         weekdays    uint64
120         anyDay      bool
121         anyWeekday  bool
122         description string
123 }
124
125 // String returns the expression with one space between its fields.
126 func (c ScheduleCron) String() string {
127         return c.description
128 }
129
130 // Next returns the first time after after whose wall time in the location of
131 // after matches, or false when no time in scheduleCronYears years matches. A
132 // wall time goes through scheduleWallTime, so a wall time that the clock skips
133 // runs later by the length of the skip, and a wall time that the clock repeats
134 // runs once, at its first occurrence.
135 func (c ScheduleCron) Next(after time.Time) (time.Time, bool) {
136         location := after.Location()
137         year, month, day := after.Date()
138         first := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
139         last := first.AddDate(scheduleCronYears, 0, 0)
140         for date := first; date.Before(last); date = date.AddDate(0, 0, 1) {
141                 if !c.day(date) {
142                         continue
143                 }
144
145                 // A wall time that the clock skips moves later, so the times of
146                 // one day are not always in order. The first time is the
147                 // smallest one.
148                 var next time.Time
149                 for hour := range 24 {
150                         if c.hours&(1<<hour) == 0 {
151                                 continue
152                         }
153
154                         for minute := range 60 {
155                                 if c.minutes&(1<<minute) == 0 {
156                                         continue
157                                 }
158
159                                 t := scheduleWallTime(date.Year(), date.Month(), date.Day(), hour, minute, location)
160                                 if t.After(after) && (next.IsZero() || t.Before(next)) {
161                                         next = t
162                                 }
163                         }
164                 }
165
166                 if !next.IsZero() {
167                         return next, true
168                 }
169         }
170
171         return time.Time{}, false
172 }
173
174 // day tells if the calendar date matches the month and the day fields.
175 func (c ScheduleCron) day(date time.Time) bool {
176         if c.months&(1<<int(date.Month())) == 0 {
177                 return false
178         }
179
180         day := c.days&(1<<date.Day()) != 0
181         weekday := c.weekdays&(1<<int(date.Weekday())) != 0
182         if c.anyDay || c.anyWeekday {
183                 return day && weekday
184         }
185
186         return day || weekday
187 }
188
189 // gap returns the shortest time in minutes between two wall times of the hour
190 // and the minute fields, also across midnight.
191 func (c ScheduleCron) gap() int {
192         var times []int
193         for hour := range 24 {
194                 for minute := range 60 {
195                         if c.hours&(1<<hour) != 0 && c.minutes&(1<<minute) != 0 {
196                                 times = append(times, 60*hour+minute)
197                         }
198                 }
199         }
200
201         gap := times[0] + 24*60 - times[len(times)-1]
202         for index := 1; index < len(times); index++ {
203                 gap = min(gap, times[index]-times[index-1])
204         }
205
206         return gap
207 }
208
209 // scheduleWallTime returns the time of a wall time in location. A wall time
210 // that the clock skips, at the start of daylight saving time, is later by the
211 // length of the skip: 02:30 becomes 03:30 when the clock goes from 02:00 to
212 // 03:00. A wall time that the clock repeats, at the end of daylight saving
213 // time, is its first occurrence, as in cron.
214 func scheduleWallTime(year int, month time.Month, day, hour, minute int, location *time.Location) time.Time {
215         t := time.Date(year, month, day, hour, minute, 0, 0, location)
216         _, before := t.Add(-3 * time.Hour).Zone()
217         _, offset := t.Zone()
218         if t.Hour() != hour || t.Minute() != minute || t.Day() != day {
219                 wall := time.Date(year, month, day, hour, minute, 0, 0, time.UTC)
220
221                 return wall.Add(-time.Duration(before) * time.Second).In(location)
222         }
223
224         if before > offset {
225                 earlier := t.Add(-time.Duration(before-offset) * time.Second)
226                 if earlier.Day() == day && earlier.Hour() == hour && earlier.Minute() == minute {
227                         return earlier
228                 }
229         }
230
231         return t
232 }
233
234 // scheduleCronField returns the set of the values of one field, from low to
235 // high.
236 func scheduleCronField(field string, low, high int) (uint64, error) {
237         var set uint64
238         for item := range strings.SplitSeq(field, ",") {
239                 base, stepText, stepped := strings.Cut(item, "/")
240                 step := 1
241                 if stepped {
242                         var err error
243                         step, err = scheduleCronNumber(stepText, 1, high)
244                         if err != nil {
245                                 return 0, fmt.Errorf("the step of %q: %w", item, err)
246                         }
247                 }
248
249                 first, last := low, high
250                 startText, endText, ranged := strings.Cut(base, "-")
251                 switch {
252                 case base == "*":
253                 case ranged:
254                         var err error
255                         first, err = scheduleCronNumber(startText, low, high)
256                         if err == nil {
257                                 last, err = scheduleCronNumber(endText, low, high)
258                         }
259
260                         if err == nil && first > last {
261                                 err = errors.New("the start is after the end")
262                         }
263
264                         if err != nil {
265                                 return 0, fmt.Errorf("the range %q: %w", base, err)
266                         }
267                 case stepped:
268                         return 0, fmt.Errorf("%q has a step after a single value: write a range N-M/S or */S", item)
269                 default:
270                         var err error
271                         first, err = scheduleCronNumber(base, low, high)
272                         if err != nil {
273                                 return 0, err
274                         }
275
276                         last = first
277                 }
278
279                 for value := first; value <= last; value += step {
280                         set |= 1 << value
281                 }
282         }
283
284         return set, nil
285 }
286
287 // scheduleCronNumber returns the value of text, a decimal number from low to
288 // high.
289 func scheduleCronNumber(text string, low, high int) (int, error) {
290         if text == "" || strings.Trim(text, "0123456789") != "" {
291                 return 0, fmt.Errorf("%q is not a number from %d to %d", text, low, high)
292         }
293
294         value, err := strconv.Atoi(text)
295         if err != nil || value < low || value > high {
296                 return 0, fmt.Errorf("%q is not a number from %d to %d", text, low, high)
297         }
298
299         return value, nil
300 }