package server import ( "context" "encoding/json" "fmt" "log" "time" ) // runAnalyzerScheduler polls due, enabled workflow_schedules for this service and runs them. It's // deliberately a simple poll loop rather than a precise cron: schedules only ever run on // minute-scale intervals, so "checked every 30s, run when due" is accurate enough and far simpler // than tracking individual timers per schedule. func (s *Server) runAnalyzerScheduler(ctx context.Context) { ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: s.runDueAnalyzerSchedules(ctx) } } } func (s *Server) runDueAnalyzerSchedules(ctx context.Context) { rows, err := s.db.Query(ctx, ` SELECT id, tool, settings FROM workflow_schedules WHERE service = $1 AND enabled = TRUE AND (next_run_at IS NULL OR next_run_at <= NOW())`, s.cfg.ServiceName) if err != nil { log.Printf("analyzer: schedule poll: failed to load due schedules: %v", err) return } type due struct { id, tool string settings []byte } items := make([]due, 0) for rows.Next() { var item due if rows.Scan(&item.id, &item.tool, &item.settings) == nil { items = append(items, item) } } rows.Close() for _, item := range items { if ctx.Err() != nil { return } var parsed struct { Types []string `json:"types"` } _ = json.Unmarshal(item.settings, &parsed) types := normalizeMediaTypes(parsed.Types, true) status := "started" started, err := s.startAnalyzerScheduledRun(item.tool, types) switch { case err != nil: status = "error: " + err.Error() case !started: status = "skipped: busy" } log.Printf("analyzer: automation schedule %s fired (tool=%s): %s", item.id, item.tool, status) // Always advance next_run_at, even on skip/error, so a busy or misconfigured schedule // doesn't get retried on every single tick - it just waits for its normal interval instead. _, _ = s.db.Exec(ctx, ` UPDATE workflow_schedules SET last_run_at = NOW(), last_status = $2, next_run_at = NOW() + make_interval(mins => interval_minutes), updated_at = NOW() WHERE id = $1`, item.id, status) } } // startAnalyzerScheduledRun dispatches one schedule's action exactly the way its corresponding // manual-trigger HTTP handler does: guard the relevant busy-state slot, then hand off to the same // background worker function used everywhere else. "started" is false (not an error) when that // slot was already busy - the schedule just waits for its next tick rather than queuing up or // failing loudly, mirroring how the dashboard's own buttons behave under the same condition. func (s *Server) startAnalyzerScheduledRun(tool string, types map[string]bool) (bool, error) { now := time.Now().UTC() switch tool { case "discover": s.scanMu.Lock() if s.scan.Running { s.scanMu.Unlock() return false, nil } s.scan = scanState{Running: true, Mode: "discover", StartedAt: &now} s.scanMu.Unlock() go s.scanMediaFiles(types) case "metadata": s.scanMu.Lock() if s.scan.Running { s.scanMu.Unlock() return false, nil } s.scan = scanState{Running: true, Mode: "metadata", StartedAt: &now} s.scanMu.Unlock() go s.refreshMetadataForTypes(types) case "cleanup": s.scanMu.Lock() if s.scan.Running { s.scanMu.Unlock() return false, nil } s.scan = scanState{Running: true, Mode: "cleanup", StartedAt: &now} s.scanMu.Unlock() go s.cleanupStaleMedia() case "thumbnails": s.thumbnailMu.Lock() if s.thumbnail.Running { s.thumbnailMu.Unlock() return false, nil } runCtx, cancel := context.WithCancel(context.Background()) s.thumbnail = thumbnailGenerationState{Running: true, State: "running", StartedAt: &now} s.thumbnailCancel = cancel s.thumbnailMu.Unlock() go s.generateThumbnails(runCtx, types) case "analyze": s.analysisMu.Lock() if s.analysis.Running { s.analysisMu.Unlock() return false, nil } runCtx, cancel := context.WithCancel(context.Background()) s.analysis = analysisState{Running: true, State: "running", StartedAt: &now} s.analysisCancel = cancel s.analysisMu.Unlock() go s.runAiAnalysis(runCtx, mediaTypesList(types)) default: return false, fmt.Errorf("unsupported schedule action: %s", tool) } return true, nil }