store

package
v0.0.0-...-952ad41 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: Unlicense Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CodeTaskCreated is emitted once when the create endpoint inserts a
	// task row for an accepted URI.
	CodeTaskCreated = "task.created"
	// CodeTaskPaused is emitted when the pause action moves a task into
	// the paused state.
	CodeTaskPaused = "task.paused"
	// CodeTaskResumed is emitted when the resume action requeues a paused
	// or errored task.
	CodeTaskResumed = "task.resumed"
	// CodeTaskRemoved is emitted when the delete endpoint tombstones a
	// task.
	CodeTaskRemoved = "task.removed"
	// CodeTaskCompleted is emitted when a task reaches the completed
	// state on its own — an engine poll reporting the transfer finished.
	// A user-forced completion writes task.force_completed instead.
	CodeTaskCompleted = "task.completed"
	// CodeTaskDataDeleted is emitted when a removal also unlinked the
	// downloaded files.
	CodeTaskDataDeleted = "task.data_deleted"
	// CodeEngineAccepted is emitted when an engine returned a handle and
	// SetEngineRef recorded it — the moment the engine took ownership of
	// the transfer. It is emitted only when the handle changes: SetEngineRef
	// is its single writer, and a no-op re-set re-learns nothing. No caller
	// may also pass it as a Transition code, or one acceptance logs twice.
	CodeEngineAccepted = "engine.accepted"
	// CodeEngineRejected is emitted when an engine refused a task. No M1
	// code path reaches an engine refusal — POST /tasks contacts no engine
	// and the admission pass (T098) owns Engine.Add — so the emission
	// point arrives with that task.
	CodeEngineRejected = "engine.rejected"
	// CodeEngineUnavailable is emitted when a task's engine cannot be
	// reached at hand-off. Like engine.rejected, no M1 code path reaches
	// the moment; the admission pass (T098) wires it.
	CodeEngineUnavailable = "engine.unavailable"
)

Task-event codes emitted in M1. A code is <area>.<subject>[.<outcome>], lower case, ASCII letters, digits and dots only. Never rename or reuse a code: a rename orphans stored history rows.

View Source
const (
	PrefixUser                = "usr_"
	PrefixSession             = "ses_"
	PrefixAPIToken            = "tok_"
	PrefixSetting             = "set_"
	PrefixEngine              = "eng_"
	PrefixCategory            = "cat_"
	PrefixTag                 = "tag_"
	PrefixTaskTracker         = "ttr_"
	PrefixTaskEvent           = "evt_"
	PrefixIndexer             = "idx_"
	PrefixSearchJob           = "sch_"
	PrefixSearchResult        = "res_"
	PrefixFeed                = "fed_"
	PrefixFeedItem            = "itm_"
	PrefixTask                = "tsk_"
	PrefixNotificationChannel = "ntf_"
	PrefixRule                = "rul_"
	PrefixRuleMatch           = "mat_"
	PrefixJob                 = "job_"
	PrefixBandwidthCell       = "bws_"
	PrefixUIPref              = "uip_"
	PrefixWatchFolder         = "wfd_"
	PrefixTaskFile            = "tfi_"
)
View Source
const (
	EngineQueued    = "queued"
	EngineSearching = "searching"
	EngineDone      = "done"
	EngineError     = "error"
)

Engine status vocabulary of the wire contract.

View Source
const (
	EngineIDAria2       = EngineIDPrefix + "aria2"
	EngineIDQBittorrent = EngineIDPrefix + "qbittorrent"
	EngineIDYTDLP       = EngineIDPrefix + "ytdlp"
)

EngineIDs are the fixed row ids the API addresses engines by. The migration seeds no engines rows; the composition root creates them from the environment when an engine is configured.

View Source
const (
	CodeTaskSchedulePaused  = "task.schedule.paused"
	CodeTaskScheduleResumed = "task.schedule.resumed"
)

The task_events codes of the schedule park and release (T081): the parked set lives in the event log, not in a new column — task.schedule.paused on park and task.schedule.resumed on release, so the set survives a restart with no schema change. Declared next to their emitting code per docs/14-conventions.md section 4; their i18next keys are recorded in the task's Evidence because the locale file sits outside its Files table.

View Source
const CodeTaskDuplicatePaused = "task.duplicate_paused"

CodeTaskDuplicatePaused is the task_events code of the pause that lands when a duplicate is discovered after metadata resolved: the transfer is paused in place and nothing is deleted (FR-023).

View Source
const DefaultIndexerPriority = 50

DefaultIndexerPriority is the documented create-time default. The API layer applies it explicitly so an intentional 0 still round-trips verbatim.

View Source
const EngineIDPrefix = PrefixEngine

EngineIDPrefix pairs with the engine kinds to form the stable row ids of the engines table: eng_aria2, eng_qbittorrent, eng_ytdlp (docs/05-api-contract.md section 11.3).

View Source
const MaxExtractPasswords = 16

MaxExtractPasswords is the doc 12 section 4.2 cap on the shared list. jobs.MaxCandidates aliases it so the write-side trim and the read-side candidate cap cannot drift apart.

View Source
const MaxWatchFolderLoaded = 4096

MaxWatchFolderLoaded bounds the per-folder loaded set; the oldest entries drop first, the same trim AppendExtractPassword applies.

Variables

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

ErrConflict is the sentinel a duplicate-name write returns; the API maps it to 409 /problems/conflict. isUniqueViolation already detects the driver's SQLITE_CONSTRAINT_UNIQUE for it.

View Source
var ErrDuplicateInfohash = errors.New("store: torrent already present")

ErrDuplicateInfohash is returned when either hash already belongs to a task whose state is not 'removed'. The API maps it to a rejected[] entry of type /problems/conflict (the slug registry of doc 05 section 1.3 is closed) and the metadata write-back maps it to the torrent_duplicate pause of a task that already exists.

View Source
var ErrIllegalTransition = errors.New("store: illegal state transition")

ErrIllegalTransition is returned when a state change is not in the transition table. ErrNotFound is deliberately not redeclared here: db.go owns it for the whole package.

View Source
var ErrInvalidSort = errors.New("store: unknown sort column")

ErrInvalidSort is returned when the sort key is outside the allowlist below. The column names never reach SQL unvalidated: the allowlist is the only way a sort expression is chosen.

View Source
var (

	// ErrNotFound is returned when no row with the given ID exists.
	ErrNotFound = errors.New("store: not found")
)
View Source
var ErrStaleCursor = errors.New("store: cursor does not match this filter")

ErrStaleCursor is returned when a cursor does not belong to the supplied filter and sort, or cannot be decoded at all. The API answers both with 422 /problems/validation-failed rather than a wrong page.

View Source
var ErrTransitionConflict = errors.New("store: task state changed since read")

ErrTransitionConflict is returned when the state a transition validated against changed before its update landed. Unlike ErrIllegalTransition the move may well be legal from the new state: the caller should re-read and decide again.

View Source
var ErrUnknownFilterState = errors.New("store: unknown state or sidebar filter")

ErrUnknownFilterState is returned when State names neither a canonical state nor a sidebar filter.

View Source
var Searches = NewSearchTracker()

Searches is the process-wide tracker instance.

Functions

func Backoff

func Backoff(now int64, attempts int) int64

Backoff is run_after = now_ms + min(600000, 5000 * 2^attempts) (docs/04-data-model.md section 3.6, rule 3).

func CompleteJob

func CompleteJob(ctx context.Context, db *sqlx.DB, id string, now int64) error

CompleteJob sets state='done'.

func CountResultsByIndexer

func CountResultsByIndexer(ctx context.Context, db *sqlx.DB, jobID string) (map[string]int, error)

CountResultsByIndexer returns the per-engine row counts of one job. The API rebuilds the engines array from it once the in-memory tracker has forgotten the job (a restart), where the volatile per-engine status no longer exists.

func CountSearchResults

func CountSearchResults(ctx context.Context, db *sqlx.DB, jobID string) (int, error)

CountSearchResults returns one job's total row count — the value FinishSearchJob stamps and the GET poll reports.

func CountUsers

func CountUsers(ctx context.Context, db *sqlx.DB) (int64, error)

CountUsers returns the number of rows in users — 0 before first-run setup, 1 after.

func CreateFeed

func CreateFeed(ctx context.Context, db *sqlx.DB, f Feed) error

CreateFeed inserts one row. The caller owns f.ID (a fed_ ULID) and f.NextFetchAt; the fetch-state fields of f are ignored — the poller writes them through UpdateFeedFetchState. created_at and updated_at stamp here. A duplicate url is ErrConflict — the API maps it to 409 /problems/conflict.

func CreateRule

func CreateRule(ctx context.Context, db *sqlx.DB, r Rule) error

CreateRule inserts one row. The caller owns r.ID (a rul_ ULID) and the mirrored columns name, enabled, priority and DefinitionJSON; created_at and updated_at stamp here. A duplicate name is ErrConflict — the API maps it to 409 /problems/conflict.

func CreateSession

func CreateSession(ctx context.Context, db *sqlx.DB, s Session) error

CreateSession inserts a session; created_at and updated_at are set to now.

func CreateUser

func CreateUser(ctx context.Context, db *sqlx.DB, u User) error

CreateUser inserts the operator account; created_at and updated_at are set to now. last_login_at comes from the struct, NULL for first-run setup.

func DeleteExpiredSessions

func DeleteExpiredSessions(ctx context.Context, db *sqlx.DB, now int64) (int64, error)

DeleteExpiredSessions removes every session whose expiry has passed and returns how many.

func DeleteFeed

func DeleteFeed(ctx context.Context, db *sqlx.DB, id string) error

DeleteFeed removes the row; its feed_items rows go with it through ON DELETE CASCADE (docs/04-data-model.md section 3.5). ErrNotFound means id addresses no row.

func DeleteRule

func DeleteRule(ctx context.Context, db *sqlx.DB, id string) error

DeleteRule removes the row. ErrNotFound means id addresses no row.

func DeleteSearchJob

func DeleteSearchJob(ctx context.Context, db *sqlx.DB, id string) error

DeleteSearchJob removes the job row; its results cascade through the ON DELETE CASCADE of docs/04-data-model.md section 3.4. ErrNotFound means the id addresses no row.

func DeleteSearchJobAndQueue

func DeleteSearchJobAndQueue(ctx context.Context, db *sqlx.DB, searchJobID string) error

DeleteSearchJobAndQueue removes the search_jobs row and its queue row in one transaction — DELETE /search/{id} either drops both or neither, so a failure cannot strand a claimable queue row or a driverless job. Both deletes become visible together at commit; their order inside the transaction is immaterial. ErrNotFound means the id addresses no job.

func DeleteSearchQueueRow

func DeleteSearchQueueRow(ctx context.Context, db *sqlx.DB, searchJobID string) error

DeleteSearchQueueRow drops the queue row of one search job, whichever state it is in: a pending row is never claimed, and a running row's handler exits quietly once the search_jobs row is gone (its first read answers ErrNotFound).

func DeleteSession

func DeleteSession(ctx context.Context, db *sqlx.DB, id string) error

