server

package
v0.7.0-dev.14 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: AGPL-3.0 Imports: 63 Imported by: 0

Documentation

Overview

Package server — Content-Security-Policy construction.

The CSP is computed once at startup from the embedded HTML entrypoints rather than hardcoded, so the inline <head> script — the anti-FOUC <script data-theme-init> IIFE (@cplieger/ui-primitives' themeInitSnippet output) — is allowed by an exact sha256 hash. Under default-src 'self' an inline script has no exception, so without a matching script-src hash the browser blocks it and the page flashes the wrong theme before the stylesheets load. Deriving the hash from the embedded file means an edit (even a whitespace-only reformat) needs no hand-updated constant. (The former second inline script, the importmap, is gone: cmd/bundle resolves every bare specifier at build time.)

Package server provides the HTTP server and history poller for subtitle management.

The package is split across several files by concern:

  • server.go — New() constructor and lifecycle (this file)
  • server_types.go — Server struct, embedded dep groups, Option functions
  • server_init.go — initHandlers (handler family construction)
  • middleware.go — requireAuth / requireRole / requireConfigured
  • routes.go — route table + registerRoutes + permission model
  • poller.go — Sonarr/Radarr history polling + import processing
  • scheduler.go — full-scan pipeline + DB maintenance + auth cleanup
  • *_handlers.go — per-concern HTTP handler families

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewProviderGateHook added in v0.6.6

func NewProviderGateHook(alerts *activity.AlertLog, label func(subflux.ProviderID) string,
	publish func(op events.ProviderOp, id subflux.ProviderID),
) func(providergate.Event)

NewProviderGateHook turns credential gate events into operator alerts and provider events. label names a provider the way the settings dialog does.

func NewProviderPublisher added in v0.6.6

func NewProviderPublisher(bus *events.EventBus, status ProviderStatusSource) func(op events.ProviderOp, id subflux.ProviderID)

NewProviderPublisher returns the only builder of provider SSE events. Every event carries the provider's full status as status reports it at publish time, because the client replaces its record with each event's status.

Types

type AuthStore added in v0.4.0

AuthStore is the persistence surface SetAuth requires: the union of the narrow interfaces its consumers declare — the library's own Authenticator contract plus the four handler-side roles. The auth library publishes no composite of its own (v4 merged the store SPI into its root package and exposes it as role interfaces), so the union is declared here, at the one site that fans a single concrete store out to all five consumers.

type Metrics

type Metrics interface {
	search.Metrics
	scanning.ScanMetrics
	polling.PollerMetrics
	queryhandlers.MetricsReader
	scheduler.ReconcileMetrics
	events.Metrics
	// contains filtered or unexported methods
}

Metrics is the observability surface the server package wires. It is a composition of roles rather than a flat method list: the first group is the seams the subsystems declare for themselves, the rest are the server's own. A consumer takes the one role it records against; this union exists only because the composition root wires a single concrete recorder to all of them, and it is the only place their sum is named.

type Option

type Option func(*Server)

Option configures a Server during construction.

func WithAlertLog added in v0.6.6

func WithAlertLog(al *activity.AlertLog) Option

WithAlertLog sets the alert log (required). The composition root owns it because the media writer raises into it before the server exists.

func WithArrClientFactories added in v0.1.106

func WithArrClientFactories(
	newSonarr func(baseURL, apiKey string, reads *arrsvc.ReadGate) (SonarrClient, error),
	newRadarr func(baseURL, apiKey string, reads *arrsvc.ReadGate) (RadarrClient, error),
) Option

WithArrClientFactories sets the factories for creating Sonarr and Radarr API clients, used by hot reload and config-save connectivity checks. The reads gate is the server's shared arr-read wrapper half; main.go's factories build the wrapped clients (arrsvc.CachedSonarr/CachedRadarr) around it.

func WithConfig

func WithConfig(cfg *config.Config) Option

WithConfig sets the initial configuration. Config-only by design: arr clients (and every other config-derived capability) are constructed by activation in both boot modes, never handed in from outside.

func WithConfigLoader

func WithConfigLoader(l confighandlers.ConfigLoader) Option

WithConfigLoader sets the config loader. Typed as the config handlers' own func type rather than re-declared here: this package never calls it, it only carries the value from the composition root to confighandlers, which does.

func WithDefaultConfig

func WithDefaultConfig(cfg []byte) Option

WithDefaultConfig sets the embedded default config bytes.

func WithLogSetup added in v0.1.148

func WithLogSetup(f func(level, format string)) Option

WithLogSetup injects the process-global logging setup so activation can re-apply a changed logging section without a restart. Owned by the composition root (main.go's setupLogging).

func WithMediaPresence added in v0.6.6

func WithMediaPresence(c *mediapresence.Checker) Option

WithMediaPresence sets the process-wide judge of which media files are gone (required by Start).

func WithMediaWriter added in v0.6.6

func WithMediaWriter(mw *mediawrite.Writer) Option

WithMediaWriter sets the process-wide media write guard (required by Start).

func WithMetrics

func WithMetrics(m Metrics) Option

WithMetrics sets the metrics recorder. REQUIRED despite being an Option: twenty-two sites dereference s.metrics unguarded, so omitting it panics rather than degrading. requireServiceable asserts it at Start.

func WithPort

func WithPort(port int) Option

WithPort sets the HTTP listen port (unconfigured mode).

func WithProviderGate added in v0.6.6

func WithProviderGate(g *providergate.Gate) Option

WithProviderGate sets the provider credential gate. REQUIRED: New installs its event hook and every activation hands it the new binding.

func WithSchema

func WithSchema(f subflux.SchemaFunc) Option

WithSchema sets the config schema function.

func WithSubtitleProc

func WithSubtitleProc(p synchandlers.SubtitleProcessor) Option

WithSubtitleProc sets the subtitle processor. WithSubtitleProc injects the SRT processor. Typed as the sync handlers' own interface rather than re-declared here: the server calls none of its methods, it only carries the value to synchandlers and previewhandlers, and previewhandlers takes a narrower view of the same value.

func WithSyncRunner added in v0.5.0

func WithSyncRunner(r synchandlers.AudioJobRunner) Option

WithSyncRunner injects the typed sync core the async job executor drives. The composition root passes the SAME syncworker client the engine's SyncExec uses, so dispatched jobs and automatic syncs share the one execution slot (a second client would double the alignment concurrency).

func WithWire

func WithWire(w wiring.Func) Option

WithWire sets the provider wiring function.

type ProviderStatusSource added in v0.6.6

type ProviderStatusSource func(id subflux.ProviderID) (status subflux.ProviderStatus, timeoutsEnabled bool)

ProviderStatusSource answers one provider's full merged status and whether provider timeouts are enabled.

type RadarrClient added in v0.4.0

RadarrClient is SonarrClient's movie-side twin; see that doc for the width and the placement. Nine methods, from the same ten consumers plus the ping.

type Server

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

Server is the main application server.

func New

func New(db Store, reg confighandlers.SchemaRegistry, opts ...Option) *Server

New creates a Server with the given options. db and reg are required.

func (*Server) AdminHandler added in v0.1.148

func (s *Server) AdminHandler() http.Handler

AdminHandler returns the admin-socket plane's handler.

Exported for the composition root: main.go owns that listener's lifecycle and binds it to the Unix socket. The plane itself lives in internal/server/adminsocket — its three handlers read one collaborator and no live state, so they were the last handler cluster with no reason to sit on this type.

The plane is constructed HERE rather than held as a field, because a field would need building after SetAuth supplies the store and would be nil until then — another ordering rule in a type that already has one too many. adminsocket.Plane holds nothing but its Deps, so building one costs nothing and this is called once per process anyway.

func (*Server) GoBackground added in v0.4.0

func (s *Server) GoBackground(fn func())

GoBackground runs fn on the server's background goroutine set — the one set serveAndWait drains, on a bounded budget, after HTTP shutdown completes. The composition root uses it for the process-lifetime goroutines it owns rather than the server (the admin bootstrap socket), so a goroutine started outside this package still has an observable completion.

Registration must happen before shutdown begins; the set is only waited on after the request context is cancelled, so an fn that serves until ctx ends is joined rather than abandoned.

func (*Server) RecordPersistentAlert added in v0.1.148

func (s *Server) RecordPersistentAlert(source, msg string)

RecordPersistentAlert records a manually-dismissable operator alert. Exported for the composition root: main.go owns the admin-socket listener lifecycle and reports its failure as a persistent alert here (degraded mode — bootstrap unavailable — rather than fatal).

func (*Server) SetAuth

func (s *Server) SetAuth(store AuthStore, rl ratelimit.Checker) error

SetAuth configures authentication dependencies on the server. WebAuthn and OIDC are deliberately absent from the signature: both are config-derived capabilities that activation builds into the live snapshot, resolved per request through the handler's resolver funcs. SetAuth returns an error only when the assembled authenticator configuration is rejected by the auth library's construction validation (a programming error, not runtime state).

func (*Server) Start

func (s *Server) Start(ctx context.Context, onReady func())

Start activates the boot config and starts the HTTP server. Cold boot and hot first-save go through the SAME activation operation (activate.go); the only cold-boot special case is the failure policy — an activation failure falls back to settings mode instead of refusing to serve, so a config that boots today keeps booting.

func (*Server) StartUnconfigured

func (s *Server) StartUnconfigured(ctx context.Context, onReady func())

StartUnconfigured starts the HTTP server without a valid config.

type SonarrClient added in v0.4.0

type SonarrClient interface {
	coveragehandlers.CoverageSonarrClient
	filehandlers.FileSonarrClient
	manualops.ManualSonarrClient
	manualops.ResolveSonarrClient
	mediahandlers.MediaSonarrClient
	polling.PollSonarrClient
	queryhandlers.StatsSonarrClient
	resolve.SonarrEpisodes
	scanning.ScanHandlerSonarr
	scanning.ScanSonarrClient

	// The connectivity check a config save runs before activating a changed
	// arr. confighandlers declares it as its own one-method surface, which is
	// why it is embedded here rather than listed: Ping is the only method of
	// these ten that no scan, poll or handler path calls.
	confighandlers.ArrPinger
}

SonarrClient and RadarrClient are the arr surfaces New requires: the union of the narrow interfaces their consumers declare, the same shape and the same reason as Store and AuthStore in server.go. This is the ONE site that fans a single concrete arr client out to every handler family, the scan and poll subsystems, the scheduler and the reference resolver, so the union belongs here rather than in a types package that implements none of it.

Composed by EMBEDDING, never by re-listing, so the width is derived: adding a method to polling.PollSonarrClient widens this automatically and removing one narrows it. The declaration these replace was a hand-written nine-method list in internal/subflux, and the ten embedded surfaces below then summed to exactly those nine — the list happened to be right, and nothing in the code would have noticed if it had stopped being. (The sum is eleven today: the coverage surface grew the error-returning exclude-tag form and the per-item tvdb→row index lookup the series summary answers from.)

The width, measured: 11 of *arrsvc.CachedSonarr's 21 exported methods and 9 of *arrsvc.CachedRadarr's 18, so unlike liveState.cfg below these ARE narrowing. No single consumer reads more than 5 of the 11 or 4 of the 9 — the poller, which is the only one that both polls history and looks items up by ID.

An interface rather than the concrete *arrsvc.CachedSonarr, which is the opposite call from cfg, and the difference is what the type is: the arr client is this process's only network boundary to Sonarr and Radarr, and this field is the one seam where it enters. internal/server's own suite drives handler behaviour through it with in-process fakes; a concrete HTTP client here would turn every one of those into a test that needs a fake server speaking arrapi's JSON. *config.Config, by contrast, is data a test can just build.

Exported because package main's arr factories name it in their return type, which is the same reason scanning.ScanCfg is exported for the scheduler.

type Store added in v0.4.0

type Store interface {
	// Handler families.
	queryhandlers.QueryStore
	synchandlers.SyncStore
	coveragehandlers.CoverageStore
	filehandlers.FileStore
	manualops.DownloadStore
	resolve.FileStore

	// Subsystems.
	polling.PollerStore
	scanning.ScanStore
	scanning.BackoffPrefixReader
	scheduler.Store
	search.Store

	// Coverage: the stats endpoint's two aggregate reads, and the one row read
	// the bound missing-count closure performs.
	queryhandlers.StatsStore
	coverage.FileReader

	// The store-backed capabilities the server itself operates: the hot
	// snapshot for the backup loop and the file gauges for /metrics. Both used
	// to be reached by type-asserting the wide interface and silently doing
	// nothing when it failed; declaring them here makes the requirement a
	// compile error instead of a Debug log.
	BackupInto(ctx context.Context, dest string) error
	StoreFileStats() (fileBytes, freelistBytes int64)

	// Read and write the history-poll watermark. Held by the server because
	// polling reads it through the write-through PollCache the server builds,
	// not directly.
	PollTimestamp(ctx context.Context, key subflux.PollKey) (time.Time, error)
	SetPollTimestamp(ctx context.Context, key subflux.PollKey, t time.Time) error

	// Drop search_attempts rows for languages and providers a config edit
	// removed. Called by activation, which is the server's own concern.
	CleanupDrift(ctx context.Context, drift subflux.ConfigDrift) error
}

Store is the persistence surface New requires: the union of the narrow interfaces its consumers declare. It is the same shape as AuthStore below and it exists for the same reason — this is the ONE site that fans a single concrete store out to every handler family, the scan and poll subsystems, the scheduler and the search engine, so the union belongs here rather than in a types package that implements none of it.

It is composed by EMBEDDING, never by re-listing. That is the whole difference from the 36-method whole-store interface this replaces: the width is derived from what the consumers ask for, so adding a method to filehandlers.FileStore widens this automatically and removing one narrows it. A hand-written list can only drift, and drifted for 36 methods of which the widest consumer used seven.

Nothing outside internal/server can take this: composition happens here, and every package below is handed the narrow interface it declared.

Directories

Path Synopsis
Package activity provides concurrent-safe activity and alert tracking for the subflux UI status indicator.
Package activity provides concurrent-safe activity and alert tracking for the subflux UI status indicator.
Package activityhandlers serves the activity log, the alert list, and the SSE event stream with its digest and presence-acknowledgement routes: the HTTP surface over the in-memory registries that record what the server is doing and what went wrong.
Package activityhandlers serves the activity log, the alert list, and the SSE event stream with its digest and presence-acknowledgement routes: the HTTP surface over the in-memory registries that record what the server is doing and what went wrong.
Package adminsocket serves the out-of-band admin plane: the one route the CLI posts to for password reset and API-key generation.
Package adminsocket serves the out-of-band admin plane: the one route the CLI posts to for password reset and API-key generation.
Package authhandlers provides shared types and utilities for the server's authentication handler cluster: login, WebAuthn, OIDC, admin user management, and security management (password change, API keys, passkeys).
Package authhandlers provides shared types and utilities for the server's authentication handler cluster: login, WebAuthn, OIDC, admin user management, and security management (password change, API keys, passkeys).
Package confighandlers provides HTTP handlers for configuration CRUD operations: get, save, reset, schema, and path validation.
Package confighandlers provides HTTP handlers for configuration CRUD operations: get, save, reset, schema, and path validation.
Package coverage provides pure computation functions for subtitle coverage analysis.
Package coverage provides pure computation functions for subtitle coverage analysis.
Package coveragehandlers provides HTTP handlers for the /api/coverage/* endpoints.
Package coveragehandlers provides HTTP handlers for the /api/coverage/* endpoints.
Package events is subflux's typed server-sent-events layer: the sealed Event/EventData types the app publishes, marshaled onto the shared cplieger/sse broadcast hub.
Package events is subflux's typed server-sent-events layer: the sealed Event/EventData types the app publishes, marshaled onto the shared cplieger/sse broadcast hub.
Package filehandlers provides HTTP handlers for the /api/files/* endpoints.
Package filehandlers provides HTTP handlers for the /api/files/* endpoints.
Package manualops implements the business logic for manual subtitle search and download operations.
Package manualops implements the business logic for manual subtitle search and download operations.
Package mediahandlers provides HTTP handlers for the /api/media/* endpoints.
Package mediahandlers provides HTTP handlers for the /api/media/* endpoints.
Package polling provides the history-polling subsystem for Sonarr/Radarr import events and the write-through poll timestamp cache.
Package polling provides the history-polling subsystem for Sonarr/Radarr import events and the write-through poll timestamp cache.
Package previewhandlers provides HTTP handlers for the video/subtitle preview and poster proxy endpoints.
Package previewhandlers provides HTTP handlers for the video/subtitle preview and poster proxy endpoints.
Package queryhandlers provides read-only HTTP query handlers: subtitle state, backoff, manual locks, providers, parsed config, score simulation, and dashboard stats.
Package queryhandlers provides read-only HTTP query handlers: subtitle state, backoff, manual locks, providers, parsed config, score simulation, and dashboard stats.
Package resolve is the one home for typed-reference resolution (S7): it maps the wire references — FileRef (one stored subtitle file) and MediaRef (the arr-known video of a media item) — to absolute filesystem paths using server-derived facts only.
Package resolve is the one home for typed-reference resolution (S7): it maps the wire references — FileRef (one stored subtitle file) and MediaRef (the arr-known video of a media item) — to absolute filesystem paths using server-derived facts only.
Package scanning implements the full-scan orchestration engine.
Package scanning implements the full-scan orchestration engine.
Package scheduler provides the periodic full-scan pipeline, DB maintenance, and auth cleanup scheduling for the subflux server.
Package scheduler provides the periodic full-scan pipeline, DB maintenance, and auth cleanup scheduling for the subflux server.
Package showskip provides a TTL-based cache for show-level subtitle pre-check results.
Package showskip provides a TTL-based cache for show-level subtitle pre-check results.
Package storeops runs the periodic operations that treat the bbolt file as an operational artifact rather than a set of rows: timestamped snapshots with retention pruning, and the file-size and freelist gauges.
Package storeops runs the periodic operations that treat the bbolt file as an operational artifact rather than a set of rows: timestamped snapshots with retention pruning, and the file-size and freelist gauges.
Package synchandlers provides HTTP handlers for subtitle sync operations (audio-based sync and manual offset adjustment).
Package synchandlers provides HTTP handlers for subtitle sync operations (audio-based sync and manual offset adjustment).
Package syncjobs owns the server-side async sync job machinery (D1, D2): a bounded FIFO dispatcher with an admission lease, the job record registry GET /api/sync/jobs serves, and the sync:done publication seam.
Package syncjobs owns the server-side async sync job machinery (D1, D2): a bounded FIFO dispatcher with an admission lease, the job record registry GET /api/sync/jobs serves, and the sync:done publication seam.

Jump to

Keyboard shortcuts

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