Documentation
¶
Overview ¶
Package service hosts the schedule-generation workflow shared by the CLI (cmd/generate.go) and the HTTP API (internal/api/schedule.go): loading the active scheduling blocks, fetching available Tunarr content, running the scheduling engine over a time window, and -- when asked -- pushing the result to Tunarr and committing engine state.
This package is a straight extraction of what cmd/generate.go used to do inline (see git history for ProcessSchedule and its helpers): the scheduling logic itself (block loading, content fetching, engine invocation, apply) is unchanged. What did change, because this code now also runs inside a long-lived API server rather than a one-shot CLI process, is presentation and lifecycle: colored fmt.Printf progress output became slog calls, context.Background() became the caller's ctx, and the CLI's per-invocation (and therefore always-empty) content cache became a Runner-scoped one that actually gets reused across calls.
Index ¶
Constants ¶
const ( SourceUI = store.ApplySourceUI SourceCron = store.ApplySourceCron SourceCLI = store.ApplySourceCLI )
Sources an apply can be attributed to, mirrored from the store's constants so callers outside internal/store name them in service terms.
Variables ¶
This section is empty.
Functions ¶
func ActiveBlocks ¶
ActiveBlocks returns the Spec of every enabled block in the store. scheduler.yaml is import-only (see blockio.Bootstrap): the store is the engine's live source of scheduling truth, and disabled blocks stay defined but out of schedule generation. Moved here from cmd/generate.go's loadActiveBlocks so both the CLI and the API server share one implementation.
Types ¶
type MediaMeta ¶ added in v0.2.0
MediaMeta is the distinct set of genre and rating values observed across every program (movies and episodes alike) in Tunarr's synced library, each sorted ascending.
type MediaShow ¶ added in v0.2.0
MediaShow is one distinct TV show observed in Tunarr's synced library: Title is the show's grouping key (tunarr.Program.ShowTitle) and EpisodeCount is how many Type == "episode" programs in the fetched library carry that title.
type Options ¶
type Options struct {
Days int
ChannelID string
Apply bool
// Source attributes an apply to the surface that asked for it -- one
// of SourceUI, SourceCron, SourceCLI -- and is recorded on the run.
// Ignored on a dry run. An empty Source on an apply records
// store.ApplySourceUnknown: a missing label is a defect to notice in
// the history page's RUNS pane, never a reason to refuse to push a
// lineup.
Source string
}
Options configures a single Run. Days is the number of 24h days ahead of now to generate a schedule for; callers (the API's handlers, cmd/generate.go) are responsible for validating it (the API restricts it to 1..30) -- Run does not re-validate it. ChannelID, when non-empty, restricts which blocks are planned at all -- see Run's doc comment for why that matters beyond just narrowing the returned/pushed result. Apply gates whether Run mutates anything: false is a pure dry-run (no UpdateSchedule calls, no Engine.Commit()).
type Result ¶
type Result struct {
Applied bool
Channels map[string][]scheduler.ScheduledSlot
Warnings []scheduler.Warning
// RunID is the apply run this Run was recorded as
// (store.ApplyRun.ID), or "" on a dry run -- a dry run applies
// nothing, so it has no run to claim.
RunID string
}
Result is what Run produces: the generated (and, if Applied, pushed) schedule, keyed by Tunarr channel ID. Warnings lists every occurrence GenerateForTimeRange planned a time slot for but then had to drop (conflict resolution -- see scheduler.Warning's doc comment); it can be non-empty on both a dry run and an apply, since conflict resolution happens during generation either way. Nil (not just empty) when there's nothing to report.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner executes the schedule-generation workflow against a store and a Tunarr client held for its lifetime.
func NewRunner ¶
NewRunner builds a Runner backed by st and tc. o.Logger and o.Location default to slog.Default() and time.Local respectively when nil, matching scheduler.NewEngine's own nil-handling.
func (*Runner) MediaMeta ¶ added in v0.2.0
MediaMeta returns the distinct genre and rating values observed across every fetched program, each sorted ascending. Like MediaShows, it reuses fetchPrograms exactly -- the same fetch+cache path, no separate one -- so a MediaShows call and a MediaMeta call against a warm cache share one underlying library snapshot and issue no Tunarr HTTP requests between them.
Unlike genres (tunarr.Program.Genres, tagged "genres" and populated for both movie and episode entries directly -- live-verified this session), a live Tunarr "episode" result carries no rating of its own at all -- only its show does, via the ShowID join MediaShows' doc comment describes (fetchPrograms -> hydrateShowsAndSeasons -> hydrateShowTitleAndRating in schedule.go). So episodes contribute to Ratings here exactly like movies do once that join runs -- this reads the same join's output, not a second implementation of it. Note this aggregate can also pick up a rating directly from a Type == "show" entry itself (those pass through fetchPrograms' returned slice unfiltered, and this loop reads every program's Rating, not just episodes') -- harmless for this method's purpose (it only cares about the distinct set of ratings observed), but worth knowing if you're trying to prove the join specifically: see internal/service/schedule_test.go's TestRunner_hydrateShowTitleAndRating for a test that isolates it.
func (*Runner) MediaShows ¶ added in v0.2.0
MediaShows returns every distinct show Runner's fetchPrograms sees, sorted by title, with each show's episode count. It calls fetchPrograms directly -- the same fetch-then-cache path Run uses to build its scheduling candidate pool (fetchLibraryPrograms, falling back to fetchAllProgramsViaSearch, cached for contentCacheDuration) -- rather than standing up a second cache or a second fetch shape: a MediaShows call served from a warm cache costs nothing beyond the grouping below, and a call that primes the cache (or finds it already primed by a prior Run/MediaMeta call) makes every one of those callers see the same library snapshot for the rest of the cache's lifetime.
Only Type == "episode" programs are grouped; a movie has no show to belong to. A program whose ShowTitle is empty is skipped rather than folded into a bogus "" show. tunarr.Program.ShowTitle is tagged `json:"showTitle,omitempty"` (internal/external/tunarr/models.go), which covers a flat-shaped fixture or test double directly. Against a real Tunarr instance, an episode result never carries a flat ShowTitle (or a nested "show" object -- an earlier round of this fix wrongly assumed one, see models.go's history) at all; it carries only a ShowID foreign key. fetchPrograms below (via fetchSingleLibrary/fetchAllProgramsViaSearch in schedule.go) runs every fetch through hydrateShowsAndSeasons, which joins that ShowID against the separate Type == "show" entries a live search interleaves in the same result stream, live-verified against a real Tunarr 1.3.13 instance this session (transcript in this task's report). So a program with an empty ShowTitle here means either Tunarr genuinely has no show data for it, or its ShowID didn't resolve to any show entry Tunarr returned -- not a client-side deserialization gap.
func (*Runner) Run ¶
Run executes one generate-(and-maybe-apply) cycle: load the active blocks (restricted to o.ChannelID's blocks when set -- see below), fetch available Tunarr content, run the scheduling engine over [now, now+o.Days days), and -- only when o.Apply is set -- push the result to Tunarr per channel and commit the engine's pending state. A dry run (o.Apply == false) never calls UpdateSchedule or Commit, so it cannot mutate the store or Tunarr.
o.ChannelID filtering happens to the *blocks*, before scheduler.Engine ever sees them -- not just to the result map after planning. This matters because Engine plans every block it's given: for each one it mutates in-memory pending state (series-cursor advances in pendingStates, "aired" rows in pendingHistory -- see planSeriesForConfig/recordHistory in engine.go) regardless of whether that block's channel ends up in the caller's requested scope. If filtering were applied only to Run's *return value* (as an earlier version of this function did), a channel-scoped Apply would still plan -- and Engine.Commit() would still persist -- every other channel's series cursors and history, even though nothing was pushed to Tunarr for them: series scheduling on untouched channels would silently skip episodes or wrongly dedup against history it never actually aired. Pre-filtering the blocks slice keeps planning itself scoped, so pendingStates/pendingHistory can only ever contain entries for blocks on the requested channel.
A ChannelID that matches no enabled block (typo, disabled, unknown channel) is not an error: blocks ends up empty, Engine plans nothing, and Run returns Result{Applied: o.Apply, Channels: <empty map>} with nothing planned or committed -- the same "well-formed request, nothing to schedule" treatment an empty result gets for any other reason. An error was considered (an unrecognized channel_id could reasonably be a caller mistake worth surfacing loudly), but Run has no channel registry to validate against here -- only Tunarr does, via GetChannels, which Run never calls -- so rejecting it would mean guessing at "known channels" from a source Run doesn't otherwise consult.
type RunnerOptions ¶ added in v0.5.7
type RunnerOptions struct {
Logger *slog.Logger
Location *time.Location
// HistoryRetention is forwarded unchanged to every scheduler.Engine
// Run builds (scheduler.EngineOptions.HistoryWindow) -- callers pass
// config.MaintenanceHistoryRetention(cfg) here (see cmd/generate.go,
// cmd/serve.go) so the engine's in-memory dedup window and its
// Commit-time schedule_history pruning both honor the configured
// maintenance.history_retention value instead of a hardcoded 7 days.
// Zero falls back to scheduler's own default (7 days) -- see
// scheduler.NewEngineWithOptions.
HistoryRetention time.Duration
// SnapshotRetention bounds occurrence-snapshot pruning
// (scheduler.EngineOptions.SnapshotRetention). Zero falls back to
// HistoryRetention, which is the single-knob behavior it was split
// out of.
SnapshotRetention time.Duration
// ApplyRunRetention bounds apply-run pruning, run after each
// successful apply. Zero disables it -- runs then accumulate until an
// operator prunes them, which is the honest behavior for an unset
// knob rather than silently picking a horizon.
ApplyRunRetention time.Duration
}
RunnerOptions carries a Runner's construction settings. A struct rather than more parameters: NewRunner was already at the five-argument lint ceiling before retention split per table.