DeleteSession removes a session; deleting an unknown id is not an error.

func EnqueueJob

func EnqueueJob(ctx context.Context, db *sqlx.DB, kind string, taskID *string, payload any, runAfter int64) (string, error)

EnqueueJob inserts one pending row and returns its id; payload is stored as JSON. state, attempts and max_attempts take their DDL defaults.

func EnqueueSearchJob

func EnqueueSearchJob(ctx context.Context, db *sqlx.DB, payload any, runAfter int64) (string, error)

EnqueueSearchJob writes one pending queue row of kind "search" with max_attempts 1 — a search is re-run by the user, not retried. The payload is stored as JSON exactly as EnqueueJob would marshal it.

func FailJob

func FailJob(ctx context.Context, db *sqlx.DB, id string, attempts, maxAttempts int, lastErr string, now int64) error

FailJob records lastErr and either reschedules with run_after = Backoff(now, attempts), or sets state='failed' once attempts >= maxAttempts; the failed row stays as its own dead-letter record.

func FinishSearchJob

func FinishSearchJob(ctx context.Context, db *sqlx.DB, id string, total int, lastErr *string, now int64) error

FinishSearchJob stamps the terminal state: finished, the total rows written across every engine, an optional job-level error summary and finished_at. ErrNotFound means the job was deleted underneath the worker — the handler treats that as a completed job, not a failure.

func IndexerSettingsMap

func IndexerSettingsMap(log *slog.Logger, row Indexer) map[string]string

IndexerSettingsMap decodes an indexer row's settings_json into the string map the dlsearch runner's Scope.Config reads — the reserved keys pass through so the runner sees allow_private_network. A stored document that is not valid JSON is treated as empty and logged: one corrupt row must not make the indexer unusable. The API's probe path and the job fan-out share this one decode so a setting can never drift between the two.

func InsertResults

func InsertResults(ctx context.Context, db *sqlx.DB, jobID, indexerID string, rows []SearchResultRow) (int, error)

InsertResults writes one engine's page in a single transaction and returns the number of rows written. It is idempotent per (search_job_id, indexer_id): it deletes that indexer's rows first, because the job queue is at-least-once — a re-run replaces the page instead of doubling it.

func ListItemMatchedRules

func ListItemMatchedRules(ctx context.Context, db *sqlx.DB, ids []string) (map[string][]ItemMatchedRule, error)

ListItemMatchedRules returns, per feed_items id, the rules that matched it: every stored rule_matches row names one, joined to rules for the display name — no status filter, since queued, sent, failed and fallback rows all represent a match. Rules list in evaluation order (priority ASC, name ASC). An empty ids slice answers an empty map without querying: an empty items page is a normal request, and skipping the query keeps that case independent of how the engine parses an empty IN list.

func MarkAllFeedItemsRead

func MarkAllFeedItemsRead(ctx context.Context, db *sqlx.DB, feedID string, now int64) (int64, error)

MarkAllFeedItemsRead marks every unread item of one feed read and returns the count.

func NewID

func NewID(prefix string) string

NewID returns a table prefix followed by a Crockford base32 ULID.

func NormaliseInfohash

func NormaliseInfohash(s string) (string, error)

NormaliseInfohash lowercases and validates one hash. It accepts 40 hex (v1), 32 base32 characters (v1, decoded to 40 hex), 64 hex (v2) and the 68-character multihash form 1220<64 hex> (v2, stripped to its 64 hex digits). It returns "" and no error for an empty input, so a caller normalising an absent v2 of a hybrid torrent needs no branch of its own.

func Open

func Open(ctx context.Context, dbPath, backupDir string) (*sqlx.DB, error)

Open prepares, migrates and verifies the SQLite database.

func OpenNotificationSecret

func OpenNotificationSecret(key secure.Secret, enc *string) (secure.Secret, error)

OpenNotificationSecret decrypts one secret_enc value back to the stored secret; a NULL column returns the empty Secret. A ciphertext that does not open is corrupt or sealed under a different key — either way an error, never a silently wrong value.

func PurgeSearchJobs

func PurgeSearchJobs(ctx context.Context, db *sqlx.DB, olderThan int64) (int64, error)

PurgeSearchJobs deletes every job created before olderThan (unix ms) and reports how many; results cascade, and each purged job's tracker entry is forgotten so the sweep cannot leak volatile state. The 24-hour retention sweep of T091 is the intended caller.

func RecoverRunningJobs

func RecoverRunningJobs(ctx context.Context, db *sqlx.DB) (int64, error)

RecoverRunningJobs returns rows stranded in 'running' by a crash to 'pending' and reports how many. Single-process only (ADR-0015): a second live worker would have its in-flight rows reset and re-run.

func SchemaVersion

func SchemaVersion(ctx context.Context, db *sqlx.DB) (int64, error)

SchemaVersion returns the newest applied goose migration.

func SealNotificationSecret

func SealNotificationSecret(key secure.Secret, plain string) (*string, error)

SealNotificationSecret encrypts one channel secret for secret_enc: base64(nonce || ciphertext). An empty plaintext seals to nil — the column stays NULL so secret_set reports false.

func SessionByTokenHash

func SessionByTokenHash(ctx context.Context, db *sqlx.DB, hash string) (Session, User, error)

SessionByTokenHash joins sessions to users and returns both. An expired session or a disabled user is ErrNotFound, like an unknown hash.

func SetCompletedHook

func SetCompletedHook(h OnTaskCompleted)

SetCompletedHook installs the post-completion callback; nil disables it. The last registered hook wins.

func SetFeedItemsRead

func SetFeedItemsRead(ctx context.Context, db *sqlx.DB, feedID string, ids []string, read bool, now int64) (int64, error)

SetFeedItemsRead marks the listed items of one feed read or unread and returns how many rows changed state. An id that names no row of this feed is skipped, which makes the call idempotent.

func SetRuleLastMatchAt

func SetRuleLastMatchAt(ctx context.Context, db *sqlx.DB, id string, at int64) error

SetRuleLastMatchAt advances the dedup watermark of docs/08-rss-automation.md section 5 step 14: the newest published_at the rule committed a grab for. The write is monotonic — MAX keeps the larger of the stored value and at, so a late or retried call cannot re-open the consumed window and re-grab items the rule already committed — and updated_at moves only when the watermark does, so a non-advancing write leaves no phantom modification. ErrNotFound means id addresses no row.

func TouchLastLogin

func TouchLastLogin(ctx context.Context, db *sqlx.DB, id string, now int64) error

TouchLastLogin stamps the user's last successful login.

func TouchSession

func TouchSession(ctx context.Context, db *sqlx.DB, id string, now int64) error

TouchSession bumps last_seen_at; the caller throttles the call rate.

func TrimFeedItems

func TrimFeedItems(ctx context.Context, db *sqlx.DB, feedID string, cap int) (int64, error)

TrimFeedItems deletes all but the newest cap rows of one feed, ordered by COALESCE(published_at, first_seen_at) DESC. cap <= 0 keeps everything. It returns the number of deleted rows.

func UpdateFeed

func UpdateFeed(ctx context.Context, db *sqlx.DB, f Feed) error

UpdateFeed writes the operator-owned columns — url, title, enabled, refresh_interval_s, item_cap, priority and updated_at — and leaves every fetch-state column untouched. ErrNotFound means id addresses no row; ErrConflict means url belongs to another row.

func UpdateFeedFetchState

func UpdateFeedFetchState(ctx context.Context, db *sqlx.DB, f Feed) error

UpdateFeedFetchState writes only etag, last_modified, ttl_minutes, last_fetch_at, last_success_at, next_fetch_at, escalation_level, disabled_till, last_error and updated_at. The ladder that computes them lives in internal/rss/poll.go (T066). ErrNotFound means id addresses no row.

func UpdateRule

func UpdateRule(ctx context.Context, db *sqlx.DB, r Rule) error

UpdateRule writes the mirrored columns and definition_json of an existing row and leaves last_match_at untouched. ErrNotFound means id addresses no row; ErrConflict means name belongs to another row.

func UpsertFeedItems

func UpsertFeedItems(ctx context.Context, db *sqlx.DB, items []FeedItem, now int64) (int, error)

UpsertFeedItems inserts items in one transaction with INSERT ... ON CONFLICT (feed_id, identity) DO UPDATE SET title=..., updated_at=... and returns how many rows were new. An empty id gets a fresh itm_ ULID and a zero first_seen_at takes now; a repeated identity inside one batch updates the row the earlier entry wrote instead of creating a second one.

Types

type APIToken

type APIToken struct {
	ID         string `db:"id" json:"id"`
	UserID     string `db:"user_id" json:"-"`
	Name       string `db:"name" json:"name"`
	TokenHash  string `db:"token_hash" json:"-"`
	Prefix     string `db:"prefix" json:"prefix"`
	LastUsedAt *int64 `db:"last_used_at" json:"-"`
	ExpiresAt  *int64 `db:"expires_at" json:"expires_at"`
	RevokedAt  *int64 `db:"revoked_at" json:"-"`
	CreatedAt  int64  `db:"created_at" json:"created_at"`
	UpdatedAt  int64  `db:"updated_at" json:"-"`
}

APIToken is one row of the api_tokens table (docs/04-data-model.md section 3.1). The bearer value itself is never stored, only its SHA-256 hex in TokenHash; TokenHash and RevokedAt never serialize, so the struct can never leak them into a response.

type ActiveCounts

type ActiveCounts struct {
	Total    int
	ByEngine map[string]int
}

ActiveCounts is one snapshot of the counted set (T098): the tasks in state downloading, checking, extracting or moving, in total and per engine. Tasks in state seeding are excluded from every count — a full seed list must not starve new downloads (docs/04-data-model.md section 4.7). ByEngine is never nil, including for an empty counted set, so a caller may index it for any engine name.

func (*ActiveCounts) Reserve

func (c *ActiveCounts) Reserve(engineName string)

Reserve consumes one unit of headroom for engineName: total and per-engine counts both. A caller that has just promised a slot to one more task — a resume batch answering ok:true per id — uses it so the later ids of the same request see the slot spent instead of promising it twice. The admission pass re-derives the truth from the database on its next tick; a snapshot only has to be self-consistent within one batch.

type Candidate

type Candidate struct {
	ID          string  `db:"id"`
	Engine      string  `db:"engine"`
	EngineRef   *string `db:"engine_ref"` // nil when the task has never been handed to an engine
	SourceURI   *string `db:"source_uri"`
	InfohashV1  *string `db:"infohash_v1"`
	Destination string  `db:"destination"`
	// SelectFiles is the persisted selection intent the release applies
	// to the engine; DLLimit and ULLimit are the persisted per-task rate
	// limits a PATCH may have written before admission — the release
	// applies them before the transfer starts (docs/05-api-contract.md
	// section 5.5: an unadmitted task gets its limits at admission).
	SelectFiles *string `db:"select_files"`
	DLLimit     int64   `db:"dl_limit"`
	ULLimit     int64   `db:"ul_limit"`
	// AdmissionPending is the pass's persisted ownership mark of a queued
	// row mid-release: the queued candidate that skips the hold gates and
	// counts toward the active totals. A stored handle alone no longer
	// means that — an ordinary resume requeues a task whose transfer is
	// stopped, and it must pass the gates again.
	AdmissionPending int `db:"admission_pending"`
	// State is queued for a waiting candidate and paused for one the
	// disk-space guard parked (FR-048); the pass releases both, resuming
	// the paused one's partial data instead of restarting it.
	State      string `db:"state"`
	TotalBytes *int64 `db:"total_bytes"` // nil while metadata is unknown
	// CompletedBytes reads COALESCE(completed_bytes, 0): a NULL row
	// contributes 0 to its own task instead of failing the whole
	// candidate scan.
	CompletedBytes int64 `db:"completed_bytes"`
}

