package db import ( "path/filepath" "testing" "time" _ "time/tzdata" ) func newStore(t *testing.T) *Store { t.Helper() s, err := Open(filepath.Join(t.TempDir(), "d")) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = s.Close() }) return s } func TestScheduleValidate(t *testing.T) { bad := []Schedule{ {Action: "burn", Kind: KindOnce, AtUTC: "2026-01-01T10:00:00Z"}, {Action: ActionStart, Kind: "hourly"}, {Action: ActionStart, Kind: KindOnce, AtUTC: "not a time"}, {Action: ActionStart, Kind: KindWeekly, TimeOfDay: "25:00", DaysMask: 2}, {Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: 0}, {Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: 2, TZ: "Mars/Olympus"}, } for _, sc := range bad { if err := sc.Validate(); err == nil { t.Errorf("expected %+v to be rejected", sc) } } good := Schedule{Action: " START ", Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: WeekdayMask(2), TZ: "Europe/Dublin"} if err := good.Validate(); err != nil { t.Fatalf("valid schedule rejected: %v", err) } if good.Action != ActionStart { t.Errorf("action should be normalised, got %q", good.Action) } } func TestParseScheduleTimeAcceptsLocalWallClock(t *testing.T) { // A person types a local time; it must be read in the stream's zone, not // as UTC, or the event fires at the wrong hour. got, err := ParseScheduleTime("2026-07-01 19:00", "Europe/Dublin") if err != nil { t.Fatal(err) } // Dublin is UTC+1 in July. if got.UTC().Hour() != 18 { t.Errorf("19:00 Dublin in July should be 18:00 UTC, got %s", got.UTC()) } if _, err := ParseScheduleTime("", "UTC"); err == nil { t.Error("an empty time should error") } } func TestNextFireOnce(t *testing.T) { at := time.Date(2026, 3, 10, 19, 0, 0, 0, time.UTC) sc := Schedule{Action: ActionStart, Kind: KindOnce, AtUTC: at.Format(time.RFC3339), Enabled: true} before := at.Add(-time.Hour) if got := sc.NextFire(before); !got.Equal(at) { t.Errorf("NextFire = %s, want %s", got, at) } // Once the moment has passed there is no next occurrence. if got := sc.NextFire(at.Add(time.Second)); !got.IsZero() { t.Errorf("a spent once-schedule should not fire again, got %s", got) } // A disabled schedule never fires. sc.Enabled = false if got := sc.NextFire(before); !got.IsZero() { t.Errorf("a disabled schedule should not fire, got %s", got) } } func TestNextFireWeekly(t *testing.T) { // Tuesdays at 19:00 UTC. sc := Schedule{ Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: WeekdayMask(int(time.Tuesday)), TZ: "UTC", Enabled: true, } // A Monday. mon := time.Date(2026, 3, 9, 12, 0, 0, 0, time.UTC) got := sc.NextFire(mon) if got.Weekday() != time.Tuesday || got.Hour() != 19 { t.Errorf("next fire = %s, want Tuesday 19:00", got) } if d := got.Sub(mon); d < 0 || d > 48*time.Hour { t.Errorf("next fire %s is not within two days of %s", got, mon) } // From Tuesday 19:00:01 it must roll to the following week, not fire // again the same evening. justAfter := time.Date(2026, 3, 10, 19, 0, 1, 0, time.UTC) next := sc.NextFire(justAfter) if next.Weekday() != time.Tuesday { t.Errorf("next = %s, want the following Tuesday", next) } if next.Sub(justAfter) < 6*24*time.Hour { t.Errorf("next = %s, should be about a week after %s", next, justAfter) } } // A weekly event is a wall-clock commitment: a 19:00 meeting stays at 19:00 // local across a DST change. Storing a fixed UTC offset would drift an hour. func TestNextFireWeeklyAcrossDST(t *testing.T) { const zone = "Europe/Dublin" loc, err := time.LoadLocation(zone) if err != nil { t.Skipf("zone data unavailable: %v", err) } sc := Schedule{ Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: WeekdayMask(int(time.Sunday)), TZ: zone, Enabled: true, } // Ireland springs forward at 01:00 on Sunday 29 March 2026. Starting on // the 21st puts the first occurrence on 22 March (still GMT) and the // second on 29 March (already IST), so the pair straddles the change. beforeChange := time.Date(2026, 3, 21, 12, 0, 0, 0, loc) first := sc.NextFire(beforeChange) afterChange := sc.NextFire(first.Add(time.Second)) if first.In(loc).Day() != 22 || afterChange.In(loc).Day() != 29 { t.Fatalf("test set-up is wrong: occurrences are %s and %s, want 22 and 29 March", first.In(loc), afterChange.In(loc)) } // Both occurrences must read 19:00 in local time... for _, got := range []time.Time{first, afterChange} { local := got.In(loc) if local.Hour() != 19 || local.Minute() != 0 { t.Errorf("occurrence %s is %02d:%02d local, want 19:00", got, local.Hour(), local.Minute()) } } // ...which means their UTC hours differ across the change. That // difference is the proof the zone is being honoured. if first.UTC().Hour() == afterChange.UTC().Hour() { t.Errorf("UTC hour did not shift across the DST boundary (%s vs %s) — "+ "the schedule is drifting rather than tracking local time", first.UTC(), afterChange.UTC()) } } func TestNextFireWeeklyMultipleDays(t *testing.T) { sc := Schedule{ Action: ActionStart, Kind: KindWeekly, TimeOfDay: "08:30", DaysMask: WeekdayMask(int(time.Monday), int(time.Wednesday), int(time.Friday)), TZ: "UTC", Enabled: true, } // From Monday 09:00, the next is Wednesday. from := time.Date(2026, 3, 9, 9, 0, 0, 0, time.UTC) got := sc.NextFire(from) if got.Weekday() != time.Wednesday || got.Hour() != 8 || got.Minute() != 30 { t.Errorf("got %s, want Wednesday 08:30", got) } } func TestScheduleCRUDAndFiring(t *testing.T) { store := newStore(t) st, err := store.CreateStream(CreateStream{Name: "council", MPD: "https://x/a.mpd"}) if err != nil { t.Fatal(err) } // A one-off two minutes out. at := time.Now().UTC().Add(2 * time.Minute).Truncate(time.Second) sc, err := store.CreateSchedule(Schedule{ StreamID: st.ID, Action: ActionStart, Kind: KindOnce, AtUTC: at.Format(time.RFC3339), CreatedBy: "tester", }) if err != nil { t.Fatal(err) } if sc.NextFireAt == "" { t.Error("a new schedule should have a next_fire_at") } if sc.StreamName != "council" { t.Errorf("stream name = %q", sc.StreamName) } // Not due yet. if due, err := store.DueSchedules(time.Now().UTC()); err != nil || len(due) != 0 { t.Fatalf("should not be due yet: %v %d", err, len(due)) } // Due once its moment arrives. due, err := store.DueSchedules(at.Add(time.Second)) if err != nil || len(due) != 1 { t.Fatalf("want 1 due, got %d (%v)", len(due), err) } // Firing a once-schedule spends it. if err := store.MarkFired(due[0], at); err != nil { t.Fatal(err) } after, err := store.GetSchedule(sc.ID) if err != nil { t.Fatal(err) } if after.Enabled { t.Error("a fired once-schedule should be disabled") } if after.LastFiredAt == "" { t.Error("last_fired_at should be set") } if later, _ := store.DueSchedules(at.Add(time.Hour)); len(later) != 0 { t.Error("a spent schedule must not fire twice") } // A weekly schedule keeps going. weekly, err := store.CreateSchedule(Schedule{ StreamID: st.ID, Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: WeekdayMask(0, 1, 2, 3, 4, 5, 6), TZ: "UTC", }) if err != nil { t.Fatal(err) } firstNext := weekly.NextFireAt firedAt, err := time.Parse(time.RFC3339, firstNext) if err != nil { t.Fatal(err) } if err := store.MarkFired(weekly, firedAt); err != nil { t.Fatal(err) } again, _ := store.GetSchedule(weekly.ID) if !again.Enabled { t.Error("a weekly schedule should stay enabled after firing") } if again.NextFireAt == "" || again.NextFireAt == firstNext { t.Errorf("weekly next_fire_at should have advanced, was %q now %q", firstNext, again.NextFireAt) } // Listing and deleting. list, err := store.ListSchedules(st.ID) if err != nil || len(list) != 2 { t.Fatalf("want 2 schedules, got %d (%v)", len(list), err) } if err := store.DeleteSchedule(weekly.ID); err != nil { t.Fatal(err) } if err := store.DeleteSchedule(weekly.ID); err == nil { t.Error("deleting twice should report not found") } } func TestSchedulePrerollOnlyOncePerOccurrence(t *testing.T) { store := newStore(t) st, _ := store.CreateStream(CreateStream{Name: "match", MPD: "https://x/a.mpd"}) at := time.Now().UTC().Add(2 * time.Minute) sc, err := store.CreateSchedule(Schedule{ StreamID: st.ID, Action: ActionStart, Kind: KindOnce, AtUTC: at.Format(time.RFC3339), }) if err != nil { t.Fatal(err) } nowT := time.Now().UTC() pending, err := store.PendingPreroll(nowT, 5*time.Minute) if err != nil || len(pending) != 1 { t.Fatalf("want 1 pre-roll pending, got %d (%v)", len(pending), err) } if err := store.MarkPrerolled(sc.ID, pending[0].NextFireAt); err != nil { t.Fatal(err) } // Already requested: must not ask again every tick. pending, err = store.PendingPreroll(nowT, 5*time.Minute) if err != nil || len(pending) != 0 { t.Fatalf("pre-roll should not repeat, got %d (%v)", len(pending), err) } // A stop schedule never pre-rolls: there is nothing to prepare. _, err = store.CreateSchedule(Schedule{ StreamID: st.ID, Action: ActionStop, Kind: KindOnce, AtUTC: at.Format(time.RFC3339), }) if err != nil { t.Fatal(err) } pending, _ = store.PendingPreroll(nowT, 5*time.Minute) for _, p := range pending { if p.Action == ActionStop { t.Error("a stop schedule should not be pre-rolled") } } } // A server that was down over an occurrence must not fire it late. func TestRecomputeNextFireDropsMissedOnce(t *testing.T) { store := newStore(t) st, _ := store.CreateStream(CreateStream{Name: "gone", MPD: "https://x/a.mpd"}) past := time.Now().UTC().Add(-2 * time.Hour) sc, err := store.CreateSchedule(Schedule{ StreamID: st.ID, Action: ActionStart, Kind: KindOnce, AtUTC: past.Add(time.Hour).Format(time.RFC3339), }) if err != nil { // CreateSchedule accepts a past time; NextFire just yields nothing. t.Fatal(err) } if err := store.RecomputeNextFire(); err != nil { t.Fatal(err) } got, _ := store.GetSchedule(sc.ID) if got.Enabled { t.Error("a missed once-schedule should be disabled, not fired late") } if due, _ := store.DueSchedules(time.Now().UTC()); len(due) != 0 { t.Error("a missed schedule must not be due") } } func TestUpcomingSchedulesOrdering(t *testing.T) { store := newStore(t) st, _ := store.CreateStream(CreateStream{Name: "events", MPD: "https://x/a.mpd"}) far := time.Now().UTC().Add(3 * time.Hour) near := time.Now().UTC().Add(10 * time.Minute) if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart, Kind: KindOnce, AtUTC: far.Format(time.RFC3339)}); err != nil { t.Fatal(err) } if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart, Kind: KindOnce, AtUTC: near.Format(time.RFC3339)}); err != nil { t.Fatal(err) } up, err := store.UpcomingSchedules(10) if err != nil || len(up) != 2 { t.Fatalf("want 2 upcoming, got %d (%v)", len(up), err) } if up[0].NextFireAt > up[1].NextFireAt { t.Errorf("upcoming should be soonest first, got %q then %q", up[0].NextFireAt, up[1].NextFireAt) } } // Deleting a stream must take its schedules with it, or the scheduler would // keep trying to start something that no longer exists. func TestSchedulesCascadeOnStreamDelete(t *testing.T) { store := newStore(t) st, _ := store.CreateStream(CreateStream{Name: "temp", MPD: "https://x/a.mpd"}) if _, err := store.CreateSchedule(Schedule{ StreamID: st.ID, Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: WeekdayMask(1), TZ: "UTC", }); err != nil { t.Fatal(err) } if err := store.DeleteStream(st.ID); err != nil { t.Fatal(err) } list, err := store.ListSchedules(st.ID) if err != nil { t.Fatal(err) } if len(list) != 0 { t.Errorf("schedules outlived their stream: %+v", list) } } func TestDaysLabel(t *testing.T) { if got := DaysLabel(WeekdayMask(1, 3, 5)); got != "Mon,Wed,Fri" { t.Errorf("got %q", got) } if got := DaysLabel(0); got != "" { t.Errorf("empty mask = %q", got) } if got := DaysLabel(WeekdayMask(0, 6)); got != "Sun,Sat" { t.Errorf("got %q", got) } }