202 lines
6.8 KiB
Go
202 lines
6.8 KiB
Go
package scheduling
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// Duration is a schedule interval written as a duration string. It also
|
|
// reads a nanosecond count.
|
|
type Duration time.Duration
|
|
|
|
func (d Duration) MarshalJSON() ([]byte, error) {
|
|
return json.Marshal(time.Duration(d).String())
|
|
}
|
|
|
|
func (d *Duration) UnmarshalJSON(data []byte) error {
|
|
var text string
|
|
if err := json.Unmarshal(data, &text); err == nil {
|
|
value, err := time.ParseDuration(text)
|
|
if err != nil {
|
|
return fmt.Errorf("%w: interval must be a Go duration string such as %q: %w", ErrInvalidSpec, "30m", err)
|
|
}
|
|
*d = Duration(value)
|
|
return nil
|
|
}
|
|
var nanos int64
|
|
if err := json.Unmarshal(data, &nanos); err != nil {
|
|
return fmt.Errorf("%w: interval must be a Go duration string such as %q or a nanosecond count: %w", ErrInvalidSpec, "30m", err)
|
|
}
|
|
*d = Duration(nanos)
|
|
return nil
|
|
}
|
|
|
|
// Std is the standard-library duration, for arithmetic and comparison.
|
|
func (d Duration) Std() time.Duration { return time.Duration(d) }
|
|
|
|
// String renders the interval the way the document writes it, so an error
|
|
// message or a log line reads "30m0s" rather than 1800000000000.
|
|
func (d Duration) String() string { return time.Duration(d).String() }
|
|
|
|
// Schedule decides when a job is due. The Kind field selects which of
|
|
// Interval, Cron, At the store uses to compute nextRun. Empty Kind
|
|
// resolves to "interval" so the simplest recurring job needs no
|
|
// explicit kind in its JSON.
|
|
type Schedule struct {
|
|
// Kind is one of ScheduleInterval, ScheduleCron, ScheduleOnce.
|
|
// Empty resolves to ScheduleInterval.
|
|
Kind string `json:"kind,omitempty"`
|
|
|
|
// Interval is the period for ScheduleInterval. Required when Kind
|
|
// is ScheduleInterval; ignored otherwise. It is a Duration rather
|
|
// than a time.Duration so the document carries "30m0s" and not the
|
|
// nanosecond count that asked an operator to type 1800000000000.
|
|
Interval Duration `json:"interval,omitempty"`
|
|
|
|
// Cron is the 5-field cron expression for ScheduleCron. Required
|
|
// when Kind is ScheduleCron; ignored otherwise.
|
|
Cron string `json:"cron,omitempty"`
|
|
|
|
// At is the one-shot firing time for ScheduleOnce. Required when
|
|
// Kind is ScheduleOnce; ignored otherwise.
|
|
At *time.Time `json:"at,omitempty"`
|
|
|
|
// Start anchors the first run for ScheduleInterval / ScheduleCron.
|
|
// Empty means "use creation time" — a freshly-created job with no
|
|
// Start still has a finite next_run. Omitted from the wire when
|
|
// unset so operator-readable files are not noisy.
|
|
Start time.Time `json:"start"`
|
|
}
|
|
|
|
// Schedule kinds. MarkRun on an unsupported kind returns
|
|
// ErrScheduleUnsupported.
|
|
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 cron match after the last run, in that
|
|
// run's zone. Day-of-month and day-of-week are ANDed.
|
|
ScheduleCron = "cron"
|
|
|
|
// ScheduleOnce fires once at the configured At time. Subsequent
|
|
// MarkRun calls return ErrScheduleUnsupported because there is no
|
|
// recurring next-run to compute.
|
|
ScheduleOnce = "once"
|
|
)
|
|
|
|
// Validate rejects empty or unknown schedule kinds up front so Create does
|
|
// not have to defer the check until MarkRun. Interval additionally requires
|
|
// a strictly positive duration; the others defer their full validation.
|
|
func (s Schedule) Validate() error {
|
|
switch s.Kind {
|
|
case "", ScheduleInterval:
|
|
if s.Interval <= 0 {
|
|
return fmt.Errorf("%w: interval must be positive, got %v", ErrInvalidSpec, s.Interval)
|
|
}
|
|
case ScheduleCron:
|
|
if _, err := parseCronSpec(s.Cron); err != nil {
|
|
return err
|
|
}
|
|
case ScheduleOnce:
|
|
if s.At == nil {
|
|
return fmt.Errorf("%w: once schedule requires an `at` time", ErrInvalidSpec)
|
|
}
|
|
default:
|
|
return fmt.Errorf("%w: unknown schedule kind %q", ErrInvalidSpec, s.Kind)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolve maps the empty kind onto its documented default — "interval" is
|
|
// what an operator gets when they leave the field unset on the simplest
|
|
// recurring job.
|
|
func (s Schedule) resolve() Schedule {
|
|
if s.Kind == "" {
|
|
s.Kind = ScheduleInterval
|
|
}
|
|
return s
|
|
}
|
|
|
|
// firstRun returns a never-run job's first fire time: Start (or now) plus
|
|
// Interval, At for Once, or the first cron match after Start (or now).
|
|
func (s Schedule) firstRun(now time.Time) (time.Time, error) {
|
|
switch s.resolve().Kind {
|
|
case ScheduleInterval:
|
|
if !s.Start.IsZero() {
|
|
return s.Start.Add(s.Interval.Std()), nil
|
|
}
|
|
return now.Add(s.Interval.Std()), nil
|
|
case ScheduleOnce:
|
|
if s.At == nil {
|
|
return time.Time{}, fmt.Errorf("%w: once schedule has no at time", ErrScheduleUnsupported)
|
|
}
|
|
return *s.At, nil
|
|
case ScheduleCron:
|
|
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)
|
|
}
|
|
}
|
|
|
|
// 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 minute after from's minute, in from's
|
|
// location, at which sched is due.
|
|
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.due(t) {
|
|
return t, nil
|
|
}
|
|
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 !sched.hours.has(t.Hour()) {
|
|
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) }
|
|
|
|
func (s Schedule) Resolved() Schedule { return s.resolve() }
|
|
|
|
// nextRun returns the next fire time after a successful run at lastRun. Once
|
|
// returns an error.
|
|
func (s Schedule) nextRun(lastRun time.Time) (time.Time, error) {
|
|
switch s.resolve().Kind {
|
|
case ScheduleInterval:
|
|
return lastRun.Add(s.Interval.Std()), nil
|
|
case ScheduleOnce:
|
|
return time.Time{}, fmt.Errorf("%w: once schedule has no next run", ErrScheduleUnsupported)
|
|
case ScheduleCron:
|
|
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)
|
|
}
|
|
}
|