Candidate is one task the admission pass (T098) considers for release. The submission columns ride along because the pass itself rebuilds the Engine.Add request from the stored identity — the same projection the reconciler's Reconcilable makes for a re-submission — and the byte pair rides along for the disk-space gate (T099): remaining = total - completed is what a release would promise the filesystem.

type Category

type Category struct {
	ID        string `db:"id"         json:"-"`
	Name      string `db:"name"       json:"name"`
	SavePath  string `db:"save_path"  json:"save_path"`
	TaskCount int    `db:"task_count" json:"task_count"`
}

Category is one row of the categories table (docs/04-data-model.md section 3.2) with the count of its non-removed tasks attached. The id stays off the wire: the API addresses a category by its unique name.

type CodedPause

type CodedPause struct {
	EventCode    string
	EventMessage string
	ErrorCode    string
	ErrorMessage string
	FromStates   []string // the write applies only while the row is in one of these
}

CodedPause is one atomic pause landing: the state move, its event, the error-code pair the admission pass will select the row by, and the source states the move is legal from. A struct keeps the values name-bound instead of transposable across adjacent strings.

type DeletedData

type DeletedData struct {
	Files int   `json:"files"`
	Bytes int64 `json:"bytes"`
}

DeletedData carries what a delete_data removal unlinked, recorded as the detail of the task.data_deleted event (docs/05-api-contract.md 5.6 step 5: the file count and the byte total).

type Engine

type Engine struct {
	ID         string  `db:"id"`
	Kind       string  `db:"kind"`
	Name       string  `db:"name"`
	Enabled    int     `db:"enabled"`
	URL        *string `db:"url"`
	Version    *string `db:"version"`
	LastSeenAt *int64  `db:"last_seen_at"`
	LastError  *string `db:"last_error"`
}

Engine is one row of the engines table (docs/04-data-model.md section 3.2). secret_enc and username are deliberately absent: this model feeds GET /engines, and an engine secret is never returned by any API, so the column is not even selected.

type EngineStatus

type EngineStatus struct {
	ID     string  `json:"id"`
	Name   string  `json:"name"`
	Status string  `json:"status" enum:"queued,searching,done,error"`
	Count  int     `json:"count"`
	Error  *string `json:"error"`
}

EngineStatus is the volatile half of a search job: what each indexer is doing right now. status is queued | searching | done | error (docs/05-api-contract.md section 9.2).

type Feed

type Feed struct {
	ID               string  `db:"id"                 json:"id"`
	URL              string  `db:"url"                json:"-"`
	Title            *string `db:"title"              json:"title"`
	Enabled          bool    `db:"enabled"            json:"enabled"`
	RefreshIntervalS int     `db:"refresh_interval_s" json:"refresh_interval_s"`
	ItemCap          int     `db:"item_cap"           json:"item_cap"`
	Priority         int     `db:"priority"           json:"priority"`
	// UnreadCount is not a feeds column: ListFeeds and FeedByID populate it with a correlated
	// `read = 0` subquery over feed_items, and no write ever touches it.
	UnreadCount     int     `db:"unread_count"       json:"-"`
	ETag            *string `db:"etag"               json:"-"`
	LastModified    *string `db:"last_modified"      json:"-"`
	TTLMinutes      *int    `db:"ttl_minutes"        json:"-"`
	LastFetchAt     *int64  `db:"last_fetch_at"      json:"-"`
	LastSuccessAt   *int64  `db:"last_success_at"    json:"-"`
	NextFetchAt     int64   `db:"next_fetch_at"      json:"-"`
	EscalationLevel int     `db:"escalation_level"   json:"-"`
	DisabledTill    *int64  `db:"disabled_till"      json:"-"`
	LastError       *string `db:"last_error"         json:"-"`
	CreatedAt       int64   `db:"created_at"         json:"-"`
	UpdatedAt       int64   `db:"updated_at"         json:"-"`
}

Feed is one row of feeds plus the computed unread_count. Secrets never appear here; the URL is stored verbatim and redacted only on the wire (see the FeedDTO rules below).

func DueFeeds

func DueFeeds(ctx context.Context, db *sqlx.DB, now int64, limit int) ([]Feed, error)

DueFeeds returns enabled feeds with next_fetch_at <= now and no future disabled_till, oldest next_fetch_at first. It is the poller's work list.

func FeedByID

func FeedByID(ctx context.Context, db *sqlx.DB, id string) (Feed, error)

FeedByID resolves one row by id with UnreadCount populated like ListFeeds. ErrNotFound means the id addresses no row.

func ListFeeds

func ListFeeds(ctx context.Context, db *sqlx.DB) ([]Feed, error)

ListFeeds returns every feed with UnreadCount populated, ordered by (title, id) so the feed list is stable; FeedByID resolves one row the same way, ErrNotFound when the id addresses none.

type FeedItem

type FeedItem struct {
	ID          string  `db:"id"`
	FeedID      string  `db:"feed_id"`
	GUID        *string `db:"guid"`
	Identity    string  `db:"identity"`
	Title       string  `db:"title"`
	TitleNorm   string  `db:"title_norm"`
	Link        *string `db:"link"`
	DownloadURL *string `db:"download_url"`
	InfoHash    *string `db:"info_hash"` // 40 or 64 lowercase hex
	SizeBytes   *int64  `db:"size_bytes"`
	PublishedAt *int64  `db:"published_at"`
	Read        bool    `db:"read"`
	FirstSeenAt int64   `db:"first_seen_at"`
	RawJSON     *string `db:"raw_json"`
	CreatedAt   int64   `db:"created_at"`
	UpdatedAt   int64   `db:"updated_at"`
}

FeedItem is one row of feed_items. Identity is resolved by the parser (T067), never here.

func ListFeedItems

func ListFeedItems(ctx context.Context, db *sqlx.DB, f FeedItemFilter) (items []FeedItem, nextCursor string, total int, err error)

ListFeedItems pages newest first — COALESCE(published_at, first_seen_at) DESC, id DESC as the tie-break — and returns the page, the next cursor and the total matching the filter, ignoring the cursor and the limit (doc 05 §1.4).

type FeedItemFilter

type FeedItemFilter struct {
	FeedIDs    []string
	UnreadOnly bool
	Limit      int
	Cursor     string
}

FeedItemFilter scopes ListFeedItems: FeedIDs empty means every feed, UnreadOnly selects the read = 0 rows, and the cursor is bound to both — a cursor minted under another filter answers ErrStaleCursor, which the handler maps to 422 exactly like the task list's cursor.

type Indexer

type Indexer struct {
	ID               string  `db:"id"                json:"id"`
	Name             string  `db:"name"              json:"name"`
	Kind             string  `db:"kind"              json:"kind"` // torznab | newznab | dlsearch
	Enabled          bool    `db:"enabled"           json:"enabled"`
	URL              *string `db:"url"               json:"url"`
	APIKeyEnc        *string `db:"api_key_enc"       json:"-"`
	DefinitionID     *string `db:"definition_id"     json:"definition_id"`
	DefinitionSource *string `db:"definition_source" json:"definition_source"` // bundled | user | imported
	Provenance       *string `db:"provenance"        json:"provenance"`
	LegalTier        string  `db:"legal_tier"        json:"legal_tier"`
	Priority         int     `db:"priority"          json:"priority"`
	SeedersUnknown   bool    `db:"seeders_unknown"   json:"seeders_unknown"`
	SettingsJSON     *string `db:"settings_json"     json:"-"`
	CategoriesJSON   *string `db:"categories_json"   json:"-"`
	LastTestAt       *int64  `db:"last_test_at"      json:"-"`
	LastError        *string `db:"last_error"        json:"last_error"`
	CreatedAt        int64   `db:"created_at"        json:"-"`
	UpdatedAt        int64   `db:"updated_at"        json:"-"`
}

Indexer mirrors the indexers DDL of docs/04-data-model.md section 3.4. APIKeyEnc never leaves this package in clear; readers call OpenAPIKey. The allow_private_network column deliberately has no field: the flag lives in the settings_json document (task T055).

type IndexerPatch

type IndexerPatch struct {
	Name, URL, DefinitionID *string
	Kind, Provenance        *string
	Enabled                 *bool
	Priority                *int
	APIKey                  *secure.Secret
	SettingsJSON            *string
}

IndexerPatch carries only the fields docs/05-api-contract.md section 9.1 accepts; a nil field is unchanged. APIKey set to a pointer to "" clears the stored key.

type IndexerStore

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

IndexerStore seals api_key_enc with AES-256-GCM under a 32-byte key derived by HKDF-SHA256 from cfg.SecretKey with the info string "dl-tool/indexer-api-key/v1". No new environment variable and no new secret carrier is introduced.

func NewIndexerStore

func NewIndexerStore(db *sqlx.DB, sessionKey secure.Secret) (*IndexerStore, error)

NewIndexerStore derives the sealing key from sessionKey (the at-rest secret key of docs/11-config-reference.md) and returns the store. An empty key is an error: sealing under an empty secret would silently reduce to a fixed key.

func (*IndexerStore) Create

func (s *IndexerStore) Create(ctx context.Context, in Indexer, apiKey secure.Secret) (Indexer, error)

Create inserts one row with a fresh idx_ id and the sealed api_key; the stored row is returned. A duplicate definition_id is ErrConflict — the API maps it to 409 /problems/conflict.

func (*IndexerStore) Delete

func (s *IndexerStore) Delete(ctx context.Context, id string) error

Delete removes the row. ErrNotFound means id addresses no row.

func (*IndexerStore) Get

func (s *IndexerStore) Get(ctx context.Context, id string) (Indexer, error)

Get resolves one row by id. ErrNotFound means the id addresses no row.

func (*IndexerStore) List

func (s *IndexerStore) List(ctx context.Context, enabledOnly bool) ([]Indexer, error)

List returns every row ordered by priority then name; enabledOnly narrows the set to enabled = 1.

func (*IndexerStore) OpenAPIKey

func (s *IndexerStore) OpenAPIKey(row Indexer) (secure.Secret, error)

OpenAPIKey unseals the row's stored key. A row with no key returns the empty Secret. A ciphertext that does not open is corrupt or sealed under a different key; either way it is an error, never a silently wrong key.

func (*IndexerStore) RecordTest

func (s *IndexerStore) RecordTest(ctx context.Context, id string, at int64, lastErr *string) error

