store

package
v0.5.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package store provides persistence for scheduling state.

Index

Constants

View Source
const (
	ApplySourceUI      = "ui"
	ApplySourceCron    = "cron"
	ApplySourceCLI     = "cli"
	ApplySourceUnknown = "unknown"
)

Sources an apply can come from. Recorded verbatim in apply_runs.source and rendered as the RUNS pane's badge. An apply whose caller passed no source records ApplySourceUnknown rather than failing: a missing label is a code defect to notice later, never a reason to refuse to push a lineup.

View Source
const (
	ApplyStatusRunning = "running"
	ApplyStatusOK      = "ok"
	ApplyStatusError   = "error"
)

Statuses an apply run passes through. A row is written as ApplyStatusRunning before the apply touches Tunarr and finalized to OK or Error afterwards -- a row still at Running means the process died mid-apply, which the page shows rather than hides.

Variables

View Source
var ErrBackwardRange = errors.New("a history range's from must not be after its to")

ErrBackwardRange is returned when From is after To.

View Source
var ErrConflict = errors.New("conflict")

ErrConflict indicates a uniqueness constraint was violated (e.g. duplicate name).

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound indicates the requested record does not exist.

View Source
var ErrShowStillScheduled = errors.New("show is still scheduled by a block")

ErrShowStillScheduled is returned by RemoveShow when a block still lists the show. Callers turn it into a 409 naming BlockNames.

View Source
var ErrUnboundedRange = errors.New("a history range needs at least one of from or to")

ErrUnboundedRange is returned when neither end of the window is set.

Functions

func InvalidationCutoff added in v0.2.2

func InvalidationCutoff(now time.Time, spec scheduler.Block) time.Time

InvalidationCutoff returns the "now" DeleteFutureOccurrenceSnapshots should be called with to invalidate every occurrence of a block (spec) that hasn't FINISHED yet -- not just ones that haven't STARTED yet. DeleteFutureOccurrenceSnapshots deletes rows with occurrence_start > cutoff; passing now - (duration + max overflow) makes that condition equivalent to "still airing, or entirely in the future," instead of "hasn't started." MaxDurationOverflowMinutes is part of the airing envelope: a block whose actual content legitimately runs past its nominal duration (see scheduler.Block.MaxDurationOverflowMinutes) can still be on air during the overflow, and its snapshot must not survive the invalidation just because the nominal duration already elapsed.

Without the widening past "hasn't started," invalidating a show's (or block's) occurrence snapshots while one of its occurrences is CURRENTLY on air never touches that specific occurrence's own snapshot at all: its occurrence_start is already in the past by definition, so a plain "occurrence_start > now" cutoff always excludes it. The on-air occurrence then keeps feeding its stale pre-change post-state into the chain (and, if the operator-wins guard in scheduler.Engine. syncPostStates were ever the only defense, contending with the live cursor) until it finishes airing on its own and a later occurrence finally picks up the change. Every caller that invalidates snapshots outside the normal apply flow needs this: an operator's PATCH /state/series (internal/api/state.go), a block DELETE's orphan cleanup (internal/api/blocks.go -- spec EDITS deliberately don't invalidate at all, see api.UpdateBlock's doc comment), and the CLI's `schedularr state reset`/`state set`/`state import` (cmd/state.go, via InvalidateSeriesOccurrenceSnapshots below).

Types

type ApplyRun added in v0.5.7

type ApplyRun struct {
	ID           string     `db:"id"`
	StartedAt    time.Time  `db:"started_at"`
	FinishedAt   *time.Time `db:"finished_at"`
	Source       string     `db:"source"`
	Scope        string     `db:"scope"`
	Days         int        `db:"days"`
	Status       string     `db:"status"`
	ChannelCount int        `db:"channel_count"`
	SlotCount    int        `db:"slot_count"`
	Error        string     `db:"error"`

	Warnings []ApplyRunWarning `db:"-"`
}

