feat(scheduling): implement cron next-run arithmetic via pocketbase tools/cron

This commit is contained in:
sam committed 2026-09-23 02:53:39 +10:00
1 parent ed1557c12e
commit d2aa680792
2 files changed
+302 -18

No files matched your search

+73 -18
View File
@@ -4,6 +4,8 @@ import (
"encoding/json"
"fmt"
"time"
"github.com/pocketbase/pocketbase/tools/cron"
)
// Duration is a schedule interval as the document writes it: the human string
@@ -77,21 +79,20 @@ type Schedule struct {
Start time.Time `json:"start"`
}
// Schedule kinds the store recognises. Slice 1 fully implements
// Interval; Once is accepted at Create / fires at Due exactly once, but
// has no next-run arithmetic for MarkRun (one-shot by definition). Cron
// is parsed at Create but has no firing arithmetic yet — Slice 2 will
// add the parser. MarkRun on a kind this build does not implement
// returns ErrScheduleUnsupported rather than silently advancing next_run.
// Schedule kinds the store recognises. Interval and Cron have full
// next-run arithmetic; Once is accepted at Create / fires at Due exactly
// once, but has no next-run arithmetic for MarkRun (one-shot by
// definition). MarkRun on a kind this build does not implement returns
// ErrScheduleUnsupported rather than silently advancing next_run.
const (
// ScheduleInterval fires every Interval after the last successful run
// (or after Start, if never run). The simplest recurring schedule.
ScheduleInterval = "interval"
// ScheduleCron fires at the next moment matching a standard 5-field
// cron expression after the last successful run. Slice 2 will add
// the parser; until then, MarkRun on a cron job returns
// ErrScheduleUnsupported.
// 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.
ScheduleCron = "cron"
// ScheduleOnce fires once at the configured At time. Subsequent
@@ -110,8 +111,8 @@ func (s Schedule) Validate() error {
return fmt.Errorf("%w: interval must be positive, got %v", ErrInvalidSpec, s.Interval)
}
case ScheduleCron:
if s.Cron == "" {
return fmt.Errorf("%w: cron expression must be non-empty", ErrInvalidSpec)
if _, err := parseCronSpec(s.Cron); err != nil {
return err
}
case ScheduleOnce:
if s.At == nil {
@@ -136,8 +137,8 @@ func (s Schedule) resolve() Schedule {
// firstRun returns when the job should fire the very first time it has
// never run before. For Interval, it is Start + Interval (or now + Interval
// when Start is zero, so a freshly-created job with no Start still has a
// finite next-run). For Once, it is At. For Cron, it is left as a future
// responsibility — Slice 1 will not synthesise a value it cannot honour.
// finite next-run). For Once, it is At. For Cron, it is the first matching
// minute strictly after Start (or after now when Start is zero).
func (s Schedule) firstRun(now time.Time) (time.Time, error) {
switch s.resolve().Kind {
case ScheduleInterval:
@@ -151,12 +152,62 @@ func (s Schedule) firstRun(now time.Time) (time.Time, error) {
}
return *s.At, nil
case ScheduleCron:
return time.Time{}, fmt.Errorf("%w: cron parsing not yet implemented (slice 2)", ErrScheduleUnsupported)
sched, err := parseCronSpec(s.Cron)
if err != nil {
return time.Time{}, err
}
anchor := now
if !s.Start.IsZero() {
anchor = s.Start
}
return nextCronRun(sched, anchor)
default:
return time.Time{}, fmt.Errorf("%w: unknown kind %q", ErrScheduleUnsupported, s.Kind)
}
}
// 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
// the parser's field ranges cannot reject — exhausts the scan.
const cronHorizon = 5 * 365 * 24 * time.Hour
// nextCronRun returns the first wall-clock minute in the location of from
// at which sched is due, strictly after the minute containing from — the
// 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) {
t := from.Truncate(time.Minute).Add(time.Minute)
for limit := from.Add(cronHorizon); t.Before(limit); {
if sched.IsDue(cron.NewMoment(t)) {
return t, nil
}
if _, ok := sched.Months[int(t.Month())]; !ok {
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 {
t = t.Add(time.Hour).Truncate(time.Hour)
continue
}
t = t.Add(time.Minute)
}
return time.Time{}, fmt.Errorf("%w: cron expression does not match any minute within the next five years", ErrInvalidSpec)
}
func (s Schedule) FirstRun(now time.Time) (time.Time, error) { return s.firstRun(now) }
func (s Schedule) NextRun(lastRun time.Time) (time.Time, error) { return s.nextRun(lastRun) }
@@ -165,9 +216,9 @@ func (s Schedule) Resolved() Schedule { return s.resolve() }
// nextRun returns when the job should fire after a successful run at
// lastRun. It is the engine-side counterpart to firstRun: every MarkRun
// advances next_run through this function. Interval is fully implemented;
// Once and Cron deliberately fail so a silently-wrong value cannot reach
// the ticker.
// advances next_run through this function. Interval and Cron are fully
// implemented; Once deliberately fails (there is no recurring next run)
// so a silently-wrong value cannot reach the ticker.
func (s Schedule) nextRun(lastRun time.Time) (time.Time, error) {
switch s.resolve().Kind {
case ScheduleInterval:
@@ -175,7 +226,11 @@ func (s Schedule) nextRun(lastRun time.Time) (time.Time, error) {
case ScheduleOnce:
return time.Time{}, fmt.Errorf("%w: once schedule has no next run", ErrScheduleUnsupported)
case ScheduleCron:
return time.Time{}, fmt.Errorf("%w: cron arithmetic not yet implemented (slice 2)", ErrScheduleUnsupported)
sched, err := parseCronSpec(s.Cron)
if err != nil {
return time.Time{}, err
}
return nextCronRun(sched, lastRun)
default:
return time.Time{}, fmt.Errorf("%w: unknown kind %q", ErrScheduleUnsupported, s.Kind)
}
+229
View File
@@ -0,0 +1,229 @@
package scheduling
import (
"errors"
"testing"
"time"
)
// testZone is a fixed +02:00 zone: explicit, DST-free, and distinct from UTC
// so any arithmetic that silently computes in UTC fails. Every schedule test
// builds its times here, making the suite independent of the host's TZ.
var testZone = time.FixedZone("TEST", 2*60*60)
// zoned builds a wall-clock time in the fixed test zone.
func zoned(year int, month time.Month, day, hour, minute, sec int) time.Time {
return time.Date(year, month, day, hour, minute, sec, 0, testZone)
}
func TestScheduleCronNextRun(t *testing.T) {
tests := []struct {
name string
expr string
lastRun time.Time
want time.Time
}{
{
name: "minute later in the same hour",
expr: "30 14 * * *",
lastRun: zoned(2026, 8, 24, 13, 0, 0),
want: zoned(2026, 8, 24, 14, 30, 0),
},
{
name: "hour boundary skips the remainder of the hour",
expr: "*/15 * * * *",
lastRun: zoned(2026, 8, 24, 12, 7, 0),
want: zoned(2026, 8, 24, 12, 15, 0),
},
{
name: "run exactly on a matching minute advances to the next one",
expr: "0 * * * *",
lastRun: zoned(2026, 8, 24, 12, 0, 0),
want: zoned(2026, 8, 24, 13, 0, 0),
},
{
name: "across the hour boundary",
expr: "5,35 * * * *",
lastRun: zoned(2026, 8, 24, 12, 36, 0),
want: zoned(2026, 8, 24, 13, 5, 0),
},
{
name: "range with step across hours",
expr: "0 9-17/2 * * *",
lastRun: zoned(2026, 8, 24, 10, 0, 0),
want: zoned(2026, 8, 24, 11, 0, 0),
},
{
name: "across midnight",
expr: "0 0 * * *",
lastRun: zoned(2026, 8, 24, 23, 59, 0),
want: zoned(2026, 8, 25, 0, 0, 0),
},
{
name: "across the month boundary",
expr: "0 0 1 * *",
lastRun: zoned(2026, 8, 31, 12, 0, 0),
want: zoned(2026, 9, 1, 0, 0, 0),
},
{
name: "weekday rolls to next Monday",
expr: "0 0 * * 1",
lastRun: zoned(2026, 8, 21, 10, 0, 0),
want: zoned(2026, 8, 24, 0, 0, 0),
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
s := Schedule{Kind: ScheduleCron, Cron: tc.expr}
got, err := s.NextRun(tc.lastRun)
if err != nil {
t.Fatalf("NextRun(%v): %v", tc.lastRun, err)
}
if !got.Equal(tc.want) {
t.Fatalf("NextRun(%v) = %v (%s), want %v (%s)",
tc.lastRun, got, got.Format("2006-01-02 15:04:05 MST"),
tc.want, tc.want.Format("2006-01-02 15:04:05 MST"))
}
})
}
}
func TestScheduleCronNextRunMacros(t *testing.T) {
// lastRun is Monday 2026-08-24 12:15:30 TEST.
lastRun := zoned(2026, 8, 24, 12, 15, 30)
tests := []struct {
name string
expr string
want time.Time
}{
{name: "@hourly", expr: "@hourly", want: zoned(2026, 8, 24, 13, 0, 0)},
{name: "@daily", expr: "@daily", want: zoned(2026, 8, 25, 0, 0, 0)},
{name: "@midnight", expr: "@midnight", want: zoned(2026, 8, 25, 0, 0, 0)},
{name: "@weekly", expr: "@weekly", want: zoned(2026, 8, 30, 0, 0, 0)},
{name: "@monthly", expr: "@monthly", want: zoned(2026, 9, 1, 0, 0, 0)},
{name: "@yearly", expr: "@yearly", want: zoned(2027, 1, 1, 0, 0, 0)},
{name: "@annually", expr: "@annually", want: zoned(2027, 1, 1, 0, 0, 0)},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
s := Schedule{Kind: ScheduleCron, Cron: tc.expr}
got, err := s.NextRun(lastRun)
if err != nil {
t.Fatalf("NextRun(%v): %v", lastRun, err)
}
if !got.Equal(tc.want) {
t.Fatalf("NextRun(%v) with %q = %v, want %v", lastRun, tc.expr, got, tc.want)
}
})
}
}
func TestScheduleCronComputesInThePassedZone(t *testing.T) {
s := Schedule{Kind: ScheduleCron, Cron: "0 6 * * *"}
// lastRun 05:30 in +02:00: 06:00 local is 04:00 UTC.
got, err := s.NextRun(zoned(2026, 8, 24, 5, 30, 0))
if err != nil {
t.Fatalf("NextRun: %v", err)
}
if want := time.Date(2026, 8, 24, 4, 0, 0, 0, time.UTC); !got.Equal(want) {
t.Fatalf("fixed-zone NextRun = %v (%s), want %v UTC", got, got.Format("15:04 MST"), want)
}
// The same wall-clock spec anchored in UTC must land on 06:00 UTC instead.
got, err = s.NextRun(time.Date(2026, 8, 24, 5, 30, 0, 0, time.UTC))
if err != nil {
t.Fatalf("NextRun: %v", err)
}
if want := time.Date(2026, 8, 24, 6, 0, 0, 0, time.UTC); !got.Equal(want) {
t.Fatalf("UTC NextRun = %v, want %v UTC", got, want)
}
}
func TestScheduleCronFirstRun(t *testing.T) {
t.Run("anchored on Start", func(t *testing.T) {
s := Schedule{
Kind: ScheduleCron,
Cron: "0 12 * * *",
Start: zoned(2026, 8, 24, 9, 0, 0),
}
want := zoned(2026, 8, 24, 12, 0, 0)
got, err := s.FirstRun(time.Date(2026, 8, 24, 6, 0, 0, 0, testZone))
if err != nil {
t.Fatalf("FirstRun: %v", err)
}
if !got.Equal(want) {
t.Fatalf("FirstRun = %v, want %v", got, want)
}
})
t.Run("zero Start anchors on now", func(t *testing.T) {
s := Schedule{Kind: ScheduleCron, Cron: "0 12 * * *"}
now := zoned(2026, 8, 24, 12, 30, 0)
want := zoned(2026, 8, 25, 12, 0, 0)
got, err := s.FirstRun(now)
if err != nil {
t.Fatalf("FirstRun: %v", err)
}
if !got.Equal(want) {
t.Fatalf("FirstRun(%v) = %v, want %v", now, got, want)
}
})
}
func TestScheduleCronValidate(t *testing.T) {
t.Run("empty cron is rejected", func(t *testing.T) {
err := Schedule{Kind: ScheduleCron}.Validate()
if !errors.Is(err, ErrInvalidSpec) {
t.Fatalf("Validate() = %v, want ErrInvalidSpec", err)
}
})
t.Run("valid expressions pass", func(t *testing.T) {
for _, expr := range []string{"*/15 * * * *", "0 9-17/2 * * *", "@daily", "@yearly"} {
if err := (Schedule{Kind: ScheduleCron, Cron: expr}).Validate(); err != nil {
t.Fatalf("Validate(%q) = %v, want nil", expr, err)
}
}
})
}
func TestScheduleCronInvalidExpressions(t *testing.T) {
tests := []struct {
name string
expr string
}{
{name: "minute out of range", expr: "61 * * * *"},
{name: "hour out of range", expr: "* 24 * * *"},
{name: "day of month out of range", expr: "0 0 32 * *"},
{name: "month out of range", expr: "0 0 * 13 *"},
{name: "day of week out of range", expr: "0 0 * * 7"},
{name: "too few fields", expr: "* * * *"},
{name: "too many fields", expr: "* * * * * *"},
{name: "non-numeric field", expr: "banana * * * *"},
{name: "zero step", expr: "*/0 * * * *"},
{name: "empty", expr: ""},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
s := Schedule{Kind: ScheduleCron, Cron: tc.expr}
if err := s.Validate(); !errors.Is(err, ErrInvalidSpec) {
t.Errorf("Validate() = %v, want ErrInvalidSpec", err)
}
_, err := s.FirstRun(zoned(2026, 8, 24, 12, 0, 0))
if !errors.Is(err, ErrInvalidSpec) {
t.Errorf("FirstRun err = %v, want ErrInvalidSpec", err)
}
_, err = s.NextRun(zoned(2026, 8, 24, 12, 0, 0))
if !errors.Is(err, ErrInvalidSpec) {
t.Errorf("NextRun err = %v, want ErrInvalidSpec", err)
}
})
}
}