|
| 1 | +// Copyright (c) Berk D. Demir and the runitor contributors. |
| 2 | +// SPDX-License-Identifier: 0BSD |
| 3 | +package internal |
| 4 | + |
| 5 | +import ( |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "strconv" |
| 9 | + "strings" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +var ( |
| 14 | + ErrCronFieldCount = errors.New("expected 5 fields") |
| 15 | + ErrCronInvalidStep = errors.New("invalid step") |
| 16 | + ErrCronPositiveStep = errors.New("step must be positive") |
| 17 | + ErrCronRangeStart = errors.New("invalid range start") |
| 18 | + ErrCronRangeEnd = errors.New("invalid range end") |
| 19 | + ErrCronInvalidValue = errors.New("invalid value") |
| 20 | + ErrCronOutOfRange = errors.New("value out of range") |
| 21 | + ErrCronRangeOrder = errors.New("range start > end") |
| 22 | +) |
| 23 | + |
| 24 | +// Cron represents a parsed cron schedule. |
| 25 | +type Cron struct { |
| 26 | + minutes [60]bool |
| 27 | + hours [24]bool |
| 28 | + dom [32]bool // 1-31 |
| 29 | + months [13]bool // 1-12 |
| 30 | + dow [8]bool // 0-7 (7 is Sunday, aliased to 0) |
| 31 | + domAll bool |
| 32 | + dowAll bool |
| 33 | +} |
| 34 | + |
| 35 | +// ParseCron parses a standard 5-field cron string. |
| 36 | +// Supported features: |
| 37 | +// - lists (1,2,3) |
| 38 | +// - ranges (1-5) |
| 39 | +// - steps (*/5, 1-10/2) |
| 40 | +// - * (all) |
| 41 | +// - day of week: 0-7 (Sunday=0 or 7) |
| 42 | +func ParseCron(s string) (*Cron, error) { |
| 43 | + fields := strings.Fields(s) |
| 44 | + if len(fields) != 5 { |
| 45 | + return nil, fmt.Errorf("%w, got %d", ErrCronFieldCount, len(fields)) |
| 46 | + } |
| 47 | + |
| 48 | + c := &Cron{} |
| 49 | + var err error |
| 50 | + |
| 51 | + if _, err = parseField(fields[0], 0, 59, c.minutes[:]); err != nil { |
| 52 | + return nil, fmt.Errorf("parsing minutes: %w", err) |
| 53 | + } |
| 54 | + if _, err = parseField(fields[1], 0, 23, c.hours[:]); err != nil { |
| 55 | + return nil, fmt.Errorf("parsing hours: %w", err) |
| 56 | + } |
| 57 | + if c.domAll, err = parseField(fields[2], 1, 31, c.dom[:]); err != nil { |
| 58 | + return nil, fmt.Errorf("parsing dom: %w", err) |
| 59 | + } |
| 60 | + if _, err = parseField(fields[3], 1, 12, c.months[:]); err != nil { |
| 61 | + return nil, fmt.Errorf("parsing months: %w", err) |
| 62 | + } |
| 63 | + // Allow 0-7 for Day of Week |
| 64 | + if c.dowAll, err = parseField(fields[4], 0, 7, c.dow[:]); err != nil { |
| 65 | + return nil, fmt.Errorf("parsing dow: %w", err) |
| 66 | + } |
| 67 | + |
| 68 | + // Handle 7 as Sunday (alias to 0) |
| 69 | + if c.dow[7] { |
| 70 | + c.dow[0] = true |
| 71 | + } |
| 72 | + |
| 73 | + return c, nil |
| 74 | +} |
| 75 | + |
| 76 | +// parseField parses a cron field and returns true if the field was literally "*". |
| 77 | +func parseField(s string, min, max int, dest []bool) (bool, error) { |
| 78 | + // If field is "*", set all to true. |
| 79 | + if s == "*" { |
| 80 | + for i := min; i <= max; i++ { |
| 81 | + dest[i] = true |
| 82 | + } |
| 83 | + return true, nil |
| 84 | + } |
| 85 | + |
| 86 | + parts := strings.Split(s, ",") |
| 87 | + for _, part := range parts { |
| 88 | + step := 1 |
| 89 | + rangeStr := part |
| 90 | + |
| 91 | + if i := strings.Index(part, "/"); i >= 0 { |
| 92 | + stepStr := part[i+1:] |
| 93 | + var err error |
| 94 | + step, err = strconv.Atoi(stepStr) |
| 95 | + if err != nil { |
| 96 | + return false, fmt.Errorf("%w %q: %w", ErrCronInvalidStep, stepStr, err) |
| 97 | + } |
| 98 | + if step <= 0 { |
| 99 | + return false, ErrCronPositiveStep |
| 100 | + } |
| 101 | + rangeStr = part[:i] |
| 102 | + } |
| 103 | + |
| 104 | + var start, end int |
| 105 | + var err error |
| 106 | + |
| 107 | + if rangeStr == "*" { |
| 108 | + start, end = min, max |
| 109 | + } else if i := strings.Index(rangeStr, "-"); i >= 0 { |
| 110 | + startStr := rangeStr[:i] |
| 111 | + endStr := rangeStr[i+1:] |
| 112 | + start, err = strconv.Atoi(startStr) |
| 113 | + if err != nil { |
| 114 | + return false, fmt.Errorf("%w %q: %w", ErrCronRangeStart, startStr, err) |
| 115 | + } |
| 116 | + end, err = strconv.Atoi(endStr) |
| 117 | + if err != nil { |
| 118 | + return false, fmt.Errorf("%w %q: %w", ErrCronRangeEnd, endStr, err) |
| 119 | + } |
| 120 | + } else { |
| 121 | + start, err = strconv.Atoi(rangeStr) |
| 122 | + if err != nil { |
| 123 | + return false, fmt.Errorf("%w %q: %w", ErrCronInvalidValue, rangeStr, err) |
| 124 | + } |
| 125 | + end = start |
| 126 | + } |
| 127 | + |
| 128 | + if start < min || end > max { |
| 129 | + return false, fmt.Errorf("%w [%d, %d]", ErrCronOutOfRange, min, max) |
| 130 | + } |
| 131 | + if start > end { |
| 132 | + return false, ErrCronRangeOrder |
| 133 | + } |
| 134 | + |
| 135 | + for i := start; i <= end; i += step { |
| 136 | + dest[i] = true |
| 137 | + } |
| 138 | + } |
| 139 | + return false, nil |
| 140 | +} |
| 141 | + |
| 142 | +// Next returns the next scheduled time after t. |
| 143 | +// It assumes t is in the desired location (timezone). |
| 144 | +func (c *Cron) Next(t time.Time) time.Time { |
| 145 | + // Start checking from the next minute |
| 146 | + next := t.Truncate(time.Minute).Add(time.Minute) |
| 147 | + |
| 148 | + // To prevent infinite loops (though unlikely with valid cron), limit search to a few years. |
| 149 | + // 5 years seems safe. |
| 150 | + limit := next.AddDate(5, 0, 0) |
| 151 | + |
| 152 | + for next.Before(limit) { |
| 153 | + // Month check |
| 154 | + month := int(next.Month()) |
| 155 | + if !c.months[month] { |
| 156 | + // Move to start of next month |
| 157 | + // Simply adding 1 to month logic handles year rollover |
| 158 | + next = time.Date(next.Year(), next.Month()+1, 1, 0, 0, 0, 0, next.Location()) |
| 159 | + continue |
| 160 | + } |
| 161 | + |
| 162 | + // Day check |
| 163 | + dom := next.Day() |
| 164 | + dow := int(next.Weekday()) |
| 165 | + |
| 166 | + // Logic: |
| 167 | + // If both DOM and DOW are restricted (not *), then match if EITHER matches. |
| 168 | + // If only one is restricted, match that one (the other is *). |
| 169 | + // If both are *, match everything (AND/OR doesn't matter). |
| 170 | + isDomRestricted := !c.domAll |
| 171 | + isDowRestricted := !c.dowAll |
| 172 | + |
| 173 | + matchDom := c.dom[dom] |
| 174 | + matchDow := c.dow[dow] |
| 175 | + |
| 176 | + matchDay := false |
| 177 | + if isDomRestricted && isDowRestricted { |
| 178 | + matchDay = matchDom || matchDow |
| 179 | + } else { |
| 180 | + matchDay = matchDom && matchDow |
| 181 | + } |
| 182 | + |
| 183 | + if !matchDay { |
| 184 | + // Advance day |
| 185 | + next = time.Date(next.Year(), next.Month(), next.Day()+1, 0, 0, 0, 0, next.Location()) |
| 186 | + continue |
| 187 | + } |
| 188 | + |
| 189 | + // Hour check |
| 190 | + hour := next.Hour() |
| 191 | + if !c.hours[hour] { |
| 192 | + next = next.Add(time.Hour) |
| 193 | + // Reset minute |
| 194 | + next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), 0, 0, 0, next.Location()) |
| 195 | + continue |
| 196 | + } |
| 197 | + |
| 198 | + // Minute check |
| 199 | + minute := next.Minute() |
| 200 | + if !c.minutes[minute] { |
| 201 | + next = next.Add(time.Minute) |
| 202 | + continue |
| 203 | + } |
| 204 | + |
| 205 | + return next |
| 206 | + } |
| 207 | + return time.Time{} // Should not happen |
| 208 | +} |
| 209 | + |
0 commit comments