ApplyRun is one recorded apply. Scope is the channel ID an apply was narrowed to, or "" for every channel -- the same value service.Options.ChannelID carries. Warnings is hydrated by ListApplyRuns and written by FinishApplyRun; it is not a column.

type ApplyRunWarning added in v0.5.7

type ApplyRunWarning struct {
	RunID             string    `db:"run_id"`
	BlockName         string    `db:"block_name"`
	OccurrenceStart   time.Time `db:"occurrence_start"`
	BlockingBlockName string    `db:"blocking_block_name"`
	ChannelID         string    `db:"channel_id"`
	DurationMinutes   int       `db:"duration_minutes"`
}

ApplyRunWarning is the persisted form of scheduler.Warning: one occurrence that was planned a slot and then dropped because a higher- (or equal-, first-come) priority occurrence on the same channel overlapped it. ChannelID and DurationMinutes are the enrichment the page needs to say what would have aired and where, without re-deriving the block spec.

type BlockRecord

type BlockRecord struct {
	ID      string // uuid string
	Name    string // unique
	Enabled bool
	// DisabledUntil suppresses this block from schedule generation until
	// the instant it names, after which the block returns on its own.
	// Independent of Enabled: a block is planned only when Enabled is true
	// AND it is not currently dark. Nil means no dark window; a value in
	// the past is stale data that no longer suppresses anything, so a
	// caller rendering a "dark" affordance must compare against now rather
	// than test for non-nil.
	DisabledUntil *time.Time
	Spec          scheduler.Block // full block definition
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

BlockRecord is the persisted representation of a scheduling block. Blocks are the API-editable source of truth for scheduling, replacing the static blocks previously defined in scheduler.yaml.

type HistoryRange added in v0.5.12

type HistoryRange struct {
	From      time.Time
	To        time.Time
	ChannelID string
	BlockName string
	ShowTitle string
}

HistoryRange selects airings for counting or deletion: a time window, optionally narrowed to one channel, block, or show.

The window is over scheduled_at, NOT occurrence_start. That is the axis GET /history filters on and the axis the AS-RUN pane groups its days by, so a dry run counts the rows the operator is actually looking at. A range measured on the other column would preview one set and delete another, and they would confirm against the wrong number.

A zero From means "everything up to To"; a zero To means "everything from From onward". Both zero is refused rather than treated as "all history": a destructive default with no operator intent behind it is how an accident happens.

type RemovalReport added in v0.5.11

type RemovalReport struct {
	SeriesStates int64
	Airings      int64
	Snapshots    int64
	EmptiedSlots int64
}

RemovalReport counts what a removal actually touched, per table.

type ShowStillScheduledError added in v0.5.11

type ShowStillScheduledError struct {
	ShowTitle  string
	BlockNames []string
}

ShowStillScheduledError carries which blocks are keeping a show alive.

func (*ShowStillScheduledError) Error added in v0.5.11

func (e *ShowStillScheduledError) Error() string

func (*ShowStillScheduledError) Unwrap added in v0.5.11

func (e *ShowStillScheduledError) Unwrap() error

type StorageCounts added in v0.5.12

type StorageCounts struct {
	SeriesStates int64
	Airings      int64
	Sentinels    int64
	Snapshots    int64
	ApplyRuns    int64
	Warnings     int64

	OldestAiring *time.Time
	NewestAiring *time.Time
}

StorageCounts is what is ACTUALLY stored, per table, right now.

It reports rows, never policy. Retention says what should age out; a database whose retention was widened, or that has been running since before a knob existed, holds whatever it holds. Reporting the configured window here would be reporting an intention as a measurement -- the same failure the guide's draft mode refuses when it words every verdict "vs the reading taken at HH:MM".

OldestAiring and NewestAiring are nil on an empty table. They cost one MIN/MAX in the same pass and they are what makes the range-cleanup form pickable instead of a guess.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store implements the persistence layer for Schedularr.

func New

func New(dsn string) (*Store, error)

New creates a new Store instance connected to the specified SQLite database. dsn is augmented with sqliteDSNParams -- see its doc comment.

func (*Store) Backup

func (s *Store) Backup(ctx context.Context, destPath string) error

Backup creates a safe backup of the database to the specified path using VACUUM INTO.

func (*Store) CleanupApplyRuns added in v0.5.7

func (s *Store) CleanupApplyRuns(ctx context.Context, window time.Duration) (int64, error)

CleanupApplyRuns deletes runs that started more than window ago, and their warnings. Warnings go first and explicitly: foreign keys are not enabled on this database (see sqliteDSNParams), so a declared cascade would be inert and the rows would leak. Returns the number of RUNS deleted -- the unit the operator counts in.

func (*Store) CleanupOccurrenceSnapshots added in v0.2.2

func (s *Store) CleanupOccurrenceSnapshots(ctx context.Context, window time.Duration) (int64, error)

CleanupOccurrenceSnapshots deletes occurrence snapshot rows written (recorded_at, refreshed on every upsert) more than window ago, mirroring CleanupScheduleHistory's retention window and, like it, keying off a real-wall-clock write timestamp rather than occurrence_start -- see the recorded_at column's doc comment in migration 000005 for why. Returns the number of rows deleted.

func (*Store) CleanupScheduleHistory

func (s *Store) CleanupScheduleHistory(ctx context.Context, window time.Duration) (int64, error)

CleanupScheduleHistory removes schedule history entries older than the window.

func (*Store) Close

func (s *Store) Close() error

Close closes the database connection.

func (*Store) CountBlocks

func (s *Store) CountBlocks(ctx context.Context) (int64, error)

CountBlocks returns the total number of blocks.

func (*Store) CountHistoryRange added in v0.5.12

func (s *Store) CountHistoryRange(ctx context.Context, r HistoryRange) (RemovalReport, error)

CountHistoryRange reports what DeleteHistoryRange would remove, without removing it. This is the dry run every destructive confirm is built on.

func (*Store) CountShowRemoval added in v0.5.12

func (s *Store) CountShowRemoval(ctx context.Context, showTitle string) (RemovalReport, error)

CountShowRemoval reports what RemoveShow would remove, without removing it -- the dry run every destructive confirm is built on.

It runs the SAME refusal check first: a preview that promised a removal the real call would refuse is worse than no preview, because the operator would meet the 409 only after confirming.

func (*Store) CreateBlock

func (s *Store) CreateBlock(ctx context.Context, rec *BlockRecord) error

CreateBlock inserts a new block, setting CreatedAt/UpdatedAt. Returns ErrConflict if a block with the same name already exists.

func (*Store) CreateBlocks added in v0.2.4

func (s *Store) CreateBlocks(ctx context.Context, recs []*BlockRecord) error

CreateBlocks inserts every record in recs in a single transaction: either all of them are persisted or none are, mirroring RecordScheduleHistory's and ImportSeriesStates' transactional pattern (sqlite.go). This is what makes POST /blocks/import all-or-nothing even when a concurrent create races past the handler's pre-existing-name check: the racing name's unique-constraint violation rolls the whole batch back instead of leaving earlier blocks from the same request half-imported. Returns ErrConflict when any record's name already exists (or duplicates another record in the same batch).

func (*Store) DeleteBlock

func (s *Store) DeleteBlock(ctx context.Context, id string) error

DeleteBlock removes a block by ID. Returns ErrNotFound if it does not exist.

func (*Store) DeleteFutureOccurrenceSnapshots added in v0.2.2

func (s *Store) DeleteFutureOccurrenceSnapshots(ctx context.Context, blockID string, now time.Time) error

DeleteFutureOccurrenceSnapshots deletes every occurrence snapshot for blockID with occurrence_start > now -- see the interface doc comment (internal/scheduler/interfaces.go) for when and why callers do this.

func (*Store) DeleteHistoryRange added in v0.5.12

func (s *Store) DeleteHistoryRange(ctx context.Context, r HistoryRange) (RemovalReport, error)

DeleteHistoryRange removes the airings a range selects, in ONE transaction, keeping every occurrence it empties committed.

IT DOES NOT TOUCH SNAPSHOTS OR CURSORS. A date range is not a statement about any particular show, and a snapshot describes one occurrence of one block that may have carried several. Removing a show's progression is RemoveShow's job, and it scrubs the snapshot keys itself; snapshots outside that flow age out on maintenance.snapshot_retention.

AN EMPTIED OCCURRENCE KEEPS ITS SENTINEL, for the reason RemoveShow's doc comment gives: without it GetCommittedOccurrence answers "never planned" and the next apply re-plans a slot that already went out.

func (*Store) ExportAllSeriesStates

func (s *Store) ExportAllSeriesStates(ctx context.Context) ([]scheduler.SeriesState, error)

ExportAllSeriesStates exports all series states to a slice for backup/export.

func (*Store) FinishApplyRun added in v0.5.7

func (s *Store) FinishApplyRun(ctx context.Context, run ApplyRun) error

FinishApplyRun finalizes run's outcome and persists its warnings, in one transaction: a run whose counts landed but whose warnings did not would understate what the apply dropped.

func (*Store) GetBlock

func (s *Store) GetBlock(ctx context.Context, id string) (*BlockRecord, error)

GetBlock retrieves a block by ID. Returns ErrNotFound if it does not exist.

func (*Store) GetCommittedOccurrence added in v0.2.2

func (s *Store) GetCommittedOccurrence(ctx context.Context, blockName string, occurrenceStart time.Time) ([]tunarr.Program, bool, error)

GetCommittedOccurrence returns the program assignment previously committed for one occurrence of blockName starting at occurrenceStart, reconstructed in playback order from the persisted schedule_history rows -- see scheduler.ScheduleHistoryEntry's and Engine.PlanBlock's doc comments for why this is stored (and looked up) separately from the scheduled_at-keyed recency-dedup rows the same table already served.

func (*Store) GetOccurrenceSnapshot added in v0.2.2

func (s *Store) GetOccurrenceSnapshot(ctx context.Context, blockID string, occurrenceStart time.Time) (scheduler.OccurrenceSnapshot, bool, error)

GetOccurrenceSnapshot returns the pre/post cursor snapshot captured when a series block's occurrence (blockID, occurrenceStart) was planned. See scheduler.OccurrenceSnapshot's and scheduler.Engine.planSeriesOccurrences' doc comments for the mechanism. A NULL post_state_json (a legacy row written before migration 000006) comes back as a nil PostStates -- the marker the engine's aired branch treats as "no cursor advance of this occurrence's own to replay."

func (*Store) GetPersistedSeriesState

func (s *Store) GetPersistedSeriesState(ctx context.Context, showTitle string) (*scheduler.SeriesState, error)

GetPersistedSeriesState retrieves the tracking state for a given show, returning ErrNotFound if no row is persisted for it. This is the existence-aware counterpart to GetSeriesState: GetSeriesState always succeeds with a fabricated S01E01 default for an untracked show (useful for the scheduler engine, which needs a starting point regardless), which makes it unsuitable for callers that must map "unknown show" to a 404 -- currently the state API's PatchSeriesState handler (internal/api/state.go).

func (*Store) GetSeriesState

func (s *Store) GetSeriesState(ctx context.Context, showTitle string) (*scheduler.SeriesState, error)

GetSeriesState retrieves the tracking state for a given show. If no state exists, it returns a default starting state (S01E01).

func (*Store) ImportSeriesStates

func (s *Store) ImportSeriesStates(ctx context.Context, states []scheduler.SeriesState) error

ImportSeriesStates imports series states from a slice, replacing existing states. It is an operator write (the CLI's `state import` restoring a backup), so every imported row is stamped with a FRESH operator_updated_at -- the file's own stamp, if any, records when some PAST write happened, not this one, and a NULL/stale stamp would let the next apply's aired-occurrence replays silently re-advance the just-restored cursor (see scheduler.SeriesState.OperatorUpdatedAt). cursor_plan_seq is taken from the file (typically 0/absent for backups): provenance protection for imports comes from the operator stamp, and plans made after the import allocate fresh, higher sequences regardless.

func (*Store) InvalidateSeriesOccurrenceSnapshots added in v0.2.2

func (s *Store) InvalidateSeriesOccurrenceSnapshots(ctx context.Context, showTitle string) error

InvalidateSeriesOccurrenceSnapshots deletes every not-yet-FINISHED occurrence snapshot (see InvalidationCutoff) for every block whose Series config references showTitle -- the store-level mechanism behind every caller that changes a show's series_state outside the normal apply flow and needs its not-yet-aired (and on-air) occurrences to re-derive against the new value instead of a stale cached snapshot: api.PatchSeriesState (internal/api/state.go) and the CLI's `schedularr state reset`/`state set`/`state import` (cmd/state.go) all call this directly; api.DeleteBlock (internal/api/blocks.go) invalidates by block ID directly instead, since it already knows exactly which block is gone and doesn't need this show-title-based lookup. Spec edits (api.UpdateBlock) invalidate nothing -- see its doc comment for why the seed must survive an edit.

Matches by scanning every block's Spec.Series (there is no reverse index from show_title to block IDs; the blocks table is small enough -- one row per configured block -- that a full scan on an infrequent operator/CLI action like this is the right tradeoff over adding one).

func (*Store) LastApplyAt added in v0.5.0

func (s *Store) LastApplyAt(ctx context.Context) (*time.Time, error)

LastApplyAt returns when the most recent apply pushed a lineup to Tunarr, or nil when no apply has been recorded (a fresh install, or a database predating migration 000009 with no apply since). Feeds GET /status's last_applied_at field (internal/api/tunarr.go's GetStatus).

func (*Store) ListAppliedChannels added in v0.2.4

func (s *Store) ListAppliedChannels(ctx context.Context) ([]string, error)

ListAppliedChannels returns the channel IDs a previous apply pushed a lineup to and that have not been cleared since, ordered for determinism.

func (*Store) ListApplyRuns added in v0.5.7

func (s *Store) ListApplyRuns(ctx context.Context, since time.Time, limit int) ([]ApplyRun, error)

ListApplyRuns returns runs started at or after since, newest first, at most limit of them, each with its warnings hydrated. Warnings are read in one second query and bucketed by run ID rather than one query per run -- a 90-day window at the cron default is a few hundred runs, and N+1 queries over that is gratuitous.

func (*Store) ListBlocks

func (s *Store) ListBlocks(ctx context.Context) ([]BlockRecord, error)

ListBlocks returns all blocks ordered by name.

func (*Store) ListScheduleHistory

func (s *Store) ListScheduleHistory(ctx context.Context, since time.Time) ([]scheduler.ScheduleHistoryEntry, error)

ListScheduleHistory returns schedule history entries scheduled at or after since, ordered by scheduled_at DESC (most recent first). This backs the GET /history API endpoint (internal/api/history.go), which maps a caller-supplied days window to since = now - days.

func (*Store) MarkChannelApplied added in v0.2.4

func (s *Store) MarkChannelApplied(ctx context.Context, channelID string, at time.Time) error

MarkChannelApplied records that an apply pushed a lineup to channelID at the given time, upserting the applied_channels row. The set of marked channels is what clearStaleChannels (internal/service) consults to find channels whose blocks have all since been deleted or disabled -- see migration 000008's comment for the full rationale.

func (*Store) MaxPlanSeq added in v0.2.2

func (s *Store) MaxPlanSeq(ctx context.Context) (int64, error)

MaxPlanSeq returns the highest plan-provenance sequence recorded anywhere in the store -- see StateStore.MaxPlanSeq's doc comment (internal/scheduler/interfaces.go) for why engine construction seeds its allocator floor from this.

func (*Store) Ping

func (s *Store) Ping(ctx context.Context) error

Ping verifies the database connection is live by executing a trivial `SELECT 1` round-trip, rather than sql.DB's own PingContext (which some drivers implement as a no-op connection check rather than an actual query). Used by the API server's /readyz endpoint (internal/api/router.go) to report readiness -- distinct from process liveness, which /healthz reports without touching the store at all.

func (*Store) RecordScheduleHistory

func (s *Store) RecordScheduleHistory(ctx context.Context, entries []scheduler.ScheduleHistoryEntry) error

RecordScheduleHistory persists schedule history entries for future filtering.

func (*Store) RemoveShow added in v0.5.11

func (s *Store) RemoveShow(ctx context.Context, showTitle string) (RemovalReport, error)

RemoveShow deletes every trace of one show's progression from the store, in ONE transaction: its series_state cursor, its airings in schedule_history, and its keys inside every occurrence snapshot.

IT REFUSES WHILE A BLOCK STILL LISTS THE SHOW. backfillChainFromLive re-adds any block.Series title missing from the chain, seeded from a fabricated S01E01 -- so a removal that ran anyway would be undone by the next apply AND would reset the cursor it just deleted. Rewriting the operator's block specs from a history deletion was the alternative, and it is far too large a blast radius for one click: it can empty a block entirely. Refusing tells them exactly which blocks to edit first.

SNAPSHOTS LOSE A KEY, NOT A ROW. A snapshot describes one occurrence of one block, which may have carried several shows; deleting the row would take the others with it. The two JSON maps are rewritten in place by a direct UPDATE rather than through SaveOccurrenceSnapshot, whose upsert sets plan_seq = excluded.plan_seq and would rewrite the provenance of an occurrence that already aired.

A NULL post_state_json STAYS NULL. Turning it into "{}" flips replayAiredOccurrence from "re-seed the chain from live state" to "apply nothing", which silently changes behavior for every OTHER title in that occurrence.

AN EMPTIED OCCURRENCE KEEPS ITS SENTINEL. Deleting the last airing of an occurrence would leave GetCommittedOccurrence answering "never planned", and the next apply would re-plan a slot that has already gone out -- rewriting history rather than removing from it. The empty-ProgramID sentinel row keeps it "committed, produced nothing", which is what actually happened.

No endpoint calls this yet; the UI that drives it is the next slice.

func (*Store) ReplaceOccurrenceHistory added in v0.2.2

func (s *Store) ReplaceOccurrenceHistory(ctx context.Context, blockName string, occurrenceStart time.Time, entries []scheduler.ScheduleHistoryEntry) error

ReplaceOccurrenceHistory atomically replaces every schedule_history row for one occurrence (blockName, occurrenceStart) with entries -- see its interface doc comment (internal/scheduler/interfaces.go) for why a re-derived series occurrence needs replacement rather than the append-only insert RecordScheduleHistory does for a first-time plan.

func (*Store) ReservePlanSeqBlock added in v0.5.11

func (s *Store) ReservePlanSeqBlock(ctx context.Context, count int64) (first, last int64, err error)

ReservePlanSeqBlock atomically reserves `count` consecutive plan sequences and returns the first and last of them. No other caller, in this process or any other, can be handed a sequence in that range.

One statement, not a read-then-write transaction: transactions in this package are DEFERRED, so a read that later upgrades to a write can hit SQLITE_BUSY on the upgrade rather than waiting out the busy timeout -- the classic SQLite deadlock. An upsert with RETURNING sidesteps it.

The reserved range starts at max(stored, wall clock), so the sequence keeps the property its original design chose it for: it moves forward with real time, and cannot be dragged backwards by a stale row. Both sides of that comparison are CAST to INTEGER because app_meta.value is TEXT, where '9' > '10'.

func (*Store) ResetSeriesState

func (s *Store) ResetSeriesState(ctx context.Context, showTitle string) error

ResetSeriesState resets a series to its starting state (S01E01, not completed). It is an operator write (the CLI's `state reset`), so it stamps operator_updated_at -- see scheduler.SeriesState.OperatorUpdatedAt for what that protects.

func (*Store) SaveOccurrenceSnapshot added in v0.2.2

func (s *Store) SaveOccurrenceSnapshot(ctx context.Context, blockID string, occurrenceStart time.Time, snapshot scheduler.OccurrenceSnapshot) error

SaveOccurrenceSnapshot persists a series block occurrence's pre/post cursor snapshot, stamping recorded_at with the current wall clock (the snapshot's own RecordedAt field is ignored on write -- the store owns the commit stamp). It upserts: a not-yet-aired occurrence's snapshot can be rewritten when an earlier occurrence of the same block is re-derived and its actual end-state is carried forward as this occurrence's new baseline (see Engine.planSeriesOccurrences' chain mechanism) -- so a second call for the same (blockID, occurrenceStart) is expected, not a bug. An aired occurrence's snapshot is never written to again because aired occurrences are never re-derived in the first place -- which is exactly what freezes recorded_at at the plan the occurrence actually aired with, the commit stamp Engine.syncPostStates' operator-wins guard compares against.

func (*Store) SetLastApplyAt added in v0.5.0

func (s *Store) SetLastApplyAt(ctx context.Context, at time.Time) error

SetLastApplyAt records at (normalized to UTC, second precision) as the most recent apply instant, upserting the app_meta row. Written by service.Runner.applyChannels at the end of any apply that pushed at least one lineup -- deliberately NOT derived from applied_channels, whose rows are a tracking set that clearStaleChannels removes again (see migration 000009's comment for the full rationale).

func (*Store) SetSeriesState

func (s *Store) SetSeriesState(ctx context.Context, showTitle string, season, episode int) error

SetSeriesState sets a series to a specific season and episode. If the series doesn't exist, it creates a new entry. It is an operator write (the CLI's `state set`), so it stamps operator_updated_at -- see scheduler.SeriesState.OperatorUpdatedAt for what that protects.

func (*Store) StartApplyRun added in v0.5.7

func (s *Store) StartApplyRun(ctx context.Context, run ApplyRun) error

StartApplyRun writes run as an in-flight record. Called before the apply pushes anything to Tunarr so that a crash mid-apply still leaves evidence the apply was attempted, and so the schedule_history rows written during the apply reference a row that already exists.

func (*Store) StorageCounts added in v0.5.12

func (s *Store) StorageCounts(ctx context.Context) (StorageCounts, error)

StorageCounts counts every table that grows with time.

func (*Store) UnmarkChannelApplied added in v0.2.4

func (s *Store) UnmarkChannelApplied(ctx context.Context, channelID string) error

UnmarkChannelApplied removes channelID from the applied set -- called after a stale channel's lineup has been cleared, so it is cleared exactly once and a later manual takeover of the channel in Tunarr is never clobbered by subsequent applies. Removing an ID that is not present is a no-op, not an error.

func (*Store) UpdateBlock

func (s *Store) UpdateBlock(ctx context.Context, rec *BlockRecord) error

UpdateBlock updates an existing block's fields and bumps UpdatedAt. Returns ErrNotFound if no block with the given ID exists, or ErrConflict if the update would violate the unique name constraint.

Every column is written from rec, so a nil DisabledUntil CLEARS any dark window the stored row still carries. Callers that mean "leave the dark window alone" must read the record first and carry the field forward -- the same whole-record contract Name, Enabled and Spec already have.

func (*Store) UpdateSeriesState

func (s *Store) UpdateSeriesState(ctx context.Context, state *scheduler.SeriesState) error

UpdateSeriesState updates or inserts the tracking state for a show. operator_updated_at is written from the struct like any other column: operator entry points (api.PatchSeriesState) stamp it before calling this, while the engine's Commit only ever writes clones of the state it read, so the stamp rides through engine writes unchanged.

func (*Store) WasRecentlyScheduled

func (s *Store) WasRecentlyScheduled(ctx context.Context, programID, channelID string, window time.Duration) (bool, error)

WasRecentlyScheduled returns true if a program was scheduled within the provided window.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL