diff --git a/internal/maintenance/maintenance.go b/internal/maintenance/maintenance.go new file mode 100644 index 0000000..dcfa5c8 --- /dev/null +++ b/internal/maintenance/maintenance.go @@ -0,0 +1,209 @@ +// 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 +} diff --git a/internal/maintenance/maintenance_test.go b/internal/maintenance/maintenance_test.go new file mode 100644 index 0000000..e8e9d35 --- /dev/null +++ b/internal/maintenance/maintenance_test.go @@ -0,0 +1,136 @@ +package maintenance + +import ( + "testing" + "time" +) + +var berlin, _ = time.LoadLocation("Europe/Berlin") + +func starts(spans []Span, loc *time.Location) []string { + out := make([]string, len(spans)) + for i, s := range spans { + out[i] = s.Start.In(loc).Format("2006-01-02 15:04 Mon") + } + return out +} + +func equal(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestOccurrences(t *testing.T) { + start := time.Date(2026, 3, 24, 2, 0, 0, 0, berlin) // a Tuesday before the DST change + until := time.Date(2026, 4, 3, 0, 0, 0, 0, berlin) + tests := []struct { + name string + r Rule + from time.Time + to time.Time + want []string + }{ + {"once", Rule{Start: start, Duration: time.Hour, Location: berlin, Recurrence: Once}, + start.Add(-time.Hour), start.Add(48 * time.Hour), []string{"2026-03-24 02:00 Tue"}}, + {"every second day", Rule{Start: start, Duration: time.Hour, Location: berlin, Recurrence: Daily, Every: 2}, + start, start.AddDate(0, 0, 7), []string{"2026-03-24 02:00 Tue", "2026-03-26 02:00 Thu", "2026-03-28 02:00 Sat", "2026-03-30 02:00 Mon"}}, + // Daylight saving starts on 2026-03-29; the wall clock stays 02:00. + {"weekly Tue and Thu across DST", Rule{Start: start, Duration: time.Hour, Location: berlin, Recurrence: Weekly, Weekdays: []time.Weekday{time.Thursday, time.Tuesday}}, + start, start.AddDate(0, 0, 14), []string{"2026-03-24 02:00 Tue", "2026-03-26 02:00 Thu", "2026-03-31 02:00 Tue", "2026-04-02 02:00 Thu"}}, + {"until", Rule{Start: start, Duration: time.Hour, Location: berlin, Recurrence: Weekly, Weekdays: []time.Weekday{time.Tuesday, time.Thursday}, Until: &until}, + start, start.AddDate(0, 1, 0), []string{"2026-03-24 02:00 Tue", "2026-03-26 02:00 Thu", "2026-03-31 02:00 Tue", "2026-04-02 02:00 Thu"}}, + {"monthly on the 31st skips short months", Rule{Start: time.Date(2026, 1, 31, 22, 0, 0, 0, berlin), Duration: time.Hour, Location: berlin, Recurrence: Monthly}, + time.Date(2026, 1, 1, 0, 0, 0, 0, berlin), time.Date(2026, 6, 1, 0, 0, 0, 0, berlin), []string{"2026-01-31 22:00 Sat", "2026-03-31 22:00 Tue", "2026-05-31 22:00 Sun"}}, + {"weekly starting mid-week skips earlier weekdays", Rule{Start: start.AddDate(0, 0, 1), Duration: time.Hour, Location: berlin, Recurrence: Weekly, Weekdays: []time.Weekday{time.Monday, time.Wednesday}}, + start, start.AddDate(0, 0, 9), []string{"2026-03-25 02:00 Wed", "2026-03-30 02:00 Mon", "2026-04-01 02:00 Wed"}}, + {"an occurrence in progress at from counts", Rule{Start: start, Duration: 3 * time.Hour, Location: berlin, Recurrence: Daily}, + start.Add(time.Hour), start.Add(2 * time.Hour), []string{"2026-03-24 02:00 Tue"}}, + } + for _, tt := range tests { + if got := starts(tt.r.Occurrences(tt.from, tt.to), berlin); !equal(got, tt.want) { + t.Errorf("%s: Occurrences() = %v, want %v", tt.name, got, tt.want) + } + } + // The UTC hour moves with DST while the local time stays. + occ := Rule{Start: start, Duration: time.Hour, Location: berlin, Recurrence: Weekly}.Occurrences(start, start.AddDate(0, 0, 8)) + if occ[0].Start.UTC().Hour() != 1 || occ[1].Start.UTC().Hour() != 0 { + t.Errorf("UTC hours = %d, %d, want 1 and 0", occ[0].Start.UTC().Hour(), occ[1].Start.UTC().Hour()) + } +} + +// Skipping ahead must find exactly what walking from the start finds. +func TestSkipAheadMatchesFullWalk(t *testing.T) { + start := time.Date(2025, 1, 31, 23, 30, 0, 0, berlin) + rules := []Rule{ + {Start: start, Duration: 2 * time.Hour, Location: berlin, Recurrence: Daily, Every: 3}, + {Start: start, Duration: 2 * time.Hour, Location: berlin, Recurrence: Weekly, Every: 2, Weekdays: []time.Weekday{time.Sunday, time.Wednesday}}, + {Start: start, Duration: 2 * time.Hour, Location: berlin, Recurrence: Monthly, Every: 2}, + {Start: start, Duration: 2 * time.Hour, Location: berlin, Recurrence: Monthly}, + } + for _, r := range rules { + for from := start; from.Before(start.AddDate(2, 0, 0)); from = from.Add(97 * time.Hour) { + to := from.AddDate(0, 0, 40) + var want []string + for _, s := range r.Occurrences(start.Add(-time.Hour), to) { + if s.End.After(from) { + want = append(want, s.Start.String()) + } + } + var got []string + for _, s := range r.Occurrences(from, to) { + got = append(got, s.Start.String()) + } + if !equal(got, want) { + t.Fatalf("%s every %d from %v: got %v, want %v", r.Recurrence, r.Every, from, got, want) + } + } + } +} + +func TestActiveAndNext(t *testing.T) { + start := time.Date(2026, 5, 1, 22, 0, 0, 0, time.UTC) + r := Rule{Start: start, Duration: 2 * time.Hour, Recurrence: Daily} + if _, ok := r.ActiveAt(start.Add(-time.Minute)); ok { + t.Error("active before the start") + } + if s, ok := r.ActiveAt(start.AddDate(0, 0, 3).Add(90 * time.Minute)); !ok || !s.Start.Equal(start.AddDate(0, 0, 3)) { + t.Errorf("ActiveAt() = %v %t", s, ok) + } + if _, ok := r.ActiveAt(start.Add(2 * time.Hour)); ok { + t.Error("active at the end") + } + if s, ok := r.Next(start.Add(3*time.Hour), 7*24*time.Hour); !ok || !s.Start.Equal(start.AddDate(0, 0, 1)) { + t.Errorf("Next() = %v %t", s, ok) + } + if s, ok := r.Next(start.AddDate(-5, 0, 0), 24*time.Hour); !ok || !s.Start.Equal(start) { + t.Errorf("Next() long before the first occurrence = %v %t", s, ok) + } +} + +func TestValidate(t *testing.T) { + start := time.Now() + for _, tc := range []struct { + r Rule + ok bool + }{ + {Rule{Start: start, Duration: time.Hour, Recurrence: Once}, true}, + {Rule{Start: start, Duration: 30 * time.Second, Recurrence: Once}, false}, + {Rule{Start: start, Duration: 25 * time.Hour, Recurrence: Daily}, false}, + {Rule{Start: start, Duration: 47 * time.Hour, Recurrence: Daily, Every: 2}, true}, + {Rule{Start: start, Duration: 25 * time.Hour, Recurrence: Weekly, Weekdays: []time.Weekday{time.Monday, time.Tuesday}}, false}, + {Rule{Start: start, Duration: 25 * time.Hour, Recurrence: Weekly, Weekdays: []time.Weekday{time.Monday, time.Thursday}}, true}, + {Rule{Start: start, Duration: time.Hour, Recurrence: "hourly"}, false}, + {Rule{Start: start, Duration: time.Hour, Recurrence: Daily, Until: new(start.Add(-time.Hour))}, false}, + } { + if err := tc.r.Validate(); (err == nil) != tc.ok { + t.Errorf("%+v.Validate() = %v, want ok=%t", tc.r, err, tc.ok) + } + } +}