Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion cmd/silo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4416,6 +4416,7 @@ func main() {
nil,
)
collectionHandler.ArtworkStore = deps.Blobs.Assets
collectionHandler.ArtworkReservations = catalog.NewArtworkReservations(deps.DB)
collectionHandler.ArtworkResolver = deps.ArtworkResolver
collectionHandler.FrontendFS = deps.FrontendFS
collectionHandler.SectionRepo = sectionRepo
Expand Down Expand Up @@ -5089,6 +5090,11 @@ func trickplayURLResolver(deps *api.Dependencies) artworkurl.Resolver {
return deps.ArtworkResolver
}

// The settings value main passes to configureBlobStorage must keep the atomic
// update the response override needs; the assertion in configureBlobStorage
// drops a mismatch silently, so this line makes it a build error.
var _ blobstore.ResponseOverrideSettings = (*serversettings.EncryptedSettingsRepo)(nil)

// configureBlobStorage initializes blob storage only in processes that own the
// catalog. Workers share settings but do not have storage clients.
func configureBlobStorage(ctx context.Context, mode string, cfg *config.Config, deps *api.Dependencies, settings blobstore.SettingsStore) error {
Expand All @@ -5111,13 +5117,20 @@ func configureBlobStorage(ctx context.Context, mode string, cfg *config.Config,
if direct, ok := store.(blobstore.DirectURLer); ok {
ttl := cfg.S3.MetadataPresignExpiry
if ttl <= 0 {
ttl = 4 * time.Hour
ttl = artworkkey.DefaultGrace
}
deps.ArtworkResolver = artworkurl.NewDirectResolver(direct, deps.S3Public.EffectivePresignTTL(ttl))
deps.ArtworkDelivery = api.ArtworkDelivery{
Scope: deps.S3Public.ArtworkDeliveryScope(),
External: deps.S3Public.UsesExternalDelivery(),
}
// Only a client that mints SigV4 links can carry the response override.
// The worker returns at once; start-up never waits for the check. A
// settings value that lacks the atomic update (or none) leaves it off.
if !deps.S3Public.UsesExternalDelivery() {
overrideSettings, _ := settings.(blobstore.ResponseOverrideSettings)
blobstore.StartResponseOverride(ctx, deps.S3Public, overrideSettings, nil)
}
}
deps.ArtworkResolver = chapterthumbs.NewURLResolver(deps.DB, deps.ArtworkResolver)
probeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
Expand Down
9 changes: 5 additions & 4 deletions docs/architecture/backups.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,10 +273,11 @@ blob a backup carries.
Blobs are copied after the snapshot closes, so the copy is not frozen with it.
A key replaced in place (library posters, some collection images) may carry
bytes newer than the snapshot. A referenced key can be deleted during the
backup: superseded collection image revisions and replaced downloaded
subtitles are deleted immediately, and only derived media images go through
the delayed `blob_gc_queue`. No delay is guaranteed for the blobs a backup
copies. A key missing at copy time is recorded in `missing_blobs` and the
backup: replaced downloaded subtitles are deleted immediately, and derived
media images go through the delayed `blob_gc_queue`. Superseded collection
image revisions are queued for the artwork revision collector and kept for the
retention period (78 hours), not deleted at once. No delay is guaranteed for
the blobs a backup copies. A key missing at copy time is recorded in `missing_blobs` and the
backup completes with warnings: the database and every other blob are still a
valid recovery point. Any other read error fails the backup.

Expand Down
183 changes: 158 additions & 25 deletions docs/architecture/blob-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -489,32 +489,153 @@ reveal whether a key exists.

For artwork, the path is the identity and the query is the authorization.
Clients and CDNs cache images by full URL, so a new URL for unchanged bytes
costs a download the client already has. A revisioned key names immutable bytes,
so at the default lifetime (`s3.metadata_presign_expiry`) its URL stays the same
for a UTC day on every replica and is valid for at least the TTL. A leaked
revisioned URL therefore works for up to a day plus the TTL; lowering the
setting shortens the TTL but not the day.

Every other URL is stable within a 15-minute issuance bucket, or a bucket as
long as the TTL when that is shorter, and is valid for at least its TTL and at
most one bucket longer. A mutable key, such as a library poster or collection
image replaced in place, must get a new URL soon after its bytes change. A
capability requested for less than the default, such as an avatar or a chapter
thumbnail, keeps its extra lifetime within its own TTL. Revisioned responses are
cacheable for the URL's remaining lifetime and marked immutable; mutable keys
use private caching and revalidate with the ETag.

S3 installations use direct presigned or public URLs. A revisioned key's
presigned URL at the default lifetime is signed at the start of its UTC day and
expires a day plus the TTL later, so every replica mints the same URL. That
relies on every replica signing with the same static access key, the only
credential mode the S3 client uses; rotating session credentials would change
the URL at each rotation and end it when the credential expires. A TTL
near the SigV4 seven-day limit shortens that window rather than the TTL. The
costs a download the client already has. `internal/artworkkey` owns the values
and the rules that pick them for a key: the Window (72 hours), the Grace (the
default of `s3.metadata_presign_expiry`, 6 hours), the Short bucket (15
minutes), and the two long `Cache-Control` values.

A key whose bytes never change at that name (a content revision in its file
name, or a chapter or marker thumbnail directory named by its digest) keeps one
URL for the Window on every replica, valid until the Grace after the Window
ends. A freshly signed link works for between the Grace and Window + Grace
(3 days 6 hours) after hand-out, and a copied link for at most Window + Grace;
lowering the setting shortens the Grace, not the Window. The stored-art
resolver remembers a link for at most 5 minutes, so just after a Window
boundary it can hand out the previous Window's link for up to about 5 minutes;
such a link has up to 5 minutes less than the Grace left. A library poster
(`library-posters/`) is replaced in place at one key, so on S3 and token links
every read signs a fresh URL (a read at least one second later gets a new one,
since signing times have one-second precision) and the local route keeps the
Short bucket and revalidates with the ETag. Every other key (a legacy avatar or
catalog file, a legacy chapter key) is stable within a Short bucket at the
default lifetime and valid for at least the Grace and at most one bucket
longer. A capability requested for less than the default, such as an avatar or
a pushed chapter thumbnail, takes no Window and keeps its extra lifetime within
its own TTL: a local link works between its TTL and one bucket past it, an S3
link for exactly its TTL, a token link for the token lifetime.

**Replaced art outlives its links.** Artwork a row stops naming waits in the
revision collector for `artworkkey.ReplacedRetention` (78 hours: the Window plus
the default Grace) before the collector may delete it, so a link issued before
the replacement keeps working until it expires. This holds at the default Grace;
Comment on lines +517 to +520

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Major · Data Integrity & Integration · Heavy lift

Protect displaced artwork from the daily sweep.

If a catalog object is older than 24 hours when it is replaced, the daily sweep can delete it before its 78-hour retention deadline. On a page with fewer than 50 parsed objects, the sweep does not check the revision collector's schedule. A still-valid link can then return a missing-object response.

Make the sweep preserve displaced artwork until its retention deadline before relying on this guarantee.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right, and this PR depends on #5916 for exactly this. The daily storage sweep deletes an unreferenced object older than 24 hours without reading the collector's deadline, so it can remove a replaced catalog image inside the 78 hours. #5916 moves the sweep's delete under the collector's row locks and skips any revision whose row has not_before in the future. Every displaced catalog revision has that row, because the trigger writes it with now plus 78 hours, so the guard holds on every page, not only the lopsided ones. The PR body says this PR should merge after #5916, and I'll rebase onto it when it lands. On that rebase I'll also add the deadline to the sweep paragraph in docs/architecture/blob-storage.md.

🤖 Claude Code (claude-opus-5-5)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Analysis chain

Script executed:

#!/bin/bash
set -u
echo '=== Pull request #5916 ==='
gh api repos/Silo-Server/silo-server/pulls/5916 --jq '{state,merged,merged_at,title,base:.base.ref,head:.head.sha,body}' || true
echo '=== Pull request #5928 ==='
gh api repos/Silo-Server/silo-server/pulls/5928 --jq '{state,merged,base:.base.ref,head:.head.sha,body}' || true
echo '=== Current revision ==='
git rev-parse HEAD
echo '=== Current artwork sweep symbols ==='
rg -n -C 3 'artwork_revision_gc_candidates|not_before|sweepArtwork|SweepArtwork|parsedObjects' internal/metadata -g '*artwork*' | head -230
echo '=== Reconcile file outline ==='
ast-grep outline internal/metadata/artwork_reconcile.go --items all --type function --match '[Ss]weep|[Aa]rtwork'
echo '=== Pull request #5916 relevant file changes ==='
gh api --paginate repos/Silo-Server/silo-server/pulls/5916/files --jq '.[] | select(.filename | test("artwork|sweep|gc"; "i")) | {filename,status,patch}' || true

Length of output: 72441


@darthShadow Thanks for identifying the dependency. At the time of the check, #5916 was still open. Its current patch checks not_before under the revision row lock.

I’m not marking this finding addressed yet. After #5916 merges and this PR is rebased, please verify that the sweep preserves an object older than 24 hours while its collector deadline is in the future, including on a small page.


📝 Learnings were not changed: only organization members or users with write access to this repository can add or remove learnings.

You are interacting with an AI system.

a Grace above 6 hours, or a token lifetime above 3 days 6 hours, issues links
that outlive the retention. Database triggers queue the
displaced path when a catalog row or a collection's poster or backdrop changes,
and when a collage row is deleted; a collection trigger queues a path only when
it lies in that collection's own image directory, so a path the row borrowed
from another surface is never queued. An uploaded collection image reserves its
exact object keys with the collector before the first object is written
(`catalog.ArtworkReservations`): an upload that dies before the row names the
revision is collected after the retention, and a reservation for a path a
collector worker is processing is refused, which answers the upload 503
`unavailable` with `Retry-After: 30`. Deleting a collection removes its uploaded
poster and backdrop at once and leaves its collages to the collector.

**Origin headers and URL lifetimes are separate.** A link's lifetime decides how
long a client may fetch it, and `exp` limits cold reads at the origin only. The
response's `Cache-Control` decides how long a client or shared cache may keep
the bytes:

- Month, `public, max-age=2592000, immutable`: catalog art, including `local/`
and `nfo/` copies, and new admin collection uploads.
- Week, `private, max-age=604800, immutable`: versioned avatars, chapter and
marker thumbnails, seek-preview sheets and new personal collection uploads.
Week responses never go to a shared cache.
- No long header for any other key (collages, legacy collection uploads, legacy
avatars and catalog files, legacy chapter keys, library posters).
`artworkkey.CacheControl` returns `""` for a key in a private namespace that
is not exactly a Week shape, so a malformed key under `profile-avatars/` or
`user-collection-images/` never gets the public value.

The S3 adapter writes the value as object metadata on every upload
(`Put`, `PutStream`, `PutStreamParts` and `CreateExclusive`) and writes none for
a key under an unserved namespace (`backups/`, `diagnostics/`,
`catalog-seeds/`). Re-caching still skips identical bytes, so objects stored
before this header existed keep none; a header-less object bounds only how long
a URL is reused, not what a client revalidates. The local artwork route sends
the same value for a classified key, on 200 and on 304, and otherwise keeps
`private, max-age=<remaining>, immutable` for a revisioned key and
`private, no-cache` for the rest. Offline-download artwork sends the Week value.
Branding assets send the Month value on an exact content-version request, and
overlay images, whose keys name their content digest, send it on every request.

S3 installations use direct presigned or public URLs. A versioned key's
presigned URL at the default lifetime is signed at the start of its Window and
expires Window + Grace later (`X-Amz-Expires` 280,800 s at the default), so
every replica mints the same URL. That relies on every replica signing with the
same static access key, the only credential mode the S3 client uses; rotating
session credentials would change the URL at each rotation and end it when the
credential expires. A Grace near the SigV4 seven-day limit shortens the Window
rather than the Grace: above 96 hours the Window is shorter than 72 hours. The
Cloudflare WAF rule fixes a token's lifetime from its timestamp, so token
timestamps are truncated to a quarter of the token TTL instead, which leaves
each URL valid for at least three quarters of it. Other presigned and token
URLs are issued fresh on every resolve, and public URLs never change.
timestamps are truncated to the larger of the token lifetime minus the Grace and
a quarter of the token lifetime, capped at the Window. At the default token
lifetime of 3 hours that is 45 minutes; at 6 hours it is 1 hour 30
minutes; at 8 hours, 2 hours; and at 3 days 6 hours (280,800 s), the full 72
hours. A token lifetime under 8 hours leaves a link with less than the 6-hour
Grace. Other presigned and token URLs for a key in the Short class are stable
within the bucket, library posters are issued fresh on every resolve, and
public URLs never change.

**Signed response override.** A SigV4 presigned link may carry
`response-cache-control`, and the storage then answers with that value as the
response's `Cache-Control` (AWS documents it for 200 responses). It gives the
header to objects stored before the header existed, which carry none. It
applies to the assets store only, and only when its client signs with SigV4
(`UsesExternalDelivery()` is false): a public or token link carries no SigV4
signature, which the parameter needs, and a local install's route already sends
the header. `S3.DirectURL` knows only the key, so every key that has a class
gets the parameter, with the value `artworkkey.CacheControl` returns, and
unserved keys never do. That covers old objects, new objects (where it repeats
the stored header) and any header an operator set on Silo's artwork objects,
which it replaces. A 206 carries no promise, and a 304 keeps the stored headers.

A replica signs the parameter only after a check passed for its storage. The
check runs at a replica's start when the row below has no entry for its
storage, in a background worker that starts after the store opens; start-up and
readiness never wait for it. It writes a fixed fixture under
`.silo-artwork-override-check/` (a storage transition's copy pass leaves that
prefix out), signs one plain link and two override links (the Month and the
Week value) through the production signer, fetches each with no credentials and
no redirect under one 30-second deadline, and deletes the fixture. The result
is `pass` when each override link returns the fixture with exactly its value
and no other `Cache-Control`. It is `fail` when a link returns the fixture with
a missing or different header, the storage refuses the parameter with a 4xx
other than 408 or 429 and other than a provider rate limit, or the plain link
already carries a `Cache-Control`. A provider rate limit is an S3 error body
whose code the S3 client's retry table lists as a throttle, such as Wasabi's
403 `RequestRateLimitExceeded`. Anything else is inconclusive (a timeout, a
network error, a redirect, 408, 429, a provider rate limit, 5xx, a body that is
not the fixture, a fixture that could not be written, or a settings error):
nothing is recorded, the override stays off, and the
worker reads the row again and retries an hour later. Each outcome writes one
log line and never the link. A `fail` or an inconclusive result from this
replica's own check carries a reason category, and the status code when there is
one; a recorded or adopted entry and a `pass` carry no reason.

The result lives in the machine-managed row `artwork.response_override_check`,
hidden from the admin settings API like `artwork.storage_identity`. Its value
is a JSON object that maps a settings fingerprint to `pass` or `fail`, with no
time. The fingerprint is a SHA-256 over the endpoint, bucket and key prefix (as
`S3Identity` normalizes them), the region, the path style, the access key ID
and a probe version that changes with the tested values or the pass rule; it
leaves out the secret key. A replica that finds an entry for its fingerprint
adopts it and never checks. Replicas publish through the key-locked settings
update and the first entry for a fingerprint stays, so replicas that checked at
the same time sign the same links, and an entry for other settings is never
touched. Settings that change (a saved S3 setting takes effect at the next
restart, as does a storage transition) have a new fingerprint and are checked
at that start.

A recorded result lasts until an operator clears it; nothing re-checks on a
timer. If the storage's behavior changes under the same settings, a stale
`pass` breaks cold reads of every direct link that carries the override when
the storage now refuses it, and a stale `fail` keeps the gain off. A replica
checks again only at its next start after the row is deleted: a running
replica keeps its decision in memory, and a retrying worker only ever
publishes a fresh check. Links already handed out with the override keep
failing until clients receive new ones or the links expire, up to 3 days 6
hours.

Every backend consults the publication manifest for a rung a ladder change
added: existing revisions lack the new widest rung until the ladder backfill
Expand Down Expand Up @@ -570,3 +691,15 @@ backend serves them from the shared root with signed delivery. A public artwork
bucket alone does not enable avatar uploads: an S3 deployment without a private
bucket has no operational store, and uploads stay unavailable. Avatar URL
generation does not probe storage.

An avatar upload stores `original.<revision>.webp` and `w256.<revision>.webp`
under `profile-avatars/<user>/<profile>/`, where the revision is the hex SHA-256
of the encoded bytes. A new upload never overwrites the avatar a client is
loading, and the same image uploaded again lands on the same keys. The profile
names the versioned original and clients display the `w256` variant of the same
revision. A versioned avatar's link takes the Window like any revisioned key.
A replacement upload deletes nothing: earlier versions stay in the prefix until
the profile switches to a preset, the avatar is cleared, or the profile is
deleted; each of those removes the whole prefix. An avatar uploaded before
versioning keeps its `original.webp` and `w256.webp` keys and its short-lived
links until a new upload replaces it.
8 changes: 5 additions & 3 deletions docs/architecture/collection-posters.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ the same posters:
reserves its path in that queue, past the build, and saving the row releases it in the same
transaction. A build that fails or dies anywhere in between leaves its objects to the
collector. A build waits for a later read while a collector worker holds its path. Deleting a
collection also deletes its whole `collection-images/` prefix right away.
collection deletes its `collection-images/{collection}/poster/` and `.../backdrop/` images
right away. Its collage images stay for the collector.
- The artwork reconcile sweeps the table like other artwork surfaces. A cleared row reads as a
missing collage and is rebuilt on the next read.

Expand Down Expand Up @@ -143,8 +144,9 @@ differences:
trigger is the same `queue_deleted_collection_collage`.
- Objects live at `user-collection-images/{collection}/collage/{variant}.{key}.webp`, beside
uploaded posters. Deleting a collection, a profile or an account deletes the
`user-collection-images/{collection}/` prefix of every collection it removed once the delete
commits: the profile delete returns the IDs of the collections it deleted, and the account
`user-collection-images/{collection}/poster/` and `.../backdrop/` images of every collection it
removed once the delete commits, and leaves the collage images to the collector (the delete
trigger above queues them): the profile delete returns the IDs of the collections it deleted, and the account
delete reads them from Postgres in its transaction before the `users` cascade removes them,
so deleting an account on the per-user SQLite store leaves its collections' artwork. A failed
cleanup only logs, and nothing retries it.
Expand Down
4 changes: 3 additions & 1 deletion docs/architecture/trickplay.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,9 @@ A manifest is served only while all of these hold:
Sheets are stored at `trickplay/<media_files.id>/<revision>/<index>.<revision>.jpg`
in the assets store. The revision repeats in the file name so that
`artworkkey.Revision` reads it: the artwork route then serves sheets as
immutable, and signed sheet URLs stay stable for a day.
immutable, and signed sheet URLs stay stable for the 72-hour window. The
local route and S3 objects send the private one-week `Cache-Control`
(`artworkkey.CacheWeek`) for a sheet whose two revisions match.

## Reading previews

Expand Down
4 changes: 3 additions & 1 deletion docs/collections-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ The server reads and decodes a poster before it writes anything. `uploadCollecti
decode; and a `source_url` or `poster_source_url` with no http(s) host, an answer other than
`200`, or more than 10 MiB.
- `503 dependency_unavailable` with `Retry-After` when the server is too busy to decode another
image. The poster may be fine; send the request again.
image, and, for `uploadCollectionPoster`, when the revision collector holds the path the
poster would be stored at (a new collection's path is never held); `Retry-After: 30` in both
cases. The poster may be fine; send the request again.
- `500 internal_error` for any other failure, such as a source that could not be reached, a
source address the server refuses (above), or a storage error. The answer carries no detail;
the server logs the cause, except for a refused address, which is not logged. For a source it
Expand Down
Loading