divine-upload-server is the Rust upload data plane for Divine Blossom media. It receives blob bytes, stores them content-addressed in Google Cloud Storage, Backblaze B2, or both, and fires the media follow-up hooks (thumbnails, dimension probes, HLS transcoding, transcription) that turn a raw upload into a playable asset. It handles both single-request uploads and resumable, chunked sessions.
It is the data plane only. The Fastly-facing Blossom control plane (divine-blossom) answers client control-plane requests such as HEAD /upload, validates Blossom auth, and proxies short init and complete calls to this service. In the Divine resumable flow:
https://media.divine.videois the client-facing control plane and CDN origin.https://upload.divine.videois the opaque resumable session data plane served by this service.uploadUrlvalues returned to clients are server-issued session URLs and must be treated as opaque.
- Direct Blossom uploads —
PUT /uploadstreams a blob to GCS, hashes it, and returns the canonical Blossom descriptor. - Resumable, chunked uploads — an
init/ chunk /completesession protocol backed by GCS resumable uploads, with offset queries and resume support. - Blossom Nostr auth — verifies
Authorization: Nostr <base64 event>(kind24242) including event id, expiration, action tag, and Schnorr signature. - Content-addressed storage — finalized blobs are stored under their
sha256, so identical content is deduplicated. - Media follow-up hooks — video thumbnail extraction, dimension probing, HLS transcoding, and transcription are triggered as non-blocking work; failures never fail the upload.
- BUD-04 mirror / migration —
POST /migratefetches a blob from an allowlisted Blossom or CDN host and re-stores it. - Audit-log ingress —
POST /auditaccepts entries from the Fastly Blossom control plane and re-emits them as structured Cloud Logging JSON.
The service runs a single axum router over HTTP/1 and HTTP/2. Endpoints that mutate state require Blossom auth or a session token as noted; most routes also answer OPTIONS for CORS preflight.
| Method | Path | Auth | Purpose |
|---|---|---|---|
PUT |
/upload, / |
Nostr (upload) |
Direct single-request blob upload; streams to GCS and runs follow-up hooks. |
POST |
/upload/init |
Nostr (upload) |
Open a resumable session; returns uploadId, opaque uploadUrl, chunkSize, and a Bearer session token. |
PUT |
/sessions/:upload_id |
Bearer session token | Upload one chunk, addressed by Content-Range. |
HEAD |
/sessions/:upload_id |
Bearer session token | Query the next expected offset to resume an interrupted upload. |
POST |
/upload/:upload_id/complete |
Nostr (upload) |
Verify the assembled bytes against the declared sha256 and promote them to the canonical blob. |
DELETE |
/upload/:upload_id |
Bearer session token | Abort a session and discard its temporary object. |
POST |
/migrate |
none (server-side Blossom auth) | Mirror a blob from an allowlisted Blossom/CDN host. |
POST |
/audit |
none | Ingest a control-plane audit-log entry. |
GET |
/thumbnail/auth-check |
Blossom service token (X-Divine-Thumbnail-Token) when configured |
Non-destructive credential verification used by backfill-thumbnails.py before deleting stored JPEGs (204 with X-Divine-Thumbnail-Auth: open|verified, or 404). |
GET |
/thumbnail/:hash |
Blossom service token (X-Divine-Thumbnail-Token), once required |
Return (or generate on demand) the JPEG thumbnail for a stored video. See Thumbnail service token. |
GET |
/ |
none | Human-readable landing page describing upload.divine.video. |
Direct upload. PUT /upload validates the Blossom auth event, streams the body to GCS while computing its SHA-256, and stores it under <sha256> with an owner metadata tag. For video content types it also extracts a thumbnail, probes dimensions, and (fire-and-forget) triggers HLS transcoding and transcription. The response is a Blossom blob descriptor: sha256, size, content_type, uploaded, a url on the CDN base, and optional thumbnail_url / dim.
Resumable upload. The client opens a session with POST /upload/init, sending the target sha256, size, and contentType. If the auth event carries an x hash tag it must match the declared sha256. The service creates a GCS resumable upload for a temporary object, persists a session manifest, and returns:
uploadIdand an opaqueuploadUrlpointing at/sessions/:upload_id,- the advertised
chunkSizeandnextOffset, requiredHeadersincludingAuthorization: Bearer <session token>,capabilities(resume,queryOffset).
The client then PUTs chunks to /sessions/:upload_id with a Content-Range header. Chunks must arrive in order at the expected offset and — except for the final chunk — be a multiple of 256 KiB. HEAD /sessions/:upload_id returns the next offset so an interrupted transfer can resume. POST /upload/:upload_id/complete requires the whole declared size to be committed, re-hashes the stored bytes, rejects a mismatch, and copies the temporary object to the canonical <sha256> blob (skipping the copy if that blob already exists) before deleting the temp object. DELETE /upload/:upload_id aborts and cleans up.
Send exactly one X-Divine-Video-Processing: copy-only header on direct
PUT /upload (or PUT /) to store the original without submitting eager HLS
work. This also applies to duplicate uploads of already stored bytes, preventing
an eager dispatch before the control plane commits its copy-only policy. The
header only reduces work; it neither grants encoding permission nor persists or
replaces authoritative media policy. Subsequent on-demand delivery must resolve
that policy through the control plane.
For resumable uploads, send the header on POST /upload/:upload_id/complete.
Completion preserves its existing on-demand HLS behavior. POST /upload/init
rejects the header with HTTP 400 because sessions do not persist this directive.
Unrecognized, empty, combined, or repeated values return HTTP 400. Original
storage, thumbnails, probing, transcription, and moderation retain their
existing behavior; this is not a switch disabling all media processing.
Copy-only requests are supported only without a configured processing outbox, retained coordination database, or original-write journal runtime. In these unsupported durable modes, direct uploads and completion return HTTP 400 before body consumption, admission, storage writes, or session changes. Existing durable contracts cannot carry this restriction, and historical intents could otherwise submit processing before the control plane records it. Ordinary requests and mirror processing retain their existing contracts. No outbox or journal schema is changed by this header.
GCS is the default backend (bucket default divine-blossom-media); B2 and dual-write modes use the same public object keys:
- Canonical blobs live at the object key
<sha256>— content-addressed and deduplicated. - Resumable temp objects live under
__resumable/uploads/<upload_id>/blob. In B2 and dual modes each chunk is instead stored as its own object under__resumable/staged/<mode>/<hex GCS bucket>/<hex B2 bucket>/<upload_id>/chunks/, and the chunks are assembled at completion. - Without
COORDINATION_DATABASE_URL, session manifests are JSON at__resumable/sessions/<upload_id>.json, holding the owner, declared hash/size, offset, session URL, and token. With it, sessions are stored in PostgreSQL instead. Sessions expire afterRESUMABLE_SESSION_TTL_SECS. - Thumbnails are stored alongside blobs as
<sha256>.jpg.
divine-blossom (Fastly) is the client-facing Blossom control plane; this service is the data plane behind upload.divine.video. Finalized blobs and thumbnails are served from the CDN at media.divine.video. Video uploads hand off to the transcoder (TRANSCODER_URL) for HLS, the transcription service (TRANSCRIBER_URL), and the self-hosted detector (AI_DETECTOR_BASE_URL) for evidence-only NSFW scanning. These calls are best-effort and asynchronous, so upload latency is unaffected and a downstream outage does not lose the blob. Repeated uploads of an already stored hash do not resubmit detector evidence.
Requires a Rust toolchain and ffmpeg on PATH for thumbnail extraction and video probing.
Run the test suites:
cargo test
python3 -m unittest discover -s tests -p 'test_*.py'Run the service locally (defaults to port 8080):
cargo runWithout GCS credentials the storage-backed routes will fail, but the server starts and serves the landing page and CORS preflight. The Python helpers at the repository root — export-video-upload-hashes.py and backfill-thumbnails.py — are standalone operational scripts.
All configuration comes from environment variables. The table below lists the code defaults, which are not always what production deploys — see the note under the table.
| Variable | Default | Purpose |
|---|---|---|
GCS_BUCKET |
divine-blossom-media |
Bucket for blobs, thumbnails, and session state. |
CDN_BASE_URL |
https://media.divine.video |
Base URL for returned blob and thumbnail URLs. |
UPLOAD_BASE_URL |
https://upload.divine.video |
Base URL used to build opaque session uploadUrls. |
PORT |
8080 |
Listen port. |
METRICS_PORT |
— | Optional internal Prometheus listener. Exposes /metrics on a separate port. |
MAX_CONCURRENT_UPLOADS |
4 |
Active upload requests per process. The same number can wait for a slot. |
MAX_CONCURRENT_THUMBNAILS |
2 |
Active on-demand thumbnail extraction slots per process (1–1024). Up to 2x as many requests can wait for a slot. |
THUMBNAIL_WAIT_SECS |
6 |
Maximum wait in seconds for a thumbnail extraction slot before returning 503 (1–60). |
MIGRATION_NSEC |
— | Nostr secret key used to sign Blossom auth when mirroring via /migrate. |
TRANSCODER_URL |
— | Legacy direct HLS admission when TRANSCODE_ADMISSION_SECRET is unset. Also the default transcription origin. |
TRANSCODE_ADMISSION_SECRET |
— | Dedicated credential that opts direct HLS into the Hetzner worker's authenticated queue endpoint. |
TRANSCRIBER_URL |
falls back to TRANSCODER_URL |
Transcription endpoint for audio/video. |
AI_DETECTOR_BASE_URL |
— | Self-hosted detector base URL. Newly stored videos request the nsfw signal asynchronously; unset disables the hook. |
THUMBNAIL_SERVICE_TOKEN |
— | Shared token divine-blossom sends on /thumbnail/:hash in X-Divine-Thumbnail-Token. Unset leaves the route open and logs a startup warning. |
THUMBNAIL_TOKEN_REQUIRED |
false |
true refuses /thumbnail/:hash requests without a valid token with 404. Requires THUMBNAIL_SERVICE_TOKEN; the server refuses to start otherwise. |
RESUMABLE_SESSION_TTL_SECS |
86400 |
Resumable session lifetime (24h). |
RESUMABLE_CHUNK_SIZE |
8388608 |
Advertised chunk size (8 MiB), capped to RESUMABLE_MAX_REQUEST_BODY_SIZE. |
RESUMABLE_MAX_REQUEST_BODY_SIZE |
1048576 |
Upper bound on the advertised chunk size (1 MiB); UPLOAD_ROUTE_MAX_BODY_SIZE is accepted as an alias. |
Before setting TRANSCODE_ADMISSION_SECRET, verify the worker accepts authenticated
requests at https://transcoder-worker.divine.video/transcode/queue and the
synthetic job reaches playback. Keep the current TRANSCODER_URL or explicitly
configure TRANSCRIBER_URL to preserve transcription. To roll back HLS admission,
remove the secret binding, redeploy, and verify Cloud Run accepts new HLS jobs
before closing the Hetzner endpoint. This setting only affects the direct
upload dispatch path. Copy-only suppression and configured outbox routes retain
their existing behavior.
RESUMABLE_CHUNK_SIZE is capped to RESUMABLE_MAX_REQUEST_BODY_SIZE before it is advertised in /upload/init.
RESUMABLE_MAX_REQUEST_BODY_SIZE is not an enforced request-body limit, despite the name — it is consumed only by that clamp. Inbound chunk size is bounded by the ingress: the divine-upload-server HTTPRoute attaches the upload-body-size SnippetsFilter (client_max_body_size 16m), a location-context directive that overrides the 100 MiB gateway-wide ClientSettingsPolicy.
On the chunk PUT path the server independently caps the collected body at 16 MiB and shares the MAX_CONCURRENT_UPLOADS admission slots. A chunk must also satisfy that the Content-Range total equals the session's declared size, that the range lies inside that size, that the range start equals the session's next offset, that the range length matches the body length, and that a non-final chunk is a multiple of 256 KiB. Lowering the advertised chunk size does not reject larger aligned chunks within the 16 MiB body cap and the declared size.
Authenticated direct uploads, session chunks, and resumable completions share a
bounded admission queue. Requests can wait up to five seconds for an active
slot. The server starts reading direct and chunk request bodies after admission.
Chunk session checks have a separate concurrency limit of the same size. A full
queue, exhausted session-check limit, or expired wait returns HTTP 503 with
Retry-After: 5.
The internal metrics listener reports divine_upload_active,
divine_upload_waiting, divine_upload_capacity, divine_thumbnail_active,
divine_thumbnail_waiting, and divine_thumbnail_capacity from the admission
semaphores, plus the divine_thumbnail_authenticated_total,
divine_thumbnail_unauthenticated_total, and divine_thumbnail_rejected_total
counters described under
Thumbnail service token. Scale on active and waiting requests to include storage I/O pressure.
On SIGTERM or Ctrl-C the HTTP server stops accepting connections and allows
existing requests up to 300 seconds to finish. Configure the pod termination
grace period above that drain timeout.
These are code defaults. Deployed values differ per environment and live in the divine-upload-server manifests in divine-iac-coreconfig; read those rather than assuming the defaults are what production runs.
divine-blossom decides who may see a thumbnail (moderation status, owner, age
gate, admin) before it asks this service for one, then calls
GET /thumbnail/:hash on the public upload host. This service cannot read that
moderation state, so without a credential anyone holding a banned or
age-restricted video's hash could fetch its frame here. Blossom therefore sends
a shared token in X-Divine-Thumbnail-Token, and this service can require it
(issue #52).
THUMBNAIL_SERVICE_TOKEN |
THUMBNAIL_TOKEN_REQUIRED |
Behavior |
|---|---|---|
| unset | unset or false |
Unchanged: every request is served. Startup logs a warning that the route is unauthenticated. |
| set | unset or false |
Every request is served. Requests without a valid token are logged with their reason and request id. |
| set | true |
Requests without a valid token get the same 404 as a missing video, before any cache read or generation. |
| unset | true |
The server refuses to start. |
The token must be visible ASCII with no spaces, or the server refuses to start.
It is compared in constant time and never logged. Whenever a token is
configured, every GET or HEAD /thumbnail/:hash response returned by the
thumbnail handler (served, refused, or failed) carries
Cache-Control: private, no-store and Vary: X-Divine-Thumbnail-Token, so no
shared cache can hand an authorized response to an unauthenticated caller or
keep serving a refusal (OPTIONS CORS preflight and pre-handler Axum path
rejections run outside that handler).
The internal metrics listener counts every request reaching the handler once a token is configured:
| Counter | Meaning |
|---|---|
divine_thumbnail_authenticated_total |
Carried the valid token (Blossom traffic, backfill-thumbnails.py, and any authenticated request that later fails with 400/404/500/503). |
divine_thumbnail_unauthenticated_total{reason="missing"} |
Served without any token (observe mode). |
divine_thumbnail_unauthenticated_total{reason="invalid"} |
Cumulative requests served with a wrong or duplicate token (observe mode). New increments mean a caller or secret copy does not match. |
divine_thumbnail_rejected_total{reason="missing"|"invalid"} |
Refused (required mode). |
backfill-thumbnails.py requires THUMBNAIL_SERVICE_TOKEN by default (pass
--allow-unauthenticated only when the target server has no token configured),
enforces an HTTPS origin (requiring --allow-non-default-upload-url for hosts
other than DEFAULT_UPLOAD_URL), disables HTTP redirects on token-bearing
requests, and runs a non-destructive preflight against GET /thumbnail/auth-check
before deleting any stored JPEG. The preflight requires 204 with
X-Divine-Thumbnail-Auth: verified (when sending a token) or
X-Divine-Thumbnail-Auth: open (when using --allow-unauthenticated against
an unauthenticated server), so a generic 400, 404 (including observe mode
with a wrong token), missing header, or redirect stops the run before any
object is deleted, without incrementing the /thumbnail/:hash counters. --dry-run
validates hashes and prints the planned count without needing credentials or
making network calls. Because backfill-thumbnails.py deletes <hash>.jpg before
regenerating, only run it against a stable deployment — never during a token
rollout flip, token rotation, or mixed-replica rollout.
The token comes from GCP Secret Manager in dv-platform-prod, through an
External Secrets binding in the divine-upload-server manifests in
divine-iac-coreconfig. The same value goes into GCP Secret Manager in
rich-compiler-479518-d2 for divine-blossom's Cloud Run blossom-upload-rust,
which serves the same route, and into Blossom's Fastly blossom_secrets store as
thumbnail_service_token. All three copies are listed under
Rotating the token.
-
Deploy with the token set and the flag off (observe).
-
Put the same value in Fastly
blossom_secrets, then deploy the Blossom change that sends it. -
Flip each receiver only after confirming known Blossom requests are authenticated on it, rather than gating on global counters that include every caller of the public route:
- On
divine-upload-server(GKE): start from thumbnail generations in Blossom's own edge logs, find their ids in this service's access log (matching on the truncated prefix) alongsidedivine_thumbnail_authenticated_total, and confirm none of them appears on a"Thumbnail served without a valid service token (not yet required)"line (which logsrequest_idandreason). - On
blossom-upload-rust(Cloud Run): confirm authenticated Blossom requests using its own observe-mode logging/metrics as documented indivinevideo/divine-blossom#417.
Blossom pins an id on every viewer request before routing, so its viewer
GETandHEADcalls sendx-request-id: blossom-thumbnail-<Blossom request id>(truncated to 64 characters in upload logs), while archive-import calls and ids with no usable characters send bareblossom-thumbnail. Any caller can send anyx-request-id, so always start from Blossom's edge logs before counting a hit as Blossom's. Treat aggregatedivine_thumbnail_unauthenticated_total{reason="invalid"}/reason="missing"rates as diagnostic signals rather than sole gates: newreason="invalid"increments point to a mismatched secret copy, andreason="missing"may never reach zero on a public route. - On
-
Set
THUMBNAIL_TOKEN_REQUIRED=true.
Rolling back means setting THUMBNAIL_TOKEN_REQUIRED=false in
divine-iac-coreconfig and a manual ArgoCD sync, so it is not instant. While a
wrong flip is live, only thumbnails not yet in storage fail: Blossom serves
stored thumbnails directly and edge-caches the resulting 404s for about a minute.
There are three copies of the one token, and every copy must change before the token is required again:
- GCP Secret Manager in
dv-platform-prod, read by this service on GKE through External Secrets. - GCP Secret Manager in
rich-compiler-479518-d2, bound to divine-blossom's Cloud Runblossom-upload-rust, which serves the same route. - Fastly
blossom_secrets(thumbnail_service_token), which Blossom sends.
The token is read once at startup and a single value is accepted, so rotation as documented here goes through observe mode, which temporarily reopens the route to callers without the token while it lasts. Whether that window is acceptable, or whether rotation requires overlapping tokens so enforcement never lapses, is a Platform decision. With the window, change the receivers before the sender:
- Set
THUMBNAIL_TOKEN_REQUIRED=falseon both upload services and roll them. From here no copy can break a request. - Update both GCP secrets, then roll this service once External Secrets has
refreshed (up to an hour, or force a refresh) and deploy a new
blossom-upload-rustrevision. Blossom still sends the old token, which shows asreason="invalid"but is served. - Update Fastly
blossom_secrets. Blossom now sends the new token:authenticatedrises. - Set the flag back to
trueon each service only after confirming Blossom's requests authenticate on it as in Rollout step 3, and recheck every other supported caller (such asbackfill-thumbnails.py): a caller that sends no token shows only asreason="missing", neverinvalid, soreason="invalid"stopping is not proof by itself.
MEDIA_WRITE_PROVIDER=b2_primary selects a separate staged migration policy:
B2 is authoritative and is written and fully verified first. By default, the
canonical GCS backup must then be stored and independently verified before
upload success; both immutable references are returned in B2, GCS order. With
media backups disabled, success records a verified B2-only completion and
returns only that immutable reference. Public hash URLs remain
unchanged. dual retains its historical GCS-first policy.
Admission-record updates retry GCS HTTP 429 responses at most twice with backoff, retaining the exact payload and generation precondition. A lost response can be confirmed by reading back the exact proposed record. Upload retries with a verified B2 receipt and acknowledged GCS backup take a fresh attempt fence, so an older in-flight attempt cannot also complete, then reverify both recorded object versions before completing the final receipt. Issued writes without a pinned acknowledgement still require authorized reconciliation.
This mode uses the existing GCS bucket for small private admission records and
resumable session state; it requires no coordination database or new worker.
Keep MEDIA_FINALIZED_URL and MEDIA_FINALIZED_TOKEN unset: startup rejects
those settings in this mode so an intake-only outbox cannot suppress the existing
HLS, transcription and NSFW hooks. With backups enabled, those processors can
continue reading the verified canonical GCS copy. Their existing best-effort
and retry limitations are unchanged. Resumable completion retains its existing NSFW/Core publication and
on-demand HLS behavior; it does not promise eager HLS or a thumbnail.
Required configuration is the existing GCS bucket/credentials and
B2_MEDIA_BUCKET, B2_REGION, B2_ACCESS_KEY_ID, B2_SECRET_ACCESS_KEY.
GCS compatibility must remain enabled. MEDIA_ORIGINAL_WRITE_ENABLED remains off;
its preparation-only API is not used as an upload prerequisite.
Set MEDIA_GCS_BACKUP_ENABLED=false alongside MEDIA_WRITE_PROVIDER=b2_primary
to store new canonical originals and thumbnails only in B2 without uploading or
verifying GCS media backups. Omission or true retains verified GCS backups;
any other value fails startup. The switch does not change new admissions in
gcs, dual, or plain b2 mode. Switching new admissions back to gcs also
restores backup requirements for retries of previously accepted B2-primary keys;
it does not retarget those keys to a new GCS-first write.
Before disabling backups, verify that playback and all follow-up processors can read a new original stored only in B2. This includes the transcoder used for HLS and transcription, and the CDN URL fetched by the NSFW scanner. Keep backups enabled until those paths work end to end on a candidate deployment. The companion transcoder change supports B2 reads while retaining legacy GCS input fallback, but does not verify the deployed read paths. This switch changes storage writes, not hook routing.
Disabling backups skips new GCS backup uploads and verifies only B2 on ordinary
B2-primary retries. A retry of a previously acknowledged GCS backup still
finishes its pinned readback; an uncertain issued write still fails closed
for explicit reconciliation. Existing GCS objects are not deleted or modified.
Resumable sessions admitted under a non-b2_primary mode retain their original
copy requirements: GCS and dual sessions repair a missing required backup
through the original admission fence using verified staged bytes, while plain
B2 sessions do not require GCS. Recorded B2-primary outbox contracts, including
historical recovery and sessions admitted through an outbox, still require both
copies regardless of the current switch. The bounded outbox reconciler only
verifies existing copies; it does not create missing backups. GCS remains
required in b2_primary mode for small private admission
records and resumable staging until a coordination database is
provisioned for plain b2 mode. Re-enabling MEDIA_GCS_BACKUP_ENABLED=true
causes subsequent retries for B2-only keys to write and verify their missing
GCS backups without rewriting B2 or treating a completed original as newly
stored. A completed B2-only thumbnail remains a valid read-only cache hit after
re-enabling backups or switching new admissions back to GCS: its recorded B2
version, admitted digest, size and provenance are verified. Completed two-copy
records also retain pinned primary verification with backups off; with backups
on, their recorded GCS copy is verified too. An incomplete admission cannot
fall through to an unpinned cache read. An eligible direct
video retry can also repair that thumbnail's backup using the existing JPEG
bytes; a read-only thumbnail request does not issue this repair.
The v1 admission JSON shape and slot variants remain unchanged. Its opaque
attempt token records B2-only completion as
b2-only-complete-v1:<32 lowercase hex nonce>, only after the pinned B2 bytes and
metadata pass verification. Every takeover replaces the nonce through the same
generation precondition; backup repair preserves the completion marker. An
unmarked verified-B2/unissued-GCS record is treated as interrupted, so a fenced
retry can report a new completion and offer its best-effort hooks again. A
marked replay or backup-only repair does not report a new original. This is
storage completion tracking, not a durable hook receipt: a crash after the
marker commits but before a hook is submitted can still lose that best-effort
hook. Neither exactly-once nor eventual moderation delivery is promised.
Older strict v1 JSON readers can deserialize these records, but that is not an older-image serving guarantee. They do not understand completed B2-only cache entries and can still return missing-backup errors until those objects are repaired. Older writers may replace the opaque token and conservatively repeat a hook. To roll back the setting, keep a release with these completion/cache read semantics and re-enable backups. Before downgrading to an older image, restore the copies its read paths require; re-enabling the flag alone does not backfill all old keys. See the candidate validation plan.
New resumable sessions stage bytes in GCS under
__resumable/b2_primary/<hex GCS bucket>/<hex B2 bucket>/<upload_id>/blob.
Completion checks the declared digest and promotes through the pinned B2-first
policy, including after new admissions are switched back to GCS. New-mode JSON
session manifests use generation preconditions; deleting a session retains a
small tombstone so stale writers cannot resurrect it. Old GCS/B2/dual sessions
retain their original policy and provider requirements. Session JSON now records
whether processing was admitted through the outbox, independently of later
configuration. A recorded legacy choice keeps its follow-up selection per
completion, even if a dispatcher is
configured later. A pre-field native GCS session in a historical PostgreSQL store
with no processing intent/receipt cannot prove that choice: completion stays
unavailable before promotion until the original processing configuration is
restored or the retained state is explicitly reconciled. This does not apply to
the ordinary GCS-only deployment without a coordination database. Expiry cleanup
retains the session if historical contract lookup or receipt removal fails.
Expiry cleanup checks existing receipts separately from permission to promote:
an expired unknown-choice session with no receipt is cleaned normally. A partial
processing schema or failed receipt lookup/removal retains the discovery state.
Per-key admission records at __resumable/b2-primary-writes/v1/ bind the bytes,
first metadata and provider buckets using GCS create-only/generation CAS.
Provider issuance is recorded before effects; the actual immutable B2 receipt
is recorded before verification, and verified primary identity before backup
I/O. Multipart upload IDs are retained in the same records. New-mode multipart writes
do not use the legacy PostgreSQL tracker, including when an old database is
retained to drain historical sessions. Completed replays
read exact recorded versions and verify bytes. An explicitly retried verified
primary with a backup that was never issued can continue without rewriting B2.
An admission whose provider slots are both still not-issued can be reacquired
with generation CAS after a lost admission response or restart; the old actor
cannot then issue an effect using its stale generation.
An issued operation with missing/unverified receipt stays pending for explicit
reconciliation; no TTL, latest-HEAD adoption, automatic repair or blind re-PUT
clears it. These private records are retained, not automatically garbage-collected.
This conservative policy also holds a received provider error or a failed read
of an acknowledged version pending; it does not automatically classify errors
as safe to reissue. No operator reconciliation command ships in this change.
Before activation, assign an operator and an authorized reconciliation procedure
for original and derivative records, including <hash>.jpg. A post-issuance
failure can otherwise keep that key unavailable.
Direct, mirror and on-demand policy selection checks accepted state before either legacy or outbox handling: a validated GCS primary record pins its provider set; otherwise an existing PostgreSQL contract retains its accepted policy; otherwise the current mode selects new admission. Contradictory accepted records fail without rewriting either policy. This precedence also applies when an existing outbox is configured during GCS rollback. Mirror processing registrations remain anonymous with retained history, whether or not a dispatcher is configured. Completed historical source contracts are read independently of dispatcher availability for on-demand thumbnails. Event provenance is retained: a B2-only event combined with an older GCS-only event keeps the historical dual ordering; it cannot masquerade as one explicit B2-primary finalization. Background recovery governed by a primary record requires its settled exact receipts, checks both pinned copies exist, and verifies their bytes; it never adopts current HEAD versions around unknown effects or repeatedly downloads a surviving copy when its recorded backup is missing.
Historical resumable sessions retain their original provider ordering. If a primary admission already owns the same key, a historical session can only reuse both settled copies after checking their exact versions and full byte identity; it cannot perform a legacy write around a partial primary admission.
If a database already holds historical pending upload intents, retaining its
existing configuration preserves that state: direct/mirror retries resolve the
old reservation, thumbnail barrier and ordered event receipt per request. New
hashes do not create PostgreSQL intents or suppress legacy processing. Historical
events still require their already configured consumer/deployment for delivery;
this mode does not create a replacement dispatcher. A deployment with no such
history needs no database. Do not discard an existing history database or its
consumer while accepted work remains.
The dispatcher is part of the legacy-mode service binary. Retain a separately
running historical b2/dual service with its existing database and
MEDIA_FINALIZED_* consumer configuration until its backlog drains; a new
b2_primary instance is not a dispatcher for it. Neither is a GCS-mode or GCS
rollback instance with historical database state but no MEDIA_FINALIZED_*
consumer configured. Alternatively, drain accepted work before switching the
only instance. Do not activate with a stranded backlog.
An accepted primary record or retained PostgreSQL source contract determines on-demand thumbnail policy. Without either recorded contract, new-mode reads do not fall back to GCS for old media. Before routing such historical thumbnail requests here, backfill and verify their original/thumbnail copies in B2, or retain their existing serving route. An unrecorded GCS-only historical original is not a readable B2-primary thumbnail source.
To roll back new admissions, keep this image, GCS compatibility and the B2
bucket/credential bindings, and set MEDIA_WRITE_PROVIDER=gcs. This GCS-plus-B2
drain configuration does not require PostgreSQL. New hashes use GCS; recorded
B2-primary direct/mirror retries and on-demand derivative policy still use their
accepted record. Existing new-mode resumable sessions finish against their
pinned buckets. Keep the same GCS bucket as the state anchor; moving that bucket
is not a supported admission rollback. Within that retained state namespace,
missing or changed B2 bindings fail instead of silently retargeting. Historical
b2/dual PostgreSQL sessions still require their old database and processing settings; this path does not convert or migrate them.
These controls serialize this uploader's new-mode writes; they do not add shared copy/erasure exclusion or publication approval. Existing Core pre/post-upload policy checks and delivery guards remain in force, with their existing race and lookup-error limitations. Ordinary upload paths do not currently join the shared B2 copy/erasure gate. Source checks do not prove provider-backed erasure, full artifact parity or an activated cutover. Operators must route normal Core uploads through this data plane and validate both copies and normal publication before claiming the upload switch is working; GCS retirement remains separate.
MEDIA_WRITE_PROVIDER selects gcs (the default), dual, or b2. In dual
mode every finalized original and locally generated thumbnail must be verified
in both configured destinations before its storage operation succeeds. A failed
second write is returned as an error; retrying repairs the missing copy. Public
Blossom URLs stay on CDN_BASE_URL.
B2 requires B2_MEDIA_BUCKET, B2_REGION, B2_ACCESS_KEY_ID, and
B2_SECRET_ACCESS_KEY. Use the private authoritative media bucket agreed with
Blossom, never the approved-only playback canary bucket. Credentials belong in
secret bindings. B2-only startup does not require Google credentials. Set GCS_COMPAT_ENABLED=true
when B2 mode still needs to finish old GCS sessions. When switching new writes
back to GCS, retain B2 settings so existing B2 sessions can finish.
B2 and dual modes also require COORDINATION_DATABASE_URL, MEDIA_FINALIZED_URL,
and MEDIA_FINALIZED_TOKEN. The PostgreSQL database holds durable upload state
and processing work. The HTTPS processing endpoint must implement the versioned
finalization contract; an ordinary
transcoder endpoint is not a compatible substitute. Queue acceptance is distinct
from completed thumbnail/transcode/transcript work. Deploy the companion consumer
and verify B2 processing and erasure coordination before enabling these modes.
Existing GCS sessions retain their backend. Keep their credentials available until they finish or expire; changing the new-upload mode does not migrate an active session. To stop creating B2 uploads, change admission back to GCS while retaining the B2-capable binary, workers, database, and credentials to drain work. Do not roll back to an older GCS-only image after accepting B2 uploads.
The legacy backfill-thumbnails.py deletion helper supports GCS only and rejects
B2/dual selection; it must not delete one copy while another remains cached.
With the outbox enabled, direct and mirror retries use an unfinished intent's
recorded provider policy, even after the new-upload mode changes. Keep every
required provider and bucket available: an unavailable or changed destination
returns 409 rather than retargeting the intent. A dual retry still requires both
copies after GCS admission is restored. Resumable sessions retain their own
policy, so completing one for bytes whose unfinished intent was recorded under
another mode still returns 409; drain or reconcile those intents before a mode
switch. See the deployment runbook for reconciliation before changing bucket
mappings. With the outbox enabled, unauthenticated /migrate
events always have a null owner instead of trusting the request's declaration.
Thumbnail generation and mirroring have independent configurable admission pools
(MAX_CONCURRENT_THUMBNAILS, default 2; MAX_CONCURRENT_MIRRORS, default 1), separate
from uploads. Thumbnail cache hits bypass generation admission; when all extraction
slots are busy, up to twice MAX_CONCURRENT_THUMBNAILS requests wait up to
THUMBNAIL_WAIT_SECS (default 6, range 1–60) before returning 503 with
Retry-After: 5. Mirror fetches use HTTPS allowlisted hosts without redirects
and are bounded by MIRROR_FETCH_TIMEOUT_SECS (default 120). Busy session locks
return 503 with Retry-After.
The service is packaged as a multi-stage Docker image (Rust build stage, Debian slim runtime with ca-certificates and ffmpeg) and runs on production GKE behind https://upload.divine.video.
CI (.github/workflows/ci.yml) checks formatting, runs clippy with warnings denied, and runs the Rust and Python test suites on every pull request. CI and local checks use Rust 1.98.1 (rust-toolchain.toml) so a moving stable toolchain cannot change the release gate unexpectedly. On pushes to main it authenticates to Google Cloud via Workload Identity Federation and publishes divine-upload-server to us-central1-docker.pkg.dev/dv-platform-prod/containers-production, tagged latest, the existing seven-character source SHA, and the full source SHA. Short-SHA tags remain available for existing manual promotion consumers. The build summary records the full SHA and pushed image digest; the new GitOps sender requests a digest-pinned release, never latest.
The optional GitOps promotion job requests a digest-pinned production image-update PR in divinevideo/divine-iac-coreconfig after both verification and image publication succeed. Existing production approvals remain required. The job stays disabled until the companion receiver and protected-environment prerequisites are ready. Dispatch acceptance is not deployment completion. See the sender runbook for prerequisites, the payload contract, reruns, and the link to private operational instructions.
Video follow-up currently points at the existing transcoder endpoint through TRANSCODER_URL. export-video-upload-hashes.py reads both the legacy Cloud Run audit logs and the GKE k8s_container audit logs, so historic exports keep working across the platform migration.
The optional durable finalization inbox and processing authority reuses PostgreSQL coordination and the existing finalization event contract. It is default-off, requires separate intake/worker credentials, and starts no automatic processing workers. Persisted intake is distinct from complete registration, moderation and artifact production; these remain outbox activation requirements.
The default-off producer preparation journal persists attempt nonces and immutable seven-artifact plans. Journal scope cannot dispatch provider writes or commit new processing results without the remaining authenticated parent-exclusion integration.
The default-off original-upload preparation boundary
records signed upload authorization and accepted storage destinations before
original finalization. MEDIA_ORIGINAL_WRITE_ENABLED=true requires PostgreSQL
and deliberately returns unavailable before new original provider I/O; it does
not enable upload execution. Existing committed resumable receipts remain
readable. Keep this flag off until the shared writer/policy and settlement
integration is complete.
Part of Divine — your playground for human creativity · Brand guidelines