Documentation
¶
Overview ¶
Package scheduler provides the core scheduling engine for Schedularr.
Index ¶
- func FilterPrograms(programs []tunarr.Program, f Filter) ([]tunarr.Program, error)
- func NewCronParser() cron.Parser
- func NextOccurrences(expr string, from time.Time, count int) ([]time.Time, error)
- type Block
- type BlockType
- type CompletionAction
- type Config
- type Engine
- type EngineOptions
- type FallbackMode
- type FillerConfig
- type Filter
- type OccurrenceSnapshot
- type OnAir
- type ScheduleHistory
- func (sh *ScheduleHistory) RecordPrograms(programs []tunarr.Program, channelID, blockName string, ...)
- func (sh *ScheduleHistory) RecordScheduled(programID, channelID, blockName string, scheduledAt, occurrenceStart time.Time)
- func (sh *ScheduleHistory) WasRecentlyScheduled(programID, channelID string, occurrenceStart time.Time) bool
- func (sh *ScheduleHistory) Window() time.Duration
- type ScheduleHistoryEntry
- type ScheduledSlot
- type SeriesConfig
- type SeriesFallback
- type SeriesState
- type SeriesStateSnapshot
- type StateStore
- type Warning
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FilterPrograms ¶
FilterPrograms filters a list of programs based on the provided filter criteria.
func NewCronParser ¶ added in v0.5.10
NewCronParser builds the project's ONE cron parser configuration: standard 5-field expressions plus descriptors (@daily, @every 1h30m).
It exists so the engine and NextOccurrences cannot drift apart about what a valid expression is. A block whose cron the planner accepts must be one the UI can show occurrences for, and the reverse -- two parsers with different option sets would produce exactly that lie.
func NextOccurrences ¶ added in v0.5.10
NextOccurrences returns the next `count` start instants strictly after `from`, in from's own location.
Strictly after, so a `from` that sits exactly on an occurrence does not return that occurrence again -- the caller is asking what happens NEXT. This is deliberately a different convention from the engine's window walk, which seeds at from-1s precisely so an occurrence exactly at the window start IS included; a window is inclusive of its edge, "next" is not.
The result may be SHORTER than count. robfig's SpecSchedule.Next returns the zero time when it finds no match within five years -- February 30th is a well-formed expression that never fires -- so the walk stops there rather than letting a zero instant reach a caller and serialize as 0001-01-01.
A @every descriptor yields a ConstantDelaySchedule measured from the argument rather than from a calendar. That is the library's intent, not a bug to correct.
Types ¶
type Block ¶
type Block struct {
// ID is the block's stable store identity (store.BlockRecord.ID, a
// UUID) -- populated by service.ActiveBlocks from the store record
// this Spec came from, since scheduler.yaml-imported/test-constructed
// Blocks have no such identity of their own. Unlike Name (unique, but
// renameable), ID never changes across a block's lifetime, which is
// what keys series_occurrence_snapshots by (see
// Engine.planSeriesOccurrences and StateStore.GetOccurrenceSnapshot's
// doc comments) rather than Name -- a rename would otherwise orphan
// every not-yet-aired occurrence's stored cursor snapshot. May be
// empty for a Block never sourced from the store (e.g. some tests) --
// callers that key off it must tolerate that.
ID string `mapstructure:"-" yaml:"-" json:"-"`
Type BlockType `mapstructure:"type" yaml:"type,omitempty" json:"type"` // "filter" or "series", default "filter"; omitempty so a zero value re-renders as absent and CUE's *"filter" default applies instead of "" failing the disjunction
Name string `mapstructure:"name" yaml:"name" json:"name"`
Cron string `mapstructure:"cron" yaml:"cron" json:"cron"` // Cron expression for start time
Duration int `mapstructure:"duration" yaml:"duration" json:"duration"` // Duration in minutes
Filter Filter `mapstructure:"filter" yaml:"filter" json:"filter,omitempty"`
ChannelID string `mapstructure:"channel_id" yaml:"channel_id" json:"channel_id"`
Priority int `mapstructure:"priority" yaml:"priority" json:"priority"` // Higher priority overrides overlapping blocks
MaxDurationOverflowMinutes int `` // Max minutes a block's actual duration can exceed its planned duration
/* 128-byte string literal not displayed */
Filler FillerConfig `mapstructure:"filler" yaml:"filler" json:"filler,omitempty"` // Filler content configuration
Series []SeriesConfig `mapstructure:"series" yaml:"series" json:"series,omitempty"` // For BlockTypeSeries
Fallback SeriesFallback `mapstructure:"fallback" yaml:"fallback,omitempty" json:"fallback,omitempty"` // For BlockTypeSeries
}
Block defines a scheduled programming block
type CompletionAction ¶
type CompletionAction string
CompletionAction defines what to do when a series completes all episodes
const ( // CompletionActionContinue keeps the series in the block but marks it complete (default) CompletionActionContinue CompletionAction = "continue" // CompletionActionRestart restarts the series from the beginning CompletionActionRestart CompletionAction = "restart" // CompletionActionDisable removes the series from future scheduling CompletionActionDisable CompletionAction = "disable" )
type Config ¶
type Config struct {
Blocks []Block `mapstructure:"blocks" yaml:"blocks" json:"blocks"`
}
Config holds the scheduling configuration
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the scheduling engine that generates programming schedules.
func NewEngine ¶
func NewEngine(client *tunarr.Client, blocks []Block, store StateStore, logger *slog.Logger, loc *time.Location) *Engine
NewEngine creates a new scheduling engine with the given Tunarr client and scheduling blocks, using the default 7-day history window. Callers that need a configured window (e.g. service.NewRunner, which threads through maintenance.history_retention) should use NewEngineWithOptions instead, which also lets them thread a real context through the construction-time plan-sequence floor read; this convenience constructor uses context.Background() for it.
func NewEngineWithOptions ¶
func NewEngineWithOptions(ctx context.Context, client *tunarr.Client, blocks []Block, store StateStore, opts EngineOptions) *Engine
NewEngineWithOptions creates a new scheduling engine with optional configuration. Any zero-valued field in opts falls back to the same default NewEngine uses: opts.Logger -> slog.Default(), opts.Location -> time.Local, opts.HistoryWindow -> defaultHistoryWindow (7 days). ctx bounds the construction-time plan-sequence floor read (MaxPlanSeq -- see nextPlanSeq's doc comment); it is not retained.
func (*Engine) Commit ¶
Commit persists all pending state changes to the store: series cursor advances and schedule history from occurrences planned for the first time this Run (pendingStates/pendingHistory -- the only path that ever really advances a series cursor, see PlanBlock's doc comment), plus this Run's series-occurrence idempotence bookkeeping (pendingSnapshots/pendingReplacements).
func (*Engine) GenerateForTimeRange ¶
func (e *Engine) GenerateForTimeRange(start, end time.Time, availablePrograms []tunarr.Program) (map[string][]ScheduledSlot, []Warning, error)
GenerateForTimeRange generates a schedule for the given window with priority-based conflict resolution. It returns a map of ChannelID -> []ScheduledSlot, plus a Warning for every occurrence that got planned a time slot but then lost conflict resolution (see resolveConflicts and Warning's doc comment).
This runs in three phases, deliberately in this order:
- Build occurrence "shells" for every block -- StartTime/EndTime/Block only, no Programs -- by walking each block's cron schedule across [start, end). Grouped both per channel (channelShells, for phase 2) and per block in each block's own chronological order (perBlockShells, for phase 3).
- Resolve conflicts per channel on the shells (resolveConflicts never reads .Programs, so this works identically on content-less shells), recording which occurrences survive in the survived set and collecting a Warning for every one that doesn't.
- Plan content -- Engine.PlanBlock, the only step that can advance a series cursor or write schedule_history -- one block at a time, in that block's own perBlockShells order, skipping any shell conflict resolution already dropped.
Phases 2 and 3 used to be one step: the original single-pass version called PlanBlock for every occurrence *before* resolveConflicts ever ran, so a losing occurrence's cursor advance and history write already happened by the time it got thrown away -- a plan that never aired still permanently consumed a series' next episode. Splitting content planning out until after conflict resolution is what fixes that: only occurrences that actually make it into the returned schedule ever reach PlanBlock.
Phase 3 iterates block-by-block (not channel-by-group, the way phase 1's channelShells or the final resolvedSchedule are organized) because that's what preserves each block's own chronological occurrence order: channelShells (and therefore resolvedSchedule) can interleave more than one block's occurrences on the same channel in whatever order the phase-1 outer loop happened to visit those blocks, not time order (see buildAnchoredLineup in internal/service/schedule.go, which has the same problem on the output side and the same fix -- sort by time itself rather than trust the map's order). A series block's cursor is only correct if its own occurrences are planned in the order they'll actually air, so phase 3 has to walk perBlockShells, not resolvedSchedule.
func (*Engine) PlanBlock ¶
func (e *Engine) PlanBlock(block Block, availablePrograms []tunarr.Program, occurrenceStart, now time.Time) ([]tunarr.Program, error)
PlanBlock generates the list of programs for one occurrence of block -- the one whose cron-computed start time is occurrenceStart -- filling its duration. now is the current apply's own time reference (service.Runner.Run's start, i.e. effectively "now" for this whole Run) -- not necessarily literally time.Now() at the moment this executes, but a single, stable value shared by every occurrence this Run plans, which is what "has this occurrence aired yet" needs to mean consistently across a whole GenerateForTimeRange call.
This is idempotent per (block.Name, occurrenceStart) for filter blocks, and per (block.ID, occurrenceStart) for series blocks (see why the key differs in StateStore.GetOccurrenceSnapshot's doc comment): the schedule-generation window is 24h and re-applies happen more often than that (the serve cron loop's default 6h interval), so the same future occurrence falls inside several consecutive applies' windows -- naive re-planning on every one of them used to advance a series block's episode cursor and write a new schedule_history row each time, for content that was never actually going to air differently, since the *next* apply would just overwrite it again. A Saturday-8pm block observed E01 on its first apply and E04 after two more, and a show's cursor drifted multiple episodes ahead of anything that had actually aired.
Filter blocks have no spec-derived cursor to worry about re-deriving (a filter's random pick has nothing consistent to recompute toward), so any already-committed occurrence -- aired or not -- is simply replayed verbatim via GetCommittedOccurrence/resolveCommittedPrograms: freezing the choice once made is the only idempotent option, and is also just good behavior (a live Tunarr lineup that flip-flopped its random pick every 6h would be its own bug).
Series blocks DO have a cursor (SeriesState, keyed by show title) that should visibly respond to a block spec edited before an occurrence airs -- reordering block.Series, adding/removing a series, or changing episodes_per_block/duration -- so freezing the final program list verbatim (like filter blocks) isn't good enough: it would silently ignore such an edit until the stale occurrence ages out of the window entirely. This single-occurrence entry point delegates to planSeriesOccurrences (a single-element shell slice) for that -- GenerateForTimeRange's phase 3 calls planSeriesOccurrences directly with a whole block's surviving occurrences at once instead, which is what actually matters for correctness: see its own doc comment for why a single-occurrence view (this method, or a naive per-occurrence loop) isn't sufficient on its own once more than one not-yet-aired occurrence of the same block is in play.
GenerateForTimeRange's phase 3 (the only production caller of the underlying planning, whether through this method for filter blocks or directly through planSeriesOccurrences for series ones) only plans occurrences that survived conflict resolution, so a conflict-dropped occurrence never reaches either path at all -- it can't advance a cursor, capture a snapshot, or get recorded either. See GenerateForTimeRange's own doc comment for why that ordering (resolve conflicts, *then* plan content) matters.
type EngineOptions ¶
type EngineOptions struct {
// HistoryWindow bounds both the in-memory dedup check (filterByHistory)
// and, via Commit's CleanupScheduleHistory call, how much of the
// persisted schedule_history table survives each apply. service.Runner
// sets this from the maintenance.history_retention config key so the
// two stay coherent: GET /history?days=N (api/openapi.yaml, 1..90) can
// only ever return data as far back as this window allows -- a wider
// history_retention is required to actually query a wider days range.
// Zero uses defaultHistoryWindow (7 days).
HistoryWindow time.Duration
// SnapshotRetention bounds Commit's CleanupOccurrenceSnapshots call.
// Split from HistoryWindow in v0.5.7 (maintenance.snapshot_retention)
// so the two tables prune on their own clocks; zero falls back to the
// history window, which is what the single-knob behavior was.
SnapshotRetention time.Duration
// RunID is the apply run this engine's Commit belongs to
// (store.ApplyRun.ID). Stamped onto every schedule_history row Commit
// writes, so an aired program can be traced back to the apply that
// put it there. Left empty by a dry-run caller: a dry run plans
// entries too, and they must not claim a run that never happened.
RunID string
Logger *slog.Logger
Location *time.Location
}
EngineOptions contains optional configuration for the scheduling engine.
type FallbackMode ¶
type FallbackMode string
FallbackMode defines how to handle empty time in a series block
const ( // FallbackModeRedistribute redistributes remaining time to other series FallbackModeRedistribute FallbackMode = "redistribute" // FallbackModeFiller fills remaining time with content matching FillerFilter FallbackModeFiller FallbackMode = "filler" )
type FillerConfig ¶
type FillerConfig struct {
Enabled bool `mapstructure:"enabled" yaml:"enabled" json:"enabled"` // Whether to use filler content
FillerListID string `mapstructure:"filler_list_id" yaml:"filler_list_id" json:"filler_list_id,omitempty"` // ID of filler list to use
MaxFillerTime int `mapstructure:"max_filler_time" yaml:"max_filler_time" json:"max_filler_time,omitempty"` // Max minutes of filler allowed (0 = unlimited)
MinGapTime int `mapstructure:"min_gap_time" yaml:"min_gap_time" json:"min_gap_time,omitempty"` // Minimum gap (minutes) before adding filler
}
FillerConfig defines filler content configuration for a block
type Filter ¶
type Filter struct {
TitlePattern string `mapstructure:"title_pattern" yaml:"title_pattern" json:"title_pattern,omitempty"`
Genres []string `mapstructure:"genres" yaml:"genres" json:"genres,omitempty"`
Ratings []string `mapstructure:"ratings" yaml:"ratings" json:"ratings,omitempty"`
YearFrom int `mapstructure:"year_from" yaml:"year_from" json:"year_from,omitempty"`
YearTo int `mapstructure:"year_to" yaml:"year_to" json:"year_to,omitempty"`
MinDuration int `mapstructure:"min_duration" yaml:"min_duration" json:"min_duration,omitempty"` // in minutes
MaxDuration int `mapstructure:"max_duration" yaml:"max_duration" json:"max_duration,omitempty"` // in minutes
Tags []string `mapstructure:"tags" yaml:"tags" json:"tags,omitempty"`
}
Filter defines criteria for selecting content
type OccurrenceSnapshot ¶ added in v0.2.2
type OccurrenceSnapshot struct {
PreStates map[string]SeriesStateSnapshot
PostStates map[string]SeriesStateSnapshot
RecordedAt time.Time
// PlanSeq is the engine-allocated, strictly monotonic sequence
// (Engine.nextPlanSeq) of the plan generation that produced
// PostStates -- the replay-ordering provenance
// Engine.syncPostStates compares against SeriesState.CursorPlanSeq.
// Re-deriving a not-yet-aired occurrence allocates a fresh, higher
// sequence; an aired occurrence's row is never rewritten, freezing
// the sequence of the plan it actually aired with. Zero marks a
// legacy row written before migration 000007 (no cursor advance of
// its own -- see the migration's doc comment).
PlanSeq int64
}
OccurrenceSnapshot is everything persisted per series-block occurrence in series_occurrence_snapshots: the per-show cursor the occurrence plans FROM (PreStates -- the seed, captured at first plan and rewritten when an earlier occurrence's re-derivation shifts this occurrence's baseline, when a series ADDED to the block's spec is backfilled from its live cursor (Engine.backfillChainFromLive), or -- by omission -- when a series REMOVED from the spec is scoped out of the re-captured seed (Engine.specStates)), the per-show cursor it ends AT (PostStates, captured at that same plan time and scoped the same way), and when that plan was last written (RecordedAt -- the occurrence's commit stamp, refreshed on every upsert; an aired occurrence's row is never written again, so it freezes at the plan the occurrence actually aired with).
PostStates is what advances the persisted series_state cursor once the occurrence airs: Engine.planSeriesOccurrences' aired branch replays it (see Engine.syncPostStates for the guards) instead of re-deriving the advance from committed content metadata or a re-plan -- an occurrence's effect on the global cursor is decided exactly once, at plan time, when the full planning context (on_complete restarts, skips, season rollovers) is still in hand. A nil PostStates marks a legacy row written before migration 000006 added the column: its occurrence still replays committed content verbatim if aired (and re-derives if future) but contributes no cursor advance of its own.
type OnAir ¶ added in v0.5.11
type OnAir struct {
// Block is the block whose occurrence this is.
Block Block
// Start is when the occurrence began.
Start time.Time
// SafeAt is when it stops being on air -- the instant after which a
// change to this block can no longer affect what a viewer sees.
SafeAt time.Time
}
OnAir is one occurrence that is playing right now.
func OnAirOccurrences ¶ added in v0.5.11
OnAirOccurrences returns every occurrence of blocks that is playing at now, each with the instant it becomes safe to change.
It exists because three write paths -- deleting a block, switching one off, and (from v0.5.12) removing a show's history -- all change what the NEXT apply pushes to Tunarr, and the next apply may be minutes away and unattended: serve's cron loop applies at process start and then every cron_interval. None of them consulted the current lineup before this.
THE ENVELOPE IS DELIBERATELY THE WIDER OF THE TWO IN THIS CODEBASE. onAirOccurrenceStart, which drives the planner's own on-air shell, uses Duration alone. store.InvalidationCutoff adds MaxDurationOverflowMinutes and its doc comment argues that a block whose content legitimately overruns IS still on air. This uses the second, because the same change that this guard protects also invalidates snapshots through that path -- and a guard that cleared first would refuse to refuse on exactly the content that overran.
THE LOCATION IS A PARAMETER, NOT time.Local. A block's cron carries no CRON_TZ prefix anywhere in this codebase, so robfig matches its calendar fields against whatever location the argument carries. GenerateForTimeRange converts to the engine's location before walking, and a guard that skipped that step would answer for a different occurrence than the apply it is protecting -- in a container with no TZ set, for a different hour entirely.
IT ASKS ABOUT OCCURRENCES, NOT ABOUT CONTENT. Every block is checked, series and filter alike. A filter block schedules titles that appear nowhere in its spec, so anything driven off a show-reference lookup (store.blockReferencesShow scans spec.Series only) would silently miss every one of them.
A block whose cron will not parse is skipped rather than failing the whole answer: one bad expression must not hide a live occurrence that a caller is about to disrupt. Callers pass the blocks they care about -- for a guard, the ACTIVE ones, since a disabled or dark block generates no shell at the next apply and cannot be cut off by a change to it.
type ScheduleHistory ¶
type ScheduleHistory struct {
// contains filtered or unexported fields
}
ScheduleHistory tracks what content has been scheduled to prevent repetition
func NewScheduleHistory ¶
func NewScheduleHistory(window time.Duration) *ScheduleHistory
NewScheduleHistory creates a new schedule history tracker
func (*ScheduleHistory) RecordPrograms ¶
func (sh *ScheduleHistory) RecordPrograms(programs []tunarr.Program, channelID, blockName string, scheduledAt, occurrenceStart time.Time)
RecordPrograms records multiple programs as scheduled for one block occurrence.
func (*ScheduleHistory) RecordScheduled ¶
func (sh *ScheduleHistory) RecordScheduled(programID, channelID, blockName string, scheduledAt, occurrenceStart time.Time)
RecordScheduled records that a program was scheduled for one block occurrence. occurrenceStart is that occurrence's own cron-computed start time -- see WasRecentlyScheduled for why the entry has to carry it and not only the wall-clock scheduledAt.
func (*ScheduleHistory) WasRecentlyScheduled ¶
func (sh *ScheduleHistory) WasRecentlyScheduled(programID, channelID string, occurrenceStart time.Time) bool
WasRecentlyScheduled reports whether programID already went out on channelID inside the tracking window, for an occurrence that airs BEFORE occurrenceStart.
The occurrence bound is what makes a plan independent of how wide a window it was asked for. This tracker is populated as a single run plans, block by block in e.blocks order and each block in its own chronological order, so by the time a mid-run occurrence is planned the tracker already holds entries for occurrences that air LATER than it -- every occurrence of every block planned earlier in the run. That set grows with the requested window, so without this bound a 7-day draft and a 28-day reading would filter the same occurrence's candidates from different sets and plan it differently, and the Guide's diff would read CHANGED on a draft nobody edited. Counting only strictly-earlier occurrences makes the filtered set a function of the occurrence alone. (The persisted twin, StateStore. WasRecentlyScheduled, needs no such bound: it only ever sees occurrences committed by an earlier apply.)
func (*ScheduleHistory) Window ¶
func (sh *ScheduleHistory) Window() time.Duration
Window returns the configured tracking window for history entries.
type ScheduleHistoryEntry ¶
type ScheduleHistoryEntry struct {
ProgramID string `db:"program_id"`
ChannelID string `db:"channel_id"`
ScheduledAt time.Time `db:"scheduled_at"`
BlockName string `db:"block_name"`
OccurrenceStart time.Time `db:"occurrence_start"`
Sequence int `db:"sequence"`
DurationMs float64 `db:"duration_ms"`
Title string `db:"title"`
// ShowTitle is the SHOW this airing belongs to, where Title is the
// EPISODE. Empty for anything that belongs to no show -- a movie, or a
// program Tunarr could not resolve a show for -- and for every row
// written before migration 000012, which cannot be backfilled.
//
// It is filled from tunarr.Program.ShowTitle rather than from the
// block's series config on purpose: a FILTER block can select an
// episode too, and that episode belongs to its show no matter which
// kind of block put it on air. Keying off the block would have made
// "remove this show" miss exactly those airings.
ShowTitle string `db:"show_title"`
Type string `db:"type"`
// RunID is the apply run (store.ApplyRun.ID) that committed this row,
// or "" for rows written before apply runs were recorded (v0.5.7) --
// runs cannot be backfilled, so an empty RunID means "unknown apply",
// not "no apply". Stamped by Engine.Commit from EngineOptions.RunID,
// never by the planner: a dry run produces entries too, and they must
// not claim a run that never happened.
RunID string `db:"run_id"`
}
ScheduleHistoryEntry represents a single program that was scheduled.
ScheduledAt and OccurrenceStart serve two different purposes and are deliberately not the same value: ScheduledAt is the wall-clock instant planning happened (time.Now() at the moment Engine.PlanBlock ran) -- the recency-dedup WINDOW (ScheduleHistory.WasRecentlyScheduled, StateStore.WasRecentlyScheduled) is measured against it. OccurrenceStart is the block occurrence's own cron-computed StartTime. It is the identity half of the (block_name, occurrence_start) key Engine.PlanBlock's idempotence check looks up (see its doc comment in engine.go) -- the same occurrence re-planned in a later apply must resolve to the same assignment, which requires a key that doesn't change between applies the way ScheduledAt (a fresh time.Now() every time) does -- and it is also the ORDER the in-memory dedup check reads entries by, so a run's own not-yet-aired occurrences cannot filter an earlier one's candidates (see ScheduleHistory.WasRecentlyScheduled).
Sequence, DurationMs, Title, and Type exist purely to make an occurrence's assignment fully replayable without depending on the live Tunarr catalog still containing every program by ID: Sequence preserves playback order (a lineup's wall-clock anchoring depends on it -- see service.buildAnchoredLineup), and DurationMs/Title/Type are enough to reconstruct a valid tunarr.Program on their own.
type ScheduledSlot ¶
type ScheduledSlot struct {
StartTime time.Time
EndTime time.Time
Block Block
Programs []tunarr.Program
}
ScheduledSlot represents a scheduled time slot with its block and priority
type SeriesConfig ¶
type SeriesConfig struct {
ShowTitle string `mapstructure:"show_title" yaml:"show_title" json:"show_title"`
EpisodesPerBlock int `mapstructure:"episodes_per_block" yaml:"episodes_per_block" json:"episodes_per_block"`
StartSeason int `mapstructure:"start_season" yaml:"start_season" json:"start_season,omitempty"` // Optional: override start point
StartEpisode int `mapstructure:"start_episode" yaml:"start_episode" json:"start_episode,omitempty"` // Optional: override start point
OnComplete CompletionAction `mapstructure:"on_complete" yaml:"on_complete" json:"on_complete,omitempty"` // Action when series completes (default: continue)
SkipEpisodes []string `mapstructure:"skip_episodes" yaml:"skip_episodes" json:"skip_episodes,omitempty"` // Episodes to skip (format: "S01E05", "S02E10")
MaxRuns int `mapstructure:"max_runs" yaml:"max_runs" json:"max_runs,omitempty"` // Max times to run through series (0 = unlimited)
}
SeriesConfig defines configuration for a specific series in a block
type SeriesFallback ¶
type SeriesFallback struct {
Mode FallbackMode `mapstructure:"mode" yaml:"mode" json:"mode,omitempty"`
FillerFilter Filter `mapstructure:"filler_filter" yaml:"filler_filter" json:"filler_filter,omitempty"` // Used if Mode is Filler
}
SeriesFallback defines fallback behavior when series content runs out or doesn't fill duration
type SeriesState ¶
type SeriesState struct {
ShowTitle string `json:"show_title" db:"show_title"` // Primary key (or part of it)
CurrentSeason int `json:"current_season" db:"current_season"` // Next season to air
CurrentEpisode int `json:"current_episode" db:"current_episode"` // Next episode to air
Completed bool `json:"completed" db:"completed"` // True if all available episodes have aired
LastAired *time.Time `json:"last_aired" db:"last_aired"` // Timestamp of last successful schedule (nullable)
RunCount int `json:"run_count" db:"run_count"` // Number of times series has been completed (for restart tracking)
Disabled bool `json:"disabled" db:"disabled"` // True if series has been disabled due to completion
// OperatorUpdatedAt is when an operator last wrote this row directly
// (PATCH /state/series, or the CLI's `state set`/`state reset`/
// `state import`) -- nil if never. Engine.syncPostStates skips any
// aired-occurrence post-state replay whose own commit predates this
// stamp, so an operator write -- a BACKWARD cursor jump included --
// is never re-advanced by an occurrence planned before it.
// Engine-side writes (Commit's UpdateSeriesState calls) carry the
// stamp through unchanged; only the operator entry points ever set
// it.
OperatorUpdatedAt *time.Time `json:"operator_updated_at,omitempty" db:"operator_updated_at"`
// CursorPlanSeq is the provenance of the current cursor value: the
// plan sequence (Engine.nextPlanSeq) of the plan whose post-state
// last wrote this row through Engine.syncPostStates. An
// aired-occurrence replay wins exactly when its own
// OccurrenceSnapshot.PlanSeq is newer than this -- in either
// direction, so an on_complete:restart wrap (S01E05 -> S01E01) lands
// instead of being dropped as "backward" -- while a stale replay from
// an OLDER plan (e.g. a slower block sharing the show) is rejected.
// Zero means no post-state replay (or plan-time real-plan write) has
// stamped this row yet. Operator writes leave it untouched: they are
// protected by OperatorUpdatedAt, not by provenance.
CursorPlanSeq int64 `json:"cursor_plan_seq,omitempty" db:"cursor_plan_seq"`
}
SeriesState tracks the playback progress of a specific series.
type SeriesStateSnapshot ¶ added in v0.2.2
type SeriesStateSnapshot struct {
CurrentSeason int `json:"current_season"`
CurrentEpisode int `json:"current_episode"`
Completed bool `json:"completed"`
Disabled bool `json:"disabled"`
RunCount int `json:"run_count"`
Seeded bool `json:"seeded"`
}
SeriesStateSnapshot is the per-show cursor captured immutably the FIRST time a series block's occurrence is ever planned, keyed by show title within a per-occurrence map (one snapshot entry per show the block's spec referenced at that moment) -- see Engine.PlanBlock's doc comment for the full mechanism this supports: idempotent re-apply of a not-yet-aired occurrence that still lets a block spec edited before it airs (series reordered, added, removed, episodes_per_block or duration changed) change that occurrence's content. It's a value-only subset of SeriesState -- no ShowTitle (implied by its map key) -- except Seeded, which stands in for LastAired.
Seeded records whether the captured *SeriesState already had a non-nil LastAired (i.e. was already past its one-time start_season/start_episode initialization) at the moment of capture -- see Engine.initializeSeriesState: it only applies start_season/start_episode when LastAired is nil, treating that as "never initialized." A reconstructed snapshot used to always leave LastAired nil (see statesFromSnapshot), which made initializeSeriesState re-apply start_season/start_episode on *every* re-derive of a not-yet-aired occurrence, silently re-pinning its cursor back to the configured start position regardless of how far the snapshot had actually progressed (e.g. start_episode: 5 configured, occurrence legitimately at E6 -- every re-apply re-derived it back to E5). Seeded fixes that: a reconstructed SeriesState gets a non-nil marker LastAired exactly when the snapshot says the underlying cursor was already initialized, so initializeSeriesState correctly treats it as "already past the start position," same as the live cursor it was captured from.
type StateStore ¶
type StateStore interface {
GetSeriesState(ctx context.Context, showTitle string) (*SeriesState, error)
UpdateSeriesState(ctx context.Context, state *SeriesState) error
RecordScheduleHistory(ctx context.Context, entries []ScheduleHistoryEntry) error
WasRecentlyScheduled(ctx context.Context, programID, channelID string, window time.Duration) (bool, error)
CleanupScheduleHistory(ctx context.Context, window time.Duration) (int64, error)
// GetCommittedOccurrence returns the program assignment previously
// committed for one occurrence of blockName starting at
// occurrenceStart, if any -- see Engine.PlanBlock's doc comment for
// why this is the mechanism behind idempotent apply for filter blocks
// (and for an aired series block occurrence). ok is false when no such
// occurrence has ever been committed.
GetCommittedOccurrence(ctx context.Context, blockName string, occurrenceStart time.Time) (programs []tunarr.Program, ok bool, err error)
// GetOccurrenceSnapshot returns the pre/post cursor snapshot captured
// when a series block's occurrence (blockID, occurrenceStart) was
// planned -- see OccurrenceSnapshot's and
// Engine.planSeriesOccurrences' doc comments. ok is false when this
// occurrence has never been planned before (or its snapshot was since
// invalidated). Keyed by blockID (the block's stable store UUID,
// scheduler.Block.ID) rather than the block's name, which is
// renameable -- a rename must not orphan a not-yet-aired occurrence's
// stored cursor snapshot.
GetOccurrenceSnapshot(ctx context.Context, blockID string, occurrenceStart time.Time) (snapshot OccurrenceSnapshot, ok bool, err error)
// SaveOccurrenceSnapshot persists a series block occurrence's pre/post
// cursor snapshot, refreshing its RecordedAt commit stamp. It is an
// upsert: the first time an occurrence is planned this creates its
// row, and re-deriving a not-yet-aired occurrence (see
// planSeriesOccurrences' chain mechanism) overwrites it with the
// occurrence's new baseline and post-state -- carried forward from
// whatever the block's PRECEDING occurrence actually ended up at, not
// necessarily what was stored before. An aired occurrence's snapshot,
// once written, is never touched again (aired occurrences aren't
// re-derived at all).
SaveOccurrenceSnapshot(ctx context.Context, blockID string, occurrenceStart time.Time, snapshot OccurrenceSnapshot) error
// CleanupOccurrenceSnapshots deletes snapshot rows for occurrences that
// started more than window before now. Since v0.5.7 window comes from
// its own config knob (maintenance.snapshot_retention,
// EngineOptions.SnapshotRetention) rather than the history window,
// though the default value is the same: a snapshot for an occurrence
// outside the SCHEDULE-HISTORY window can never be re-derived (its
// schedule_history rows, if any, are gone too), so setting snapshot
// retention longer than history retention keeps rows that serve no
// purpose. Returns the number of rows deleted.
CleanupOccurrenceSnapshots(ctx context.Context, window time.Duration) (int64, error)
// DeleteFutureOccurrenceSnapshots deletes every occurrence snapshot for
// blockID with occurrence_start > now. Used whenever a pending
// occurrence's cached SEED itself must be overridden -- an operator
// cursor write (api.PatchSeriesState, the CLI's `state set`/`state
// reset`/`state import`) -- plus api.DeleteBlock's orphan cleanup,
// so the next apply treats those occurrences as unseen again and
// re-derives them from current state/spec. Spec EDITS deliberately
// do NOT call this: a pending occurrence already re-derives from its
// preserved seed + the CURRENT spec on every apply, and deleting the
// seed turned "same episodes, new arrangement" into "skip to the
// live cursor" (the v0.2.3 live bug -- see api.UpdateBlock's doc
// comment).
DeleteFutureOccurrenceSnapshots(ctx context.Context, blockID string, now time.Time) error
// MaxPlanSeq returns the highest plan-provenance sequence recorded
// anywhere in the store -- across both series_occurrence_snapshots.
// plan_seq and series_state.cursor_plan_seq -- or 0 when none exists.
// Engine construction seeds its sequence allocator's floor from this
// (see Engine.nextPlanSeq), so newly allocated sequences always
// outrank every stored one even after a backward wall-clock step or
// an import that carried a clock-ahead cursor_plan_seq; without the
// floor, either would wedge the provenance guard (every replay <=
// live provenance, silently dropped) until the clock caught up.
MaxPlanSeq(ctx context.Context) (int64, error)
// ReservePlanSeqBlock atomically reserves count consecutive
// plan-provenance sequences and returns the first and last of them.
// Nothing else -- in this process or any other sharing the database --
// can be handed a sequence in that range.
//
// MaxPlanSeq alone is a floor OBSERVED, which is sound for one process
// and unsound for two: `serve` and a concurrent `generate --apply` can
// both read it before either commits, allocate from the same
// nanosecond neighborhood, and the second commit is then silently
// discarded by the provenance guard in syncPostStates.
ReservePlanSeqBlock(ctx context.Context, count int64) (first, last int64, err error)
// ReplaceOccurrenceHistory atomically replaces every schedule_history
// row for one occurrence (blockName, occurrenceStart) with entries --
// used when a not-yet-aired series occurrence is re-derived against a
// possibly-changed block spec, so its stored assignment (and any
// re-derivation after it, via GetCommittedOccurrence once it airs)
// reflects the latest re-derivation rather than accumulating stale
// rows from every prior one. Still keyed by blockName (unlike the
// occurrence snapshot table): schedule_history is out of scope for
// the blockID rekey, see store/sqlite.go's schema doc comment.
ReplaceOccurrenceHistory(ctx context.Context, blockName string, occurrenceStart time.Time, entries []ScheduleHistoryEntry) error
}
StateStore defines the interface for persisting series state.
type Warning ¶ added in v0.2.2
type Warning struct {
BlockName string // the block whose occurrence was dropped
OccurrenceStart time.Time // that occurrence's cron-computed start time
BlockingBlockName string // the block whose occurrence it lost to
ChannelID string // the channel both occurrences contended for
DurationMinutes int // how long the dropped occurrence would have run
}
Warning describes one occurrence GenerateForTimeRange planned a time slot for but then had to drop, because a higher- (or equal-, first-come) priority occurrence on the same channel overlapped it (see resolveConflicts). Previously this was only visible in a server-side INFO log line ("scheduling conflict - block blocked by higher priority") -- API callers (POST /generate, POST /apply) had no way to know an occurrence they might have expected never actually got scheduled.