Vellum/internal/subsonic/subsonic.go
mithral 35442e4aff Phase 2: split the fat packages along real boundaries
Four extractions, each chosen because the two halves have different callers,
different failure modes or different testing needs. Not a line-count exercise.

internal/home out of internal/media
- media serves item RESOURCES (detail, file, cover, progress); home computes
  AGGREGATES (the five shelves). The 2328-line package was doing both.
- media keeps POST /items/{id}/view because it is item-scoped and must stay in
  the package that authorizes the item; it imports home.RecordView for that one
  thing. home does not import media.
- Verified live: all five shelves non-empty, and two consecutive /home calls
  return different explore ids, which is the non-determinism the Explore rewrite
  exists for.

internal/scanner out of internal/library
- The scanner walks the filesystem and reconciles; library CRUD is an admin HTTP
  surface. Different callers (a job vs a request), different failure modes.
- The registry deliberately STAYED in internal/library: three of its four callers
  are not the scanner (modules register types, handlers serve the list, metadata
  reads the group mode, subsonic calls CleanTitle). It is a property of the kind,
  not of the scan. The one genuinely scanner-owned helper became
  library.ExtensionsFor.
- Two tests moved with the code rather than being rewritten; they now exercise
  the boundary by calling library.ListMissing across it.
- Verified live: first scan updates, rescan reports unchanged=N, so change
  detection still short-circuits.

internal/providers out of internal/metadata
- Providers talk to third-party APIs; the enrich job owns the matching policy and
  the database writes. The split's whole point is that a provider is testable
  WITHOUT a database, so a DB-free test was added and OpenLibrary gained a
  BaseURL override to make it possible.
- providers imports zero internal packages — a true leaf.
- The matching policy (searchTitle, artistHint, pickBest) is untouched. It exists
  because real false matches were found.

dto packages out of internal/jellyfin and internal/subsonic
- The wire types and their mapping are now separate from the handler logic, so
  the contract with clients we do not control is reviewable on its own.
- Both dto packages are PURE: zero references to sql.DB or net/http, verified by
  grep. That is what makes them reviewable.
- No field name, tag or error code changed.

internal/arch did its job: it failed the build twice during this phase, once for
each new package that was not yet placed in a layer. That is the rule working,
not an obstacle.

Verified: gofmt clean, build exit 0, vet exit 0, 23 packages pass, svelte-check
0/0, and end to end against a running server — home shelves, a queued scan
reporting unchanged, Jellyfin /Items, and Subsonic ping.

Process note: one agent (dto) stopped mid-task and left the tree red — the dto
packages unlayered and its test still referencing constants that had moved. The
arch test caught it immediately. I finished it by hand: exported constant
references in the test, and both dto packages placed at layer 3.

Still open from Phase 1: internal/jellyfin has no test files, catalog is
item-centric while Subsonic is file-first, and subsonic loadAlbum now scopes to
the item's own library.
2026-10-11 16:03:10 -04:00

81 lines
3.2 KiB
Go

// Package subsonic translates Vellum's storage into the frozen Subsonic REST
// API (1.16.1) that real clients — Symfonium, Ultrasonic, play:Sub, DSub,
// Substreamer, Feishin — speak to browse and stream.
//
// It is a translation layer, not a second media server. Every query goes
// through media_items / media_files / people / item_people / assets, and every
// request resolves to an auth.User through the same grant chokepoint the web
// app uses (auth.VisibleLibraryIDs / auth.CanAccessLibrary). Credentials are
// apitoken.KindSubsonic tokens, so revoking one in the web UI revokes the
// client too.
//
// The wire shapes — the response envelope, the element names, the error codes,
// the opaque ids — live in internal/subsonic/dto, which is the contract with
// clients. This package owns the HTTP handlers and the queries.
//
// # Authentication
//
// Subsonic carries its credentials on every request, not in a cookie: u names
// the user and one of p (the key directly), t=md5(key+salt) with s, or apiKey.
// A bad credential is a Subsonic error envelope with code 40, never an HTTP
// 401 — clients read the envelope and many treat a non-200 as a network fault.
//
// # No transcoding
//
// Vellum runs on a headless, GPU-less host. stream serves the original file
// (format=raw) with full Range support so seeking works, and refuses a request
// for any other target format with a clear error instead of pretending. ffmpeg
// is never invoked.
//
// # Root mounting
//
// Routes live under /rest/ at the ROOT because that is where Subsonic clients
// look. internal/httpapi/static.go owns "/", "/healthz" and "/api/"; "/rest/"
// is a more specific ServeMux pattern, so requests route here first and the SPA
// fallback is never shadowed. isAPIPath in static.go does not know /rest/, so
// this package installs its own JSON 404 for the subtree rather than letting an
// unknown /rest/... path fall through to the SPA shell.
package subsonic
import (
"net/http"
"strings"
"github.com/mithral/vellum/internal/subsonic/dto"
)
// envelope starts a response. XML needs the namespace; nodeJSON drops it.
func envelope(status string) *dto.Node {
return dto.Envelope(status)
}
// wantsJSON reports whether the caller asked for the JSON form. The default,
// per the spec, is XML. jsonp is treated as json: the wrapping callback is a
// browser convenience this LAN server does not need, and returning the plain
// JSON body is still parseable by a jsonp client that ignores the callback.
func wantsJSON(r *http.Request) bool {
switch strings.ToLower(r.FormValue("f")) {
case "json", "jsonp":
return true
default:
return false
}
}
// write serialises a response in the requested format.
func (h *Handlers) write(w http.ResponseWriter, r *http.Request, root *dto.Node) {
if wantsJSON(r) {
writeJSONResponse(w, root)
return
}
writeXMLResponse(w, root)
}
// fail writes a Subsonic error envelope. The HTTP status stays 200 on purpose:
// Subsonic clients read the envelope's status/error, and a non-200 is often
// surfaced as a transport error rather than "wrong password".
func (h *Handlers) fail(w http.ResponseWriter, r *http.Request, code int, msg string) {
root := envelope(dto.StatusFailed)
root.Add(dto.ErrorNode(code, msg))
h.write(w, r, root)
}