RecordTest stamps the outcome of one probe: last_test_at always moves, last_error carries the failure or is cleared by a nil lastErr. ErrNotFound means id addresses no row.

func (*IndexerStore) SetCaps

func (s *IndexerStore) SetCaps(ctx context.Context, id string, categoriesJSON string, seedersUnknown bool) error

SetCaps stores the flattened categories document of a fetched caps and the indexer's seeders_unknown flag. ErrNotFound means id addresses no row.

func (*IndexerStore) Update

func (s *IndexerStore) Update(ctx context.Context, id string, patch IndexerPatch) (Indexer, error)

Update writes the non-nil patch fields onto the addressed row and always stamps updated_at, then reads the row back. A nil patch still moves updated_at, matching the patch contract. ErrNotFound means id addresses no row; ErrConflict means definition_id belongs to another row.

type ItemMatchedRule

type ItemMatchedRule struct {
	ID   string `db:"id"`
	Name string `db:"name"`
}

ItemMatchedRule is one {id, name} pair of an item's matched_rules member (docs/05-api-contract.md section 10.1).

type Job

type Job struct {
	ID          string  `db:"id"`
	Kind        string  `db:"kind"`
	TaskID      *string `db:"task_id"`
	PayloadJSON string  `db:"payload_json"`
	State       string  `db:"state"` // pending | running | done | failed
	Attempts    int     `db:"attempts"`
	MaxAttempts int     `db:"max_attempts"`
	RunAfter    int64   `db:"run_after"` // unix ms
	LockedAt    *int64  `db:"locked_at"`
	LastError   *string `db:"last_error"`
}

Job is one row of the jobs table — the durable queue of docs/04-data-model.md section 3.6.

func ClaimJob

func ClaimJob(ctx context.Context, db *sqlx.DB, now int64) (Job, error)

ClaimJob runs the claim statement of docs/04-data-model.md section 3.6 against the oldest eligible row. It returns ErrNotFound when nothing is eligible. The returned row carries only the claimed columns.

type NotificationChannel

type NotificationChannel struct {
	ID         string  `db:"id"           json:"-"`
	Kind       string  `db:"kind"         json:"-"` // webhook | ntfy | gotify | apprise
	Name       string  `db:"name"         json:"-"`
	Enabled    int     `db:"enabled"      json:"-"`
	ConfigJSON string  `db:"config_json"  json:"-"`
	SecretEnc  *string `db:"secret_enc"   json:"-"`
	EventMask  string  `db:"event_mask"   json:"-"`
	LastSendAt *int64  `db:"last_send_at" json:"-"`
	LastError  *string `db:"last_error"   json:"-"`
	CreatedAt  int64   `db:"created_at"   json:"-"`
	UpdatedAt  int64   `db:"updated_at"   json:"-"`
}

NotificationChannel is one row of the notification_channels table (docs/04-data-model.md section 4.8). It is a store-internal shape: every field carries json:"-" so the row can never be serialised to an API response — the API renders channels through its own view — and SecretEnc only ever leaves the row as ciphertext. The notifier (internal/jobs) is the sole caller that opens it.

type OnTaskCompleted

type OnTaskCompleted func(ctx context.Context, taskID string)

OnTaskCompleted is the callback fired once per committed transition into completed. It runs on a context detached from the caller's cancellation — the transition already committed, so a cancelled request context must not silently drop the chain's enqueue — and the installing adapter bounds the detached work with its own timeout.

type Progress

type Progress struct {
	TotalBytes     *int64
	CompletedBytes int64
	UploadedBytes  int64
	DownloadRate   int64
	UploadRate     int64
	ETASeconds     *int64
}

Progress carries the mutable transfer counters an engine poll produces.

type QueueMove

type QueueMove int

QueueMove names one of the four queue rewrites of docs/05-api-contract.md section 5.7.

const (
	QueueMoveTop QueueMove = iota
	QueueMoveUp
	QueueMoveDown
	QueueMoveBottom
)

type Reconcilable

type Reconcilable struct {
	ID          string  `db:"id"`
	EngineRef   string  `db:"engine_ref"` // the map key of ListNonTerminalByEngine
	State       string  `db:"state"`      // never completed, removed or error
	SourceURI   *string `db:"source_uri"`
	InfohashV1  *string `db:"infohash_v1"`
	Destination string  `db:"destination"`
	// SelectFiles, DLLimit and ULLimit are the persisted intent a
	// re-submission must restore on the fresh engine handle — the same
	// columns Candidate carries for the admission pass.
	SelectFiles *string `db:"select_files"`
	DLLimit     int64   `db:"dl_limit"`
	ULLimit     int64   `db:"ul_limit"`
}

Reconcilable is the non-terminal task a reconciliation sweep needs (T026): enough to write engine-reported state back through UpdateProgress and Transition, and — when the engine no longer knows the handle — to re-submit the transfer from its stored source with resume semantics. It is a projection of the tasks row, not the row itself: the sweep never needs the display or patch columns.

type Rule

type Rule struct {
	ID             string `db:"id"              json:"id"`
	Name           string `db:"name"            json:"name"`
	Enabled        bool   `db:"enabled"         json:"enabled"`
	Priority       int    `db:"priority"        json:"priority"`
	DefinitionJSON string `db:"definition_json" json:"-"`
	LastMatchAt    *int64 `db:"last_match_at"   json:"-"`
	CreatedAt      int64  `db:"created_at"      json:"-"`
	UpdatedAt      int64  `db:"updated_at"      json:"-"`
}

Rule is one row of rules (docs/04-data-model.md section 3.5): DefinitionJSON is the validated rule document of docs/08-rss-automation.md section 4 rendered compact, and name, enabled and priority are its mirrored columns — the evaluation order reads them without parsing the document.

func ListRules

func ListRules(ctx context.Context, db *sqlx.DB, enabledOnly bool) ([]Rule, error)

ListRules returns every rule ordered by (priority ASC, name ASC) — the evaluation order of docs/08-rss-automation.md section 5. enabledOnly selects the enabled rows, the poller's working set.

func RuleByID

func RuleByID(ctx context.Context, db *sqlx.DB, id string) (Rule, error)

RuleByID resolves one rule by id. ErrNotFound means the id addresses no row.

func RuleByName

func RuleByName(ctx context.Context, db *sqlx.DB, name string) (Rule, error)

RuleByName resolves one rule by its unique name, ErrNotFound when none carries it. The `auto:<feed_id>` lifecycle resolves by name, never by a stored back-reference (docs/05-api-contract.md section 10.1).

type ScheduleMode

type ScheduleMode string

ScheduleMode is the stored bandwidth_schedule.mode value (docs/04-data-model.md section 3.6). The API renders the cells as the integers of docs/05-api-contract.md section 11.2; the translation is owned there, not here.

const (
	ScheduleNoDownload  ScheduleMode = "no_download"
	ScheduleDefault     ScheduleMode = "default"
	ScheduleAlternative ScheduleMode = "alternative"
)

type SearchJob

type SearchJob struct {
	ID             string  `db:"id"`
	Query          string  `db:"query"`
	IndexerIDsJSON string  `db:"indexer_ids_json"`
	CategoriesJSON *string `db:"categories_json"`
	Finished       bool    `db:"finished"`
	Total          int     `db:"total"`
	LastError      *string `db:"last_error"`
	StartedAt      int64   `db:"started_at"`
	FinishedAt     *int64  `db:"finished_at"`
	CreatedAt      int64   `db:"created_at"`
	UpdatedAt      int64   `db:"updated_at"`
}

SearchJob is one row of the search_jobs table (docs/04-data-model.md section 3.4): the durable half of an asynchronous search.

func CreateSearchJob

func CreateSearchJob(ctx context.Context, db *sqlx.DB, j SearchJob) (SearchJob, error)

CreateSearchJob inserts one running job row; the id (sch_…), started_at and the timestamps are assigned here. IndexerIDsJSON and CategoriesJSON are the verbatim JSON documents the job fans out over.

func CreateSearchJobAndEnqueue

func CreateSearchJobAndEnqueue(ctx context.Context, db *sqlx.DB, j SearchJob, payloadOf func(searchJobID string) any, runAfter int64) (SearchJob, error)

CreateSearchJobAndEnqueue writes the search_jobs row and its queue row in one transaction: a search that exists always has its driver, and a failed enqueue cannot leave an orphaned job that polls queued forever. payloadOf builds the queue payload from the assigned job id — the id only exists inside the transaction, so the payload cannot be marshaled before it.

func GetSearchJob

func GetSearchJob(ctx context.Context, db *sqlx.DB, id string) (SearchJob, error)

GetSearchJob resolves one row by id. ErrNotFound means the id addresses no row — deleted and unknown are the same answer.

type SearchResultRow

type SearchResultRow struct {
	ID                     string   `db:"id"`
	SearchJobID            string   `db:"search_job_id"`
	IndexerID              string   `db:"indexer_id"`
	Title                  string   `db:"title"`
	DownloadURL            *string  `db:"download_url"`
	MagnetURI              *string  `db:"magnet_uri"`
	InfoHash               *string  `db:"info_hash"`
	SizeBytes              *int64   `db:"size_bytes"`
	Seeders                *int     `db:"seeders"`
	Leechers               *int     `db:"leechers"`
	Grabs                  *int     `db:"grabs"`
	PublishedAt            *int64   `db:"published_at"` // unix ms
	DetailsURL             *string  `db:"details_url"`
	CategoryIDsJSON        *string  `db:"category_ids_json"`
	CategoryDesc           *string  `db:"category_desc"`
	DownloadVolumeFactor   float64  `db:"download_volume_factor"`
	UploadVolumeFactor     float64  `db:"upload_volume_factor"`
	MinimumRatio           *float64 `db:"minimum_ratio"`
	MinimumSeedTimeSeconds *int     `db:"minimum_seed_time_seconds"`
	IMDBID                 *string  `db:"imdb_id"`
	TMDBID                 *string  `db:"tmdb_id"`
	TVDBID                 *string  `db:"tvdb_id"`
	Year                   *int     `db:"year"`
	Genre                  *string  `db:"genre"`
	Language               *string  `db:"language"`
	Publisher              *string  `db:"publisher"`
	Author                 *string  `db:"author"`
	Album                  *string  `db:"album"`
	Artist                 *string  `db:"artist"`
	CreatedAt              int64    `db:"created_at"`
	UpdatedAt              int64    `db:"updated_at"`
}

SearchResultRow mirrors the search_results DDL. Package store never imports internal/search, so the job handler converts search.SearchResult into this type. DownloadURL, MagnetURI and DetailsURL are acquisition handles — they persist for the later POST /tasks resolution but are never serialized by an API mapper (07-search-and-indexers.md section 5 rule 6).

func GetSearchResult

func GetSearchResult(ctx context.Context, db *sqlx.DB, id string) (SearchResultRow, error)

