// Package maintenance computes when planned maintenance takes place. // // A window starts at a wall-clock time in a time zone and lasts a fixed // duration. It happens once or repeats every N days, every N weeks on chosen // weekdays, or every N months on the start's day of the month, optionally // until a date. Repeats keep their wall-clock time across daylight saving // changes: "Tuesdays 02:00 Europe/Berlin" stays at 02:00 local time. package maintenance import ( "errors" "slices" "time" ) // Recurrence names how a window repeats. type Recurrence string // Recurrences. const ( Once Recurrence = "none" Daily Recurrence = "daily" Weekly Recurrence = "weekly" Monthly Recurrence = "monthly" ) // Rule describes when a window takes place. type Rule struct { // Start is the first occurrence; its wall clock in Location is kept for // repeats. Start time.Time Duration time.Duration Location *time.Location Recurrence Recurrence // Every repeats every Nth day, week or month; zero means 1. Every int // Weekdays of weekly windows; empty means the start's weekday. Weekdays []time.Weekday // Until ends the repetition: no occurrence starts after it. Until *time.Time } // Span is one occurrence. type Span struct { Start, End time.Time } // Validation errors. var ( ErrDuration = errors.New("maintenance: duration must be between one minute and 30 days") ErrOverlap = errors.New("maintenance: a repeating window must end before it repeats") ErrRecurrence = errors.New("maintenance: unknown recurrence") ErrUntil = errors.New("maintenance: the repetition ends before it starts") ErrEvery = errors.New("maintenance: interval must be between 1 and 365") ) // Validate rejects rules whose occurrences would be meaningless. func (r Rule) Validate() error { if r.Duration < time.Minute || r.Duration > 30*24*time.Hour { return ErrDuration } if r.Every < 0 || r.Every > 365 { return ErrEvery } if r.Until != nil && r.Until.Before(r.Start) { return ErrUntil } every := time.Duration(r.every()) switch r.Recurrence { case Once: case Daily: if r.Duration > every*24*time.Hour { return ErrOverlap } case Weekly: if r.Duration > minWeekdayGap(r.weekdays())*24*time.Hour { return ErrOverlap } case Monthly: if r.Duration > 28*24*time.Hour { return ErrOverlap } default: return ErrRecurrence } return nil } func (r Rule) every() int { return max(r.Every, 1) } func (r Rule) loc() *time.Location { if r.Location == nil { return time.UTC } return r.Location } func (r Rule) weekdays() []time.Weekday { if len(r.Weekdays) == 0 { return []time.Weekday{r.Start.In(r.loc()).Weekday()} } ws := slices.Clone(r.Weekdays) slices.Sort(ws) return slices.Compact(ws) } // minWeekdayGap is the fewest days between two consecutive weekdays of ws, // wrapping around the week. func minWeekdayGap(ws []time.Weekday) time.Duration { gap := 7 for i, w := range ws { next := ws[(i+1)%len(ws)] d := (int(next) - int(w) + 7) % 7 if d == 0 { d = 7 } gap = min(gap, d) } return time.Duration(gap) } // maxSteps bounds the work for absurd ranges. const maxSteps = 5000 // Occurrences returns the occurrences overlapping [from, to), oldest first. func (r Rule) Occurrences(from, to time.Time) []Span { var out []Span add := func(start time.Time) bool { if !start.Before(to) || (r.Until != nil && start.After(*r.Until)) { return false } if end := start.Add(r.Duration); end.After(from) && !start.Before(r.Start) { out = append(out, Span{Start: start, End: end}) } return true } ls := r.Start.In(r.loc()) at := func(y int, m time.Month, d int) time.Time { return time.Date(y, m, d, ls.Hour(), ls.Minute(), ls.Second(), 0, r.loc()) } // Skip ahead to shortly before from instead of walking from the start. skip := func(period time.Duration) int { if n := int(from.Sub(r.Start)-r.Duration) / int(period); n > 1 { return n - 1 } return 0 } n := r.every() switch r.Recurrence { case Once: add(r.Start) case Daily: for i := skip(time.Duration(n)*24*time.Hour) * n; i < maxSteps*n; i += n { if !add(at(ls.Year(), ls.Month(), ls.Day()+i)) { break } } case Weekly: monday := ls.Day() - (int(ls.Weekday())+6)%7 ws := r.weekdays() weeks: for w := skip(time.Duration(n)*7*24*time.Hour) * n; w < maxSteps*n; w += n { for _, wd := range ws { if !add(at(ls.Year(), ls.Month(), monday+7*w+(int(wd)+6)%7)) { break weeks } } } case Monthly: months := (from.Year()-ls.Year())*12 + int(from.Month()-ls.Month()) - 2 for i := max(months, 0) / n * n; i < maxSteps*n; i += n { start := at(ls.Year(), ls.Month()+time.Month(i), ls.Day()) // Months without the day, like 31 in April, are skipped // rather than spilling into the next month. if start.Day() != ls.Day() { continue } if !add(start) { break } } } return out } // ActiveAt returns the occurrence in progress at t. func (r Rule) ActiveAt(t time.Time) (Span, bool) { for _, s := range r.Occurrences(t, t.Add(time.Nanosecond)) { if !t.Before(s.Start) && t.Before(s.End) { return s, true } } return Span{}, false } // Next returns the first occurrence that ends after t: the current one or // the next to come. It looks horizon past t, or past the first occurrence if // that is later. func (r Rule) Next(t time.Time, horizon time.Duration) (Span, bool) { end := t.Add(horizon) if r.Start.After(t) { end = r.Start.Add(horizon) } occ := r.Occurrences(t, end) if len(occ) == 0 { return Span{}, false } return occ[0], true }