Documentation
¶
Overview ¶
Package api implements the Schedularr HTTP API defined by api/openapi.yaml.
Index ¶
- func ContextWithRequestID(ctx context.Context, id string) context.Context
- func NewRouter(cfg Config, d Deps) (http.Handler, error)
- func RequestIDFromContext(ctx context.Context) string
- func WriteProblem(w http.ResponseWriter, r *http.Request, status int, title, detail string)
- type Config
- type Deps
- type Handlers
- func (h *Handlers) ApplySchedule(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) CreateBlock(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) DeleteBlock(w http.ResponseWriter, r *http.Request, id string)
- func (h *Handlers) ExportBlocks(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) GenerateSchedule(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) GetBlock(w http.ResponseWriter, r *http.Request, id string)
- func (h *Handlers) GetHistory(w http.ResponseWriter, r *http.Request, params gen.GetHistoryParams)
- func (h *Handlers) GetMediaMeta(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) GetSchedule(w http.ResponseWriter, r *http.Request, params gen.GetScheduleParams)
- func (h *Handlers) GetStatus(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) ImportBlocks(w http.ResponseWriter, r *http.Request, params gen.ImportBlocksParams)
- func (h *Handlers) ListBlocks(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) ListChannels(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) ListMediaShows(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) ListSeriesState(w http.ResponseWriter, r *http.Request)
- func (h *Handlers) PatchSeriesState(w http.ResponseWriter, r *http.Request, showTitle string)
- func (h *Handlers) UpdateBlock(w http.ResponseWriter, r *http.Request, id string)
- type MediaAPI
- type Problem
- type TunarrAPI
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContextWithRequestID ¶
ContextWithRequestID returns a copy of ctx carrying the given request ID. The request-ID middleware (internal/api/middleware.RequestID) calls this once per request.
func NewRouter ¶
NewRouter builds the full HTTP handler for the Schedularr API server.
Four endpoints are served unauthenticated and outside the RequestID/Logging/BearerAuth chain entirely, so health and metrics probes stay cheap and never depend on a caller having a token. They do still run through Recovery (and only Recovery): a panic in any of them gets structured-logged and turned into a clean 500 problem+json response instead of net/http's bare connection-drop default, without paying for a request id or a logged line on every routine probe hit.
- GET /healthz -- process liveness only, no dependency checks.
- GET /readyz -- liveness plus a bounded store round-trip (store.Store.Ping, i.e. `SELECT 1`); 503 problem+json if the store isn't reachable within readyzTimeout.
- GET /metrics -- Prometheus text exposition via promhttp.Handler(), scraping the same default registry internal/metrics registers its collectors to.
- GET /openapi.json -- the OpenAPI contract itself, marshaled straight from gen.GetSpec() so it can never drift from what internal/api/gen actually implements.
Everything else is generated by gen.HandlerFromMux from d (via NewHandlers), mounted under /api/v1 on a chi sub-router wrapped RequestID -> Logging -> Recovery -> BearerAuth (outermost to innermost -- see each middleware's own doc comment for why that order matters: RequestID must run before Logging so a request id already exists to log, and Logging must wrap Recovery so a recovered panic's 500 still gets logged with the right status). BearerAuth is the innermost layer, right before the real handler; it's included unless cfg.InsecureNoAuth is set. An unmatched /api/v1/* path answers 404 problem+json (apiNotFoundHandler), not the UI's HTML 404 page.
Finally, when cfg.UI is set, every other GET/HEAD (i.e. anything that isn't one of the four system routes or under /api/v1) is served from it as a static site -- see newUIHandler. cfg.UI == nil skips this entirely, leaving chi's own default 404 for unmatched paths.
NewRouter itself performs no I/O and never blocks. Constructing middleware.BearerAuth is its only fallible step, so -- with InsecureNoAuth false -- the returned error is always a token-validation error: Token is empty or shorter than 32 characters.
func RequestIDFromContext ¶
RequestIDFromContext returns the request ID stored by ContextWithRequestID, or "" if none was set.
func WriteProblem ¶
WriteProblem writes an RFC 7807 problem+json response. Type is set to "about:blank" since Schedularr does not publish per-error type URIs. RequestID is populated from the request context when the request-ID middleware has set one.
Types ¶
type Config ¶
type Config struct {
// Token is the bearer token required on /api/v1/* requests
// (Authorization: Bearer <token>). middleware.BearerAuth enforces a
// 32-character minimum; NewRouter returns an error if Token is shorter
// than that (including empty) unless InsecureNoAuth is set.
Token string
// InsecureNoAuth skips bearer-auth on /api/v1/* entirely. NewRouter
// logs a WARN when this is set, since every /api/v1 endpoint (blocks
// CRUD, schedule apply, series-state patch, ...) becomes reachable by
// anyone who can reach the listener. Meant for local development only,
// never a real deployment.
InsecureNoAuth bool
// UI is the embedded web UI's filesystem (web.Site(), rooted so
// "index.html" and "404.html" are top-level entries). When set,
// NewRouter installs it as the router's catch-all r.NotFound handler
// (see newUIHandler) so any GET/HEAD that doesn't match a system route
// or /api/v1/* serves a file from it, falling back to 404.html. When
// nil, NewRouter leaves chi's default 404 behavior untouched -- the
// previous behavior, before the UI existed.
UI fs.FS
}
Config configures the bearer-auth gate NewRouter applies to /api/v1/*.
type Deps ¶
type Deps struct {
Store *store.Store
Logger *slog.Logger
Version string
// Tunarr is the Tunarr API boundary used by ListChannels and GetStatus
// (see tunarr.go). Production wiring passes a *tunarr.Client, which
// satisfies TunarrAPI as-is; tests pass a fake. A nil Tunarr means
// "Tunarr integration not configured" -- both handlers treat that as a
// normal, expected state rather than a programming error, since a
// Schedularr deployment need not run Tunarr at all.
Tunarr TunarrAPI
// Sched is the schedule-generation boundary used by GenerateSchedule,
// ApplySchedule, and GetSchedule (see schedule.go). Production wiring
// passes a *service.Runner, which satisfies ScheduleRunner as-is;
// tests pass a fake.
Sched service.ScheduleRunner
// Media is the media-discovery boundary used by ListMediaShows and
// GetMediaMeta (see media.go). Production wiring passes the same
// *service.Runner as Sched -- MediaAPI is a separate, narrower
// interface (matching TunarrAPI/ScheduleRunner's precedent of one
// interface per concern) rather than folding MediaShows/MediaMeta
// into ScheduleRunner, but one concrete Runner satisfies both, which
// is what guarantees media discovery reuses Run's exact fetch+cache
// path instead of standing up a second one. Tests pass a fake.
Media MediaAPI
}
Deps holds the dependencies Handlers needs to serve requests.
type Handlers ¶
type Handlers struct {
// contains filtered or unexported fields
}
Handlers implements gen.ServerInterface.
func (*Handlers) ApplySchedule ¶
func (h *Handlers) ApplySchedule(w http.ResponseWriter, r *http.Request)
ApplySchedule implements gen.ServerInterface. Unlike GenerateSchedule, it runs with service.Options.Apply: true, so a successful response means Runner.Run pushed the plan to Tunarr (UpdateSchedule per channel) and committed the engine's pending state.
func (*Handlers) CreateBlock ¶
func (h *Handlers) CreateBlock(w http.ResponseWriter, r *http.Request)
CreateBlock implements gen.ServerInterface.
func (*Handlers) DeleteBlock ¶
DeleteBlock implements gen.ServerInterface.
func (*Handlers) ExportBlocks ¶
func (h *Handlers) ExportBlocks(w http.ResponseWriter, r *http.Request)
ExportBlocks implements gen.ServerInterface. It lists every stored block -- enabled and disabled alike, since export doubles as a backup mechanism and silently dropping disabled blocks would make a restored import lossy -- and renders their specs as YAML via blockio.RenderYAML, the same renderer ParseYAML's round-trip depends on. The response body is untyped in gen/ for the same reason the import request body is: no Go type is generated for an application/yaml response.
func (*Handlers) GenerateSchedule ¶
func (h *Handlers) GenerateSchedule(w http.ResponseWriter, r *http.Request)
GenerateSchedule implements gen.ServerInterface. It always runs a dry run (service.Options.Apply: false) regardless of the request body -- only POST /apply mutates anything; this route exists purely to preview a plan.
func (*Handlers) GetHistory ¶
func (h *Handlers) GetHistory(w http.ResponseWriter, r *http.Request, params gen.GetHistoryParams)
GetHistory implements gen.ServerInterface.
gen.GetHistoryParams.Days is populated straight from the raw query string with no validation and no default substitution: the generated ServerInterfaceWrapper.GetHistory (internal/api/gen/server.gen.go) only calls runtime.BindQueryParameterWithOptions with Type: "integer" -- it does not apply the OpenAPI schema's default/minimum/maximum for the days parameter. So a nil Days here means "the client omitted it", not "0" or "7", and an out-of-range value reaches this handler unrejected; both are handled here rather than by generated code.
func (*Handlers) GetMediaMeta ¶ added in v0.2.0
func (h *Handlers) GetMediaMeta(w http.ResponseWriter, r *http.Request)
GetMediaMeta implements gen.ServerInterface. See ListMediaShows's doc comment for the nil-Deps.Media / error-mapping convention this shares.
func (*Handlers) GetSchedule ¶
func (h *Handlers) GetSchedule(w http.ResponseWriter, r *http.Request, params gen.GetScheduleParams)
GetSchedule implements gen.ServerInterface. It always dry-runs (there is no request body on a GET, and no apply concept for this route).
func (*Handlers) GetStatus ¶
func (h *Handlers) GetStatus(w http.ResponseWriter, r *http.Request)
GetStatus implements gen.ServerInterface. Unlike every other handler in this package, it never returns a problem+json error response: Tunarr reachability is a probe result reported in the body (tunarr_reachable / tunarr_error), not an HTTP-level failure, and a block-count store error degrades to omitting Blocks (logged server-side via the same convention as logAndWriteInternalError, minus the response write) rather than failing the whole request.
func (*Handlers) ImportBlocks ¶
func (h *Handlers) ImportBlocks(w http.ResponseWriter, r *http.Request, params gen.ImportBlocksParams)
ImportBlocks implements gen.ServerInterface. The request body is untyped in gen/ (oapi-codegen does not generate a Go type for an application/yaml requestBody), so the raw bytes are read directly off r.Body rather than JSON-decoded.
Binding order:
- Read the body (capped at maxImportBodyBytes).
- blockio.ParseYAML: strict YAML decode + duplicate-in-file name rejection + CUE schema validation. Any failure here -> 400, with ParseYAML's wrapped error (which includes CUE's own detail) as the problem detail.
- validateSeriesShowTitles (blocks.go) per parsed block: closes the same CUE gap blocks CRUD closes -- see that function's doc comment. Any failure -> 400.
- Pre-check every parsed block's name against the store's existing block names. Any collision -> 409 listing the colliding name(s), with zero writes: this is the transactional-batch alternative Task 9 parked (see writeBlockStoreError's doc comment) -- since blocks CRUD writes one row per call with no batch/transaction primitive in internal/store, the only way to guarantee "nothing partially imported" without adding one is to make the collision impossible before the first write.
- dry_run=true (default false) stops here and reports the would-be result without writing anything.
- Otherwise, create every parsed block (uuid.NewString ID, Enabled true -- imported blocks start active, matching Bootstrap's behavior in blockio/bootstrap.go). Given step 4's pre-check, a create failure here is unexpected (e.g. a genuine store/driver fault, or a name collision from a concurrent request racing this one); either way it is logged and reported as a generic 500, matching every other unexpected-store-error path in this package (logAndWriteInternalError). A batch transaction that could roll back a partial write on such a race stays out of scope, per the same parked ruling step 4 references.
func (*Handlers) ListBlocks ¶
func (h *Handlers) ListBlocks(w http.ResponseWriter, r *http.Request)
ListBlocks implements gen.ServerInterface.
func (*Handlers) ListChannels ¶
func (h *Handlers) ListChannels(w http.ResponseWriter, r *http.Request)
ListChannels implements gen.ServerInterface.
A nil Deps.Tunarr (Tunarr integration not configured for this deployment) and a live Tunarr call failing are both reported the same way: 502 with title "tunarr unreachable". From the client's perspective both mean "the channel list is unavailable right now" -- the detail string distinguishes them ("tunarr not configured" vs. the wrapped connectivity error).
func (*Handlers) ListMediaShows ¶ added in v0.2.0
func (h *Handlers) ListMediaShows(w http.ResponseWriter, r *http.Request)
ListMediaShows implements gen.ServerInterface.
A nil Deps.Media always maps to 502 "tunarr unreachable" -- the same convention ListChannels uses (tunarr.go): Tunarr integration isn't configured at all, so "unreachable" is accurate. A live MediaShows call failing maps to one of two distinct 502s -- see writeMediaAPIError's doc comment for why a single "tunarr unreachable" wording stopped being accurate for every failure this can have: Runner.fetchPrograms (MediaShows/MediaMeta's shared fetch path) can fail because Tunarr genuinely wasn't reachable, OR because Tunarr responded but sent a response body Client.SearchPrograms/GetSeason couldn't decode -- live-verified this session as a real, distinguishable failure mode (httpclient.IsDecodeError), not a hypothetical.
func (*Handlers) ListSeriesState ¶
func (h *Handlers) ListSeriesState(w http.ResponseWriter, r *http.Request)
ListSeriesState implements gen.ServerInterface.
store.ExportAllSeriesStates already returns exactly the wire shape this endpoint needs (every persisted series_state row, ordered by show_title), so this calls it directly rather than adding a same-shaped "ListSeriesStates" wrapper the brief floated as an option -- there is no name/behavior mismatch to paper over, only a rename, which isn't worth the extra indirection.
func (*Handlers) PatchSeriesState ¶
PatchSeriesState implements gen.ServerInterface.
Only fields present in the request body change (gen.SeriesStatePatch represents "not provided" as a nil pointer for each field); a body with no fields set is rejected with 400 rather than silently no-op'ing. An unknown show_title -- no persisted series_state row -- is rejected with 404: store.GetSeriesState is unsuitable for that check because it fabricates a default S01E01 state for any show, tracked or not (see its doc comment), so this uses store.GetPersistedSeriesState instead, which returns store.ErrNotFound when no row exists.
func (*Handlers) UpdateBlock ¶
UpdateBlock implements gen.ServerInterface.
PUT replaces the block's spec, enabled flag, and (if body.Spec.Name differs from the stored name) its name: BlockWrite carries the full desired spec, including name, so a body whose spec.name doesn't match the existing record's name renames the block rather than being rejected. store.UpdateBlock enforces the same unique-name constraint CreateBlock does, so a rename that collides with another block's name surfaces as ErrConflict -> 409, same as a colliding create.
type MediaAPI ¶ added in v0.2.0
type MediaAPI interface {
MediaShows(ctx context.Context) ([]service.MediaShow, error)
MediaMeta(ctx context.Context) (*service.MediaMeta, error)
}
MediaAPI is the subset of *service.Runner that Handlers needs to serve GET /media/shows and GET /media/meta. It is deliberately a separate interface from service.ScheduleRunner (Deps.Sched) even though production wiring (cmd/serve.go) passes the same *service.Runner value to both fields: schedule generation and media discovery are different concerns, and TunarrAPI (tunarr.go) already established the precedent of one narrow interface per concern in this Deps struct, so a handler test double for one never has to also implement the other. Both boundaries resolving to the same concrete Runner in production is what guarantees MediaShows/MediaMeta reuse Run's exact fetch+cache path rather than standing up a second one.
type Problem ¶
Problem is an RFC 7807 problem+json error body. It is a type alias for problem.Problem: see internal/problem's package doc for why the type (and the helpers below) moved to their own leaf package -- in short, internal/api/router.go needs to import internal/api/middleware, and internal/api/middleware needs these, so they can no longer live in internal/api itself without an import cycle. The alias means every existing caller in this package (and its tests) is unaffected.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package gen provides primitives to interact with the openapi HTTP API.
|
Package gen provides primitives to interact with the openapi HTTP API. |
|
Package middleware provides the HTTP middleware shared by every route on the Schedularr API server: request-id propagation, structured request logging, panic recovery, and bearer-token authentication.
|
Package middleware provides the HTTP middleware shared by every route on the Schedularr API server: request-id propagation, structured request logging, panic recovery, and bearer-token authentication. |