GetSearchResult resolves an opaque res_ id to its stored row — including the server-only acquisition fields — while its search job is live. An id whose job was deleted or purged, or whose row carries no non-empty magnet_uri or download_url, is indistinguishable from an unknown id: ErrNotFound. dl-tool is single-user (ADR-0019), so "authorise each result through its own search job" (docs/05 section 9.2) means the id resolves only while its search_jobs row exists; there is no per-user owner column to check.

func ListResults

func ListResults(ctx context.Context, db *sqlx.DB, jobID, sort string, limit int, cursor string) (rows []SearchResultRow, nextCursor string, total int, err error)

ListResults pages one job's results. sort is one of seeders, title, size_bytes, leechers, published_at, indexer, each reversible with a leading '-'; the default is "-seeders". Every column sorts NULLS LAST in both directions — an unknown seeder count never outranks a real one. The cursor is a base64 JSON token holding the last row's sort value, its id and a hash of (job, sort), exactly like ListTasks; a mismatched or undecodable token is ErrStaleCursor. total counts the job's rows, ignoring the cursor (docs/05-api-contract.md section 1.4).

type SearchTracker

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

SearchTracker holds EngineStatus per running search job. One process, one tracker: the durable rows live in search_jobs and search_results, this holds only what is in flight. Searches is the process-wide instance both internal/api and internal/jobs use.

func NewSearchTracker

func NewSearchTracker() *SearchTracker

NewSearchTracker returns an empty tracker.

func (*SearchTracker) Forget

func (t *SearchTracker) Forget(jobID string)

Forget drops one job's entry; DELETE /search/{id} and the retention purge call it.

func (*SearchTracker) Set

func (t *SearchTracker) Set(jobID, indexerID, status string, count int, errText *string)

Set updates one engine of one job. An unknown job — deleted, forgotten or never started — is a no-op: a row deleted under a running fan-out must not resurrect its tracker entry.

func (*SearchTracker) Snapshot

func (t *SearchTracker) Snapshot(jobID string) ([]EngineStatus, bool)

Snapshot returns a copy of one job's engine list; the bool is false once the job was forgotten (or never started), which is how the API knows to reconstruct the list from stored counts.

func (*SearchTracker) Start

func (t *SearchTracker) Start(jobID string, engines []EngineStatus)

Start (re)seeds one job's engine list; the fan-out worker calls it with every engine "searching" before the goroutines launch, so a re-run of the same job row resets a stale snapshot instead of leaking it.

type SelectionIntent

type SelectionIntent struct {
	Indices    []int       `json:"indices"`
	Priorities map[int]int `json:"priorities"`
}

SelectionIntent is the JSON document tasks.select_files persists: the file selection dl-tool believes the task should have, written at creation from select_files and rewritten by PATCH /tasks/{id}/files so a re-admission or engine-handle recreation restores the operator's selection rather than the engine's default. Indices are the files to download — an index absent from the listing and the map is skipped — and Priorities carries the resolved per-file integer of docs/04-data-model.md section 4.3 (0, 1, 6, 7), empty for an engine that drives selection alone.

func DecodeSelectionIntent

func DecodeSelectionIntent(raw string) (SelectionIntent, error)

DecodeSelectionIntent parses the stored select_files document. A malformed value is an error, not a silent default: applying a guessed selection would download files the operator skipped. The same goes for a document that parses but carries no sane intent — a negative index or a priority outside the doc 04 §4.3 set — so the decode validates what it hands the engine.

func SelectionIntentFromFiles

func SelectionIntentFromFiles(files []TaskFile) *SelectionIntent

SelectionIntentFromFiles builds the intent a task_files listing encodes: every selected index, and every file's stored priority — which is nil only on an engine without per-file priority. The rows mirror the engine's listing, so the intent they build is the selection the engine currently holds.

type Session

type Session struct {
	ID         string `db:"id" json:"id"`
	UserID     string `db:"user_id" json:"user_id"`
	TokenHash  string `db:"token_hash" json:"-"`
	CSRFToken  string `db:"csrf_token" json:"-"`
	ExpiresAt  int64  `db:"expires_at" json:"expires_at"`
	LastSeenAt int64  `db:"last_seen_at" json:"last_seen_at"`
}

Session is a cookie-authenticated login. The cookie value itself is never stored, only its SHA-256 hex in TokenHash. last_seen_at is throttled bookkeeping, not an idle timeout; only expires_at bounds a session.

type SettingsStore

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

SettingsStore reaches the configuration tables of docs/04-data-model.md section 3.2: the engines table here, and the settings rows with the tasks that own them (T092 and later extend this file).

func NewSettingsStore

func NewSettingsStore(db *sqlx.DB) *SettingsStore

NewSettingsStore builds the configuration-table store over db.

func (*SettingsStore) AppendExtractPassword

func (s *SettingsStore) AppendExtractPassword(ctx context.Context, pw string) error

AppendExtractPassword appends pw to the extract_passwords array in one transaction when it is absent, keeping at most maxExtractPasswords entries, oldest dropped first. The password is a secret: it is bound as a parameter, never interpolated into a query, log line or error.

func (*SettingsStore) CategoryByName

func (s *SettingsStore) CategoryByName(ctx context.Context, name string) (Category, error)

CategoryByName resolves one row by its unique name, carrying the same task_count the list does. ErrNotFound means no category carries it.

func (*SettingsStore) CreateCategory

func (s *SettingsStore) CreateCategory(ctx context.Context, c Category) error

CreateCategory inserts one row; a name already taken is ErrConflict. The caller owns c.ID (a cat_ ULID) and the already-resolved SavePath.

func (*SettingsStore) DefaultDestination

func (s *SettingsStore) DefaultDestination(ctx context.Context) (string, error)

DefaultDestination returns the default_destination settings row's value (docs/11-config-reference.md section 5). The migration seeds no row: an absent row or an empty value returns "" with a nil error, and the caller's first-root fallback applies.

func (*SettingsStore) DeleteCategory

func (s *SettingsStore) DeleteCategory(ctx context.Context, name string) error

DeleteCategory removes the row. The tasks.category_id and watch_folders.category_id references carry ON DELETE SET NULL (docs/04-data-model.md section 3.3), so its tasks and watch folders become uncategorised and no task row and no file is touched. ErrNotFound means name addresses no row.

func (*SettingsStore) EngineByID

func (s *SettingsStore) EngineByID(ctx context.Context, id string) (Engine, error)

EngineByID resolves one row by id. ErrNotFound means the id addresses no known engine.

func (*SettingsStore) EnsureEngine

func (s *SettingsStore) EnsureEngine(ctx context.Context, id, kind, name, url string, at int64) error

EnsureEngine creates or refreshes the identity row of a configured engine. The environment is the source of truth for name and url, so the row cannot drift when an operator moves an engine; the probe history columns (version, last_seen_at, last_error) stay owned by TouchEngine.

func (*SettingsStore) ExtractPasswords

func (s *SettingsStore) ExtractPasswords(ctx context.Context) ([]string, error)

ExtractPasswords reads the extract_passwords settings key. It returns an empty slice when the key is absent. The value is a secret: it is never logged and GET /settings renders it "__redacted__". One caveat is already documented in doc 12 section 4.2: the extract handler passes each candidate to 7zz as -p<password>, visible in /proc/<pid>/cmdline for the child's lifetime — acceptable while every container process runs as the same unprivileged user.

func (*SettingsStore) GetInt64

func (s *SettingsStore) GetInt64(ctx context.Context, key string, def int64) (int64, error)

GetInt64 reads one settings key as an integer, returning def when the row is absent. The stored grammar is a bare JSON integer — `4`, never `"4"` or `4.0` — the same shape parseNonNegativeSettingInt enforces for the admission keys, so a malformed row is an error, never a guess.

func (*SettingsStore) GetNotificationChannel

func (s *SettingsStore) GetNotificationChannel(ctx context.Context, id string) (NotificationChannel, error)

GetNotificationChannel resolves one row by id. ErrNotFound means the id addresses no known channel.

func (*SettingsStore) GetWatchFolder

func (s *SettingsStore) GetWatchFolder(ctx context.Context, id string) (WatchFolder, error)

GetWatchFolder returns one row by id, or ErrNotFound.

func (*SettingsStore) ListCategories

func (s *SettingsStore) ListCategories(ctx context.Context) ([]Category, error)

ListCategories returns every categories row, ordered by name, each with the count of its non-removed tasks.

func (*SettingsStore) ListEnabledWatchFolders

func (s *SettingsStore) ListEnabledWatchFolders(ctx context.Context) ([]WatchFolder, error)

ListEnabledWatchFolders returns every row of watch_folders with enabled = 1.

func (*SettingsStore) ListEngines

func (s *SettingsStore) ListEngines(ctx context.Context) ([]Engine, error)

ListEngines returns every engines row, ordered by kind.

func (*SettingsStore) ListNotificationChannels

func (s *SettingsStore) ListNotificationChannels(ctx context.Context) ([]NotificationChannel, error)

ListNotificationChannels returns every notification_channels row, ordered by name. The fan-out filters on enabled and event_mask itself — a disabled channel is still listed so the test send can reach it.

func (*SettingsStore) ListTags

func (s *SettingsStore) ListTags(ctx context.Context) ([]Tag, error)

ListTags returns every row of tags sorted by name, including tags with no tasks; task_count counts every non-removed task carrying the tag.

func (*SettingsStore) MarkWatchFolderLoaded

func (s *SettingsStore) MarkWatchFolderLoaded(ctx context.Context, folderID, infohash string) error

MarkWatchFolderLoaded adds infohash to the folder's loaded set in one transaction when it is absent, keeping at most MaxWatchFolderLoaded entries, oldest dropped first. Eviction is graceful but visible: a still-present file whose infohash was trimmed re-surfaces as SkipDuplicate on the next sweep — task dedup, not the loaded set, keeps it from loading twice.

func (*SettingsStore) Prefs

func (s *SettingsStore) Prefs(ctx context.Context, userID string) (map[string]any, error)

Prefs returns the account's ui_prefs rows assembled into one document, or an empty document when the account has never stored one — the SPA owns the defaults (docs/09-web-ui-spec.md section 3.3). Members the server does not model come back verbatim, which is what lets the SPA add a preference without a server change.

func (*SettingsStore) PutPrefs

func (s *SettingsStore) PutPrefs(ctx context.Context, userID string, doc map[string]any) error

PutPrefs replaces the document wholesale in one transaction: the account's existing rows are deleted and one row per top-level member is inserted, each value_json holding the member's JSON. Members the server does not model are stored verbatim (docs/05-api-contract.md section 11.4).

func (*SettingsStore) ReplaceSchedule

func (s *SettingsStore) ReplaceSchedule(ctx context.Context, enabled bool, cells [168]ScheduleMode) error

ReplaceSchedule writes all 168 cells and the schedule_enabled flag in one sqlx.Tx — PUT /settings/schedule carries both, so a partial write is impossible: either every cell and the flag land or none does (docs/05-api-contract.md section 11.2). A mode outside the stored vocabulary is rejected before the transaction opens, and the flag is upserted as a bare JSON boolean — the grammar ScheduleEnabled accepts.

func (*SettingsStore) Schedule

func (s *SettingsStore) Schedule(ctx context.Context) (cells [168]ScheduleMode, err error)

