package scheduling import ( "encoding/json" "errors" "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. func (d Duration) String() string { return time.Duration(d).String() } // Timing kinds. const ( // TimingInterval fires on a grid of Interval steps anchored at Start. TimingInterval = "interval" // TimingCron fires at each cron match in the instance time zone. // Day-of-month and day-of-week are ANDed. TimingCron = "cron" // TimingOnce fires once at At. TimingOnce = "once" ) var ( // ErrInvalidSpec is returned when a schedule fails validation. ErrInvalidSpec = errors.New("scheduling: invalid schedule") // ErrNotFound is returned for an unknown schedule or run. ErrNotFound = errors.New("scheduling: schedule not found") // ErrBuiltIn is returned when a change only a user schedule allows is // asked of a built-in one. ErrBuiltIn = errors.New("scheduling: built-in schedules cannot be deleted or have their action changed") ) // Timing decides when a schedule is due. Times are UTC instants; only a cron // expression is read in a zone. type Timing struct { Kind string `json:"kind"` Interval Duration `json:"interval,omitempty"` Cron string `json:"cron,omitempty"` At *time.Time `json:"at,omitempty"` // Start anchors the interval grid. Zero means the moment the schedule is // stored, which the store fills in. Start time.Time `json:"start"` } // Validate rejects an unknown kind or a kind missing its field. func (t Timing) Validate() error { switch t.Kind { case TimingInterval: if t.Interval < Duration(time.Minute) { return fmt.Errorf("%w: interval must be at least a minute, got %v", ErrInvalidSpec, t.Interval) } case TimingCron: if _, err := parseCronSpec(t.Cron); err != nil { return err } case TimingOnce: if t.At == nil { return fmt.Errorf("%w: a once schedule needs an at time", ErrInvalidSpec) } default: return fmt.Errorf("%w: unknown timing kind %q", ErrInvalidSpec, t.Kind) } return nil } // Next returns the first fire time strictly after after, or false when the // timing never fires again. Interval steps are counted from Start, so a late // or missed run never shifts the grid; cron is matched in loc. func (t Timing) Next(after time.Time, loc *time.Location) (time.Time, bool, error) { switch t.Kind { case TimingInterval: step := t.Interval.Std() if after.Before(t.Start) { return t.Start.UTC(), true, nil } steps := int64(after.Sub(t.Start)/step) + 1 return t.Start.Add(time.Duration(steps * int64(step))).UTC(), true, nil case TimingOnce: if t.At != nil && t.At.After(after) { return t.At.UTC(), true, nil } return time.Time{}, false, nil case TimingCron: spec, err := parseCronSpec(t.Cron) if err != nil { return time.Time{}, false, err } next, err := nextCronRun(spec, after.In(loc)) if err != nil { return time.Time{}, false, err } return next.UTC(), true, nil default: return time.Time{}, false, fmt.Errorf("%w: unknown timing kind %q", ErrInvalidSpec, t.Kind) } } // cronHorizon bounds the next-run scan. A satisfiable expression always // fires well within it; only one that can never fire, such as "0 0 30 2 *", // exhausts it. const cronHorizon = 5 * 365 * 24 * time.Hour // nextCronRun returns the first minute after from at which sched is due, // reading wall-clock fields in from's location. A wall-clock minute repeated // when clocks go back fires only its first time. func nextCronRun(sched *cronSpec, from time.Time) (time.Time, error) { loc := from.Location() t := from.Truncate(time.Minute).Add(time.Minute) for limit := from.Add(cronHorizon); t.Before(limit); { if !sched.months.has(int(t.Month())) { t = time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, loc) continue } if !sched.hours.has(t.Hour()) { t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour()+1, 0, 0, 0, loc) continue } if sched.due(t) && !repeatedWallClock(t) { return t, nil } t = t.Add(time.Minute) } return time.Time{}, fmt.Errorf("%w: cron expression does not match any minute within the next five years", ErrInvalidSpec) } // repeatedWallClock reports whether t's wall-clock hour already happened an // hour earlier, which is the second pass through an hour the clocks went // back over. func repeatedWallClock(t time.Time) bool { earlier := t.Add(-time.Hour) return earlier.Hour() == t.Hour() && earlier.Day() == t.Day() }