package worker import ( "context" "database/sql" "log/slog" "sync" "time" "vidarchive/internal/models" "vidarchive/internal/service" ) // Scheduler periodically enqueues downloads for subscriptions whose next run is // due. It reuses the worker Pool and the normal download pipeline; refresh-mode // and pruning behaviour live in DownloadService.ExecuteDownload. type Scheduler struct { subscriptionSvc *service.SubscriptionService downloadSvc *service.DownloadService pool *Pool interval time.Duration ctx context.Context cancel context.CancelFunc wg sync.WaitGroup } func NewScheduler(subscriptionSvc *service.SubscriptionService, downloadSvc *service.DownloadService, pool *Pool, interval time.Duration) *Scheduler { if interval <= 0 { interval = time.Minute } ctx, cancel := context.WithCancel(context.Background()) return &Scheduler{ subscriptionSvc: subscriptionSvc, downloadSvc: downloadSvc, pool: pool, interval: interval, ctx: ctx, cancel: cancel, } } func (s *Scheduler) Start() { s.backfillNextRuns() s.wg.Add(1) go s.loop() } // Stop cancels the loop and waits for it to return. Waiting matters: main // closes the database next, and a checkDue still in flight would query a closed // handle or queue a run nobody will service. func (s *Scheduler) Stop() { s.cancel() s.wg.Wait() } func (s *Scheduler) loop() { defer s.wg.Done() ticker := time.NewTicker(s.interval) defer ticker.Stop() // Check once promptly on startup so a subscription that came due during // downtime doesn't wait a full interval. s.checkDue() for { select { case <-ticker.C: s.checkDue() case <-s.ctx.Done(): return } } } // backfillNextRuns gives any enabled subscription without a next run time one, // without running it — so a fresh restart doesn't fire every subscription that // happens to have a null next_run_at. func (s *Scheduler) backfillNextRuns() { subs, err := s.subscriptionSvc.GetAll() if err != nil { slog.Error("scheduler backfill failed to list subscriptions", "err", err) return } now := time.Now() for _, sub := range subs { if !sub.Enabled || sub.NextRunAt.Valid { continue } next, err := s.subscriptionSvc.ComputeNextRun(sub, now) if err != nil { slog.Warn("scheduler: invalid schedule", "subscription_id", sub.ID, "err", err) continue } sub.NextRunAt = sql.NullTime{Time: next, Valid: true} if err := s.subscriptionSvc.Update(sub); err != nil { slog.Error("scheduler: failed to set next run", "subscription_id", sub.ID, "err", err) } } } func (s *Scheduler) checkDue() { now := time.Now() due, err := s.subscriptionSvc.GetDue(now) if err != nil { slog.Error("scheduler: failed to query due subscriptions", "err", err) return } for _, sub := range due { s.run(sub, now) } } func (s *Scheduler) run(sub *models.Subscription, now time.Time) { next, err := s.subscriptionSvc.ComputeNextRun(sub, now) if err != nil { // Don't keep retrying a broken schedule every tick; push it out a day. slog.Warn("scheduler: invalid schedule, deferring", "subscription_id", sub.ID, "err", err) next = now.Add(24 * time.Hour) } // Skip this run if the previous one is still queued or downloading — a run // longer than the interval would otherwise stack duplicate downloads. Advance // next_run_at so we don't re-evaluate it every tick, preserving the last run. if active, aErr := s.downloadSvc.HasActiveForSubscription(sub.ID); aErr != nil { slog.Error("scheduler: active-run check failed", "subscription_id", sub.ID, "err", aErr) } else if active { lastRun := now if sub.LastRunAt.Valid { lastRun = sub.LastRunAt.Time } slog.Info("scheduler: active run in progress, skipping", "subscription_id", sub.ID, "next_run", next.Format(time.RFC3339)) if mErr := s.subscriptionSvc.MarkRun(sub.ID, lastRun, next, "skipped"); mErr != nil { slog.Error("scheduler: failed to mark run", "subscription_id", sub.ID, "err", mErr) } return } d, err := s.downloadSvc.CreateForSubscription(sub) if err != nil { slog.Error("scheduler: failed to queue subscription", "subscription_id", sub.ID, "err", err) if mErr := s.subscriptionSvc.MarkRun(sub.ID, now, next, "error"); mErr != nil { slog.Error("scheduler: failed to mark run", "subscription_id", sub.ID, "err", mErr) } return } s.pool.Submit(d) if err := s.subscriptionSvc.MarkRun(sub.ID, now, next, "queued"); err != nil { slog.Error("scheduler: failed to mark run", "subscription_id", sub.ID, "err", err) } slog.Info("scheduler: queued subscription", "subscription_id", sub.ID, "download_id", d.ID, "next_run", next.Format(time.RFC3339)) }