Introducing a new way to review your PRs.

Read the announcement

calicastle / cali.so

Personal website for Cali Castle

View on GitHub

21 documents · Updated Sep 21, 2026

docs / media-administration-and-retention

Media administration and retention

Media administration is the owner-only control surface for reviewing Media Assets, recovering incomplete processing, moving assets between the Library and Archived views, and permanently purging retained media. It connects the protected admin UI to catalog, Photo Selection, storage, and reconciliation services so that an operator action keeps private records and public media state aligned.

The broader media system is described in Media management platform. Media ingestion and storage explains how Originals become Renditions, while Photo selection and publication explains how eligible assets become public.

Protected administration boundary

The administration boundary limits media reads and mutations to the owner and applies the same security checks to every media API. Page loaders check ownership before they load data. Route handlers authenticate the request again, rate-limit mutations, and record privileged actions.

The main interface is /admin/media. /admin/photos uses the same protected boundary when it reads the active asset set and the current Draft Photo Selection. The media APIs are grouped by the work they support:

AreaInterfacePurpose
Asset viewsGET /api/admin/media/assets?view=active|archivedLoad the owner’s ready assets for the Library or Archived view.
Asset reviewPOST /api/admin/media/assets/:mediaAssetIdSave Display Metadata or Alt Text. Archive, restore, and undo an archive.
RecoveryPOST /api/admin/media/assets/:mediaAssetId/resumeResume a recoverable processing attempt.
SuggestionsPOST /api/admin/media/assets/:mediaAssetId/alt-text and /location-labelRequest an Alt Text Suggestion or a Location Label Suggestion.
RetentionGET or POST /api/admin/media/assets/:mediaAssetId/purgeRead purge progress or start and retry an irreversible Purge.
Transfers/api/admin/media/upload-intents/*Create, continue, complete, list, or discard owner transfers.

The API returns stable error classes such as unauthorized, invalid state, rate limited, and retryable failure. This lets the UI show a safe next action without exposing storage or provider details.

Owner authorization and mutation protection

Owner authorization is the first condition for access to a Media Asset. The service also checks ownership when it queries or changes catalog rows, so a valid asset identifier cannot be used to cross the owner boundary. Mutation requests pass through request protection and audit recording before the media operation runs. References: app/…/layout.tsx• L7-23, lib/…/http.ts• L183-217, lib/…/server.ts• L140-170

Media library and asset review

The Media page presents ready assets as a searchable contact sheet. It keeps active and Archived assets in separate views, shows whether an asset is ready to publish, and opens an inspector for human review. The inspector edits the owner-controlled Display Metadata, bilingual Alt Text, and Focal Point without changing the protected Original.

Review uses two different states. Catalog State describes whether an asset is active, Archived, or being purged. Processing State describes whether the Original has been verified and its Renditions are ready. An active asset can enter a Photo Selection only when it is ready, has a preview Rendition, and has approved Chinese and English Alt Text; the server remains the final authority for this rule.

The inspector also exposes safe repair actions. The owner can regenerate an Alt Text Suggestion, fill a Location Label from the private Capture Location when available, or resume a failed processing attempt. A new suggestion auto-applies as approved Alt Text only when the asset has no approved text. Existing approved text is not replaced by regeneration.

The review flow moves from an owner action to a catalog update and then back to both admin views. This diagram shows the relationship between the review surface, the protected API, the catalog, and publication eligibility.

flowchart LR
  Owner[Owner] --> MediaUI[Media page]
  MediaUI --> ReviewAPI[Protected asset API]
  ReviewAPI --> Catalog[Media Asset catalog]
  ReviewAPI --> Suggestions[Alt Text or Location Label service]
  Catalog --> Eligible{Eligible for Photo Selection?}
  Eligible -->|Yes| Photos[Photo Selection]
  Eligible -->|No| Repair[Review or resume processing]

Reviewable asset state

The UI treats processing and publication readiness as related but separate concerns. An amber marker means the asset is still processing or lacks approved Alt Text. A red marker means the processing pipeline needs repair. Archived and purging assets remain visible in the Archived view so the owner can restore or retry retention work. References: app/…/MediaLibrary.tsx• L128-159, app/…/MediaLibrary.tsx• L475-505, lib/…/eligibility.ts• L3-31, lib/…/service.ts• L166-239

Review metadata and suggestions

Display Metadata is the safe public-facing description of an image. The inspector can edit bilingual Location Labels, approved bilingual Alt Text, and the Focal Point. Capture details may be shown for review, but the private Capture Location itself is only used to help suggest a Location Label. References: app/…/MediaLibrary.tsx• L439-617, lib/…/http.ts• L301-475, lib/…/repository.ts• L224-270

Transfer visibility and recovery

The Transfers panel gives the owner a durable view of work that has not reached a ready Media Asset. It shows the difference between waiting for the Original again, active processing, a failed attempt, and an in-progress discard. Closing the panel does not stop work.

The browser queue reports immediate progress. The server-side Transfer Job list preserves work across page loads or lost browser state. The owner can choose the same Original again when the browser no longer has the file, retry processing when the asset exists, or permanently Discard an incomplete transfer. A Discard removes the unfinished Original and its chunks; if processing has already created an asset, the operation uses the asset Purge path instead.

Transfer completion is idempotent and resumable. The UI retries individual chunks or processing rather than starting an unrelated job, and the server keeps the durable state that tells the next attempt what work remains. Detailed byte transfer and image derivation behavior belongs in Media ingestion and storage.

Transfer job states

The panel maps durable transfer records to a small set of owner actions:

StateMeaningOwner action
Awaiting fileThe reservation exists but the browser must provide the Original again.Choose the matching Original.
ProcessingThe Original was accepted and image work is in progress.Wait, retry processing, or Discard.
FailedProcessing needs another attempt or a source fix.Retry or Discard.
DiscardingCleanup has started but is not complete.Retry Discard.

References: app/…/TransferDialog.tsx• L24-58 app/…/TransferDialog.tsx• L199-245 lib/…/service.ts• L5-17 lib/…/repository.ts• L18-76

Archive and selection withdrawal

Archive is a reversible catalog action that hides a ready asset from the normal Library and prevents new Photo Selection use. It does not remove the Original or Renditions. Archive also withdraws the asset from the owner’s Draft and from the Published Photo Selection when it is present.

The archive operation records enough selection history to offer a short Undo window. Undo restores the prior Draft position and the prior published membership only when the relevant selection revisions have not changed. A later Restore returns the asset to the Library, but it does not put the asset back into a selection automatically. The public publication changes only when withdrawal affects the published selection; unrelated Draft edits remain unpublished.

The UI offers Undo for a short period after Archive and otherwise sends the owner to the Archived view. A known Rendition URL is not revoked by Archive. Only a completed Purge removes the stored files and the CDN cache.

Archive and undo flow

This flow shows why Archive affects both catalog state and selection state while keeping later Restore separate from the short-lived Undo path.

sequenceDiagram
  participant O as Owner
  participant U as Media UI
  participant A as Asset API
  participant C as Catalog and selections
  participant P as Public publication

  O->>U: Archive asset
  U->>A: POST archive
  A->>C: Withdraw from Draft and Published selection
  C-->>A: Asset and Undo operation
  A-->>U: Archived asset
  C->>P: Refresh when publication changed
  O->>U: Undo within window
  U->>A: POST undo_archive
  A->>C: Restore prior membership if revisions match
  A-->>U: Active asset or conflict

References: app/…/MediaLibrary.tsx• L630-694 lib/…/repository.ts• L273-455 lib/…/withdrawal.ts• L246-332

Purge workflow and progress tracking

Purge is the irreversible retention action for an Archived Media Asset. It withdraws the asset from selections, removes every recorded Rendition object, purges each Rendition from the CDN, removes the Original, and then removes the catalog record. The system does not treat the database row as gone until the storage work is complete.

The owner must confirm the word PURGE. The first request creates or resumes a durable purge job and marks the asset as purging. Each storage step is recorded after it succeeds. A later request skips completed steps, which makes a failed Purge safe to retry without repeating work that the system already confirmed.

The purge status endpoint reports the progress that the UI or an operator tool needs:

Progress fieldMeaning
statuspurging, failed, or completed.
renditionCountNumber of recorded Rendition objects in the job.
renditionObjectsDeletedRendition objects removed from storage.
renditionCdnPurgedRendition cache entries removed from the CDN.
originalDeletedWhether the Original was removed.
lastErrorCodeThe last step that failed, when a retry is needed.

The purge claim has a lease so a stalled worker or request can be resumed. Concurrent Purge, Discard, and processing work for one asset are serialized. Selection changes use the owner-level lock before asset changes, which prevents an asset from being published between the withdrawal check and the Purge state change.

Purge progress lifecycle

The lifecycle records external storage effects before the catalog is finalized. This keeps a failed provider call visible and leaves the job available for a later retry.

flowchart TD
  Archived[Archived asset] --> Claim[Claim or resume purge job]
  Claim --> Withdraw[Withdraw from Draft and Published selection]
  Withdraw --> Renditions[Delete Rendition objects]
  Renditions --> CDN[Purge Rendition CDN entries]
  CDN --> Original[Delete Original]
  Original --> Complete[Delete catalog records and mark completed]
  Renditions --> Failed[Record failed step]
  CDN --> Failed
  Original --> Failed
  Failed --> Retry[Retry Purge]
  Retry --> Claim

References: app/…/MediaLibrary.tsx• L383-407 lib/…/service.ts• L8-32 lib/…/service.ts• L165-291 lib/…/repository.ts• L83-225 db/…/0008_media_purge_progress.sql• L1-31

Reconciliation operations

Reconciliation is the repair process for durable media work that stopped between transfer, verification, processing, and Alt Text generation. It finds stale work, retries recoverable processing, removes expired abandoned Upload Intents, and fills missing Alt Text Suggestions in small batches.

An operator can resume one owned asset through the protected admin API. A scheduled internal call runs the broader batch without exposing it to the owner UI. The batch reports counts for resumed assets, cleaned reservations, generated suggestions, and failures. A failure in one candidate does not erase progress from other candidates.

Reconciliation only acts on stale or incomplete work. It does not make an incomplete asset publishable by bypassing the processing and Alt Text rules. When a provider or AI service is unavailable, the durable record remains available for a later run.

Reconciliation candidate classes

The reconciliation service groups work by the recovery action that can safely follow:

CandidateRecovery action
Expired Upload Intent with no Media AssetDelete the Original and chunks, then remove the reservation.
Verified or retryable active assetRe-enter upload completion and processing.
Stale processing assetReclaim processing and continue from recorded progress.
Ready asset without an Alt Text SuggestionRequest a suggestion without changing image processing.

References: lib/…/service.ts• L19-24 lib/…/service.ts• L98-199 lib/…/repository.ts• L24-71 lib/…/repository.ts• L129-188

Internal media operations endpoint

GET /api/internal/media/reconcile is an internal operations endpoint for scheduled reconciliation. It does not use owner session authentication. It requires a Bearer token that matches CRON_SECRET, returns a disabled response when that secret is not configured, and returns only a small reconciliation result or a safe dependency error.

The endpoint is separate from owner APIs because it operates across owners and is intended for a trusted scheduler. Its caller must treat a successful response as a batch result rather than proof that every media item is healthy; the result includes a failure count for work that needs another run or direct owner review.

References: app/…/route.ts• L1-11 lib/…/http.ts• L5-43

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the owner identity checks in page loaders, route handlers, and repository queries aligned. A new media action must not rely on a page-level check alone.
  • Keep Catalog State transitions synchronized with selection withdrawal and public cache invalidation. Archive and Purge can change the Published Photo Selection without a Draft publish.
  • Keep each Purge progress step idempotent and tied to the recorded object manifest. A provider retry must not leave an untracked object or mark the CDN step before object deletion.
  • Keep Transfer Job state mapping aligned with the actions shown in the Transfers panel. A new durable state needs a safe retry or Discard path.
  • Keep reconciliation thresholds and batch limits compatible with the scheduler time limit. A run must leave stale work available for the next run.
  • Keep the CRON_SECRET contract and Bearer-token check unchanged across deployment and the internal route.

Important failure modes

TriggerConsequenceGuard
An owner request lacks valid session access or fails mutation protectionThe API returns an authorization or rate-limit error and does not touch media state.Page and route checks use the owner authenticator and shared security service.
Archive or Purge changes a selection but public cache invalidation failsThe catalog change is committed, but the public view can remain stale until invalidation is retried.The operation reports cache_invalidation_failed; Purge retries invalidation on resumed work.
A storage delete or CDN purge fails during PurgeThe asset stays in purging or failed state and the catalog record is retained for retry.Per-step progress and the last failed step are stored.
Purge loses its claim lease or overlaps processingThe operation cannot safely finalize the asset.Claim leases and the per-asset lifecycle lock serialize processing, Discard, and Purge.
Archive Undo arrives after the operation window or after selection revisions changeThe asset is not restored to the prior selection.Server-side expiry and revision checks reject the Undo without overwriting newer selection work.
Reconciliation meets an unavailable storage or AI dependencyThe candidate remains recoverable and the batch reports a failure.Candidate progress is durable and later runs retry only stale or missing work.

Key files

FileWhy to read it
app/…/page.tsxShows the protected Media page load and the active, Archived, Draft, and Transfer data assembled for the UI.
app/…/MediaLibrary.tsxShows the owner review surface, Catalog State actions, eligibility markers, and Purge confirmation.
app/…/TransferDialog.tsxShows the owner-facing states and recovery actions for durable Transfer Jobs.
lib/…/http.tsDefines the protected media API behavior, shared authentication, mutation controls, and error mapping.
lib/…/service.tsDefines asset review rules and the Catalog State actions exposed to administration.
lib/…/repository.tsShows how Archive, Undo, and Restore coordinate catalog rows with Photo Selection withdrawal.
lib/…/service.tsDefines the irreversible Purge sequence and the progress contract.
lib/…/repository.tsShows durable Purge claims, step markers, final catalog removal, and selection locking.
lib/…/service.tsDefines stale-work recovery and the batch result used by internal operations.
lib/…/http.tsDefines the internal scheduler authentication and response boundary.
app/…/route.tsExposes the scheduled reconciliation operation and its runtime limit.
lib/…/withdrawal.tsExplains the shared withdrawal and restoration behavior used by Archive and Purge.