Repository navigation
feat: add external API runtime and request control plane - #810
Conversation
4517a3e to
56bb87b
Compare
That was the plan! I just went ahead and started building out the PR's since i was confusing myself what was going where, but left them as draft. Once we get those first two I'll rebase and submit for review. |
c84bcf4 to
e7415ba
Compare
dialmaster
left a comment
There was a problem hiding this comment.
Heh, I know I left a lot of comments on this, but this is a big change and I want to make sure we get it right :)
Most of my inline comments come from one design decision: request state only changes inside an HTTP handler. There's no worker. A request moves forward only when a create, an idempotent retry, an admin approve, or a read that happens to reconcile touches it. That's why:
- provisioning runs yt-dlp under the apikeys row lock (externalRequestExecution.js:108) and unlink runs under row locks (:193)
- a stale processing row can't tell auto-approval from admin approval (externalRequestService.js:271)
- finished downloads don't show under
?status=completeduntil someone reads the right page (:435) - an approve POST waits on yt-dlp for up to two minutes and times out behind Cloudflare (externalRequestReviewService.js:462)
- a storage pause fails the request for good instead of holding it (externalRequestExecution.js:90)
I think the fix is contained: create and approve only flip the row to approved and charge quota; a small in-process executor (or the existing job queue) picks up approved rows outside any lock, re-checks authority, and does the slow work; and a jobModule.onJobEnded listener closes video requests (server.js:296 already wires one for the run tracker). Catalog, quotas, auth, and the review validation don't need to change.
Two more things:
- The 14 new
external*.jsfiles plusapiKeyChannelGrantModule.jsandsafeCommandLogging.jssit flat inserver/modules/. Features this size live in a subfolder here (channel/,mediaServers/,notifications/). Can these move toserver/modules/externalApi/? - A few changes alter behavior for everyone and aren't needed for the API: the path redaction in
safeCommandLogging, the TV-Y7 rating change, droppingx-request-id, and the removed downloads-directory log line.
The no-auth 403 on the review routes (externalRequests.js:12) is still open from the first round and is a blocker for me since it's my own setup.
Restore the downloads-directory and cookie temp-dir log lines, the x-request-id correlation header outside the external API namespace, TV-Y7's text rating fallback, and unredacted yt-dlp stderr in server logs. Drop the bare 'key' redaction path so config upgrade logs keep naming the corrected setting. None of these were needed by the API.
…UTF-8 bodies With AUTH_ENABLED=false, verifyToken never sets req.authType, so the review routes' session check returned 403 for every call. Deny API keys instead, matching the key-management routes. External API POST bodies declaring a charset other than UTF-8 now get a 415 rather than a parse error or 500.
Move the external API services, their tests, and the channel grant module into a feature folder like channel/, mediaServers/, and notifications/. Give TV-Y7 its PG-level policy rank inside externalEligibility instead of changing ratingMapper, which also drives NFO output for every video.
Express routes /EXTERNAL-API/v1/... into the external router, but the app-level body parser bypass, error envelopes, degraded-database 503, and request id handling compared req.path case-sensitively. Share one isExternalApiPath check that matches the mount the way Express does.
Creating or approving a request now only records the decision and charges quota. A small in-process executor picks approved rows up outside any lock, re-checks the key's authority, and does the slow work, so no yt-dlp call, download queueing, or file unlink runs under a row lock or inside an HTTP handler: - Channel provisioning resolves the channel without enabling it and takes locks only for the final write, where a terminated channel now fails the request instead of being re-enabled. - Deletions go through deleteVideos, so the channel .m3u, playlists, and storage pause are refreshed like an in-app delete. - A storage pause or a busy video holds the request approved instead of failing it; the executor's sweep retries it. - A jobModule.onJobEnded listener closes video requests when their job ends, so ?status=completed no longer depends on who reads the list. Reads and quota checks no longer reconcile or lock anything. - A new approval_source column records whether a request was auto-approved, so the executor re-checks auto-approval only for those rows. - The download job id is passed as an option to doSpecificDownloads rather than read from the job data, and addJob rejects a preferred job id that is not a UUID.
Creating the request service in server.js eagerly required the channel, deletion and storage modules, which broke the server startup suites.
- Video detail reads metadata only from the cached .info.json and never runs yt-dlp or writes backfills. - Raw catalog SQL uses snake_case aliases and POSITION() instead of LOCATE(). - Video list ordering and keyset cursors (now v3) tie-break on channel video id. - Single-channel lookups use Channel.findOne with the grant include.
Document approval, background execution and held requests, cached-only video detail, auto-approved channel grants, delete and idempotency responses, the work queue env vars and the approval_source column. Bump the contract fixture to version 5 for the approved create response.
A background wake after approval could sweep before the test changed state (for example revoking a grant), which made the database job fail at random on either engine. The wake scheduler is now injectable and the database tests turn it off.
2a99a5f to
d698fb3
Compare
Hah no worries, I'm with you. Rather get it right the first time and no worry with it moving forward. I think I've caputred what you're looking for, but let me know if you have any other thoughts! |
dialmaster
left a comment
There was a problem hiding this comment.
OK, I did another pass on this. You addressed pretty much everything I raised in the last review, but I found a few more small issues that I think need to be addressed before merge.
Thanks for your persistence on this :)
| /** jobModule.onJobEnded listener: close the request a finished job served. */ | ||
| async function handleJobEnded({ jobId } = {}) { | ||
| // Every download job ends through here; only external ones need a query. | ||
| if (jobLookup(jobId)?.jobType !== EXTERNAL_REQUEST_JOB_LABEL) return; |
There was a problem hiding this comment.
I think this misses the auto-retry case. When a download hits a transient 403 (or the cookie "Video unavailable" thing), the finalizer queues a separate Auto-retry: job and then the original job ends in Error. That ends up here, resolveVideoRequests doesn't find a Videos row yet, and the request gets marked failed "Download did not complete". Then the retry job finishes, the file is on disk, but its job type doesn't match this check so nothing ever closes the request. The client sees failed and re-requests a video we already have.
I think you either should skip failing the request when the job's failed videos were handed off (autoRetryQueued), or let the retry job's end match too.
|
I think i got it all! And it built for me at least :) |
Summary
Adds the opt-in external API runtime for #568 on the persistence foundation merged in #750. Administrator UI work remains separate in #809; this PR is usable with the existing UI.
AUTH_ENABLED=false. Scopes, channel grants, rating/media policy, durable quotas, bounded work, and idempotent requests constrain access. Legacy download keys cannot authenticate the external namespace.server/modules/externalApi/. Existing no-auth administrator review access works while every API key is rejected from management routes. Unrelated rating, request-ID, and diagnostic-path behavior is preserved.Persistence and compatibility
The four migrations merged in #750 and upstream dependency corrections remain intact. Runtime migrations add the request indexes justified by the service queries and durable approval provenance. No channel deduplication, uniqueness rewrite, or global dependency override is introduced. This follow-up requires no additional schema migration.
Normal download responses retain their existing shape; retry job identities are returned only to internal callers. Both authenticated transient-403 retries and anonymous cookie-related retries are covered, including partial admission, exhausted retries, missed events, and persisted recovery. Existing application behavior terminates queued jobs on restart; reconciliation reports that terminal outcome.
Documentation includes held/retry lifecycle semantics and HTTP 409 for idempotency keys reused with another target.
Validation
Published head:
a423d5c164739dff15c70d973e75d4ce32dddb96.Local backend tests used a canonical temporary path for an existing macOS symlink-path assertion. Documentation checks/build ran from a temporary checkout without spaces because the existing generator does not decode spaces in its source path. Test databases and provider executors use synthetic data; no live downloads, deployment, or merge occurred.
CI for the published head: all required checks passed, including both database engines, full backend/frontend tests, Storybook, documentation, security, and the aggregate All Checks gate.