// Package scheduler starts and stops streams at planned times, so a council // meeting or a match can be set up in advance instead of started by hand. package scheduler import ( "log/slog" "time" "drmdecryption/apps/streamd/internal/db" ) // Supervisor is the subset of the media supervisor the scheduler needs. type Supervisor interface { Start(id int64) error Stop(id int64) error Running(id int64) bool } // CaptureRequester asks connected agents for fresh credentials now. type CaptureRequester interface { RequestCapture(st db.Stream, reason string) int } const ( tick = 15 * time.Second // DefaultPreroll is how far ahead of a scheduled start credentials are // refreshed. A 19:00 meeting is no use if the keys expired at noon, and a // phone capture takes minutes. DefaultPreroll = 5 * time.Minute ) type Scheduler struct { Store *db.Store Sup Supervisor Capture CaptureRequester Log *slog.Logger Preroll time.Duration } func New(store *db.Store, sup Supervisor, capture CaptureRequester, lg *slog.Logger, preroll time.Duration) *Scheduler { if lg == nil { lg = slog.Default() } if preroll <= 0 { preroll = DefaultPreroll } return &Scheduler{Store: store, Sup: sup, Capture: capture, Log: lg, Preroll: preroll} } // Run drives the scheduler until stop is closed. func (s *Scheduler) Run(stop <-chan struct{}) { // A server that was down over an occurrence must not fire it late; recompute // every next_fire_at against the current time first. if err := s.Store.RecomputeNextFire(); err != nil { s.Log.Error("recompute schedule times", "err", err) } t := time.NewTicker(tick) defer t.Stop() for { select { case <-stop: return case <-t.C: s.step(time.Now().UTC()) } } } // step fires everything due and requests pre-roll captures. func (s *Scheduler) step(now time.Time) { s.preroll(now) due, err := s.Store.DueSchedules(now) if err != nil { s.Log.Error("list due schedules", "err", err) return } for _, sc := range due { st, err := s.Store.GetStream(sc.StreamID) if err != nil { // The stream is gone; the schedule row went with it via the // foreign key, so nothing to do. continue } s.fire(sc, st, now) if err := s.Store.MarkFired(sc, now); err != nil { s.Log.Error("advance schedule", "schedule", sc.ID, "err", err) } } } func (s *Scheduler) fire(sc db.Schedule, st db.Stream, now time.Time) { switch sc.Action { case db.ActionStart: if s.Sup.Running(st.ID) { s.Log.Info("scheduled start skipped: already running", "stream", st.Name) s.Store.AddEvent(db.StreamEvent{ StreamID: st.ID, Kind: db.EventScheduledStart, Severity: db.SevInfo, Actor: db.ActorSystem, Message: "scheduled start: already running", }) return } s.Log.Info("scheduled start", "stream", st.Name, "schedule", sc.ID) s.Store.AddEvent(db.StreamEvent{ StreamID: st.ID, Kind: db.EventScheduledStart, Severity: db.SevInfo, Actor: db.ActorSystem, Message: "scheduled start", }) // Enable it too, or a manual stop earlier in the day would leave the // scheduled event unable to come up. if _, err := s.Store.SetEnabled(st.ID, true); err != nil { s.Log.Error("scheduled enable failed", "stream", st.Name, "err", err) } if err := s.Sup.Start(st.ID); err != nil { s.Log.Error("scheduled start failed", "stream", st.Name, "err", err) s.Store.Eventf(st.ID, db.EventScheduledStart, db.SevError, "scheduled start failed: %v", err) } case db.ActionStop: s.Log.Info("scheduled stop", "stream", st.Name, "schedule", sc.ID) s.Store.AddEvent(db.StreamEvent{ StreamID: st.ID, Kind: db.EventScheduledStop, Severity: db.SevInfo, Actor: db.ActorSystem, Message: "scheduled stop", }) if err := s.Sup.Stop(st.ID); err != nil { s.Log.Error("scheduled stop failed", "stream", st.Name, "err", err) } if _, err := s.Store.SetEnabled(st.ID, false); err != nil { s.Log.Error("scheduled disable failed", "stream", st.Name, "err", err) } } } // preroll asks for fresh credentials shortly before a scheduled start, so the // event does not begin with a capture still in flight. func (s *Scheduler) preroll(now time.Time) { if s.Capture == nil { return } pending, err := s.Store.PendingPreroll(now, s.Preroll) if err != nil { s.Log.Error("list pre-roll schedules", "err", err) return } for _, sc := range pending { st, err := s.Store.GetStream(sc.StreamID) if err != nil { continue } // Mark it either way: a stream with good credentials needs no capture, // and re-checking it every 15s until the event would be pointless. _ = s.Store.MarkPrerolled(sc.ID, sc.NextFireAt) if !st.NeedsCapture { continue } if n := s.Capture.RequestCapture(st, "schedule_preroll"); n > 0 { s.Log.Info("pre-roll capture requested", "stream", st.Name, "fires_at", sc.NextFireAt, "agents", n) s.Store.Eventf(st.ID, db.EventCaptureStarted, db.SevInfo, "pre-roll: asked %d agent(s) for fresh credentials before the scheduled start", n) } else { s.Log.Warn("pre-roll needed but no agent is connected", "stream", st.Name, "fires_at", sc.NextFireAt) s.Store.Eventf(st.ID, db.EventCaptureFailed, db.SevWarn, "pre-roll: credentials are stale and no agent is connected") } } } // Upcoming is the dashboard's view of what is scheduled next. It returns `any` // to keep the api package free of a dependency on this one. func (s *Scheduler) Upcoming(limit int) any { list, err := s.Store.UpcomingSchedules(limit) if err != nil { return []db.Schedule{} } return list }