| 1 |
// Copyright 2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
// |
| 14 |
// Based on code from https://github.com/robfig/cron |
| 15 |
// Copyright (C) 2012 Rob Figueiredo |
| 16 |
// All Rights Reserved. |
| 17 |
// |
| 18 |
// MIT LICENSE |
| 19 |
// |
| 20 |
// Permission is hereby granted, free of charge, to any person obtaining a copy of |
| 21 |
// this software and associated documentation files (the "Software"), to deal in |
| 22 |
// the Software without restriction, including without limitation the rights to |
| 23 |
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of |
| 24 |
// the Software, and to permit persons to whom the Software is furnished to do so, |
| 25 |
// subject to the following conditions: |
| 26 |
// |
| 27 |
// The above copyright notice and this permission notice shall be included in all |
| 28 |
// copies or substantial portions of the Software. |
| 29 |
// |
| 30 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 31 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS |
| 32 |
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR |
| 33 |
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER |
| 34 |
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
| 35 |
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 36 |
|
| 37 |
package server |
| 38 |
|
| 39 |
import ( |
| 40 |
"errors" |
| 41 |
"fmt" |
| 42 |
"math" |
| 43 |
"strconv" |
| 44 |
"strings" |
| 45 |
"time" |
| 46 |
) |
| 47 |
|
| 48 |
// parseCron parses the given cron pattern and returns the next time it will fire based on the provided ts. |
| 49 |
func parseCron(pattern string, loc *time.Location, ts int64) (time.Time, error) { |
| 50 |
fields := strings.Fields(pattern) |
| 51 |
if len(fields) != 6 { |
| 52 |
return time.Time{}, fmt.Errorf("pattern requires 6 fields, got %d", len(fields)) |
| 53 |
} |
| 54 |
|
| 55 |
// If no time zone is passed, default to UTC. |
| 56 |
if loc == nil { |
| 57 |
loc = time.UTC |
| 58 |
} |
| 59 |
|
| 60 |
// Parse each field. |
| 61 |
var err error |
| 62 |
var second, minute, hour, dayOfMonth, month, dayOfWeek uint64 |
| 63 |
if second, err = getField(fields[0], seconds); err != nil { |
| 64 |
return time.Time{}, err |
| 65 |
} |
| 66 |
if minute, err = getField(fields[1], minutes); err != nil { |
| 67 |
return time.Time{}, err |
| 68 |
} |
| 69 |
if hour, err = getField(fields[2], hours); err != nil { |
| 70 |
return time.Time{}, err |
| 71 |
} |
| 72 |
if dayOfMonth, err = getField(fields[3], dom); err != nil { |
| 73 |
return time.Time{}, err |
| 74 |
} |
| 75 |
if month, err = getField(fields[4], months); err != nil { |
| 76 |
return time.Time{}, err |
| 77 |
} |
| 78 |
if dayOfWeek, err = getField(fields[5], dow); err != nil { |
| 79 |
return time.Time{}, err |
| 80 |
} |
| 81 |
|
| 82 |
// General approach |
| 83 |
// |
| 84 |
// For Month, Day, Hour, Minute, Second: |
| 85 |
// Check if the time value matches. If yes, continue to the next field. |
| 86 |
// If the field doesn't match the schedule, then increment the field until it matches. |
| 87 |
// While incrementing the field, a wrap-around brings it back to the beginning |
| 88 |
// of the field list (since it is necessary to re-verify previous field values) |
| 89 |
next := time.Unix(0, ts).In(loc) |
| 90 |
|
| 91 |
// Start at the earliest possible time (the upcoming second). |
| 92 |
next = next.Truncate(time.Second).Add(time.Second) |
| 93 |
|
| 94 |
// This flag indicates whether a field has been truncated at one point. |
| 95 |
truncated := false |
| 96 |
|
| 97 |
// If no time is found within five years, return error. |
| 98 |
yearLimit := next.Year() + 5 |
| 99 |
|
| 100 |
WRAP: |
| 101 |
if next.Year() > yearLimit { |
| 102 |
return time.Time{}, errors.New("pattern exceeds maximum range") |
| 103 |
} |
| 104 |
for 1<<uint(next.Month())&month == 0 { |
| 105 |
if !truncated { |
| 106 |
truncated = true |
| 107 |
next = time.Date(next.Year(), next.Month(), 1, 0, 0, 0, 0, loc) |
| 108 |
} |
| 109 |
if next = next.AddDate(0, 1, 0); next.Month() == time.January { |
| 110 |
goto WRAP |
| 111 |
} |
| 112 |
} |
| 113 |
for !dayMatches(dayOfMonth, dayOfWeek, next) { |
| 114 |
if !truncated { |
| 115 |
truncated = true |
| 116 |
next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, loc) |
| 117 |
} |
| 118 |
if next = next.AddDate(0, 0, 1); next.Day() == 1 { |
| 119 |
goto WRAP |
| 120 |
} |
| 121 |
} |
| 122 |
for 1<<uint(next.Hour())&hour == 0 { |
| 123 |
if !truncated { |
| 124 |
truncated = true |
| 125 |
next = time.Date(next.Year(), next.Month(), next.Day(), next.Hour(), 0, 0, 0, loc) |
| 126 |
} |
| 127 |
if next = next.Add(time.Hour); next.Hour() == 0 { |
| 128 |
goto WRAP |
| 129 |
} |
| 130 |
} |
| 131 |
for 1<<uint(next.Minute())&minute == 0 { |
| 132 |
if !truncated { |
| 133 |
truncated = true |
| 134 |
next = next.Truncate(time.Minute) |
| 135 |
} |
| 136 |
if next = next.Add(time.Minute); next.Minute() == 0 { |
| 137 |
goto WRAP |
| 138 |
} |
| 139 |
} |
| 140 |
for 1<<uint(next.Second())&second == 0 { |
| 141 |
if !truncated { |
| 142 |
truncated = true |
| 143 |
next = next.Truncate(time.Second) |
| 144 |
} |
| 145 |
if next = next.Add(time.Second); next.Second() == 0 { |
| 146 |
goto WRAP |
| 147 |
} |
| 148 |
} |
| 149 |
return next, nil |
| 150 |
} |
| 151 |
|
| 152 |
// getField returns an Int with the bits set representing all of the times that |
| 153 |
// the field represents or error parsing field value. A "field" is a comma-separated |
| 154 |
// list of "ranges". |
| 155 |
func getField(field string, r bounds) (uint64, error) { |
| 156 |
var bits uint64 |
| 157 |
ranges := strings.FieldsFuncSeq(field, func(r rune) bool { return r == ',' }) |
| 158 |
for expr := range ranges { |
| 159 |
bit, err := getRange(expr, r) |
| 160 |
if err != nil { |
| 161 |
return bits, err |
| 162 |
} |
| 163 |
bits |= bit |
| 164 |
} |
| 165 |
return bits, nil |
| 166 |
} |
| 167 |
|
| 168 |
// getRange returns the bits indicated by the given expression: number | number [ "-" number ] [ "/" number ] |
| 169 |
// or error parsing range. |
| 170 |
func getRange(expr string, r bounds) (uint64, error) { |
| 171 |
var ( |
| 172 |
start, end, step uint |
| 173 |
rangeAndStep = strings.Split(expr, "/") |
| 174 |
lowAndHigh = strings.Split(rangeAndStep[0], "-") |
| 175 |
singleDigit = len(lowAndHigh) == 1 |
| 176 |
err error |
| 177 |
) |
| 178 |
|
| 179 |
var extra uint64 |
| 180 |
if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { |
| 181 |
start = r.min |
| 182 |
end = r.max |
| 183 |
extra = starBit |
| 184 |
} else { |
| 185 |
start, err = parseIntOrName(lowAndHigh[0], r.names) |
| 186 |
if err != nil { |
| 187 |
return 0, err |
| 188 |
} |
| 189 |
switch len(lowAndHigh) { |
| 190 |
case 1: |
| 191 |
end = start |
| 192 |
case 2: |
| 193 |
end, err = parseIntOrName(lowAndHigh[1], r.names) |
| 194 |
if err != nil { |
| 195 |
return 0, err |
| 196 |
} |
| 197 |
default: |
| 198 |
return 0, fmt.Errorf("too many hyphens: %s", expr) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
switch len(rangeAndStep) { |
| 203 |
case 1: |
| 204 |
step = 1 |
| 205 |
case 2: |
| 206 |
step, err = mustParseInt(rangeAndStep[1]) |
| 207 |
if err != nil { |
| 208 |
return 0, err |
| 209 |
} |
| 210 |
// Special handling: "N/step" means "N-max/step". |
| 211 |
if singleDigit { |
| 212 |
end = r.max |
| 213 |
} |
| 214 |
if step > 1 { |
| 215 |
extra = 0 |
| 216 |
} |
| 217 |
default: |
| 218 |
return 0, fmt.Errorf("too many slashes: %s", expr) |
| 219 |
} |
| 220 |
|
| 221 |
if start < r.min { |
| 222 |
return 0, fmt.Errorf("beginning of range (%d) below minimum (%d): %s", start, r.min, expr) |
| 223 |
} |
| 224 |
if end > r.max { |
| 225 |
return 0, fmt.Errorf("end of range (%d) above maximum (%d): %s", end, r.max, expr) |
| 226 |
} |
| 227 |
if start > end { |
| 228 |
return 0, fmt.Errorf("beginning of range (%d) beyond end of range (%d): %s", start, end, expr) |
| 229 |
} |
| 230 |
if step == 0 { |
| 231 |
return 0, fmt.Errorf("step of range should be a positive number: %s", expr) |
| 232 |
} |
| 233 |
return getBits(start, end, step) | extra, nil |
| 234 |
} |
| 235 |
|
| 236 |
// parseIntOrName returns the (possibly-named) integer contained in expr. |
| 237 |
func parseIntOrName(expr string, names map[string]uint) (uint, error) { |
| 238 |
if names != nil { |
| 239 |
if namedInt, ok := names[strings.ToLower(expr)]; ok { |
| 240 |
return namedInt, nil |
| 241 |
} |
| 242 |
} |
| 243 |
return mustParseInt(expr) |
| 244 |
} |
| 245 |
|
| 246 |
// mustParseInt parses the given expression as an int or returns an error. |
| 247 |
func mustParseInt(expr string) (uint, error) { |
| 248 |
num, err := strconv.Atoi(expr) |
| 249 |
if err != nil { |
| 250 |
return 0, fmt.Errorf("failed to parse int from %s: %s", expr, err) |
| 251 |
} |
| 252 |
if num < 0 { |
| 253 |
return 0, fmt.Errorf("negative number (%d) not allowed: %s", num, expr) |
| 254 |
} |
| 255 |
return uint(num), nil |
| 256 |
} |
| 257 |
|
| 258 |
// getBits sets all bits in the range [min, max], modulo the given step size. |
| 259 |
func getBits(min, max, step uint) uint64 { |
| 260 |
var bits uint64 |
| 261 |
|
| 262 |
// If step is 1, use shifts. |
| 263 |
if step == 1 { |
| 264 |
return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min) |
| 265 |
} |
| 266 |
|
| 267 |
// Else, use a simple loop. |
| 268 |
for i := min; i <= max; i += step { |
| 269 |
bits |= 1 << i |
| 270 |
} |
| 271 |
return bits |
| 272 |
} |
| 273 |
|
| 274 |
// bounds provides a range of acceptable values (plus a map of name to value). |
| 275 |
type bounds struct { |
| 276 |
min, max uint |
| 277 |
names map[string]uint |
| 278 |
} |
| 279 |
|
| 280 |
// The bounds for each field. |
| 281 |
var ( |
| 282 |
seconds = bounds{0, 59, nil} |
| 283 |
minutes = bounds{0, 59, nil} |
| 284 |
hours = bounds{0, 23, nil} |
| 285 |
dom = bounds{1, 31, nil} |
| 286 |
months = bounds{1, 12, map[string]uint{ |
| 287 |
"jan": 1, |
| 288 |
"feb": 2, |
| 289 |
"mar": 3, |
| 290 |
"apr": 4, |
| 291 |
"may": 5, |
| 292 |
"jun": 6, |
| 293 |
"jul": 7, |
| 294 |
"aug": 8, |
| 295 |
"sep": 9, |
| 296 |
"oct": 10, |
| 297 |
"nov": 11, |
| 298 |
"dec": 12, |
| 299 |
}} |
| 300 |
dow = bounds{0, 6, map[string]uint{ |
| 301 |
"sun": 0, |
| 302 |
"mon": 1, |
| 303 |
"tue": 2, |
| 304 |
"wed": 3, |
| 305 |
"thu": 4, |
| 306 |
"fri": 5, |
| 307 |
"sat": 6, |
| 308 |
}} |
| 309 |
) |
| 310 |
|
| 311 |
const ( |
| 312 |
// Set the top bit if a star was included in the expression. |
| 313 |
starBit = 1 << 63 |
| 314 |
) |
| 315 |
|
| 316 |
// dayMatches returns true if the schedule's day-of-week and day-of-month |
| 317 |
// restrictions are satisfied by the given time. |
| 318 |
func dayMatches(dayOfMonth, dayOfWeek uint64, t time.Time) bool { |
| 319 |
var ( |
| 320 |
domMatch = 1<<uint(t.Day())&dayOfMonth > 0 |
| 321 |
dowMatch = 1<<uint(t.Weekday())&dayOfWeek > 0 |
| 322 |
) |
| 323 |
if dayOfMonth&starBit > 0 || dayOfWeek&starBit > 0 { |
| 324 |
return domMatch && dowMatch |
| 325 |
} |
| 326 |
return domMatch || dowMatch |
| 327 |
} |