Skip to content

feat: add external API runtime and request control plane - #810

Merged
dialmaster merged 28 commits into
DialmasterOrg:devfrom
bballdavis:feature/external-api-runtime
Nov 4, 2026
Merged

dialmaster merged 28 commits into
DialmasterOrg:devfrom
bballdavis:feature/external-api-runtime

Conversation

@bballdavis

@bballdavis bballdavis commented Sep 8, 2026 •

Copy link
Copy Markdown
Collaborator

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.

  • External-key authentication remains mandatory even with 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.
  • Creation and approval record the decision and quota charge, then return. A background executor claims approved rows, rechecks authority, and performs downloads, channel provisioning, and deletion outside long-held database locks. Approval provenance survives interrupted work.
  • Download completion comes from job-ended events, with periodic reconciliation for missed events and restarts. Each automatically retried video records its admitted retry job identity; the request follows the chain through success or final failure while retaining its dedupe identity and original quota charge. Terminal reconciliation refreshes video presence after reading the final job state to avoid failing a concurrently successful retry.
  • Held work rotates behind other approved requests, so a batch of storage-paused downloads cannot starve newer deletions. Library-root/subfolder refusal returns a structured unavailable-library result; deletion stays approved until storage returns, with dedupe and quota preserved. Permanent failures still fail.
  • The existing API Keys & Bookmarklet screen hides revoked keys after deletion; management responses preserve their audit history for feat: add external API administrator UI #809.
  • Catalog reads use cached metadata; catalog pagination preserves duplicate-row tie-breakers, and raw SQL uses portable substring expressions and snake_case aliases. Effective feature availability and channel database IDs are exposed to clients.
  • External feature modules live under 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.

  • Backend: 238 suites / 6,472 tests passed.
  • Frontend: 297 suites / 5,497 tests passed, including revoked-key removal after the management list refetch.
  • MariaDB 10.3.39 and MySQL 8.0.46: 29 runtime/migration integration checks passed on each. Coverage includes a five-key backlog larger than one sweep batch, deletion during a storage pause, unavailable-library recovery with unchanged quota/dedupe, and persisted retry success/failure after restart.
  • ESLint, TypeScript, production client build, 18 documentation-generator tests, and production documentation build passed.
  • Independent review found and verified the concurrent-success reconciliation fix; final verdict: ship, no remaining findings.

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.

@bballdavis
bballdavis force-pushed the feature/external-api-runtime branch from 4517a3e to 56bb87b Compare September 8, 2026 23:23

@dialmaster dialmaster left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Holding off on a full review of this until #750 is merged, since it's stacked on that one and carries the same commits. Once 750 is merged, can you rebase this on dev so the diff is just phase two? #809 is stacked on this one in turn, so this needs to go in before that.

@bballdavis

Copy link
Copy Markdown
Collaborator Author

Holding off on a full review of this until #750 is merged, since it's stacked on that one and carries the same commits. Once 750 is merged, can you rebase this on dev so the diff is just phase two? #809 is stacked on this one in turn, so this needs to go in before that.

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.

@bballdavis
bballdavis force-pushed the feature/external-api-runtime branch from c84bcf4 to e7415ba Compare October 7, 2026 04:31
@bballdavis
bballdavis marked this pull request as ready for review October 7, 2026 04:41
@bballdavis
bballdavis requested a review from dialmaster October 7, 2026 04:41
Comment thread server/routes/externalRequests.js Resolved

@dialmaster dialmaster left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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=completed until 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*.js files plus apiKeyChannelGrantModule.js and safeCommandLogging.js sit flat in server/modules/. Features this size live in a subfolder here (channel/, mediaServers/, notifications/). Can these move to server/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, dropping x-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.

Comment thread server/logger.js Resolved
Comment thread server/modules/safeCommandLogging.js Resolved
Comment thread server/server.js Resolved
Comment thread docs/EXTERNAL_API.md Resolved
Comment thread server/modules/downloadModule.js Resolved
Comment thread server/routes/externalRequests.js Resolved
@dialmaster dialmaster mentioned this pull request Oct 17, 2026
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.
@bballdavis
bballdavis force-pushed the feature/external-api-runtime branch from 2a99a5f to d698fb3 Compare October 22, 2026 13:37
@bballdavis

Copy link
Copy Markdown
Collaborator Author

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=completed` until 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*.js` files plus `apiKeyChannelGrantModule.js` and `safeCommandLogging.js` sit flat in `server/modules/`. Features this size live in a subfolder here (`channel/`, `mediaServers/`, `notifications/`). Can these move to `server/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, dropping `x-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.

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 dialmaster left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 :)

Comment thread server/modules/apiKeyModule.js Resolved
/** 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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bballdavis

Copy link
Copy Markdown
Collaborator Author

I think i got it all! And it built for me at least :)

@bballdavis
bballdavis requested a review from dialmaster October 30, 2026 03:13

@dialmaster dialmaster left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Woohoo! Approved :)

@dialmaster
dialmaster merged commit 445166f into DialmasterOrg:dev Nov 4, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants