diff --git a/CLAUDE.md b/CLAUDE.md index d89c32b60..4ad43047f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -126,7 +126,7 @@ internal/relpath/ library-relative path rules shared by catalog and auth: Cl internal/catalog/ libraries, access grants, books, FTS search, listening state (the data layer) internal/library/ filesystem view (fsview.go: SafeJoin, SafeJoinListed for the stream, /fs and a book read on demand (each name looked for in its folder's listing first, see Path spelling), and ContentPath/ContentJoin, the one hidden-segment rule) + background scanner (scanner.go: incl. IndexMoved and the .audiosilo/ walk; scanread.go: a scan reads several files at once, `scan.concurrency`, default one per CPU up to 8, and writes the index alone in discovery order, so the result is a serial scan's, a few books a transaction: `catalog.UpsertBooks`, `writeBatch`, each book under its own savepoint); attachments.go (a book's Bridge attachments: signatures, RefreshAttachments); givenup.go (givenUp: a file beside a book's audio whose bounded look was given up on keeps the book as stored, its problem recorded); ebook.go (BookEbook, the Bridge's own .epub rule, for the estimate and, through the one rule function ebookCandidate fed by the walk, books.ebook_path, the reader's ebook; a readable one only: a zip whose directory lists META-INF/container.xml, as the Bridge reads it; OpenEbook, every open of one: a regular file inside the library, checked before it is opened and the same file once open; OpenEbookBounded, the reader's, a bounded call) internal/metadata/ dhowden/tag + ffprobe extraction (fastprobe*.go: the in-process probe, ffprobe's answer read in Go by the configured ffprobe's release's rules, but a header-less VBR MP3's frames counted where ffprobe estimates, ffprobe for a file it is unsure of, see In-process probe; probeview.go: ProbeView, the comparison cmd/probediff and the fixture tests make; bounded.go: Bounded, every other look at a library file a share that stopped answering would hold (a stat, a listing, an open and its reads) under a scan read's bounds and per-mount cap, given up on as GaveUp (see In-process probe), TransientFault (the share-fault rule's transient list, see Share faults), and NamesListed; openbelow.go: Below, a request's open through an os.Root at the library's root (OpenRegularBelow, ReadDirBelow); belowcache.go: BelowFolder, the scan's (OpenBelow, StatBelow, LstatBelow), through the file's folder kept open a moment, one openat a file; toolinput.go: ToolInput (bounded, one entry point), ffprobe and ffmpeg handed the file opened so, never its path (see Path spelling, links out of the root), and InputFormats/InputFormatArgs, the one demuxer list every tool run on a library file or an episode takes; dirnames.go: DirNames, the folder listings the spelling checks read, kept 3 s (see Path spelling); tagreader.go: ReadTags, the tag reads outside Extract (media.EmbeddedCoverBelow; Extract reads through the probe's block cache): dhowden reads an ID3v2 tag through a buffer up to the tag's end, not a byte per read system call; a narrator tag beats composer in both passes; mp4narrator.go reads the iTunes \xa9nrt item, which neither reads, with a bounded box walk; a series tag ending in a marked position, "Discworld, book #40", is the series and that position: seriestag.go SplitSeriesTag; a `series-part` tag "1-3" is a range: seriesrange.go, ParseSeriesRange, the one grammar of a range position, and ParseSeriesPosition, a number or a range; incl. ReleaseDate: a date tag as YYYY[-MM[-DD]], stored as books.released, never as published); DeriveFromPath (structural path parsing, the scan's baseline: the folder holding the book is the series and the one above it the author, but a lone folder is the author; a leaf named `Author; Series; Book NN[; Title]` states the series and position, a range or none, `@rev` 3); layout.go: ReadPathLayout (author/series/book LAYOUT, the match's path facts) and FromPathLayout (a path-first library's values); absfile.go: ParseABSFile/ReadABSFile (an Audiobookshelf metadata.json, see Metadata overrides); attachments.go: AttachmentsDir `.audiosilo`, Read/ParseCharacters, Recaps, Description and Provenance (the Bridge's generated files, checked against audiosilo-meta's formats; see Bridge attachments); chapterlist.go: Read/ParseChapterList (the Bridge's `chapters.json`, chapters found in the narration; see Generated chapters); foldercode.go: FolderCodePosition (a position or range from the code leading a folder name, "DH06 - ...", "LAM05-06", its letters the series' initials; read only by the Bridge's books listing); discfolder.go: IsDiscFolder ("CD 2", "Disc 3": the scan's join rule, and the Audible backup destination check); titlepos.go: PositionInTitle (a series position read from a title that is the series' name then a number, "He Who Fights with Monsters 4: ..."; narrow: set off by a space or comma, 1-3 digits, then the end or a separator, never a range); seriestitle.go: TitleNotSeries (an album tag naming only the book's series gives way to the title tag or the path's title; LeafSeries reads an `Author; Series; Book NN; Title` leaf (a `Leaf`: series, title part, position or range) and PathLeafSeries a book's own; MaybeSeriesTitle, the scan's re-read test for a snapshot before `@rev` 2; Metadata.PartsTitle: a book of several files takes the album over its first file's title tag, unless its folder or its last file's tag says the tag is the book's (PartNamed: when that file is worth reading), `@rev` 5; see Metadata overrides in CONVENTIONS.md) -internal/media/ Range streaming, download, embedded cover extraction, transcoding (the file opened through the library root and handed over as a descriptor: fd:, else as metadata.ToolInput hands it, /dev/fd/3 through a link on Unix, a re-checked, held path on Windows, for an ffmpeg older than 6.1, a cached copy's run too; pipe:0 for a podcast episode on an older ffmpeg; every input whose demuxer ffmpeg guesses an audio container only, metadata.InputFormatArgs); filecache.go: FileCache, a cache of copies ffmpeg makes from a cacheSpec (LRU by mtime, single-flight, .part + rename, disk guard, refusals remembered for an hour; Open/Status/Queue/WarmAll); remux.go: NewRemuxer, the MP3-in-MKA remux spec (/cache/remux, 8 GiB, warmed by /item and /chapters, a cold stream transcoded after 2 s (a download, or with every transcode slot busy, after up to 45 s), own ETag; see Recognized audio); rendition.go: NewRenditionCache, the watch rendition spec (/cache/renditions/watch, AAC-LC mono 48 kbps, 10 GiB; see Watch renditions) +internal/media/ Range streaming, download, embedded cover extraction, transcoding (the file opened through the library root and handed over as a descriptor: fd:, else as metadata.ToolInput hands it, /dev/fd/3 through a link on Unix, a re-checked, held path on Windows, for an ffmpeg older than 6.1, a cached copy's run too; pipe:0 for a podcast episode on an older ffmpeg; every input whose demuxer ffmpeg guesses an audio container only, metadata.InputFormatArgs); filecache.go: FileCache, a cache of copies ffmpeg makes from a cacheSpec (LRU by mtime, single-flight, .part + rename, disk guard, refusals remembered for an hour; Open/Status/Queue/WarmAll); remux.go: NewRemuxer, the MP3-in-MKA remux spec (/cache/remux, 8 GiB, warmed by /item and /chapters, a cold stream transcoded after 2 s (a download, or with every transcode slot busy, after up to 45 s), own ETag; see Recognized audio); rendition.go: NewRenditionCache, the watch rendition spec (/cache/renditions/watch, AAC-LC mono 48 kbps, 10 GiB; see Watch renditions); remoteart.go: ArtFetcher, the one remote art fetcher (community covers, podcast artwork) over a caller's netguard transport: no user info, <= 3 redirects without a downgrade, a 200 only, a byte cap internal/names/ reading people in an Author/Narrator credit: Split (the deliberately shy co-credit rule), Reversed ("Surname, Given"), SortKey (surname first; the catalog registers it as the SQL function name_sort for the admin list's surname sort) internal/meta/ Phase 1.5 community metadata lookup: HTTP client + Service (asin/isbn, or the book's recorded match in book_matches via EnrichMatch when it names another work or those find nothing -> composed enrichment envelope; a LibriVox recording's `librivox` id and links) with a bounded TTL cache and its persistent SQLite level (store.go); the /meta bundle's previous works and spoiler gating (bundle.go); the admin console's match (match.go: metaserve works/match over tag + path facts, metadata.ReadPathLayout; works/search fallback for an older metaserve); a bulk run's spacing of its requests (pacer.go: `Pacer`, `WithPacer`, the remote leg's `pacedTransport`); a call's time budget (budget.go: `withBudget`, which a bulk run's Retry-After waits don't count against, and `WithSharedBudget` for a request that composes twice); community cover fetches (cover.go: public addresses only); owned books' work ids for the Series cards (workids.go); placing the caller's books on rails and the next rail entry (local.go); which of a work's series a book is in (seriesrules.go: the series rules below); a work's positions on this book's chapters (positionscale.go: `OnRecording`); generated content laid beside the community work (generated.go: `Answer`, `Unmatched`, `MetaGenerated`, `MetaGeneratedDescription`); cache-only reads for the Bridge's estimate and book facts (cachedenrich.go: `cachedAnswerOf`, the newer of the cache and the upcoming job's resolution; `Coverages`, `CachedWork`, a `Coverage` per book whose `Description` is the community work's `community_description`); the console's Add from LibriVox reads (librivox.go: `LibrivoxSearch`, `LibrivoxWork`, `LibrivoxRecordingOf`) internal/chapteralign/ fits a community recording's chapter list onto a book's own audio (pure, no I/O): anchors by title + time, places the rest in proportion, snaps each to its pause (an injected Prober); classifies fill/titles/refine/restructure/same or why not (length_mismatch, structure_mismatch, crosses_files). testdata/mythos is a real 34-vs-174-chapter golden case @@ -150,8 +150,9 @@ internal/backup/ database backups: VACUUM INTO the backups folder on a sche internal/jsonfile/ the small JSON files beside the database (backup's restore marker/result, the mirror's state.json): Write is owner-only, temp file synced then renamed (all or nothing); Read[T] is nil without a file internal/bridge/ the Bridge's side on the server (BRIDGE-PLAN.md): its last heartbeat (status.go: validation, the 2-minute online window, features, the lenient `estimates`, Writable, CanContribute: the `setup` block's, else the estimates'; setup.go: the lenient, bounded onboarding checklist and the reply's `accepts`) and the job queue (jobs.go: kinds the server can check (`bridge.verify`, `sidecars.generate`, `sidecars.describe`, `chapters.detect`, Phase 2b's `sidecars.contribute` and `meta.correct`, contribute.go: their strict params, `ModuleFor`, and Phase 3c's `readalong.align`, Phase 4a's `audible.poll`, 4b's `audible.import` and 4c's `audible.sync` in audible.go, LibriVox L6's `librivox.fetch` in librivox.go), dedupe, priority claim with a lease (a queued job whose managed module is off held: `ModuleOn`), long-poll wake, lease expiry, held updates and parks, cooperative cancel, `OnTransition` / `Job.Notable`); estimate.go (EstimateSidecars: a job's cost from the heartbeat's figures); priority.go (the job priority bands every queue uses); pairing and the bridge token are auth's (auth/bridge.go) internal/podcast/ podcast feed.json v1 reader and URL helpers (pure format in feed/), poll/fetch/retention scheduler, bounded on-demand media waits and scoped one-ahead prefetch; catalog/podcasts.go and podcast_{fetch,retention,move}.go hold the generation index, identity-bound status, follows, durable policies, aggregate checks and the state move of a show folder renamed by hand; library/podcast_media.go opens committed media -internal/podcast/ (2c-3) follow.go: Follower, follow by URL for the single follow and OPML rows; opmlimport.go (rows, the five-new-per-upload wave); export.go (BuildExport); discovery/ (iTunes + Podcast Index search, the artwork proxy, caches/quotas/cooldown, the build-tagged test origin); opml/ (the bounded strict OPML parser and the export writer); quota/ (token buckets with a bounded key map, slots) -internal/netguard/ the guarded dialer: PublicAddr, Control/Dialer check the address actually dialled, Downgrade refuses an https-to-http redirect (meta covers, podcast discovery) +internal/podcast/ (2c-3) follow.go: Follower, follow by URL for the single follow and OPML rows; opmlimport.go (rows, the five-new-per-upload wave); export.go (BuildExport); discovery/ (iTunes + Podcast Index search, the artwork proxy, caches/quotas/cooldown, the build-tagged test origin); opml/ (the bounded strict OPML parser and the export writer) +internal/netguard/ the guarded dialer: PublicAddr, Control/Dialer/Transport check the address actually dialled (Transport: no proxy, MaxHeaderBytes of headers), Downgrade refuses an https-to-http redirect (meta covers, podcast discovery) +internal/quota/ the one token-bucket type: PerSecond (the API's request buckets) and PerMinute (podcast discovery and OPML, a bounded key map), plus Slots internal/oidc/ Sign in with OpenID Connect (server#235), pure (no DB, no handlers): Provider (go-oidc + x/oauth2: lazy discovery with backoff, asymmetric algs only, PKCE S256, nonce/aud/azp/iat checks, userinfo for missing claims (its failure leaves the ID token's), a reachability probe at /start and the status, one 20 s CallBudget per use), the sealed flow cookie (Sealer, Replay), Claims and Decide (link, create, pending or refuse); oidctest/ is the fake IdP for tests. Storage: auth/identities.go (OIDCSignIn in one durable tx, pending sign-ins, identities); routes: api/handlers_oidc.go internal/modules/ managed modules (Bridge Phase 2a): Module (id = capability + config key, RequiresBridge, Routes, Start), Registrar, Deps, Validate, BridgeState/Active (the capability rule), Runner (each module's Start while on); modules/builtin is the registry (contributions: no routes of its own, its actions are Bridge jobs gated by `bridge.ModuleFor`; podcasts; audible) internal/audible/ the audible module's Start (Bridge Phase 4a): RunScheduler queues each due account's `audible.poll` while a Bridge offers it; see Audible accounts in CONVENTIONS.md; imports.go (Phase 4b): Queues, a title's Back up, Back up everything and AfterPoll's policy backups (`audible.import`); see Audible backups; Phase 4c: the scheduler queues each synced account's `audible.sync` every 15 min (`queueSyncs`); see Audible sync diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 2d7887530..f77ab3b0d 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -800,7 +800,7 @@ every session. CLAUDE.md keeps a one-line index of these topics. one; calendar apps read it as empty). Headers: `text/calendar; charset=utf-8`, `Content-Disposition: inline; filename="releases.ics"`, `Cache-Control: private, max-age=3600`, `ETag` `"ics-"` (a poll that has it gets a 304; `conditional`); never compressed - (`compressExcluded` holds `/api/v1/me/upcoming/`). The upcoming reads take the caller's scopes without + (registered without `compressJSON`, as are the Upcoming cover and calendar link routes). The upcoming reads take the caller's scopes without podcast libraries (`upcomingScopes`: the tables join books libraries only), and a read the client gave up on is answered without a log line (`writeUpcomingError`). **The Upcoming cover** (`GET /me/upcoming/cover?work=&size=`, requireMediaAuth: session or API key, header or `?token=`, never a cast @@ -953,18 +953,24 @@ every session. CLAUDE.md keeps a one-line index of these topics. and the comparison (a parameter has no affinity or collation either way); it only hides the value from the planner, which a statement whose plan must not follow its values wants anyway. A single-table statement and a correlated subquery are not affected. -- **JSON compression** (`api/compress.go`, PERF-SPIKE S5): `compress` wraps the mux, inside the - timeout. A request is compressible only when it is a GET (or its HEAD, which so carries the GET's - `Vary` and `Content-Encoding`, server#270) under `/api/v1/` without Range, outside - the media (`isStreamingPath`, `/meta/cover`), `/api/v1/auth/`, `/api/v1/bridge/` and `/api/v1/me/upcoming/` (the calendar feed, its token in the URL, and the Upcoming covers) - (`compressExcluded`); every credential is minted by a POST, so no compressed body holds one - (BREACH). A new GET that returns a credential joins `compressExcluded`. A new stream (media, a - download, a long poll, anything that flushes) goes in `isStreamingPath` when it must also leave - the request timeout, else in `compressExcluded`: `gzipWriter` has no Flush and holds the first - 1 KiB back, so a streamed JSON answer must never reach it. Either way it adds a - `TestCompressExclusions` row (GET and HEAD) proving it is answered identity. The answer is gzipped (BestSpeed) when it is `application/json`, at least - 1 KiB, has no Content-Encoding or ETag of its own and the client takes gzip; every JSON answer - to a compressible request carries `Vary: Accept-Encoding`. The list cache stores each answer's +- **JSON compression** (`api/compress.go`, PERF-SPIKE S5, fail closed since server#270): a route + is compressed only when its registration in `api.go` wraps the handler in `compressJSON` + (inside `requireAuth`/`requireAdmin`, so authentication runs first; the public `GET /server` is + the one wrapped bare); every other route, a new one included, answers identity. + `compressJSON` acts only on a GET (or its HEAD, which so carries the GET's `Vary` and + `Content-Encoding`) without a Range or Upgrade header. Opt in only a reviewed JSON read: never + a route that returns a credential (BREACH: every credential is minted by a POST, and + `GET /auth/tokens`, the Bridge's routes and the Upcoming calendar link stay out), and never a + stream (media, a file download, a long poll, anything that flushes; the library + export is JSON and opts in): `gzipWriter` has no Flush and holds the first 1 KiB back. A route + that stays out has a `TestCompressExclusions` row + (GET and HEAD) proving it is answered identity. The answer is gzipped (BestSpeed) when it is + `application/json`, at least 1 KiB, not a 204, 206 or 304, has no Content-Range, Content-Encoding + or ETag of its own and the client takes gzip; every JSON answer to a GET or HEAD without Range + or Upgrade on an opted-in route carries `Vary: Accept-Encoding`. `gzipAccepted(r)` is the opt-in + and the client's gzip together: the list cache and read-along choose their stored gzip (and + read-along its `-gz` ETag) from it, so both read false on a route registered without + `compressJSON` and for a Range request. The list cache stores each answer's gzip beside it and sends that on a hit (`writeCachedJSON`), so a hit compresses nothing. A whole answer gzipped in memory (the list cache's, a read-along map, a console file) is `spa.Gzip` at a level (BestSpeed per request, the default for a file), nil when gzip saves nothing. @@ -2984,8 +2990,10 @@ every session. CLAUDE.md keeps a one-line index of these topics. an image on its own host (Audible's CDN, Open Library), which the console's CSP can't load, so the server fetches it (`meta.Service.FetchCover`: http(s) only, every connection's resolved address checked public at dial time, redirects included (`netguard.PublicAddr` through - `netguard.Dialer`, shared with podcast discovery; no proxy), <= 3 - redirects, 15 s, `maxConcurrentCoverFetches`, never holding `coverReads`). + `netguard.Transport`, shared with podcast discovery; no proxy, at most 64 KiB of headers), no + user info in the URL or a redirect's, <= 3 redirects without an https to http downgrade, a 200 + only, the caller's byte cap (`media.ArtFetcher`, the one remote art fetcher, shared with + discovery's artwork), 15 s, `maxConcurrentCoverFetches`, never holding `coverReads`). `POST /admin/meta/covers` (`{urls, size}`, <= 12) returns thumbnails as `data:` URLs in order (`""` = couldn't be fetched or decoded; cached in the thumbnail cache by URL, a failed fetch not; each holds `communityReads` from its fetch to the end of its decode; asks for the @@ -3061,8 +3069,9 @@ every session. CLAUDE.md keeps a one-line index of these topics. ASIN or ISBN, or a recorded community match, `book_matches`, see Bulk matching), and `POST /admin/shares/{id}/paths` also takes `{"rules":[...]}` (<= 1000, one transaction) for adding a selection; a share created with `paths` is held to the same 1000 (`boundedList`, 400 `too_large`). -- **Rate limiting by route class** (`rateLimit` in `api/middleware.go`, buckets in - `api/ratelimit.go`, configurable values from `config.rate_limit.*` read at start through +- **Rate limiting by route class** (`rateLimit` in `api/middleware.go`, the token buckets + `quota.PerSecond` (`internal/quota`, the one bucket type, shared with podcast discovery and OPML) + wired in `api/ratelimit.go` beside the failed-attempt lockouts, configurable values from `config.rate_limit.*` read at start through `RateLimitConfig.Effective`: a rate or burst left at 0 is the current default and is never saved, so a changed default reaches existing installs), read off the handler `mux.Handler` picks: static files (`web.IsStatic`) are not counted; media @@ -4252,8 +4261,9 @@ every session. CLAUDE.md keeps a one-line index of these topics. `_SECRET`, read at start, `yaml:"-" json:"-"`, never in settings, logs, audit, cache keys or errors); a half or malformed pair turns that provider off with one warning naming the variable. Upstream fetches dial through `internal/netguard` (the dialled address checked: providers public :443, artwork - public any port; no proxy, no cookies, providers no redirects, artwork <= 3 without a downgrade), within - bounded bodies, per-user and per-provider token buckets (`internal/podcast/quota`), two provider and + public any port; no proxy, no cookies, providers no redirects, artwork through `media.ArtFetcher`: <= 3 + redirects without a downgrade or user info), within + bounded bodies, per-user and per-provider token buckets (`quota.PerMinute`, `internal/quota`), two provider and four image slots, a 15 s failure cooldown, coalesced misses and bounded TTL caches. The artwork's admission is its own, sized by a results page (BRIDGE-03): a miss past the image slots queues for one (up to 40 waiting, each at most the fetch budget, then 503 `discovery_busy`), and its per-user and diff --git a/internal/api/api.go b/internal/api/api.go index 6432ba93c..d4dba1269 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -31,6 +31,7 @@ import ( "github.com/kodestar/audiosilo-server/internal/modules" "github.com/kodestar/audiosilo-server/internal/podcast" "github.com/kodestar/audiosilo-server/internal/podcast/discovery" + "github.com/kodestar/audiosilo-server/internal/quota" "github.com/kodestar/audiosilo-server/internal/upcoming" "github.com/kodestar/audiosilo-server/internal/web" ) @@ -167,15 +168,15 @@ type API struct { // auth.oidc.enabled was off at start. oidc *oidcFlow - loginLimiter *limiter // per-IP lockout for password login - oidcLimiter *limiter // per-IP lockout for failed OIDC callbacks - redeemLimiter *limiter // per-IP lockout for auth-code redemption - demoLimiter *limiter // per-IP cap on demo account creation - accountLimiter *limiter // per-IP cap on self-service password/recovery mutations - ipLimiter *rateLimiter // general request rate, per IP (see rateLimit) - bridgeLimiter *rateLimiter // authenticated Bridge requests, per credential (see requireBridge) - tokenLimiter *rateLimiter // authenticated API rate, per credential (see requireAuth) - mediaLimiter *rateLimiter // authenticated media rate, per credential (see requireMediaAuth) + loginLimiter *limiter // per-IP lockout for password login + oidcLimiter *limiter // per-IP lockout for failed OIDC callbacks + redeemLimiter *limiter // per-IP lockout for auth-code redemption + demoLimiter *limiter // per-IP cap on demo account creation + accountLimiter *limiter // per-IP cap on self-service password/recovery mutations + ipLimiter *quota.Limiter // general request rate, per IP (see rateLimit) + bridgeLimiter *quota.Limiter // authenticated Bridge requests, per credential (see requireBridge) + tokenLimiter *quota.Limiter // authenticated API rate, per credential (see requireAuth) + mediaLimiter *quota.Limiter // authenticated media rate, per credential (see requireMediaAuth) // health is /healthz's database probe, shared by the requests within // healthReuse of it (handleHealth): the route is outside the rate limit. health healthProbe @@ -308,7 +309,6 @@ func New(cfg *config.Config, authSvc *auth.Service, cat *catalog.Catalog, scanne // off Health's list now, not at the report's monthly recheck. metaSvc.SetASINFound(clearFoundASIN(cat, log)) } - limits := cfg.RateLimit.Effective() a := &API{ boot: cfg, auth: authSvc, @@ -332,11 +332,7 @@ func New(cfg *config.Config, authSvc *auth.Service, cat *catalog.Catalog, scanne redeemLimiter: newLimiter(10, 15*time.Minute), demoLimiter: newLimiter(5, 15*time.Minute), // ≤5 demo accounts per IP / 15 min accountLimiter: newLimiter(10, 15*time.Minute), // ≤10 password/recovery mutations per IP / 15 min - // Per IP, then per credential (config rate_limit.*). - ipLimiter: newBucketLimiter(limits.Address), - bridgeLimiter: newRateLimiter(bridgeRate, bridgeBurst), - tokenLimiter: newBucketLimiter(limits.Token), - mediaLimiter: newBucketLimiter(limits.Media), + castKeepEvery: auth.CastTouchInterval, transcodeSem: make(chan struct{}, maxConcurrentTranscodes), transcodeHolds: make(map[transcodeAsk]*transcodeHold), @@ -355,6 +351,7 @@ func New(cfg *config.Config, authSvc *auth.Service, cat *catalog.Catalog, scanne opml: newOPMLTransfers(), lists: newListCache(), } + a.initRateLimits(time.Now) if cfg.DataDir != "" { if rm, err := media.NewRemuxer(filepath.Join(cfg.DataDir, "cache", "remux"), log); err != nil { log.Warn("remux cache unavailable: Matroska is served as stored", "err", err) @@ -592,17 +589,17 @@ func (a *API) StartCoverColors(ctx context.Context) { func (a *API) Handler() http.Handler { mux := http.NewServeMux() - mux.Handle("GET /api/v1/libraries/{id}/podcasts", a.requireAuth(http.HandlerFunc(a.handlePodcastShows))) - mux.Handle("GET /api/v1/libraries/{id}/podcasts/episodes", a.requireAuth(http.HandlerFunc(a.handlePodcastEpisodes))) - mux.Handle("GET /api/v1/libraries/{id}/podcasts/fetch", a.requireAuth(http.HandlerFunc(a.handlePodcastFetch))) + mux.Handle("GET /api/v1/libraries/{id}/podcasts", a.requireAuth(compressJSON(a.handlePodcastShows))) + mux.Handle("GET /api/v1/libraries/{id}/podcasts/episodes", a.requireAuth(compressJSON(a.handlePodcastEpisodes))) + mux.Handle("GET /api/v1/libraries/{id}/podcasts/fetch", a.requireAuth(compressJSON(a.handlePodcastFetch))) mux.Handle("POST /api/v1/libraries/{id}/podcasts/fetch", a.requireAuth(notDemo(http.HandlerFunc(a.handlePodcastFetch)))) - mux.Handle("GET /api/v1/me/podcasts", a.requireAuth(http.HandlerFunc(a.handleMyPodcasts))) + mux.Handle("GET /api/v1/me/podcasts", a.requireAuth(compressJSON(a.handleMyPodcasts))) pr := moduleRoutes{a: a, mux: mux, id: bridge.ModulePodcasts} pr.User("POST /api/v1/podcasts/follow", http.HandlerFunc(a.handlePodcastFollow)) pr.User("DELETE /api/v1/podcasts/follow", http.HandlerFunc(a.handlePodcastUnfollow)) pr.User("POST /api/v1/podcasts/check", http.HandlerFunc(a.handlePodcastCheck)) a.mountPodcastTransfer(mux) - mux.Handle("GET /api/v1/admin/libraries/{id}/podcasts/retention", a.requireAdmin(notDemo(http.HandlerFunc(a.handleAdminPodcastRetention)))) + mux.Handle("GET /api/v1/admin/libraries/{id}/podcasts/retention", a.requireAdmin(notDemo(compressJSON(a.handleAdminPodcastRetention)))) mux.Handle("PUT /api/v1/admin/libraries/{id}/podcasts/retention", a.requireAdmin(notDemo(http.HandlerFunc(a.handleAdminPodcastRetention)))) mux.Handle("DELETE /api/v1/admin/libraries/{id}/podcasts/retention", a.requireAdmin(notDemo(http.HandlerFunc(a.handleAdminPodcastRetention)))) mux.Handle("POST /api/v1/admin/libraries/{id}/podcasts/fetch", a.requireAdmin(notDemo(http.HandlerFunc(a.handleAdminPodcastFetch)))) @@ -610,7 +607,7 @@ func (a *API) Handler() http.Handler { mux.Handle("POST /api/v1/bridge/libraries/{id}/podcasts/retention/check", a.requireBridge(a.handleBridgePodcastRetentionCheck)) mux.Handle("GET /api/v1/bridge/libraries/{id}/marker", a.requireBridge(a.handleBridgeMarker)) // Public. - mux.HandleFunc("GET /api/v1/server", a.handleServerInfo) + mux.Handle("GET /api/v1/server", compressJSON(a.handleServerInfo)) // Liveness/readiness probe (public): reports DB read-reachability for a // container healthcheck. Both /healthz and the API-prefixed form are served // (healthPatterns), outside the rate limit. @@ -651,27 +648,27 @@ func (a *API) Handler() http.Handler { mux.Handle("POST /api/v1/auth/tokens", a.requireAuth(notKid(http.HandlerFunc(a.handleCreateAPIToken)))) mux.Handle("GET /api/v1/auth/tokens", a.requireAuth(http.HandlerFunc(a.handleListAPITokens))) mux.Handle("DELETE /api/v1/auth/tokens/{id}", a.requireAuth(http.HandlerFunc(a.handleRevokeAPIToken))) - mux.Handle("GET /api/v1/me", a.requireAuth(http.HandlerFunc(a.handleMe))) + mux.Handle("GET /api/v1/me", a.requireAuth(compressJSON(a.handleMe))) // The server's home and away addresses, for a device paired before one was set. - mux.Handle("GET /api/v1/addresses", a.requireAuth(http.HandlerFunc(a.handleAddresses))) + mux.Handle("GET /api/v1/addresses", a.requireAuth(compressJSON(a.handleAddresses))) // Content is addressed by (library, path) via ?path= - the path is the // identity. The filesystem view is filtered to the caller's share scope. - mux.Handle("GET /api/v1/libraries", a.requireAuth(http.HandlerFunc(a.handleListLibraries))) - mux.Handle("GET /api/v1/libraries/{id}/fs", a.requireAuth(http.HandlerFunc(a.handleBrowseFS))) - mux.Handle("GET /api/v1/libraries/{id}/books", a.requireAuth(http.HandlerFunc(a.handleListBooks))) - mux.Handle("GET /api/v1/libraries/{id}/authors", a.requireAuth(a.handleBrowsePeople(catalog.PeopleAuthors, "authors"))) - mux.Handle("GET /api/v1/libraries/{id}/narrators", a.requireAuth(a.handleBrowsePeople(catalog.PeopleNarrators, "narrators"))) - mux.Handle("GET /api/v1/libraries/{id}/series", a.requireAuth(http.HandlerFunc(a.handleBrowseSeries))) - mux.Handle("GET /api/v1/libraries/{id}/series/books", a.requireAuth(http.HandlerFunc(a.handleSeriesBooks))) - mux.Handle("GET /api/v1/libraries/{id}/item", a.requireAuth(http.HandlerFunc(a.handleItem))) - mux.Handle("GET /api/v1/libraries/{id}/next", a.requireAuth(http.HandlerFunc(a.handleNext))) - mux.Handle("GET /api/v1/libraries/{id}/chapters", a.requireAuth(http.HandlerFunc(a.handleChapters))) - mux.Handle("GET /api/v1/libraries/{id}/meta", a.requireAuth(http.HandlerFunc(a.handleMeta))) + mux.Handle("GET /api/v1/libraries", a.requireAuth(compressJSON(a.handleListLibraries))) + mux.Handle("GET /api/v1/libraries/{id}/fs", a.requireAuth(compressJSON(a.handleBrowseFS))) + mux.Handle("GET /api/v1/libraries/{id}/books", a.requireAuth(compressJSON(a.handleListBooks))) + mux.Handle("GET /api/v1/libraries/{id}/authors", a.requireAuth(compressJSON(a.handleBrowsePeople(catalog.PeopleAuthors, "authors")))) + mux.Handle("GET /api/v1/libraries/{id}/narrators", a.requireAuth(compressJSON(a.handleBrowsePeople(catalog.PeopleNarrators, "narrators")))) + mux.Handle("GET /api/v1/libraries/{id}/series", a.requireAuth(compressJSON(a.handleBrowseSeries))) + mux.Handle("GET /api/v1/libraries/{id}/series/books", a.requireAuth(compressJSON(a.handleSeriesBooks))) + mux.Handle("GET /api/v1/libraries/{id}/item", a.requireAuth(compressJSON(a.handleItem))) + mux.Handle("GET /api/v1/libraries/{id}/next", a.requireAuth(compressJSON(a.handleNext))) + mux.Handle("GET /api/v1/libraries/{id}/chapters", a.requireAuth(compressJSON(a.handleChapters))) + mux.Handle("GET /api/v1/libraries/{id}/meta", a.requireAuth(compressJSON(a.handleMeta))) // Community work lookup by metadata-site work id - global, read-only data // (no library, nothing to scope), so plain auth. The id is a query param // because work-id slugs are not path-segment safe. - mux.Handle("GET /api/v1/meta/work", a.requireAuth(http.HandlerFunc(a.handleMetaWork))) + mux.Handle("GET /api/v1/meta/work", a.requireAuth(compressJSON(a.handleMetaWork))) // Media GETs accept the session token as a ?token= query param (browser // /