Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Command Center (MCC)8 * File : services/internal/maintenance/recur.go9 * Module : services10 * Repository : https://git.spboucher.ai/maclustr-command-center11 * Project Website : https://clustr.spboucher.ai12 * Created : 2026-11-1813 * Last Modified : 2026-11-1814 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142package maintenance4344import (45 "errors"46 "fmt"47 "strings"48 "sync"49 "time"50 "unicode/utf8"51)5253// Recurrence semantics54//55// A window has a first occurrence [StartsAt, EndsAt) and a zone. Occurrence 056// is exactly [StartsAt, EndsAt). Occurrence n (n >= 1) is built from LOCAL57// WALL-CLOCK fields in the window zone:58//59// - start: the local date of StartsAt shifted by n days (daily), 7n days60// (weekly) or n months (monthly), at the local time of day of StartsAt;61// - end: the shifted start DATE plus the number of calendar days separating62// the local dates of StartsAt and EndsAt, at the local time of day of63// EndsAt. A 01:00–05:00 local window therefore stays 01:00–05:00 local on64// DST days, and its absolute length becomes 3 h (spring forward) or 5 h65// (fall back);66// - if that end is not after the start (pathological DST case, e.g. a67// 02:30–03:00 window on a spring-forward day), End = Start + (EndsAt −68// StartsAt).69//70// Monthly: same day of month as StartsAt (local); when the target month is71// shorter, the LAST day of that month is used (31 → 30 Apr, 28/29 Feb). Month72// n is always computed from the original date + n months, never from month73// n−1, so there is no drift: Jan 31 → Feb 28 → Mar 31.74//75// Local times that do not map to exactly one instant are resolved with one76// deterministic rule, the one of RFC 5545: use the UTC offset in effect77// BEFORE the transition (see resolveWall).78//79// - non-existent time (spring-forward gap): 02:30 on 2026-03-08 in80// America/Toronto is read as 02:30 EST = 07:30Z, i.e. 03:30 EDT;81// - ambiguous time (fall back): 01:30 on 2026-11-01 in America/Toronto is82// the FIRST instance, 01:30 EDT = 05:30Z (not 01:30 EST = 06:30Z).83//84// RecurrenceUntil is inclusive: occurrences with Start <= until belong to the85// series.8687const (88 // maxIterations is the hard cap on loop iterations of one expansion.89 maxIterations = 10000090 // nextIterations is the hard cap on loop iterations of Next.91 nextIterations = 1000092)9394var locCache sync.Map // string → *time.Location9596// loadLocation loads an IANA zone (cached). "" and "Local" are rejected:97// a window must name its zone explicitly.98func loadLocation(name string) (*time.Location, error) {99 if name == "" || name == "Local" {100 return nil, fmt.Errorf("maintenance: timezone must be an explicit IANA zone, got %q", name)101 }102 if v, ok := locCache.Load(name); ok {103 return v.(*time.Location), nil104 }105 loc, err := time.LoadLocation(name)106 if err != nil {107 return nil, fmt.Errorf("maintenance: unknown timezone %q: %w", name, err)108 }109 locCache.Store(name, loc)110 return loc, nil111}112113func knownCategory(c string) bool {114 switch c {115 case CategoryPlanned, CategoryEmergency, CategoryUpdate, CategoryHardware, CategoryInspection:116 return true117 }118 return false119}120121func knownRecurrence(r string) bool {122 switch r {123 case RecurrenceNone, RecurrenceDaily, RecurrenceWeekly, RecurrenceMonthly:124 return true125 }126 return false127}128129// Validate checks a window: Title 1..160 characters, EndsAt > StartsAt,130// duration <= MaxDuration, Timezone loadable ("" and "Local" rejected),131// known Recurrence and Category, RecurrenceUntil (if set) >= StartsAt and132// only on a recurring window, and for recurring windows a duration shorter133// than the period (daily: < 24 h; weekly: < 7 days; monthly: <= MaxDuration).134func Validate(w Window) error {135 if strings.TrimSpace(w.Title) == "" {136 return errors.New("maintenance: title is required")137 }138 if n := utf8.RuneCountInString(w.Title); n > 160 {139 return fmt.Errorf("maintenance: title is too long (%d characters, max 160)", n)140 }141 if !knownCategory(w.Category) {142 return fmt.Errorf("maintenance: unknown category %q", w.Category)143 }144 if !knownRecurrence(w.Recurrence) {145 return fmt.Errorf("maintenance: unknown recurrence %q", w.Recurrence)146 }147 if w.StartsAt.IsZero() || w.EndsAt.IsZero() {148 return errors.New("maintenance: start and end are required")149 }150 if !w.EndsAt.After(w.StartsAt) {151 return errors.New("maintenance: end must be after start")152 }153 d := w.EndsAt.Sub(w.StartsAt)154 if d > MaxDuration {155 return fmt.Errorf("maintenance: duration %s exceeds the maximum of %s", d, MaxDuration)156 }157 if _, err := loadLocation(w.Timezone); err != nil {158 return err159 }160 switch w.Recurrence {161 case RecurrenceDaily:162 if d >= 24*time.Hour {163 return fmt.Errorf("maintenance: a daily window must be shorter than 24h (got %s)", d)164 }165 case RecurrenceWeekly:166 if d >= 7*24*time.Hour {167 return fmt.Errorf("maintenance: a weekly window must be shorter than 7 days (got %s)", d)168 }169 }170 if w.RecurrenceUntil != nil {171 if w.Recurrence == RecurrenceNone {172 return errors.New("maintenance: recurrence_until requires a recurrence")173 }174 if w.RecurrenceUntil.Before(w.StartsAt) {175 return errors.New("maintenance: recurrence_until must not be before start")176 }177 }178 return nil179}180181// resolveWall returns the instant of a local wall-clock time in loc. Day (and182// other fields) may overflow and are normalized like time.Date does.183//184// It does not rely on time.Date for the zone choice (time.Date documents that185// its choice is not guaranteed around transitions). The rule is: use the UTC186// offset in effect BEFORE the transition. Hence a non-existent time (gap) is187// moved forward by the size of the gap (02:30 → 03:30 EDT) and an ambiguous188// time takes its first instance (the DST one on a fall back).189func resolveWall(loc *time.Location, y int, m time.Month, d, h, mi, s, ns int) time.Time {190 u := time.Date(y, m, d, h, mi, s, ns, time.UTC) // wall clock read as UTC191 _, before := u.Add(-24 * time.Hour).In(loc).Zone()192 _, after := u.Add(24 * time.Hour).In(loc).Zone()193 c1 := u.Add(-time.Duration(before) * time.Second)194 if before == after {195 return c1196 }197 if _, off := c1.In(loc).Zone(); off == before {198 return c1 // unique, or first instance of an ambiguous time199 }200 c2 := u.Add(-time.Duration(after) * time.Second)201 if _, off := c2.In(loc).Zone(); off == after {202 return c2203 }204 return c1 // gap: offset before the transition205}206207func daysIn(y int, m time.Month) int {208 return time.Date(y, m+1, 0, 0, 0, 0, 0, time.UTC).Day()209}210211// series is a window prepared for occurrence arithmetic.212type series struct {213 loc *time.Location214 freq string215 start, end time.Time // occurrence 0, UTC216 dur time.Duration217 until *time.Time218219 sy int220 sm time.Month221 sd int222 sh, smi, ss, sn int223 eh, emi, es, en int224 dayDelta int // calendar days between local start date and local end date225}226227func newSeries(w Window) (*series, error) {228 loc, err := loadLocation(w.Timezone)229 if err != nil {230 return nil, err231 }232 freq := w.Recurrence233 if freq == "" {234 freq = RecurrenceNone235 }236 if !knownRecurrence(freq) {237 return nil, fmt.Errorf("maintenance: unknown recurrence %q", w.Recurrence)238 }239 if !w.EndsAt.After(w.StartsAt) {240 return nil, errors.New("maintenance: end must be after start")241 }242 s := &series{loc: loc, freq: freq, start: w.StartsAt.UTC(), end: w.EndsAt.UTC()}243 s.dur = s.end.Sub(s.start)244 if w.RecurrenceUntil != nil && freq != RecurrenceNone {245 u := w.RecurrenceUntil.UTC()246 s.until = &u247 }248 ls, le := s.start.In(loc), s.end.In(loc)249 s.sy, s.sm, s.sd = ls.Date()250 s.sh, s.smi, s.ss, s.sn = ls.Hour(), ls.Minute(), ls.Second(), ls.Nanosecond()251 s.eh, s.emi, s.es, s.en = le.Hour(), le.Minute(), le.Second(), le.Nanosecond()252 ey, em, ed := le.Date()253 d0 := time.Date(s.sy, s.sm, s.sd, 0, 0, 0, 0, time.UTC)254 d1 := time.Date(ey, em, ed, 0, 0, 0, 0, time.UTC)255 s.dayDelta = int(d1.Sub(d0) / (24 * time.Hour))256 return s, nil257}258259func (s *series) single() bool { return s.freq == RecurrenceNone }260261// at returns occurrence n (n >= 0), always computed from the original date.262func (s *series) at(n int) Occurrence {263 if n <= 0 || s.single() {264 return Occurrence{Start: s.start, End: s.end}265 }266 y, m, d := s.sy, s.sm, s.sd267 switch s.freq {268 case RecurrenceDaily:269 d += n270 case RecurrenceWeekly:271 d += 7 * n272 case RecurrenceMonthly:273 total := int(s.sm) - 1 + n274 y = s.sy + total/12275 m = time.Month(total%12 + 1)276 if dim := daysIn(y, m); d > dim {277 d = dim278 }279 }280 st := resolveWall(s.loc, y, m, d, s.sh, s.smi, s.ss, s.sn)281 en := resolveWall(s.loc, y, m, d+s.dayDelta, s.eh, s.emi, s.es, s.en)282 if !en.After(st) {283 en = st.Add(s.dur)284 }285 return Occurrence{Start: st, End: en}286}287288// indexNear returns an index n0 >= 0 such that every occurrence before n0289// ends at or before t: the place to start scanning for occurrences touching290// t, a few periods before it, without iterating from occurrence 0.291func (s *series) indexNear(t time.Time) int {292 span := s.dur293 if span < MaxDuration {294 span = MaxDuration295 }296 var n int64297 switch s.freq {298 case RecurrenceDaily, RecurrenceWeekly:299 period := int64(86400)300 if s.freq == RecurrenceWeekly {301 period = 7 * 86400302 }303 slack := int64(span/time.Second) + 3*86400304 n = (t.Unix()-s.start.Unix()-slack)/period - 1305 case RecurrenceMonthly:306 lt := t.In(s.loc)307 back := int64(span/(28*24*time.Hour)) + 2308 n = int64(lt.Year())*12 + int64(lt.Month()) - int64(s.sy)*12 - int64(s.sm) - back309 default:310 return 0311 }312 if n < 0 {313 return 0314 }315 if n > 1<<31 {316 n = 1 << 31317 }318 return int(n)319}320321// Expand returns the occurrences intersecting [from, to) (End > from &&322// Start < to), ordered by Start, at most max. truncated is true when more323// occurrences existed (or when the iteration cap was hit). max <= 0 or324// max > MaxOccurrences means MaxOccurrences. An empty Recurrence is treated325// as "none".326func Expand(w Window, from, to time.Time, max int) (occ []Occurrence, truncated bool, err error) {327 s, err := newSeries(w)328 if err != nil {329 return nil, false, err330 }331 if max <= 0 || max > MaxOccurrences {332 max = MaxOccurrences333 }334 if !to.After(from) {335 return nil, false, nil336 }337 n := s.indexNear(from)338 for iter := 0; ; iter, n = iter+1, n+1 {339 if iter >= maxIterations {340 return occ, true, nil341 }342 o := s.at(n)343 if !o.Start.Before(to) {344 break345 }346 if s.until != nil && o.Start.After(*s.until) {347 break348 }349 if o.End.After(from) && (len(occ) == 0 || o.Start.After(occ[len(occ)-1].Start)) {350 if len(occ) == max {351 return occ, true, nil352 }353 occ = append(occ, o)354 }355 if s.single() {356 break357 }358 }359 return occ, false, nil360}361362// OccurrenceAt returns the occurrence in progress at t (Start <= t < End),363// if any. If several are in progress (unvalidated overlapping series), the364// earliest is returned.365func OccurrenceAt(w Window, t time.Time) (Occurrence, bool) {366 occ, _, err := Expand(w, t, t.Add(time.Nanosecond), 1)367 if err != nil || len(occ) == 0 {368 return Occurrence{}, false369 }370 return occ[0], true371}372373// OccurrenceStarting returns the occurrence whose Start equals start exactly,374// if it belongs to the series (used to find the end of an activated375// occurrence).376func OccurrenceStarting(w Window, start time.Time) (Occurrence, bool) {377 occ, _, err := Expand(w, start, start.Add(time.Nanosecond), 64)378 if err != nil {379 return Occurrence{}, false380 }381 for _, o := range occ {382 if o.Start.Equal(start) {383 return o, true384 }385 }386 return Occurrence{}, false387}388389// Next returns the first occurrence with Start > after, if any (false when390// the series is over).391func Next(w Window, after time.Time) (Occurrence, bool) {392 s, err := newSeries(w)393 if err != nil {394 return Occurrence{}, false395 }396 n := s.indexNear(after)397 for iter := 0; iter < nextIterations; iter, n = iter+1, n+1 {398 o := s.at(n)399 if s.until != nil && o.Start.After(*s.until) {400 return Occurrence{}, false401 }402 if o.Start.After(after) {403 return o, true404 }405 if s.single() {406 break407 }408 }409 return Occurrence{}, false410}411412// Overlaps reports whether any occurrence of a intersects any occurrence of b413// within [from, to), and the start of the first such intersection (the later414// of the two overlapping occurrences' starts). Work is bounded: each series415// is expanded to at most MaxOccurrences occurrences in the range. Windows416// that cannot be expanded never overlap.417func Overlaps(a, b Window, from, to time.Time) (bool, time.Time) {418 oa, _, err := Expand(a, from, to, MaxOccurrences)419 if err != nil {420 return false, time.Time{}421 }422 ob, _, err := Expand(b, from, to, MaxOccurrences)423 if err != nil {424 return false, time.Time{}425 }426 i, j := 0, 0427 for i < len(oa) && j < len(ob) {428 x, y := oa[i], ob[j]429 st, en := x.Start, x.End430 if y.Start.After(st) {431 st = y.Start432 }433 if y.End.Before(en) {434 en = y.End435 }436 if st.Before(en) && st.Before(to) && en.After(from) {437 return true, st438 }439 if x.End.Before(y.End) {440 i++441 } else {442 j++443 }444 }445 return false, time.Time{}446}447