## Why Automations store a five-field cron expression and an IANA time zone. The scheduler and the management API will parse both with `coderd/schedule/cron`, as the "Schedules" section of the [Automations RFC](https://app.notion.com/p/3ded579be59281e39950e686df02fa3d) says. This adds the parser they will call. Part of CODAGT-1135. ## What changed - `cron.Standard(spec, timeZone)` parses a five-field spec that runs on the wall clock of an IANA zone. Every field can be restricted. It returns an error for an empty spec, a wrong field count, a `CRON_TZ=` or `TZ=` prefix, an empty or unknown zone, a zone name with an empty, `.` or `..` segment such as `./localtime`, a name that starts with `posix/` or `right/` (directories of zone data that some hosts have, with other versions of the zones), `Local` (a Go name for the host's zone), a name whose last segment is `localtime`, `posixrules` or `Factory` (files in a host's zone data that are not zones), and a spec that never runs, such as `0 0 30 2 *`. - `Next` on a `Standard` schedule follows the RFC's daylight saving rule. A repeated local time runs once, at its first instance. A nonexistent local time runs at the first local time after the change. `robfig/cron` does neither: in America/New_York it runs `30 1 * * *` twice on 2026-11-01 and skips `30 2 * * *` on 2026-03-08. So `Standard` walks the matching wall-clock readings and resolves each one to an instant from the zone's UTC offsets. Every loop has a fixed bound, and `Next` always returns a later time for a `Standard` schedule. It searches at least 16 years ahead, past the eight years between two leap days across 2100. `Weekly`, `Daily` and `TimeRange` keep their behavior. - `Schedule.MinInterval()` returns the shortest distance between two times of day at which the schedule runs, counted around the clock. One time of day gives 24 hours. The management API will compare it with the deployment's minimum interval. ## Scope This PR adds no minimum interval policy and no configuration. Nothing calls the new code yet. The scheduler loop and the API come in later PRs. ## Tradeoffs - `MinInterval` reads only the hour and minute fields, with no calendar. The RFC allows a minimum interval of one minute to 24 hours, so the value only has to be right below 24 hours, and a scan over the calendar kept missing cases. While the zone's UTC offset does not change, no two runs are closer than the value. The doc comment states two limits, and a test pins each. - A change of the UTC offset (daylight saving) can shorten a gap that spans it by up to the size of the change: `1,58 1,3 * * *` in America/New_York gives 57 minutes, and its runs on 2026-03-08 are 3 minutes apart. - A pair of times across midnight counts even when the day fields never match two days in a row: `0,58 0,23 * * 1` gives 2 minutes, but its runs are 58 minutes apart at least, so a check can reject a schedule that the minimum allows. - The RFC rule, read as written, means a wildcard schedule such as `*/15 * * * *` does not run during the second pass of a repeated hour. In America/New_York on 2026-11-01 it runs at 01:45 EDT and next at 02:00 EST. - `Standard` resolves a reading from the zone's offsets and does not use Go's zone period bounds, which are wrong after the last transition in a zone's data. ## Live check None. This is a library that nothing calls yet. --- _Generated with [`xum`](https://github.com/coder/xum) • Model: `anthropic:claude-sonnet-5-5` • Thinking: `xhigh`_
339 lines
11 KiB
Go
339 lines
11 KiB
Go
// package schedule provides utilities for managing template and workspace
|
|
// autostart and autostop schedules. This includes utilities for parsing and
|
|
// deserializing cron-style expressions.
|
|
package cron
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
rbcron "github.com/robfig/cron/v3"
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
// For the purposes of this library, we only need minute, hour, and
|
|
// day-of-week. However to ensure interoperability we will use the standard
|
|
// five-valued cron format. Descriptors are not supported.
|
|
const parserFormat = rbcron.Minute | rbcron.Hour | rbcron.Dom | rbcron.Month | rbcron.Dow
|
|
|
|
var defaultParser = rbcron.NewParser(parserFormat)
|
|
|
|
// Weekly parses a Schedule from spec scoped to a recurring weekly event.
|
|
// Spec consists of the following space-delimited fields, in the following order:
|
|
// - timezone e.g. CRON_TZ=US/Central (optional)
|
|
// - minutes of hour e.g. 30 (required)
|
|
// - hour of day e.g. 9 (required)
|
|
// - day of month (must be *)
|
|
// - month (must be *)
|
|
// - day of week e.g. 1 (required)
|
|
//
|
|
// Example Usage:
|
|
//
|
|
// local_sched, _ := cron.Weekly("59 23 *")
|
|
// fmt.Println(sched.Next(time.Now().Format(time.RFC3339)))
|
|
// // Output: 2022-04-04T23:59:00Z
|
|
//
|
|
// us_sched, _ := cron.Weekly("CRON_TZ=US/Central 30 9 1-5")
|
|
// fmt.Println(sched.Next(time.Now()).Format(time.RFC3339))
|
|
// // Output: 2022-04-04T14:30:00Z
|
|
func Weekly(raw string) (*Schedule, error) {
|
|
if err := validateWeeklySpec(raw); err != nil {
|
|
return nil, xerrors.Errorf("validate weekly schedule: %w", err)
|
|
}
|
|
|
|
return parse(raw)
|
|
}
|
|
|
|
// Daily parses a Schedule from spec scoped to a recurring daily event.
|
|
// Spec consists of the following space-delimited fields, in the following order:
|
|
// - timezone e.g. CRON_TZ=US/Central (optional)
|
|
// - minutes of hour e.g. 30 (required)
|
|
// - hour of day e.g. 9 (required)
|
|
// - day of month (must be *)
|
|
// - month (must be *)
|
|
// - day of week (must be *)
|
|
//
|
|
// Example Usage:
|
|
//
|
|
// local_sched, _ := cron.Weekly("59 23 * * *")
|
|
// fmt.Println(sched.Next(time.Now().Format(time.RFC3339)))
|
|
// // Output: 2022-04-04T23:59:00Z
|
|
//
|
|
// us_sched, _ := cron.Weekly("CRON_TZ=US/Central 30 9 * * *")
|
|
// fmt.Println(sched.Next(time.Now()).Format(time.RFC3339))
|
|
// // Output: 2022-04-04T14:30:00Z
|
|
func Daily(raw string) (*Schedule, error) {
|
|
if err := validateDailySpec(raw); err != nil {
|
|
return nil, xerrors.Errorf("validate daily schedule: %w", err)
|
|
}
|
|
|
|
return parse(raw)
|
|
}
|
|
|
|
// TimeRange parses a Schedule from a cron specification interpreted as a continuous time range.
|
|
//
|
|
// For example, the expression "* 9-18 * * 1-5" represents a continuous time span
|
|
// from 09:00:00 to 18:59:59, Monday through Friday.
|
|
//
|
|
// The specification consists of space-delimited fields in the following order:
|
|
// - (Optional) Timezone, e.g., CRON_TZ=US/Central
|
|
// - Minutes: must be "*" to represent the full range within each hour
|
|
// - Hour of day: e.g., 9-18 (required)
|
|
// - Day of month: e.g., * or 1-15 (required)
|
|
// - Month: e.g., * or 1-6 (required)
|
|
// - Day of week: e.g., * or 1-5 (required)
|
|
//
|
|
// Unlike standard cron, this function interprets the input as a continuous active period
|
|
// rather than discrete scheduled times.
|
|
func TimeRange(raw string) (*Schedule, error) {
|
|
if err := validateTimeRangeSpec(raw); err != nil {
|
|
return nil, xerrors.Errorf("validate time range schedule: %w", err)
|
|
}
|
|
|
|
return parse(raw)
|
|
}
|
|
|
|
func parse(raw string) (*Schedule, error) {
|
|
// If schedule does not specify a timezone, default to UTC. Otherwise,
|
|
// the library will default to time.Local which we want to avoid.
|
|
if !strings.HasPrefix(raw, "CRON_TZ=") {
|
|
raw = "CRON_TZ=UTC " + raw
|
|
}
|
|
|
|
specSched, err := defaultParser.Parse(raw)
|
|
if err != nil {
|
|
return nil, xerrors.Errorf("parse schedule: %w", err)
|
|
}
|
|
|
|
schedule, ok := specSched.(*rbcron.SpecSchedule)
|
|
if !ok {
|
|
return nil, xerrors.Errorf("expected *cron.SpecSchedule but got %T", specSched)
|
|
}
|
|
|
|
if schedule.Location == time.Local {
|
|
return nil, xerrors.Errorf("schedules scoped to time.Local are not supported")
|
|
}
|
|
|
|
// Strip the leading CRON_TZ prefix so we just store the cron string.
|
|
// The timezone info is available in SpecSchedule.
|
|
cronStr := raw
|
|
if strings.HasPrefix(raw, "CRON_TZ=") {
|
|
cronStr = strings.Join(strings.Fields(raw)[1:], " ")
|
|
}
|
|
|
|
cronSched := &Schedule{
|
|
sched: schedule,
|
|
cronStr: cronStr,
|
|
}
|
|
return cronSched, nil
|
|
}
|
|
|
|
// Schedule represents a cron schedule.
|
|
// It's essentially a wrapper for robfig/cron/v3 that has additional
|
|
// convenience methods.
|
|
type Schedule struct {
|
|
sched *rbcron.SpecSchedule
|
|
// XXX: there isn't any nice way for robfig/cron to serialize
|
|
cronStr string
|
|
// wallClock selects the daylight saving rules that Standard documents.
|
|
// Other schedules keep the robfig/cron behavior.
|
|
wallClock bool
|
|
}
|
|
|
|
// String serializes the schedule to its original format.
|
|
// The leading CRON_TZ is maintained.
|
|
func (s Schedule) String() string {
|
|
var sb strings.Builder
|
|
_, _ = sb.WriteString("CRON_TZ=")
|
|
_, _ = sb.WriteString(s.sched.Location.String())
|
|
_, _ = sb.WriteString(" ")
|
|
_, _ = sb.WriteString(s.cronStr)
|
|
return sb.String()
|
|
}
|
|
|
|
// Humanize returns a slightly more human-friendly representation of the
|
|
// schedule.
|
|
func (s Schedule) Humanize() string {
|
|
var sb strings.Builder
|
|
_, _ = sb.WriteString(s.Time())
|
|
_, _ = sb.WriteString(" ")
|
|
_, _ = sb.WriteString(s.DaysOfWeek())
|
|
_, _ = sb.WriteString(" (")
|
|
_, _ = sb.WriteString(s.Location().String())
|
|
_, _ = sb.WriteString(")")
|
|
return sb.String()
|
|
}
|
|
|
|
// Location returns the IANA location for the schedule.
|
|
func (s Schedule) Location() *time.Location {
|
|
return s.sched.Location
|
|
}
|
|
|
|
// Cron returns the cron spec for the schedule with the leading CRON_TZ
|
|
// stripped, if present.
|
|
func (s Schedule) Cron() string {
|
|
return s.cronStr
|
|
}
|
|
|
|
// Next returns the next time in the schedule after t. The zero time means that
|
|
// Next found no run, which does not happen for a schedule from Standard: it
|
|
// always has a later run, because Standard rejects a spec that never runs, and
|
|
// Next searches at least 16 years ahead, past the longest gap between runs
|
|
// (eight years, between two leap days across 2100). A caller treats the zero
|
|
// time from such a schedule as an error and not as the end of the schedule. For
|
|
// a schedule from Standard, Next follows the daylight saving rules that
|
|
// Standard documents.
|
|
func (s Schedule) Next(t time.Time) time.Time {
|
|
if s.wallClock {
|
|
return s.nextWallClock(t)
|
|
}
|
|
return s.sched.Next(t)
|
|
}
|
|
|
|
// IsWithinRange interprets a cron spec as a continuous time range,
|
|
// and returns whether the provided time value falls within that range.
|
|
//
|
|
// For example, the expression "* 9-18 * * 1-5" represents a continuous time range
|
|
// from 09:00:00 to 18:59:59, Monday through Friday.
|
|
func (s Schedule) IsWithinRange(t time.Time) bool {
|
|
// Truncate to the beginning of the current minute.
|
|
currentMinute := t.Truncate(time.Minute)
|
|
|
|
// Go back 1 second from the current minute to find what the next scheduled time would be.
|
|
justBefore := currentMinute.Add(-time.Second)
|
|
next := s.Next(justBefore)
|
|
|
|
// If the next scheduled time is exactly at the current minute,
|
|
// then we are within the range.
|
|
return next.Equal(currentMinute)
|
|
}
|
|
|
|
var (
|
|
t0 = time.Date(1970, 1, 1, 1, 1, 1, 0, time.UTC)
|
|
tMax = t0.Add(168 * time.Hour)
|
|
)
|
|
|
|
// Min returns the minimum duration of the schedule.
|
|
// This is calculated as follows:
|
|
// - Let t(0) be a given point in time (1970-01-01T01:01:01Z00:00)
|
|
// - Let t(max) be 168 hours after t(0).
|
|
// - Let t(1) be the next scheduled time after t(0).
|
|
// - Let t(n) be the next scheduled time after t(n-1).
|
|
// - Then, the minimum duration of s d(min)
|
|
// = min( t(n) - t(n-1) ∀ n ∈ N, t(n) < t(max) )
|
|
//
|
|
// Min looks at one week from 1970-01-01, so for a schedule that restricts the
|
|
// day of month or the month it can report more than the shortest time between
|
|
// runs. For those schedules use MinInterval.
|
|
func (s Schedule) Min() time.Duration {
|
|
durMin := tMax.Sub(t0)
|
|
tPrev := s.Next(t0)
|
|
tCurr := s.Next(tPrev)
|
|
for {
|
|
dur := tCurr.Sub(tPrev)
|
|
if dur < durMin {
|
|
durMin = dur
|
|
}
|
|
tPrev = tCurr
|
|
tCurr = s.Next(tCurr)
|
|
if tCurr.After(tMax) {
|
|
break
|
|
}
|
|
}
|
|
return durMin
|
|
}
|
|
|
|
// TimeParsed returns the parsed time.Time of the minute and hour fields. If the
|
|
// time cannot be represented in a valid time.Time, a zero time is returned.
|
|
func (s Schedule) TimeParsed() time.Time {
|
|
minute := strings.Fields(s.cronStr)[0]
|
|
hour := strings.Fields(s.cronStr)[1]
|
|
maybeTime := fmt.Sprintf("%s:%s", hour, minute)
|
|
t, err := time.ParseInLocation("15:4", maybeTime, s.sched.Location)
|
|
if err != nil {
|
|
return time.Time{}
|
|
}
|
|
return t
|
|
}
|
|
|
|
// Time returns a humanized form of the minute and hour fields.
|
|
func (s Schedule) Time() string {
|
|
minute := strings.Fields(s.cronStr)[0]
|
|
hour := strings.Fields(s.cronStr)[1]
|
|
maybeTime := fmt.Sprintf("%s:%s", hour, minute)
|
|
t, err := time.ParseInLocation("15:4", maybeTime, s.sched.Location)
|
|
if err != nil {
|
|
// return the original cronspec for minute and hour, who knows what's in there!
|
|
return fmt.Sprintf("cron(%s %s)", minute, hour)
|
|
}
|
|
return t.Format(time.Kitchen)
|
|
}
|
|
|
|
// DaysOfWeek returns a humanized form of the day-of-week field.
|
|
func (s Schedule) DaysOfWeek() string {
|
|
dow := strings.Fields(s.cronStr)[4]
|
|
if dow == "*" {
|
|
return "daily"
|
|
}
|
|
for _, weekday := range []time.Weekday{
|
|
time.Sunday,
|
|
time.Monday,
|
|
time.Tuesday,
|
|
time.Wednesday,
|
|
time.Thursday,
|
|
time.Friday,
|
|
time.Saturday,
|
|
} {
|
|
dow = strings.Replace(dow, fmt.Sprintf("%d", weekday), weekday.String()[:3], 1)
|
|
}
|
|
return dow
|
|
}
|
|
|
|
// validateWeeklySpec ensures that the day-of-month and month options of
|
|
// spec are both set to *
|
|
func validateWeeklySpec(spec string) error {
|
|
parts := strings.Fields(spec)
|
|
if len(parts) < 5 {
|
|
return xerrors.Errorf("expected schedule to consist of 5 fields with an optional CRON_TZ=<timezone> prefix")
|
|
}
|
|
if len(parts) == 6 {
|
|
parts = parts[1:]
|
|
}
|
|
if parts[2] != "*" || parts[3] != "*" {
|
|
return xerrors.Errorf("expected day-of-month and month to be *")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateDailySpec ensures that the day-of-month, month and day-of-week
|
|
// options of spec are all set to *
|
|
func validateDailySpec(spec string) error {
|
|
parts := strings.Fields(spec)
|
|
if len(parts) < 5 {
|
|
return xerrors.Errorf("expected schedule to consist of 5 fields with an optional CRON_TZ=<timezone> prefix")
|
|
}
|
|
if len(parts) == 6 {
|
|
parts = parts[1:]
|
|
}
|
|
if parts[2] != "*" || parts[3] != "*" || parts[4] != "*" {
|
|
return xerrors.Errorf("expected day-of-month, month and day-of-week to be *")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateTimeRangeSpec ensures that the minutes field is set to *
|
|
func validateTimeRangeSpec(spec string) error {
|
|
parts := strings.Fields(spec)
|
|
if len(parts) < 5 {
|
|
return xerrors.Errorf("expected schedule to consist of 5 fields with an optional CRON_TZ=<timezone> prefix")
|
|
}
|
|
if len(parts) == 6 {
|
|
parts = parts[1:]
|
|
}
|
|
if parts[0] != "*" {
|
|
return xerrors.Errorf("expected minutes to be *")
|
|
}
|
|
return nil
|
|
}
|