Documentation
¶
Overview ¶
Package store provides persistence for scheduling state.
Index ¶
- Variables
- func InvalidationCutoff(now time.Time, spec scheduler.Block) time.Time
- type BlockRecord
- type Store
- func (s *Store) Backup(ctx context.Context, destPath string) error
- func (s *Store) CleanupOccurrenceSnapshots(ctx context.Context, window time.Duration) (int64, error)
- func (s *Store) CleanupScheduleHistory(ctx context.Context, window time.Duration) (int64, error)
- func (s *Store) Close() error
- func (s *Store) CountBlocks(ctx context.Context) (int64, error)
- func (s *Store) CreateBlock(ctx context.Context, rec *BlockRecord) error
- func (s *Store) DeleteBlock(ctx context.Context, id string) error
- func (s *Store) DeleteFutureOccurrenceSnapshots(ctx context.Context, blockID string, now time.Time) error
- func (s *Store) ExportAllSeriesStates(ctx context.Context) ([]scheduler.SeriesState, error)
- func (s *Store) GetBlock(ctx context.Context, id string) (*BlockRecord, error)
- func (s *Store) GetCommittedOccurrence(ctx context.Context, blockName string, occurrenceStart time.Time) ([]tunarr.Program, bool, error)
- func (s *Store) GetOccurrenceSnapshot(ctx context.Context, blockID string, occurrenceStart time.Time) (scheduler.OccurrenceSnapshot, bool, error)
- func (s *Store) GetPersistedSeriesState(ctx context.Context, showTitle string) (*scheduler.SeriesState, error)
- func (s *Store) GetSeriesState(ctx context.Context, showTitle string) (*scheduler.SeriesState, error)
- func (s *Store) ImportSeriesStates(ctx context.Context, states []scheduler.SeriesState) error
- func (s *Store) InvalidateSeriesOccurrenceSnapshots(ctx context.Context, showTitle string) error
- func (s *Store) ListBlocks(ctx context.Context) ([]BlockRecord, error)
- func (s *Store) ListScheduleHistory(ctx context.Context, since time.Time) ([]scheduler.ScheduleHistoryEntry, error)
- func (s *Store) MaxPlanSeq(ctx context.Context) (int64, error)
- func (s *Store) Ping(ctx context.Context) error
- func (s *Store) RecordScheduleHistory(ctx context.Context, entries []scheduler.ScheduleHistoryEntry) error
- func (s *Store) ReplaceOccurrenceHistory(ctx context.Context, blockName string, occurrenceStart time.Time, ...) error
- func (s *Store) ResetSeriesState(ctx context.Context, showTitle string) error
- func (s *Store) SaveOccurrenceSnapshot(ctx context.Context, blockID string, occurrenceStart time.Time, ...) error
- func (s *Store) SetSeriesState(ctx context.Context, showTitle string, season, episode int) error
- func (s *Store) UpdateBlock(ctx context.Context, rec *BlockRecord) error
- func (s *Store) UpdateSeriesState(ctx context.Context, state *scheduler.SeriesState) error
- func (s *Store) WasRecentlyScheduled(ctx context.Context, programID, channelID string, window time.Duration) (bool, error)
Constants ¶
This section is empty.
Variables ¶
var ErrConflict = errors.New("conflict")
ErrConflict indicates a uniqueness constraint was violated (e.g. duplicate name).
var ErrNotFound = errors.New("not found")
ErrNotFound indicates the requested record does not exist.
Functions ¶
func InvalidationCutoff ¶ added in v0.2.2
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 or a block edit/delete (internal/api/state.go, internal/api/blocks.go -- a block EDIT must pass its PRE-edit spec, since the snapshots being invalidated were captured under the old airing envelope), and the CLI's `schedularr state reset`/`state set` (cmd/state.go, via InvalidateSeriesOccurrenceSnapshots below).
Types ¶
type BlockRecord ¶
type BlockRecord struct {
ID string // uuid string
Name string // unique
Enabled bool
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 Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store implements the persistence layer for Schedularr.
func New ¶
New creates a new Store instance connected to the specified SQLite database. dsn is augmented with sqliteDSNParams -- see its doc comment.
func (*Store) Backup ¶
Backup creates a safe backup of the database to the specified path using VACUUM INTO.
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 ¶
CleanupScheduleHistory removes schedule history entries older than the window.
func (*Store) CountBlocks ¶
CountBlocks returns the total number of blocks.
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) DeleteBlock ¶
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) ExportAllSeriesStates ¶
ExportAllSeriesStates exports all series states to a slice for backup/export.
func (*Store) GetBlock ¶
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 ¶
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
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` (cmd/state.go) both call this directly; api.UpdateBlock/DeleteBlock (internal/api/blocks.go) invalidate by block ID directly instead, since they already know exactly which block changed and don't need this show-title-based lookup.
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) 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) MaxPlanSeq ¶ added in v0.2.2
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 ¶
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) 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) ResetSeriesState ¶
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) SetSeriesState ¶
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) 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.
func (*Store) UpdateSeriesState ¶
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.