Schedule reads all 168 rows of bandwidth_schedule and returns them as cells indexed day*24+hour, day 0 = Monday. The table always holds exactly 168 rows, seeded by 00001_init.sql with 'default'; a short, out-of-range or unknown-mode read is an error rather than a partially zeroed grid the scheduler would evaluate as unintended pauses.

func (*SettingsStore) ScheduleEnabled

func (s *SettingsStore) ScheduleEnabled(ctx context.Context) (bool, error)

ScheduleEnabled reads the schedule_enabled settings key (docs/11-config-reference.md section 5): false when the row is absent, an error when the stored value is not a JSON boolean — the same grammar strictness GetInt64 applies to the integer keys.

func (*SettingsStore) ScheduleSnapshot

func (s *SettingsStore) ScheduleSnapshot(ctx context.Context) (cells [168]ScheduleMode, enabled bool, err error)

ScheduleSnapshot returns the grid and the schedule_enabled flag from one read transaction, so a concurrent ReplaceSchedule cannot interleave the pair — the response the API renders is one committed version, never new cells beside the old flag.

func (*SettingsStore) SeedWatchFolder

func (s *SettingsStore) SeedWatchFolder(ctx context.Context, path, destination string) (created bool, err error)

SeedWatchFolder inserts one enabled row for path — the DLTOOL_WATCH_DIR seed — and reports whether it created the row.

func (*SettingsStore) SetInt64

func (s *SettingsStore) SetInt64(ctx context.Context, key string, v int64) error

SetInt64 upserts one settings key as a bare JSON integer — the grammar GetInt64 accepts.

func (*SettingsStore) TouchEngine

func (s *SettingsStore) TouchEngine(ctx context.Context, id string, version, lastErr *string, at int64) error

TouchEngine records the outcome of a probe. A success (lastErr nil) stamps last_seen_at, clears last_error and stores version whenever the probe resolved one; a failure records last_error alone, so the last successful contact survives an outage.

func (*SettingsStore) TouchNotificationChannel

func (s *SettingsStore) TouchNotificationChannel(ctx context.Context, id string, lastErr *string, at int64) error

TouchNotificationChannel records the outcome of one delivery attempt: last_send_at is the attempt time on success and failure alike, and last_error carries the failure text or NULL after a success (the semantics of docs/04-data-model.md section 3.2). ErrNotFound means the channel was deleted between enqueue and delivery.

func (*SettingsStore) TouchWatchFolder

func (s *SettingsStore) TouchWatchFolder(ctx context.Context, id string, at int64, lastErr string) error

TouchWatchFolder writes last_scan_at and last_error after a scan; an empty lastErr clears the column. ErrNotFound means the id addresses no row.

func (*SettingsStore) UpdateCategory

func (s *SettingsStore) UpdateCategory(ctx context.Context, name string, newName, savePath *string) error

UpdateCategory writes the addressed row's name and save_path; a nil argument leaves that column untouched. ErrNotFound means name addresses no row; ErrConflict means newName belongs to another row.

func (*SettingsStore) WatchFolderLoaded

func (s *SettingsStore) WatchFolderLoaded(ctx context.Context, folderID, infohash string) (bool, error)

WatchFolderLoaded reports whether the folder's loaded set already holds infohash. An absent settings row is the empty set.

type Tag

type Tag struct {
	Name      string `db:"name"       json:"name"`
	TaskCount int    `db:"task_count" json:"task_count"`
}

Tag is one row of the tags table with the count of its non-removed tasks attached; the id never leaves the store because the API addresses a tag by its unique name.

type Task

type Task struct {
	ID         string  `db:"id" json:"id"`
	Engine     string  `db:"engine" json:"engine"`
	EngineRef  *string `db:"engine_ref" json:"engine_ref"`
	SourceKind string  `db:"source_kind" json:"source_kind"`
	SourceURI  *string `db:"source_uri" json:"source_uri"`
	// SourceDisplayURI is the API-safe reference rendered where the API would
	// otherwise show source_uri — "search-result:<res_id>" for a task created
	// from a search result, NULL for every other source. It is written at
	// insert and never re-derived; sync.DisplaySourceURI is the one sanitizing
	// fallback for rows that predate the column.
	SourceDisplayURI *string `db:"source_display_uri" json:"source_display_uri"`
	Name             string  `db:"name" json:"name"`
	InfohashV1       *string `db:"infohash_v1" json:"infohash_v1"`
	InfohashV2       *string `db:"infohash_v2" json:"infohash_v2"`
	State            string  `db:"state" json:"state"`
	ErrorCode        *string `db:"error_code" json:"error_code"`
	ErrorMessage     *string `db:"error_message" json:"error_message"`
	Destination      string  `db:"destination" json:"destination"`
	ContentPath      *string `db:"content_path" json:"content_path"`
	CategoryID       *string `db:"category_id" json:"category_id"`
	TotalBytes       *int64  `db:"total_bytes" json:"total_bytes"`
	CompletedBytes   int64   `db:"completed_bytes" json:"completed_bytes"`
	UploadedBytes    int64   `db:"uploaded_bytes" json:"uploaded_bytes"`
	DownloadRate     int64   `db:"download_rate" json:"download_rate"`
	UploadRate       int64   `db:"upload_rate" json:"upload_rate"`
	ETASeconds       *int64  `db:"eta_seconds" json:"eta_seconds"`
	Sequential       int     `db:"sequential" json:"sequential"`
	QueuePosition    *int64  `db:"queue_position" json:"queue_position"`
	// SelectFiles is the persisted create-time file selection of
	// docs/05-api-contract.md section 5.2, one JSON SelectionIntent — the
	// selection the admission pass and re-submissions apply to the engine.
	SelectFiles *string `db:"select_files" json:"select_files"`
	DLLimit     int64   `db:"dl_limit" json:"dl_limit"`
	ULLimit     int64   `db:"ul_limit" json:"ul_limit"`
	AddedAt     int64   `db:"added_at" json:"added_at"`
	StartedAt   *int64  `db:"started_at" json:"started_at"`
	CompletedAt *int64  `db:"completed_at" json:"completed_at"`
	CreatedAt   int64   `db:"created_at" json:"created_at"`
	UpdatedAt   int64   `db:"updated_at" json:"updated_at"`
}

Task is one row of the tasks table. Column names and types are owned by docs/04-data-model.md section 3.3; the columns not present here take their DDL defaults on insert and are written by the tasks that own them (T020, T026, T036, T074).

type TaskEvent

type TaskEvent struct {
	ID         string  `db:"id" json:"id"`
	TaskID     string  `db:"task_id" json:"task_id"`
	At         int64   `db:"at" json:"at"`
	Level      string  `db:"level" json:"level"`
	Code       string  `db:"code" json:"code"`
	Message    string  `db:"message" json:"message"`
	DetailJSON *string `db:"detail_json" json:"detail_json"`
	CreatedAt  int64   `db:"created_at" json:"created_at"`
	UpdatedAt  int64   `db:"updated_at" json:"updated_at"`
}

TaskEvent is one row of the task_events table (docs/04-data-model.md section 3.3). Code is a dotted i18n key, never a formatted value (docs/14-conventions.md section 4).

type TaskFile

type TaskFile struct {
	ID             string `db:"id"`
	TaskID         string `db:"task_id"`
	FileIndex      int    `db:"file_index"`
	Path           string `db:"path"`
	SizeBytes      int64  `db:"size_bytes"`
	CompletedBytes int64  `db:"completed_bytes"`
	Selected       int    `db:"selected"`
	Priority       *int   `db:"priority"`
	CreatedAt      int64  `db:"created_at"`
	UpdatedAt      int64  `db:"updated_at"`
}

TaskFile is one row of the task_files table (docs/04-data-model.md section 3.3). Path is relative to tasks.destination; joining it onto the destination belongs to the caller, which owns the path-safety check.

type TaskFileSelection

type TaskFileSelection struct {
	Selected int
	Priority *int
}

TaskFileSelection is one index's new selection state: the 0/1 selected flag and the priority of docs/04-data-model.md section 4.3. A nil Priority writes NULL — the storage shape of an engine that drives selection alone, aria2's.

type TaskFilter

type TaskFilter struct {
	State       string // a canonical state, or a sidebar filter name
	Category    string
	HasCategory bool
	Tag         string
	HasTag      bool
	Query       string // case-insensitive substring of name
	Sort        string // a column from the allowlist, optionally prefixed with '-'
	Limit       int    // 1..500, default 100
	Cursor      string // opaque; bound to the filter and sort that produced it
}

TaskFilter is the parsed query of GET /tasks. An empty field means "no constraint"; Category and Tag set to the empty string with the matching Has flag select uncategorised and untagged tasks.

type TaskPatch

type TaskPatch struct {
	Name             *string
	CategoryID       *string
	DLLimit          *int64
	ULLimit          *int64
	RatioLimit       *float64
	SeedingTimeLimit *int64
	Sequential       *bool
}

TaskPatch carries the PATCH-able columns of docs/05-api-contract.md section 5.5. A nil field leaves its column untouched. Tags are absent because they live in task_tags, and destination is absent because the cross-filesystem move is owned by T076.

func (TaskPatch) Empty

func (p TaskPatch) Empty() bool

Empty reports whether the patch carries no column at all — a tags-only PATCH, whose set lives in task_tags and never reaches Update.

type TaskStore

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

TaskStore persists tasks rows and enforces the task state machine.

func NewTaskStore

func NewTaskStore(db *sqlx.DB) *TaskStore

NewTaskStore returns a TaskStore over db.

func (*TaskStore) AppendEvent

func (s *TaskStore) AppendEvent(ctx context.Context, taskID, level, code, message string, detail any) error

AppendEvent inserts one task_events row. level is "info", "warn" or "error"; code is a dotted vocabulary key from docs/14-conventions.md section 4, never a formatted value. detail is marshalled into detail_json; a nil detail stores NULL.

func (*TaskStore) ClaimParkedDiskFull

func (s *TaskStore) ClaimParkedDiskFull(ctx context.Context, id string) (bool, error)

