package db import ( "database/sql" "errors" "fmt" "strings" "time" ) // Schedule actions and kinds. const ( ActionStart = "start" ActionStop = "stop" KindOnce = "once" KindWeekly = "weekly" ) // Schedule is one timed action on a stream: a council meeting at 19:00 every // Tuesday, or a one-off match on Saturday. type Schedule struct { ID int64 `json:"id"` StreamID int64 `json:"stream_id"` StreamName string `json:"stream_name,omitempty"` Action string `json:"action"` Kind string `json:"kind"` // AtUTC is the moment a "once" schedule fires, RFC3339. AtUTC string `json:"at_utc,omitempty"` // DaysMask is a bitmask of weekdays for a "weekly" schedule, with // Sunday as bit 0 through Saturday as bit 6. DaysMask int `json:"days_mask,omitempty"` // TimeOfDay is "HH:MM" in TZ, for a "weekly" schedule. TimeOfDay string `json:"time_of_day,omitempty"` // TZ is an IANA zone name. Local wall-clock time is what an operator // means by "19:00", so the zone is stored rather than a UTC offset: an // offset would drift by an hour across a DST boundary. TZ string `json:"tz,omitempty"` Enabled bool `json:"enabled"` LastFiredAt string `json:"last_fired_at,omitempty"` NextFireAt string `json:"next_fire_at,omitempty"` CreatedBy string `json:"created_by,omitempty"` CreatedAt string `json:"created_at,omitempty"` // PrerollFiredFor records the NextFireAt a pre-roll capture was already // requested for, so it happens once per occurrence. PrerollFiredFor string `json:"-"` } func (s *Store) migrateSchedules() error { _, err := s.DB.Exec(` CREATE TABLE IF NOT EXISTS schedules ( id INTEGER PRIMARY KEY AUTOINCREMENT, stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE, action TEXT NOT NULL, kind TEXT NOT NULL, at_utc TEXT NOT NULL DEFAULT '', days_mask INTEGER NOT NULL DEFAULT 0, time_of_day TEXT NOT NULL DEFAULT '', tz TEXT NOT NULL DEFAULT 'UTC', enabled INTEGER NOT NULL DEFAULT 1, last_fired_at TEXT NOT NULL DEFAULT '', next_fire_at TEXT NOT NULL DEFAULT '', preroll_fired_for TEXT NOT NULL DEFAULT '', created_by TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS idx_schedules_next ON schedules(enabled, next_fire_at); CREATE INDEX IF NOT EXISTS idx_schedules_stream ON schedules(stream_id); `) return err } // Validate checks a schedule and normalises its fields. func (sc *Schedule) Validate() error { sc.Action = strings.ToLower(strings.TrimSpace(sc.Action)) switch sc.Action { case ActionStart, ActionStop: default: return fmt.Errorf("action must be %q or %q", ActionStart, ActionStop) } sc.Kind = strings.ToLower(strings.TrimSpace(sc.Kind)) if sc.TZ = strings.TrimSpace(sc.TZ); sc.TZ == "" { sc.TZ = "UTC" } if _, err := time.LoadLocation(sc.TZ); err != nil { return fmt.Errorf("unknown timezone %q", sc.TZ) } switch sc.Kind { case KindOnce: t, err := ParseScheduleTime(sc.AtUTC, sc.TZ) if err != nil { return fmt.Errorf("at_utc: %w", err) } sc.AtUTC = t.UTC().Format(time.RFC3339) case KindWeekly: if _, _, err := parseHHMM(sc.TimeOfDay); err != nil { return fmt.Errorf("time_of_day: %w", err) } if sc.DaysMask&0x7F == 0 { return errors.New("days_mask must select at least one weekday") } sc.DaysMask &= 0x7F default: return fmt.Errorf("kind must be %q or %q", KindOnce, KindWeekly) } return nil } // ParseScheduleTime accepts an RFC3339 instant, or a local "YYYY-MM-DD HH:MM" // interpreted in tz — which is how a person types a meeting time. func ParseScheduleTime(s, tz string) (time.Time, error) { s = strings.TrimSpace(s) if s == "" { return time.Time{}, errors.New("a time is required") } if t, err := time.Parse(time.RFC3339, s); err == nil { return t, nil } loc, err := time.LoadLocation(tz) if err != nil { loc = time.UTC } for _, layout := range []string{"2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02 15:04:05"} { if t, err := time.ParseInLocation(layout, s, loc); err == nil { return t, nil } } return time.Time{}, fmt.Errorf("could not parse %q as a time", s) } func parseHHMM(s string) (hour, minute int, err error) { s = strings.TrimSpace(s) t, err := time.Parse("15:04", s) if err != nil { return 0, 0, fmt.Errorf("want HH:MM, got %q", s) } return t.Hour(), t.Minute(), nil } // NextFire computes the next time this schedule should fire, strictly after // the given moment. The zero time means "never again". func (sc Schedule) NextFire(after time.Time) time.Time { if !sc.Enabled { return time.Time{} } switch sc.Kind { case KindOnce: t, err := time.Parse(time.RFC3339, sc.AtUTC) if err != nil || !t.After(after) { return time.Time{} } return t.UTC() case KindWeekly: hour, minute, err := parseHHMM(sc.TimeOfDay) if err != nil { return time.Time{} } loc, err := time.LoadLocation(sc.TZ) if err != nil { loc = time.UTC } // Walk forward day by day in the target zone. Constructing the time // per local day is what makes this correct across a DST change: the // event stays at 19:00 wall clock rather than drifting an hour. local := after.In(loc) for i := 0; i <= 8; i++ { day := local.AddDate(0, 0, i) if sc.DaysMask&(1< 0 { q += ` WHERE sc.stream_id = ?` args = append(args, streamID) } q += ` ORDER BY sc.next_fire_at = '', sc.next_fire_at, sc.id` rows, err := s.DB.Query(q, args...) if err != nil { return nil, err } defer rows.Close() out := []Schedule{} for rows.Next() { sc, err := scanSchedule(rows) if err != nil { return nil, err } out = append(out, sc) } return out, rows.Err() } // UpcomingSchedules lists the soonest pending occurrences across all streams. func (s *Store) UpcomingSchedules(limit int) ([]Schedule, error) { if limit <= 0 || limit > 200 { limit = 20 } rows, err := s.DB.Query(scheduleSelect+` WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at >= ? ORDER BY sc.next_fire_at LIMIT ?`, now(), limit) if err != nil { return nil, err } defer rows.Close() out := []Schedule{} for rows.Next() { sc, err := scanSchedule(rows) if err != nil { return nil, err } out = append(out, sc) } return out, rows.Err() } // DueSchedules returns enabled schedules whose moment has arrived. func (s *Store) DueSchedules(at time.Time) ([]Schedule, error) { rows, err := s.DB.Query(scheduleSelect+` WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at <= ? ORDER BY sc.next_fire_at`, at.UTC().Format(time.RFC3339)) if err != nil { return nil, err } defer rows.Close() out := []Schedule{} for rows.Next() { sc, err := scanSchedule(rows) if err != nil { return nil, err } out = append(out, sc) } return out, rows.Err() } // PendingPreroll returns start schedules firing within the lead time, whose // pre-roll has not been requested yet. func (s *Store) PendingPreroll(at time.Time, lead time.Duration) ([]Schedule, error) { until := at.Add(lead).UTC().Format(time.RFC3339) rows, err := s.DB.Query(scheduleSelect+` WHERE sc.enabled = 1 AND sc.action = 'start' AND sc.next_fire_at <> '' AND sc.next_fire_at <= ? AND sc.next_fire_at > ? AND sc.preroll_fired_for <> sc.next_fire_at ORDER BY sc.next_fire_at`, until, at.UTC().Format(time.RFC3339)) if err != nil { return nil, err } defer rows.Close() out := []Schedule{} for rows.Next() { sc, err := scanSchedule(rows) if err != nil { return nil, err } out = append(out, sc) } return out, rows.Err() } // MarkPrerolled records that a pre-roll was requested for this occurrence. func (s *Store) MarkPrerolled(id int64, forTime string) error { _, err := s.DB.Exec(`UPDATE schedules SET preroll_fired_for=? WHERE id=?`, forTime, id) return err } // MarkFired advances a schedule after it has run. A "once" schedule is // disabled, since its moment has passed. func (s *Store) MarkFired(sc Schedule, at time.Time) error { next := sc.NextFire(at.Add(time.Second)) nextStr := "" if !next.IsZero() { nextStr = next.Format(time.RFC3339) } enabled := 1 if sc.Kind == KindOnce || nextStr == "" { enabled = 0 } _, err := s.DB.Exec(` UPDATE schedules SET last_fired_at=?, next_fire_at=?, enabled=? WHERE id=?`, at.UTC().Format(time.RFC3339), nextStr, enabled, sc.ID) return err } // PatchSchedule updates a schedule and recomputes when it next fires. func (s *Store) PatchSchedule(id int64, in Schedule, setEnabled *bool) (Schedule, error) { cur, err := s.GetSchedule(id) if err != nil { return Schedule{}, err } if in.Action != "" { cur.Action = in.Action } if in.Kind != "" { cur.Kind = in.Kind } if in.AtUTC != "" { cur.AtUTC = in.AtUTC } if in.TimeOfDay != "" { cur.TimeOfDay = in.TimeOfDay } if in.TZ != "" { cur.TZ = in.TZ } if in.DaysMask != 0 { cur.DaysMask = in.DaysMask } if setEnabled != nil { cur.Enabled = *setEnabled } if err := cur.Validate(); err != nil { return Schedule{}, err } next := cur.NextFire(time.Now().UTC()) nextStr := "" if !next.IsZero() { nextStr = next.Format(time.RFC3339) } en := 0 if cur.Enabled { en = 1 } _, err = s.DB.Exec(` UPDATE schedules SET action=?, kind=?, at_utc=?, days_mask=?, time_of_day=?, tz=?, enabled=?, next_fire_at=?, preroll_fired_for='' WHERE id=?`, cur.Action, cur.Kind, cur.AtUTC, cur.DaysMask, cur.TimeOfDay, cur.TZ, en, nextStr, id) if err != nil { return Schedule{}, err } return s.GetSchedule(id) } func (s *Store) DeleteSchedule(id int64) error { res, err := s.DB.Exec(`DELETE FROM schedules WHERE id=?`, id) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return errors.New("schedule not found") } return nil } // RecomputeNextFire refreshes next_fire_at for every enabled schedule, called // at startup so a server that was down over an occurrence does not fire a // stale one and then sit with a past timestamp. func (s *Store) RecomputeNextFire() error { list, err := s.ListSchedules(0) if err != nil { return err } nowT := time.Now().UTC() for _, sc := range list { if !sc.Enabled { continue } next := sc.NextFire(nowT) nextStr := "" if !next.IsZero() { nextStr = next.Format(time.RFC3339) } enabled := 1 if nextStr == "" { // A "once" schedule whose moment has passed is spent. enabled = 0 } _, _ = s.DB.Exec(`UPDATE schedules SET next_fire_at=?, enabled=? WHERE id=?`, nextStr, enabled, sc.ID) } return nil } // WeekdayMask builds a days_mask from weekday numbers (0 = Sunday). func WeekdayMask(days ...int) int { m := 0 for _, d := range days { if d >= 0 && d <= 6 { m |= 1 << uint(d) } } return m } // DaysLabel renders a mask as "Mon,Tue". func DaysLabel(mask int) string { names := []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} var out []string for i := range names { if mask&(1<