refactor(scheduling): own the cron dialect instead of pocketbase tools/cron

This commit is contained in:
sam committed 2026-09-24 14:26:41 +10:00
1 parent 00e3520a1e
commit 10023b8bc2
4 files changed
+182 -23

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
package scheduling
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
// cronSlots is the set of values one cron field matches, as a bitmask; every
// field's range fits in 64 bits.
type cronSlots uint64
func (s cronSlots) has(v int) bool { return v >= 0 && v < 64 && s&(1<<v) != 0 }
// cronSpec is a parsed 5-field cron expression. A time is due only when every
// field matches: day-of-month and day-of-week are ANDed, unlike Vixie cron's
// OR, so "0 0 1 * 1" means only a Monday that is the 1st.
type cronSpec struct {
minutes, hours, days, months, weekdays cronSlots
}
func (c *cronSpec) due(t time.Time) bool {
return c.minutes.has(t.Minute()) && c.hours.has(t.Hour()) && c.days.has(t.Day()) &&
c.months.has(int(t.Month())) && c.weekdays.has(int(t.Weekday()))
}
var cronMacros = map[string]string{
"@yearly": "0 0 1 1 *",
"@annually": "0 0 1 1 *",
"@monthly": "0 0 1 * *",
"@weekly": "0 0 * * 0",
"@daily": "0 0 * * *",
"@midnight": "0 0 * * *",
"@hourly": "0 * * * *",
}
// parseCronSpec parses the project's cron dialect: five space-separated
// fields (minute, hour, day of month, month, day of week) each a wildcard,
// value, range, step (*/n or a-b/n) or comma list of those, or one of the
// @yearly, @annually, @monthly, @weekly, @daily, @midnight and @hourly
// macros. Any failure wraps ErrInvalidSpec.
func parseCronSpec(expr string) (*cronSpec, error) {
spec, err := parseCron(expr)
if err != nil {
return nil, fmt.Errorf("%w: cron expression %q: %w", ErrInvalidSpec, expr, err)
}
return spec, nil
}
func parseCron(expr string) (*cronSpec, error) {
if macro, ok := cronMacros[expr]; ok {
expr = macro
}
fields := strings.Split(expr, " ")
if len(fields) != 5 {
return nil, errors.New("must be a macro or exactly 5 space-separated fields")
}
bounds := [5][2]int{{0, 59}, {0, 23}, {1, 31}, {1, 12}, {0, 6}}
var slots [5]cronSlots
for i, field := range fields {
parsed, err := parseCronSegment(field, bounds[i][0], bounds[i][1])
if err != nil {
return nil, err
}
slots[i] = parsed
}
return &cronSpec{minutes: slots[0], hours: slots[1], days: slots[2], months: slots[3], weekdays: slots[4]}, nil
}
// parseCronSegment parses one field whose values lie in [lo, hi].
func parseCronSegment(segment string, lo, hi int) (cronSlots, error) {
var slots cronSlots
for part := range strings.SplitSeq(segment, ",") {
base, stepText, stepped := strings.Cut(part, "/")
step := 1
if stepped {
n, err := strconv.Atoi(stepText)
if err != nil || n < 1 || n > hi {
return 0, fmt.Errorf("step %q must be between 1 and %d", stepText, hi)
}
step = n
}
first, last := lo, hi
if base != "*" {
from, to, ranged := strings.Cut(base, "-")
if !ranged && stepped {
return 0, fmt.Errorf("step in %q needs a wildcard or a range", part)
}
var err error
if first, err = cronValue(from, lo, hi); err != nil {
return 0, err
}
last = first
if ranged {
if last, err = cronValue(to, first, hi); err != nil {
return 0, err
}
}
}
for v := first; v <= last; v += step {
slots |= 1 << v
}
}
return slots, nil
}
func cronValue(text string, lo, hi int) (int, error) {
v, err := strconv.Atoi(text)
if err != nil {
return 0, fmt.Errorf("value %q is not a number", text)
}
if v < lo || v > hi {
return 0, fmt.Errorf("value %d must be between %d and %d", v, lo, hi)
}
return v, nil
}
+56
View File
@@ -0,0 +1,56 @@
package scheduling
import (
"errors"
"slices"
"testing"
)
func TestParseCronSegment(t *testing.T) {
tests := []struct {
segment string
want []int
wantErr bool
}{
{segment: "*", want: []int{0, 1, 2, 3, 4, 5, 6}},
{segment: "*/3", want: []int{0, 3, 6}},
{segment: "1-5/2", want: []int{1, 3, 5}},
{segment: "0,2-3,6", want: []int{0, 2, 3, 6}},
{segment: "4", want: []int{4}},
{segment: "4/2", wantErr: true},
{segment: "5-2", wantErr: true},
{segment: "*/7", wantErr: true},
{segment: "1/2/3", wantErr: true},
{segment: "1-2-3", wantErr: true},
{segment: "", wantErr: true},
}
for _, tc := range tests {
t.Run(tc.segment, func(t *testing.T) {
got, err := parseCronSegment(tc.segment, 0, 6)
if tc.wantErr {
if err == nil {
t.Fatalf("parseCronSegment(%q) = %v, want an error", tc.segment, got)
}
return
}
if err != nil {
t.Fatalf("parseCronSegment(%q): %v", tc.segment, err)
}
var slots []int
for v := 0; v <= 6; v++ {
if got.has(v) {
slots = append(slots, v)
}
}
if !slices.Equal(slots, tc.want) {
t.Fatalf("parseCronSegment(%q) = %v, want %v", tc.segment, slots, tc.want)
}
})
}
}
func TestParseCronSpecWrapsErrInvalidSpec(t *testing.T) {
if _, err := parseCronSpec("0 0 * * 7"); !errors.Is(err, ErrInvalidSpec) {
t.Fatalf("parseCronSpec = %v, want ErrInvalidSpec", err)
}
}
+6 -21
View File
@@ -4,8 +4,6 @@ import (
"encoding/json"
"fmt"
"time"
"github.com/pocketbase/pocketbase/tools/cron"
)
// Duration is a schedule interval as the document writes it: the human string
@@ -91,9 +89,8 @@ const (
// ScheduleCron fires at the next moment matching a 5-field cron
// expression (or one of the @ macros) after the last successful
// run, computed in the zone of that run time. Expressions are parsed
// with pocketbase tools/cron, which ANDs day-of-month with day-of-week
// instead of Vixie cron's OR: "0 0 1 * 1" means only Monday the 1st,
// run, computed in the zone of that run time. The dialect (cron.go)
// ANDs day-of-month with day-of-week instead of Vixie cron's OR: "0 0 1 * 1" means only Monday the 1st,
// not "the 1st or any Monday".
ScheduleCron = "cron"
@@ -168,18 +165,6 @@ func (s Schedule) firstRun(now time.Time) (time.Time, error) {
}
}
// parseCronSpec parses expr with pocketbase tools/cron — the project's
// chosen cron dialect: standard 5-field expressions plus the @yearly,
// @monthly, @weekly, @daily and @hourly macros — and wraps any parse
// failure in ErrInvalidSpec so callers need only the one sentinel.
func parseCronSpec(expr string) (*cron.Schedule, error) {
sched, err := cron.NewSchedule(expr)
if err != nil {
return nil, fmt.Errorf("%w: cron expression %q: %w", ErrInvalidSpec, expr, err)
}
return sched, nil
}
// cronHorizon bounds the next-run scan. A satisfiable expression always
// fires well within it (the sparsest realistic case, Feb 29, recurs every
// four years); only a spec that can never fire — e.g. "0 0 30 2 *", which
@@ -191,17 +176,17 @@ const cronHorizon = 5 * 365 * 24 * time.Hour
// minute that just fired is never its own successor. Whole months and
// hours that cannot match are skipped, so even a sparse expression costs
// a handful of iterations per year scanned.
func nextCronRun(sched *cron.Schedule, from time.Time) (time.Time, error) {
func nextCronRun(sched *cronSpec, from time.Time) (time.Time, error) {
t := from.Truncate(time.Minute).Add(time.Minute)
for limit := from.Add(cronHorizon); t.Before(limit); {
if sched.IsDue(cron.NewMoment(t)) {
if sched.due(t) {
return t, nil
}
if _, ok := sched.Months[int(t.Month())]; !ok {
if !sched.months.has(int(t.Month())) {
t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()).AddDate(0, 1, 0)
continue
}
if _, ok := sched.Hours[t.Hour()]; !ok {
if !sched.hours.has(t.Hour()) {
t = t.Add(time.Hour).Truncate(time.Hour)
continue
}
+2 -2
View File
@@ -36,8 +36,8 @@ func TestScheduleCronNextRun(t *testing.T) {
want: zoned(2026, 8, 24, 12, 15, 0),
},
{
// pins the pocketbase AND semantics: Vixie cron would give the
// next Monday (2026-08-31); tools/cron gives Monday the 1st.
// pins the AND semantics: Vixie cron would give the next Monday
// (2026-08-31); this dialect gives Monday the 1st.
name: "dual-restricted day-of-month and day-of-week AND, not Vixie OR",
expr: "0 0 1 * 1",
lastRun: zoned(2026, 8, 24, 12, 15, 30),