ClaimParkedDiskFull atomically revalidates the persisted paused+disk_full pair: one guarded no-op write whose RETURNING row reports whether the store still holds the pair the caller selected the candidate by. It is the admission pass's claim before its first engine call (T128): once taken, the pair stays untouched — a crash between the claim and the engine call leaves the row exactly as selectable as before and needs no recovery write, because no marker was stored. Clearing the stamp as the claim would instead make that crash indistinguishable from an operator takeover and strand the row outside the candidate query. The registry's task-operation lease owns in-process exclusion (ADR-0004's one process); this write owns the persisted revalidation after selection. taken is false when the row is present but the pair no longer matches — moved or cleared, an overtaken candidate, never an engine rejection; a missing id is ErrNotFound, distinguished from a decline by a read in the same transaction. The update's guard is never loosened to tell the two apart, and changed-row counts are never read: RETURNING answers directly.

func (*TaskStore) ClearHoldCode

func (s *TaskStore) ClearHoldCode(ctx context.Context, id string) error

ClearHoldCode clears a hold stamp unless the task is paused, and only ever a hold stamp: the write matches the two admission hold codes, so a row that moved on to a real failure between the pass's read and this clear keeps its own code. The admission pass's release cleanup uses it: between the release's transition and its cleanup a concurrent disk-full pause may have parked the task carrying disk_full, and wiping that stamp would strand the row outside the pass's selection (FR-048). A missing id is ErrNotFound; a paused row or a row carrying anything but a hold code is left untouched and reports success — the clear lost the race on purpose.

func (*TaskStore) ClearPausedHoldCode

func (s *TaskStore) ClearPausedHoldCode(ctx context.Context, id string) (bool, error)

ClearPausedHoldCode clears a hold stamp (disk_full or concurrency_limit) off a paused row and reports whether it wiped one: the operator pause's takeover (T127). Only a paused row carrying a hold stamp matches, so the admission pass — which selects candidates by the paused+disk_full pair — can never resume a task the operator deliberately parked. A row in any other state, or a paused row carrying any other code, is left untouched and reports false; a missing id is ErrNotFound, distinguished from a declined clear by a read in the same transaction. It never touches state: the task is paused already, and only the stamp hands the row to the pass. Unlike ClearHoldCode — the admission release's cleanup, which refuses paused rows on purpose — this clear exists precisely for them.

func (*TaskStore) CountActive

func (s *TaskStore) CountActive(ctx context.Context) (ActiveCounts, error)

CountActive returns the concurrency-counted set as one snapshot: total and per-engine counts of the four counted states, seeding excluded by the query itself.

func (*TaskStore) Create

func (s *TaskStore) Create(ctx context.Context, t Task) (Task, error)

Create inserts one task, generating the id when empty, defaulting an empty state to the state machine's entry state queued (docs/03-architecture.md section 8.1) and stamping added_at, created_at and updated_at with the same Unix millisecond. It returns the row as stored. It writes no event: fixtures and internal seeds use it, and the create path uses CreateLogged so a task row never exists without its task.created row (FR-150).

func (*TaskStore) CreateLogged

func (s *TaskStore) CreateLogged(ctx context.Context, t Task) (Task, error)

CreateLogged inserts one task and its task.created event in a single transaction, so a task row can never persist without the first entry of its event log. The row semantics are Create's.

func (*TaskStore) Delete

func (s *TaskStore) Delete(ctx context.Context, id string) error

Delete removes the task row outright; task_events, task_files, tags and pending jobs follow by ON DELETE CASCADE. This is the hard delete the post-download auto-remove preference needs (doc 04 section 3.6) — MarkRemoved's tombstone keeps the row, Delete erases it. A missing id is ErrNotFound.

func (*TaskStore) ExtractPassword

func (s *TaskStore) ExtractPassword(ctx context.Context, id string) (secure.Secret, error)

ExtractPassword returns the task's stored extraction password, the empty Secret when the column is NULL. ErrNotFound means the id addresses no task. The value is a secret: it never enters a log line, an error string or an API payload.

func (*TaskStore) FindByInfohash

func (s *TaskStore) FindByInfohash(ctx context.Context, v1, v2 string) (Task, error)

FindByInfohash returns the live task matching either hash. Empty arguments never match. A hybrid torrent submitted by its v1 magnet and later by its v2 magnet resolves to the same row, which is why the two columns are always queried together and never one at a time. It returns ErrNotFound when no live task carries either hash.

func (*TaskStore) Get

func (s *TaskStore) Get(ctx context.Context, id string) (Task, error)

Get returns the task with the given id, or ErrNotFound.

func (*TaskStore) ListEvents

func (s *TaskStore) ListEvents(
	ctx context.Context,
	taskID string,
	limit int,
	cursor string,
) ([]TaskEvent, string, int, error)

ListEvents returns one page of events for a task, newest first, with the same cursor envelope as every other list endpoint (docs/05-api-contract.md section 1.4): limit defaults to 100 and is re-checked against the 1..500 range, total counts every row of the task ignoring the cursor, and nextCursor is empty exactly on the last page. cursor is the opaque token a previous page returned; a token that is not one is ErrStaleCursor. There is no filter or sort to bind a token to — the endpoint's filter is the task id and its sort is fixed — so a well-formed token of another task simply continues that task's walk.

func (*TaskStore) ListFiles

func (s *TaskStore) ListFiles(ctx context.Context, taskID string) ([]TaskFile, error)

ListFiles returns the task's recorded files in file_index order, the enumerated targets of the delete path (docs/05-api-contract.md 5.6 step 1). It reads task_files alone — never the filesystem.

func (*TaskStore) ListNonTerminalByEngine

func (s *TaskStore) ListNonTerminalByEngine(ctx context.Context, engineName string) (map[string]Reconcilable, error)

ListNonTerminalByEngine returns engine_ref -> Reconcilable for one engine's tasks, skipping the terminal states and the tasks that hold no engine handle yet. It is the join input of the reconciliation sweep: the reconciler matches the engine's live list against these handles, and a handle the map does not carry is foreign and ignored (ADR-0017).

func (*TaskStore) ListScheduleParked

func (s *TaskStore) ListScheduleParked(ctx context.Context) ([]string, error)

ListScheduleParked returns the ids of the parked set: tasks currently paused whose most recent task_events row carries task.schedule.paused. A task the user paused has task.paused as its most recent row and is never returned; a parked task the user resumed has task.resumed and likewise left the set.

func (*TaskStore) ListTasks

func (s *TaskStore) ListTasks(ctx context.Context, f TaskFilter) ([]Task, string, int, error)

ListTasks returns one page plus the next cursor and the total matching the filter, ignoring the cursor. ErrStaleCursor is returned when the cursor was issued for a different filter or sort. The page is ordered by the sort column with the id as tiebreak, so the ordering is total and the cursor walk misses nothing.

func (*TaskStore) MarkAdmissionPending

func (s *TaskStore) MarkAdmissionPending(ctx context.Context, id string) (bool, error)

MarkAdmissionPending records the admission pass's ownership of a queued row whose engine transfer the pass still owes work to mid-release — a pending file selection the next tick retries, or a release whose final transition did not land over a running transfer. While marked, the row counts toward the concurrency totals and skips the hold gates, because the transfer it holds is already running; engine_ref alone cannot carry that meaning, because an ordinary resume requeues a task still holding its stopped handle. The flag clears with every state transition, so it marks ownership only while the row is queued. true reports the row is queued under the pass's ownership — the write landing now or an earlier mark already standing; false a present row that is not queued; a missing id is ErrNotFound, distinguished from a decline by a read in the same transaction, the same discipline ClaimParkedDiskFull keeps.

func (*TaskStore) MarkRemoved

func (s *TaskStore) MarkRemoved(ctx context.Context, id string, data *DeletedData) error

MarkRemoved tombstones a task, running steps 5 and 6 of the delete path (docs/05-api-contract.md 5.6) in one transaction: the task.removed event, plus the warn-level task.data_deleted event carrying data when the request unlinked files, then state="removed", engine_ref=NULL, both rates zeroed and eta_seconds and queue_position cleared, so the task leaves dl-tool's queue. It never deletes a row: the task and every child row stay so the event and file history remain queryable.

func (*TaskStore) PauseDuplicate

func (s *TaskStore) PauseDuplicate(ctx context.Context, taskID string) error

PauseDuplicate lands the late collision of FR-023: the task whose metadata resolved onto another live task's identity is paused in place with error_code torrent_duplicate and one task_events row, and neither the row nor its data is deleted — the transfer stops, the history stays, and the operator decides. It is idempotent: a row already paused under this code reports success without writing, so a caller retrying after its engine-side stop failed neither errors nor double-logs.

func (*TaskStore) PauseWithCode

func (s *TaskStore) PauseWithCode(ctx context.Context, id string, p CodedPause) error

PauseWithCode moves a task to paused and stamps its error_code pair in one transaction, with one task_events row — the disk-full pause's atomic landing (FR-048). Atomicity is the whole point: the admission pass's release cleanup clears hold codes concurrently, and a pause landing as two writes could be split by that clear into a paused row without the code the pass selects candidates by. FromStates closes the read-to-write window: a task that left the writing states between the caller's read and this transaction is left untouched instead of being dragged back into paused by the universal rules. An empty ErrorCode is a caller bug — the stamp is the reason this method exists. A missing id is ErrNotFound; an illegal source is ErrIllegalTransition; a state that changed underneath is ErrTransitionConflict.

func (*TaskStore) ReorderQueue

func (s *TaskStore) ReorderQueue(ctx context.Context, ids []string, move QueueMove) ([]string, error)

ReorderQueue moves ids inside the queue — every task whose queue_position is not NULL — and renumbers the whole queue densely from 1 in one transaction. No engine is contacted: dl-tool owns the queue (docs/05-api-contract.md section 5.7). It returns the requested ids that are not part of the queue, in request order, so the caller can answer them per-id.

func (*TaskStore) ReplaceTrackers

func (s *TaskStore) ReplaceTrackers(ctx context.Context, taskID string, rows []Tracker) error

ReplaceTrackers replaces the task's task_trackers rows with rows in one transaction: delete all, then re-insert the listing keyed on idx_task_trackers_url. A repeated url in the listing keeps its first occurrence — the unique index would refuse the second, and the daemon's own listing is deduplicated, so a repeat means a duplicated announce and not two trackers.

func (*TaskStore) ResolveInfohashes

func (s *TaskStore) ResolveInfohashes(ctx context.Context, engineName, ref, v1, v2 string) (bool, error)

ResolveInfohashes lands one engine-reported metadata resolution: it maps the engine handle to the live task it belongs to, writes both hashes through SetInfohashes, and pauses the task when the resolved identity collides with another live task — error_code torrent_duplicate, one task_events row, nothing deleted (FR-023's late collision). duplicate reports that this landing paused a task, so the caller stops the engine-side transfer too. A handle no live task carries is a no-op, not an error: the delta path reports every owned torrent, and ownership lapses for exactly the rows that moved on. It is the single method the qBittorrent delta path needs, so the adapter stays free of any store type (the layering of docs/03-architecture.md section 5.2 keeps adapters off the store).

func (*TaskStore) ScheduleParked

func (s *TaskStore) ScheduleParked(ctx context.Context, taskID string) error

ScheduleParked pauses one task for the schedule and records that the schedule — not the user — paused it, by appending a task_events row with code task.schedule.paused in the same transaction (T081, FR-093). The parked set ListScheduleParked reads back is exactly these rows. The write lands only while the row is in one of scheduleParkSources: a task the operator paused first keeps its task.paused tail and is never added to the set, and a task that moved on between the governor's scan and this write reports ErrTransitionConflict rather than being dragged into paused. A missing id is ErrNotFound.

func (*TaskStore) SelectQueuedCandidates

func (s *TaskStore) SelectQueuedCandidates(ctx context.Context, limit int) ([]Candidate, error)

SelectQueuedCandidates returns the pass's candidates in process order — oldest added_at first (FR-095) — at most limit of them: every queued task plus the paused tasks carrying error_code disk_full, which the pass re-examines each tick (FR-048). limit <= 0 means every candidate, which is what the admission pass asks for: a held task must carry its hold code wherever it sits in the queue, so the pass cannot stop at the first candidate it cannot release.

func (*TaskStore) SetEngineRef

func (s *TaskStore) SetEngineRef(ctx context.Context, id, engineRef string) error

SetEngineRef records the engine-side identity (aria2 GID, qBittorrent infohash, yt-dlp job id) once the engine accepted the task. A guarded update makes the write itself decide the acceptance event: the handle landing or changing writes the row, bumps updated_at and logs engine.accepted in the same transaction; a re-set of the handle already stored — a reconciliation loop re-learning it — writes nothing at all. A missing id is ErrNotFound.

func (*TaskStore) SetErrorCode

func (s *TaskStore) SetErrorCode(ctx context.Context, taskID, code, message string) error

SetErrorCode sets tasks.error_code and tasks.error_message. code must be a value of docs/04-data-model.md section 4.2; an unknown code is a programming error and panics rather than writing a value the CHECK constraint and the frontend translations both reject.

func (*TaskStore) SetErrorCodeIfState

func (s *TaskStore) SetErrorCodeIfState(ctx context.Context, id, expectedState, errorCode, message string) error

SetErrorCodeIfState writes tasks.error_code and error_message only while the row is still in expectedState, or clears both when errorCode is empty (SQL NULL is the storage form of an absent value; a cleared code never keeps its message). The state predicate is the stamp-side twin of PauseWithCode's FromStates: a hold stamp minted from a candidate snapshot must not land on a row the operator moved meanwhile — a paused row stamped disk_full is exactly the pair the admission pass selects guard-parked tasks by, and stamping it would hand the next pass a licence to resume what the user parked. A declined write (the row left expectedState) reports success on purpose: a 1 Hz pass racing an operator action must neither warn per tick nor retry. The pair guard is the quiet no-op: a row already carrying exactly this pair writes nothing, so a caller re-stamping a held task every tick is silent. No task_events row is written — this is column bookkeeping; the event moments stay with the transitions and stores that own them. A missing id is ErrNotFound.

func (*TaskStore) SetExtractProgress

func (s *TaskStore) SetExtractProgress(ctx context.Context, taskID string, percent int) error

SetExtractProgress writes tasks.unzip_progress (0–100) and holds state at extracting: the write is a no-op error on any other state, so a progress tick can never resurrect a task the operator moved on from under the extractor. The range check is a programming-error guard — the handler computes percent from capped counters.

func (*TaskStore) SetInfohashes

func (s *TaskStore) SetInfohashes(ctx context.Context, taskID, v1, v2 string) error

SetInfohashes fills both columns once metadata resolves. It is idempotent — a repeated call with the values the row already stores writes nothing, not even updated_at — refuses to overwrite a non-empty column with a different value, and returns ErrDuplicateInfohash when the resolved hash collides with another live task. An empty argument means "unknown", never "clear": the stored column survives it, and an empty string is stored as NULL because the partial unique indices cover the non-null rows only.

func (*TaskStore) SetSelectionIntent

func (s *TaskStore) SetSelectionIntent(ctx context.Context, taskID string, sel *SelectionIntent) error

SetSelectionIntent rewrites a task's persisted select_files document — the write PATCH /tasks/{id}/files makes after the engine accepted the change, so the stored intent always matches what the engine holds. A nil intent clears the column.

func (*TaskStore) Settings

func (s *TaskStore) Settings() *SettingsStore

Settings returns the sibling store over the same database, for a collaborator that spans both table families — the extract handler's password source reads tasks.extract_password and the extract_passwords settings row.

func (*TaskStore) SumRemainingByDestination

func (s *TaskStore) SumRemainingByDestination(ctx context.Context) (map[string]int64, error)

SumRemainingByDestination returns the committed-but-unwritten bytes per destination path: SUM(total_bytes - completed_bytes) over the four counted active states, the same set CountActive counts, with each task's contribution clamped at 0. The admission pass folds these per-destination sums into one pool per filesystem with fsx.FilesystemID, so two destinations on one mount share one reservation (FR-047). A task whose total_bytes is NULL reserves 0 — an unknown size reserves no headroom and is re-checked when metadata resolves — and a task reporting completed past its total cancels nothing.

func (*TaskStore) Transition

func (s *TaskStore) Transition(ctx context.Context, id, next, code, message string) error

Transition moves a task to next, writing one task_events row with code and message in the same transaction. It returns ErrIllegalTransition and mutates nothing when the move is not permitted, and ErrNotFound when the task does not exist.

func (*TaskStore) Update

func (s *TaskStore) Update(ctx context.Context, id string, patch TaskPatch) error

Update writes the columns a patch carries and bumps updated_at, in one UPDATE whose column list is built from the patch's non-nil fields alone, so an omitted field is never written (docs/05-api-contract.md 5.5). A missing id is ErrNotFound; an empty patch is a caller bug and errors rather than bumping updated_at for nothing.

func (*TaskStore) UpdateFileSelection

func (s *TaskStore) UpdateFileSelection(ctx context.Context, taskID string, sel map[int]TaskFileSelection) error

UpdateFileSelection writes selected and priority for the listed indices in one transaction, after the engine has accepted the same change: the store mirrors what the engine now reports, so the next listing's upsert writes the same values back. An index with no task_files row answers ErrNotFound naming it — the caller validated against a listing that the row set no longer matches. An empty selection is a caller bug: the endpoint's body requires at least one entry, and an empty write would silently succeed while touching nothing.

func (*TaskStore) UpdateProgress

func (s *TaskStore) UpdateProgress(ctx context.Context, id string, p Progress) error

UpdateProgress replaces the transfer counters of a task and bumps updated_at. A missing id is ErrNotFound: the poller reads that as the signal to stop polling the task.

func (*TaskStore) UpsertFiles

func (s *TaskStore) UpsertFiles(ctx context.Context, taskID string, files []TaskFile) error

UpsertFiles replaces the task's task_files rows from an engine listing, keyed on (task_id, file_index): listed indices insert or update, an index the listing no longer carries is deleted. Selected and priority come from the listing — the engine owns a listing's truth — so the write that follows a PATCH reads back the priorities the engine accepted. ids and timestamps are generated here; one transaction carries every row.

type Tracker

type Tracker struct {
	URL                string `db:"url"`
	Status             string `db:"status"`
	UpdateTimerSeconds *int   `db:"update_timer_seconds"`
	Seeds              *int   `db:"seeds"`
	Peers              *int   `db:"peers"`
	Message            string `db:"message"`
}

Tracker is one row of the task_trackers table (docs/04-data-model.md section 3.3), the mirror of the engine's listing. Status and Message are the engine-reported strings, stored verbatim — an absent engine message stores as the empty string, never NULL; the pointer columns are nil for the values the engine does not report.

type User

type User struct {
	ID           string `db:"id" json:"id"`
	Username     string `db:"username" json:"username"`
	PasswordHash string `db:"password_hash" json:"-"`
	Enabled      bool   `db:"enabled" json:"enabled"`
	Locale       string `db:"locale" json:"locale"`
	LastLoginAt  *int64 `db:"last_login_at" json:"-"`
	CreatedAt    int64  `db:"created_at" json:"-"`
	UpdatedAt    int64  `db:"updated_at" json:"-"`
}

User is the single operator account (docs/04-data-model.md section 3.1).

func UserByAPITokenHash

func UserByAPITokenHash(ctx context.Context, db *sqlx.DB, hash string) (User, error)

UserByAPITokenHash resolves a bearer token hash to its user and stamps last_used_at, at most once per apiTokenTouchIntervalMS. A revoked or expired token is ErrNotFound, like an unknown hash.

func UserByID

func UserByID(ctx context.Context, db *sqlx.DB, id string) (User, error)

UserByID returns the user with the given id, or ErrNotFound.

func UserByUsername

func UserByUsername(ctx context.Context, db *sqlx.DB, username string) (User, error)

UserByUsername returns the user with the given username, or ErrNotFound. A failed lookup must be answered like a wrong password by the caller.

type UserStore

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

UserStore owns the api_tokens table: issue, list and revoke of docs/05-api-contract.md section 12. The bearer resolution above stays a package function for its existing caller; everything else goes through this wrapper, like SettingsStore and TaskStore wrap theirs.

func NewUserStore

func NewUserStore(db *sqlx.DB) *UserStore

NewUserStore wraps db. A nil db — the openapi subcommand — builds a store whose calls fail on use, which serving prevents.

func (*UserStore) CreateAPIToken

func (s *UserStore) CreateAPIToken(ctx context.Context, t APIToken) error

CreateAPIToken inserts one api_tokens row. The caller owns every field: t.ID (a tok_ ULID), t.TokenHash (the SHA-256 hex of the bearer value) and t.Prefix (its first 8 characters) included, so the clear-text value never reaches the store — only its hash does.

func (*UserStore) ListAPITokens

func (s *UserStore) ListAPITokens(
	ctx context.Context,
	userID string,
	limit int,
	cursor string,
) ([]APIToken, string, int, error)

ListAPITokens returns one page of the account's live tokens, newest first, with the same cursor envelope as every other list endpoint (docs/05-api-contract.md section 1.4): limit defaults to 100 and is re-checked against the 1..500 range, total counts every live token ignoring the cursor, and nextCursor is empty exactly on the last page. A cursor that is not a page token is ErrStaleCursor; a well-formed one simply continues the walk — there is one account, so there is no filter to bind it to. Revoked rows are the audit trail only and never list.

func (*UserStore) RevokeAPIToken

func (s *UserStore) RevokeAPIToken(ctx context.Context, userID, id string) error

RevokeAPIToken sets revoked_at on the token owned by userID. The row is kept — it is the audit trail — but it no longer lists or authenticates. An unknown, foreign or already-revoked id is ErrNotFound.

func (*UserStore) TouchAPIToken

func (s *UserStore) TouchAPIToken(ctx context.Context, id string, at int64) error

TouchAPIToken stamps last_used_at, at most once per apiTokenTouchIntervalMS: the update is a no-op while the stored stamp is fresher, so a chatty bearer client never turns into a write per request. The revoked_at recheck keeps a token revoked after its lookup unstamped.

type WatchFolder

type WatchFolder struct {
	ID              string  `db:"id"`
	Path            string  `db:"path"`
	Enabled         int     `db:"enabled"`
	Destination     string  `db:"destination"`
	Category        *string `db:"category"`
	DeleteAfterLoad int     `db:"delete_after_load"`
	PollIntervalS   int     `db:"poll_interval_s"`
	LastScanAt      *int64  `db:"last_scan_at"`
	LastError       *string `db:"last_error"`
	CreatedAt       int64   `db:"created_at"`
	UpdatedAt       int64   `db:"updated_at"`
}

WatchFolder is one row of watch_folders with the category name joined in from categories (docs/04-data-model.md section 3.6); Category is NULL when the folder has none or the category row was deleted (ON DELETE SET NULL).

Jump to

Keyboard shortcuts

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