✨ Reference the file data storage object with a foreign key (#12769)

* ✨ Reference the file data storage object with a foreign key

The file data pointer lived in `file_data.metadata.storage-ref-id`, a JSON
key. The storage GC parsed it to find live references, and nothing stopped it
from physically deleting an object a live row still pointed at: a failure in
that scan lost the blob.

Migration 0159 moves the pointer to a nullable `storage_object_id` column on
`file_data`, backfills it from the metadata key, removes the key from the
rows it backfills, indexes the column and rebuilds the foreign key to
`storage_object(id)` as `NO ACTION DEFERRABLE INITIALLY IMMEDIATE`.
`INITIALLY IMMEDIATE` is deliberate: the GC catches the violation inside the
chunk transaction, while a deferred check would fire at commit, outside it,
and the sweep would never move past the blocked chunk.

The column is the only source of truth. The `storage-ref-id` entry is gone
from the file metadata schema, and the single point that serializes the
metadata drops it, so no write can resurrect it. `upsert!` does not query
the row: the pointer of the row being replaced travels in its params, and
the object is touched before the row is written. Fragments and snapshots
pass nil because a modified pointer always gets a new id; the offload passes
its own row; `insert-file!` drops it, since an INSERT never replaces a
persisted object.

`update-file!` takes the file map read from the database plus the fields to
change and merges them, so the pointer comes from the read map and no caller
can lose it by building a partial map. A map without `:data` raises
`:missing-file-data`: it is not `assert`, which is compiled out in the
deployed binary. The params cannot override the pointer or retarget the
write with `:id`/`:file-id`.

`bfc/file->response` strips the pointer from every response (`get-file`,
`create-file`, `duplicate-file`, the view-only bundle, the team access
request, the comments read, the library summary, the snapshot read and the
debug download). A `file-data` object is authentication-only, so a leaked id
would let any logged-in profile fetch the blob from `/assets/by-id`.
`get-file-fragment` resolves through the file data backend, so a fragment on
cold storage no longer hands nil to `blob/decode`, and answers only the keys
of its result schema.

The storage GC reference scan, the restore union and `objects-gc` read the
column. The offload reads `SELECT fd.*`, so its rows go through a
`decode-row` that decodes jsonb metadata and drops a JSON null, which the row
schema rejected; a row without a readable object raises
`:missing-storage-object` with the file and row ids. A chunk blocked by the
foreign key (SQLState 23503) is a real anomaly, since the reference scan
should have frozen the object: it stays an error with its own hint and the
chunk is retried on the next run until the reference is fixed.

The release is a coordinated restart, not a rolling deploy, and not
rollback-safe for the rows it writes: the previous code writes and scans the
metadata pointer, so a key it writes misses the backfill and removing it
loses the reference. `operations/2.20.0-file-data-storage-object-id.md`
builds the column, the index and the foreign key online and runs the
backfill with every instance stopped, then marks the step as applied; a
fresh or small instance does the whole job in the migration. The runbook
keeps the validation scan out of the stopped window and adds a lock timeout
and retry to the online statements.

Tests cover the foreign key shape, the backfill and its corrupt and orphan
guards, the rebuild of a missing index and of a wrong, non-deferrable or
deferred constraint, the deletion refused by a live reference, the metadata
cleanup, the offload row normalizations, the touched objects of the unshare
and the restore, the response stripping on every call site and the chunk
blocked by the foreign key. The backend memories and the developer guide
document the pointer, the GC behavior and the two migration paths.

Closes #12768

AI-assisted-by: deepseek-v4.1-flash
AI-assisted-by: inkling-2-small-free

* 🐛 Hold the file row lock across the migration write

`get-file` applies the pending migrations in memory and, when it finds
any, persists the result. That write read the row without a lock and
`update-file!` is an unconditional UPDATE, so a save that committed in
between was overwritten: the saved content, `revn` and `modified-at`
went back, the next save from that client failed with `:revn-conflict`
and the object the save left became an orphan the storage GC cannot
revisit once it is frozen.

The read now runs in a transaction of its own (`get-file` calls
`get-file*` inside `db/tx-run!` and accepts a cfg map only), so the
`file` row lock covers the re-check and the write. `get-file*` reads
the row once (`sql:get-file` plus `resolve-applied-migrations`) and
completes it with `attach-file-data`; only when a migration is pending
it reads the file again under `FOR UPDATE`, re-checks `need-migration?`
on that fresh map and persists it (`migrate-file`). The common case
stays at one row read and one migrations resolution, the migration case
keeps a single decoded copy in the heap, and a row that changed in
between is not overwritten. A migration found on the unlocked read is
applied in memory only, for the next read to persist.

`migrate-file` returns the reattached map when it persists, with the
`:storage-object-id` of the row the write left, and the realized map
when it does not; `:realize?` is what returns the read fully plain.
`fdata/upsert!` answers `{:written ... :storage-object-id ...}` instead
of a boolean, `update-file!` propagates it and the migrating read puts
it back in the map it returns, so a caller that persists again touches
the current object instead of the replaced one. `insert-file!` keeps
nil: an INSERT never replaces a persisted object.

The write also compares the stored pointer with the caller's value
(`IS NOT DISTINCT FROM`) and raises `:stale-file-data-pointer` when it
affects no row. Every writer holds the `file` row lock, so a pointer
that no longer matches is a protocol violation, not a race to retry.
The expected pointer is a separate argument because the storage branch
replaces `:storage-object-id` before the upsert, and the check lives in
`upsert-in-database`: the `legacy-db` branches do not use that SQL and
their count can legitimately be zero.

The save, snapshot and restore-backup reads take `FOR UPDATE` instead
of `FOR SHARE`: they inherit the lock, and the migration branch asks
for the exclusive one in the same transaction, so a shared lock that
upgrades deadlocks two concurrent readers. A data read rejects
`:lock-for-share?` for the same reason; only row-only reads accept it.
`sql:get-file-without-data` is a plain select now, not a CTE, which
makes locking legal without loading the data. Realization has a single
owner: `attach-file-data` only resolves and decodes, and `get-file*`
realizes once per path. The applied migrations no longer travel in the
`get-file-with-summary` response, cache hit and cache miss alike.

`embed-assets` reads each library without `:realize?`, so its
`:components` is an unloaded pointer map; `absorb-assets` walks it with
`vals`, `PointerMap.seq` calls `load!` and that raised with no loader
bound, so every export with `:merge-libraries` of a library with
components failed. The absorb runs under the library's own loader now.

The in-place binfile import (`import-file-and-overwrite*`,
`::overwrite`, `::bfc/file-id`) had no product caller and cannot carry
the previous `storage_object_id`, so overwriting a storage-backed row
would leave its object unreclaimed. `import-files!` rejects a cfg with
`::bfc/file-id` (`:not-supported`) and the helpers only that path used
go with it (`invalidate-thumbnails`, `*reference-file*`, the
`::overwrite` id branch of `index-object` and of `save-file!`, the
`on-conflict-do-nothing?` flag of the media insert).

Tests: a new `file-migration-read-test` pins the single read, the
locked re-read, the concurrent save interleaving, the double migration
and the read-only path; the upsert tests cover the return shape and the
stale pointer; the SQL recorder they share lives in
`backend-tests.helpers`, and the save, snapshot, restore and summary
sequences follow the new reads. The backend memories document the read
contract and the pointer.

AI-assisted-by: deepseek-v4.1-flash

* 🐛 Harden the get-file guard and skip its read-only transaction

The cfg guard of `get-file` was an `assert`, which `app.config` elides
when `:backend-asserts` is off, so a deployed binary accepted a bare
pool or connection while the docstring promised it raises. It throws
`IllegalArgumentException` now, the class the option guards of the same
namespace already use, and the existing test expects it instead of
`AssertionError`.

A read with `:read-only?` applies the pending migrations in memory and
writes nothing, so the transaction the migration write needs only costs
two round trips there. `get-file` runs it with `db/run!` instead: with
a cfg that carries a connection it still joins the caller's
transaction, and only the reads that would have opened their own skip
it. A lock option needs a read-write transaction from the caller,
because PostgreSQL rejects row locks in a read-only one; the docstring
states that.

Tests: the guard test expects the new class; a cfg marked
`::db/read-only` reads a pending migration without persisting it (the
config flag that fills that key is legacy, but the key is set by hand);
and a read-only read is pinned as not opening a transaction while the
same call without the option does. The backend memory documents the
split and the guard.

AI-assisted-by: deepseek-v4.1-flash
This commit is contained in:
Andrey Antukh 2026-11-14 19:27:18 +01:00 committed by GitHub
parent d9a9d0c2bc
commit e23ca02aa2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
44 changed files with 2695 additions and 454 deletions

View File

@ -93,7 +93,7 @@ Since `put-object!` uses backend-specific operations (`impl/resolve-backend` + `
| `organization` | Organization logos uploaded by the Nitrate management API. | Yes | Public | No reference scan. A touched object is deleted. |
| `tempfile` | Export files and temporary font downloads. | No | Authentication required | No reference scan. A touched object uses a two-hour deletion delay. |
| `upload-session` | Chunked-upload chunks. References: `upload_session_chunk.object_id` and `upload_session_chunk.session_id` (both NO ACTION DEFERRABLE: restrict semantics, procedural deletion). | No | Authentication required | Reference scan on `upload_session_chunk.object_id`; a referenced chunk freezes, an orphan is deleted after the delay. Deferred rows keep their mappings until give-up. |
| `file-data` | Encoded file data when `file-data-backend` is `storage`. Reference metadata has `storage-ref-id`, `file-id`, and the `file_data` row ID. | Yes | Authentication required | Reference scan. |
| `file-data` | Encoded file data when `file-data-backend` is `storage`. Reference: the `file_data.storage_object_id` column (FK `NO ACTION DEFERRABLE INITIALLY IMMEDIATE`); the object metadata keeps `file-id` and the `file_data` row ID. | Yes | Authentication required | Reference scan. |
| `file-data-fragment` | Compatibility value for file-data fragments. The current backend has no dedicated producer for this bucket. | No current write semantics | Public | No touched-object collector case. |
| `file-change` | Compatibility value for file changes. Current snapshots store data in `file_data`, not this bucket. | No current write semantics | Authentication required | No touched-object collector case. |
| `job-resource` | Storage objects owned by job rows (`job.resource_id`), written by `app.jobs.storage`. | No | Authentication required, owner-scoped | jobs-GC touch → reference scan. |
@ -121,15 +121,22 @@ Since `put-object!` uses backend-specific operations (`impl/resolve-backend` + `
- `file-data-backend` accepts `legacy-db`, `db`, or `storage`.
- `legacy-db` stores main data in `file.data` and snapshots in `file_change.data`.
- `db` stores encoded data in `file_data.data`.
- `storage` stores encoded data in storage subsystem with `file-data` bucket and keeps `data` nil in `file_data` table.
- The `file_data.metadata.storage-ref-id` value points to the storage object.
- `fdata/upsert!` touches a storage object from incoming metadata before it stores the new row.
- `storage` stores encoded data in storage subsystem with `file-data` bucket, keeps `data` nil in `file_data` table, and points at the object with `file_data.storage_object_id`.
- `file_data.storage_object_id` is a `NO ACTION DEFERRABLE INITIALLY IMMEDIATE` foreign key to `storage_object(id)`: the database refuses to physically delete a referenced object. The `IMMEDIATE` is load-bearing: the RI violation fires inside the `storage-gc-deleted` chunk transaction, so the chunk rolls back, is logged at error level with a generic hint plus the `constraint` and `table` the database reports (any `NO ACTION` foreign key on `storage_object` can block the delete, not only `file_data`'s) and is retried on the next run; with `INITIALLY DEFERRED` the check would fire at commit, outside the catch, and the sweep would never move past the blocked chunk.
- The column is the only source of truth. The release is a coordinated restart (no rolling deploy) when the instance uses the storage backend (`PENPOT_FILE_DATA_BACKEND=storage`) or still has rows carrying `metadata.storage-ref-id`; with the default `db` backend and no such rows the previous and the new code read the same `file_data.data` column, so a rolling deploy is safe. `metadata.storage-ref-id` is no longer written or read, and the `file-data` metadata schema does not declare it. The migration backfills the rows it can resolve (valid uuid with an existing `storage_object`) and removes the key from those rows; a corrupt or orphan pointer keeps the key, which nothing reads. A large instance runs `operations/2.20.0-file-data-storage-object-id.md`: column, index and FK online, then the backfill (only if a row still carries `metadata.storage-ref-id`) with every instance stopped, verifies, and marks the migration as applied (`INSERT INTO migrations`). The backfill must never run while the previous code serves when the storage backend is in use (or rows with the pointer remain), because that code writes and scans the metadata pointer. A rollback to the previous code cannot read the rows written by this release when the storage backend is in use.
- `fdata/upsert!` touches the `storage_object_id` it receives in the params (the pointer the persisted row had) before replacing it, so the replaced blob is reclaimed. Callers pass the column from the file map (main/restore), `nil` for a new row (fragments, snapshots, new files) or the row itself (offload); there is no query in the upsert path, which is why every caller reads the file under the row lock first (the migration-on-read path included, see `mem:backend/subtleties`). It returns `{:written <bool> :storage-object-id <uuid or nil>}`, the pointer of the object the write created (nil for `db`/`legacy-db`), and `binfile.common/update-file!` propagates it so a migrating read returns the map with the pointer of the row it persisted instead of the pre-write one. The write also compares the expected pointer with `IS NOT DISTINCT FROM` (the caller's value, not the new one) and raises `:stale-file-data-pointer` when the row changed under it, so a stale map fails instead of leaking the replaced blob; the check lives in `upsert-in-database` because the `legacy-db` branches do not use the upsert SQL.
- `binfile.common/update-file!` takes the file map read from the database plus the fields to change (`[cfg file & params]`), merges them and builds the `file_data` params from the merged map, so the pointer travels in the read map and a caller cannot lose it by building a partial map; the params cannot override `:storage-object-id`. `insert-file!` always drops it (an INSERT never replaces a persisted pointer; `duplicate-file` hands the source map there). `bfc/get-file` keeps the pointer for the write paths, and every response goes through `bfc/file->response`, which strips it and any residual `storage-ref-id` left in the metadata of the rows the migration does not backfill: each `file-data` object is authentication-only and any logged-in profile could otherwise fetch it from `/assets/by-id`.
- The in-place binfile import was removed: `import-files!` raises `:not-supported` when the cfg carries `::bfc/file-id`, so no caller can overwrite a storage-backed row without carrying its previous pointer.
- File snapshots use `file_data` for snapshot data and `file_change` for snapshot metadata.
- Tiered offload (`:tiered-file-data-storage` flag + `db` backend): `file-gc` submits an `:offload-file-data` job (priority 10, delay 1000, same params) only when it actually processed the file; the handler takes the `file` row with `FOR UPDATE SKIP LOCKED` and skips (`{:skipped 1}`, no error) when the row is locked or gone, then moves every live `file_data` row of that file with `backend = 'db'` to `backend = 'storage'` via `fdata/upsert!` (one `put-object!` in bucket `file-data` per row, `data` becomes nil) inside a single all-or-nothing transaction per file. The skip only serializes because every `file_data` writer holds at least `FOR SHARE` on the `file` row. A storage failure aborts only that file and bubbles for a runner retry; orphans go to `storage-gc-touched`. A second run is a no-op because the query only matches `backend = 'db'`.
- Tiered offload (`:tiered-file-data-storage` flag + `db` backend): `file-gc` submits an `:offload-file-data` job (priority 10, delay 1000, same params) only when it actually processed the file; the handler takes the `file` row with `FOR UPDATE SKIP LOCKED` and skips (`{:skipped 1}`, no error) when the row is locked or gone, then moves every live `file_data` row of that file with `backend = 'db'` to `backend = 'storage'` via `fdata/upsert!` (one `put-object!` in bucket `file-data` per row, `data` becomes nil and `storage_object_id` points at the new object) inside a single all-or-nothing transaction per file. The skip only serializes because every `file_data` writer locks the `file` row first (the update RPC and the snapshot paths with `FOR UPDATE` through `lock-for-update?`, the migration-on-read path with `FOR UPDATE`). A storage failure aborts only that file and bubbles for a runner retry; orphans go to `storage-gc-touched`. A second run is a no-op because the query only matches `backend = 'db'`.
- The offload normalizes each `SELECT fd.*` row before `upsert!`: the row builder omits NULL columns, jsonb metadata arrives as a `PGobject`, and a JSON `null` decodes to nil and must disappear instead of travelling as `:metadata nil`, which the update schema rejects.
- Offload pacing: none by deliberate decision. Sleeps only make sense when batching multiple transactions; the per-file transaction is short by construction and the scheduler run takes minutes per production metrics, so neither loop sleeps. `jobs/heartbeat` (pool-based liveness, ~1 write/s) stays on both paths.
- Offload metrics (bounded labels only, never ids or error text): `penpot_file_data_offload_rows_total{type}` and `penpot_file_data_offload_bytes_total{type}` (`type`: `main`/`snapshot`/`fragment`, successful runs only) plus `penpot_file_data_offload_timing_ms{result}` (`result`: `ok`/`skip`/`error`). Helpers live in `app.jobs.metrics`; the job-def requires `::mtx/metrics`.
- Writes always resolve the backend through `fdata/default-backend` (`cf/get :file-data-backend`), so post-offload edits land back in hot (`db`) storage without extra code; reads stay transparent through `fdata/resolve-file-data` + `decode-file-data` + `realize`.
- Deleting an offloaded row touches its storage object first (`objects-gc/delete-file-data-chunk` via `fdata/process-metadata`), so `storage-gc-touched` reclaims the blob with the usual delay; restoring a file unmarks the referenced objects.
- Deleting an offloaded row touches its storage object first (`objects-gc/delete-file-data-chunk` via `fdata/touch-storage-object` with the row's `storage_object_id`), so `storage-gc-touched` reclaims the blob with the usual delay; restoring a file unmarks the referenced objects.
- `storage-gc-touched` resolves the `file-data` reference with `SELECT EXISTS (SELECT 1 FROM file_data WHERE storage_object_id = ?)`, an indexed lookup that no longer parses the object metadata.
- A row with `backend='storage'` and no readable object makes `resolve-file-data` raise `:missing-storage-object` with the file and row ids instead of failing later in the storage backend.
- The `file-id` and row id kept in the storage object metadata are informational for diagnostics; nothing parses them to resolve the reference (the reference is the column).
## File Change

View File

@ -91,17 +91,17 @@
## File data persistence
- File data backends are `legacy-db`, `db`, and `storage`. The storage backend keeps encoded file data in storage bucket `file-data`; the DB row stores metadata with `storage-ref-id` and nil data.
- `fdata/upsert!` touches any storage object referenced by incoming metadata before storing the new row/blob.
- File data backends are `legacy-db`, `db`, and `storage`. The storage backend keeps encoded file data in storage bucket `file-data`; the DB row stores nil data and points at the object with the `storage_object_id` column (FK `NO ACTION DEFERRABLE`).
- `fdata/upsert!` touches the storage object the persisted row pointed at before replacing it; the pointer travels in the params (`file->file-data-params` from the read file map, `nil` for a new row, the row for the offload) and the params of `update-file!` cannot override it. `binfile.common/update-file!` merges the read file map with the fields to change, so the pointer survives; `insert-file!` drops it because an INSERT never replaces a persisted object. The column is the only source of truth and the metadata no longer carries `storage-ref-id` (the migration removes it from the backfilled rows and the write path never stores it); the release is a coordinated restart when the storage backend is in use (the previous code cannot read the new rows), while the default `db` backend reads the same data column and tolerates a rolling deploy. Responses built from a file map go through `bfc/file->response`, which strips the pointer and a residual `storage-ref-id` from the metadata.
- Pointer-map fragments are persisted separately as type `fragment`, and only modified pointer maps are written. A pointer keeps its id while nothing changes; content (`assoc`/`without`) and metadata (`with-meta`) changes produce a fresh id, so a fragment row is never rewritten after it is written. Re-assoc with an identical value returns the same map in array and hash maps alike, so a save keeps the fragment id of every page it does not change.
- `enable-objects-map` skips unloaded pointer pages: their fragment was already wrapped when it was written, and loading it only to wrap it again costs one page read per untouched page on every save. A page with a plain fragment is wrapped when it is first loaded or edited; a data migration that enables `fdata/objects-map` must rewrite the data itself.
- Snapshots share fragment rows with the live file (they are stored with pointers, not materialized). `file-gc` marks every fragment referenced neither by the current main file nor by an unpurged snapshot; the file is read unrealized and unchanged pages keep their ids via reattach, so a pass over an unchanged file writes no new fragments.
- A save attaches its automatic snapshot before applying pending file migrations: the snapshot keeps the pre-migration pointers, data and migration set, and restoring it leaves the next read to migrate the file. This also holds for files without the feature. The preview (`get-file-snapshot`) applies the pending migrations in memory with the live file's libraries and never persists them: the stored version keeps its data, the payload carries the snapshot's `:migrations` (an ordered set) and `fdata/objects-map` is realized for clients that do not declare it. The historical feature set is deliberately not checked against the enabled one: a version may predate a feature change. The window is narrow: the `get-file` RPC reads with `migrate?` on and its ETag hashes `available-migrations`, so a post-deploy read cannot be a 304 from the pre-deploy state and migrates before any save in the normal flow; the pre-migration snapshot only appears when the save is the first request to touch the file after the deploy (an open tab that saves without re-reading, or a non-UI writer). `create-file-snapshot` and the restore backup read with `migrate?` on, so those versions are stored already migrated.
- `:migrations` is always a `d/ordered-set`: `file-migrations/resolve-applied-migrations` builds one, `fmg/migrate` re-wraps the union after applying, and `file-snapshots/decode-snapshot` converts the `file_change` pgarray (as a plain vector, `set/difference` and `contains?` would compare indexes instead of names). A snapshot with NULL `:migrations` and an old `:version` predates the `file_change.migrations` column (SQL migration 0140): the preview regenerates the set from the stored version and applies that full chain, while `restore!` uses a fixed 67 baseline, so preview and restore can disagree for very old snapshots.
- The migration read path (`binfile.common/migrate-file`) captures `fdata/original-pointers` before realizing, reattaches unchanged positions after applying the migrations, and persists the reattached file; it returns the realized file because reads expose plain data. A migration that adds `fdata/objects-map` skips the reattach so the pages get wrapped.
- The migration read path (`binfile.common/get-file*`) reads the `file` row once (`sql:get-file`, with its data columns; with the storage backend the blob lives in the object, not in the column) plus an explicit `resolve-applied-migrations`, because a row read does not resolve them. A read with no pending migration is completed by `attach-file-data` on that map: one row read and one migrations resolution. Only when a migration is pending is the row re-read under `FOR UPDATE` on the `file` row, where `need-migration?` is re-checked on the fresh map and the migrated file persisted (`binfile.common/migrate-file`); that re-read resolves the migrations again, and `migrate-file` once more after persisting, to return the applied set. The migration path holds two raw copies of the blob (the first read and the locked re-read) but a single decoded one: the alternative, a row-only probe before the read, avoided the first raw copy at the cost of an extra row read on every open, and was removed. `get-file` runs the read inside `db/tx-run!` (joining the caller's transaction when the cfg carries a connection) so the persist commits with the read; a read-only read (`:read-only?`) takes no lock and writes nothing, so it runs on a plain connection (`db/run!`) instead of opening a transaction of its own, and with a cfg that already carries a connection it still joins the caller's. It accepts a cfg map only and throws an `IllegalArgumentException` otherwise (`assert` is elided without `:backend-asserts`); a data read rejects `:lock-for-share?` (only row-only reads accept it), because the migration branch re-reads with `FOR UPDATE`, and a lock option needs a read-write transaction from the caller because PostgreSQL rejects row locks in a read-only transaction. A row-only read (`load-data?` false) resolves the applied migrations by default too (`:load-migrations?`), because the row can be completed later and the caller may need them; a caller that does not want them passes `:load-migrations? false`. Persisting is an optimization of the read (the read already returns migrated data): a row that changed between the first read and the locked read is not overwritten, and a pending migration discovered on the unlocked read is applied in memory only (the next read persists it under the lock). This was the only writer of the file row outside the lock protocol (save, library absorption, restore, `file-gc` and offload already take it); without it, a save that committed in between was overwritten by the stale map (lost content, `revn` moving back so the next save fails with `:revn-conflict`, and the object the save left as a frozen orphan). `migrate-file` captures `fdata/original-pointers` before realizing, reattaches unchanged positions after applying the migrations, and persists the reattached file; it returns that reattached map when it persists (the pages the migration does not change keep their pointers and fragment ids) and the realized map when it does not, so a read is plain only when the caller asks with `:realize?`, and a migration that adds `fdata/objects-map` skips the reattach so the pages get wrapped.
- `fdata/load-pointer` reads rows that a previous `file-gc` pass marked on purpose (explicit `::db/remove-deleted false`): the fragment is only gone once `objects-gc` purges it. The `get-file-fragment` RPC keeps rejecting marked rows.
- Bind the fragment loader through `fdata/with-pointers` (reads), `fdata/with-tracked-pointers` (writes with a loader) or `fdata/with-tracked` (writes with nothing to load yet, e.g. file creation), and `fdata/with-untracked` (validation passes that must track nothing) instead of hand-rolled `binding` forms. Two direct bindings remain on purpose: the fine-grained tracked toggles of `app.rpc.commands.files-update` (validation/repair turn tracking off, restore the existing atom and read it before repairing), and `binfile.common/encode-file` (a fresh tracked set inheriting the current one). Converge them only if atom-scoped macros (`with-tracking`, `with-inherited-tracking`) are added; today the extra indirection buys nothing.
- Snapshot creation takes `FOR SHARE` on the file row: both `create-file-snapshot` and the backup read of `restore-file-snapshot` hold it from the read to the insert, so they serialize with a `file-gc` pass (`FOR UPDATE ... SKIP LOCKED`) instead of pinning fragments the pass is about to mark. `get-file-snapshot` realizes the snapshot pointers with the live file id (fragment rows are keyed by file, not by snapshot).
- Snapshot creation takes `FOR UPDATE` on the file row: both `create-file-snapshot` and the backup read of `restore-file-snapshot` hold it from the read to the insert, so they serialize with a `file-gc` pass (`FOR UPDATE ... SKIP LOCKED`) and with a concurrent save, and never pin fragments the pass is about to mark. The lock is exclusive and not `FOR SHARE` because the migration-on-read path may re-read the same row with `FOR UPDATE`: a shared lock that asks for the exclusive one deadlocks two concurrent readers (one creating a snapshot, the other saving, both seeing a pending migration). `get-file-snapshot` realizes the snapshot pointers with the live file id (fragment rows are keyed by file, not by snapshot).
- `fdata/realize` combines pointer realization and object-map realization. Use it before operations that need complete in-memory file data instead of pointer placeholders.
- A `file_data` row is one of three classes, told apart by `type`: `main` is the file's current state and carries `id = file_id`; `snapshot` is a point-in-time copy whose `id` is the one its `file_change` row shares; `fragment` is a piece of the pointer-map, referenced from the file's data.
- Their lifecycles differ: `main` and `snapshot` live with the file (dated when it is deleted, undated when it is restored), while a `fragment` carries no date and is collected by `file_gc` once the file stops referencing it. Neither is a session buffer, so do not read a `fragment` as an ephemeral revision.

View File

@ -43,7 +43,13 @@ Production runs the deployed toolbox, not the devenv one:
- **Start from the ids, not from an inventory.** The ids come from the error or the logs. Unbounded queries over tables with tens of millions of rows (`storage_object`, `file_media_object`) do not finish in a reasonable time; bounded to an id list they are index lookups.
- **One query per reference column.** Two columns in one `IN (col_a, col_b)` lose the index and scan the whole table; split them.
- The read-only replica cuts long queries: see `mem:prod-infra/grafana`.
- A migration that builds an index runs inside the migration transaction, so it cannot use `CONCURRENTLY`, and a plain `CREATE INDEX` locks the table against writes for the whole build. On a large table (file saves write to `file_change` on every save) build the index out of band, before deploying, with `CREATE INDEX CONCURRENTLY` on its own (never inside a transaction block); the shipped migration uses `IF NOT EXISTS`, finds it and does nothing. A concurrent build interrupted midway leaves the index invalid: drop it and retry (check `pg_indexes` and `pg_index.indisvalid`).
- A migration that builds an index runs inside the migration transaction, so it cannot use `CONCURRENTLY`, and a plain `CREATE INDEX` locks the table against writes for the whole build. On a large table build the index out of band, before deploying, with `CREATE INDEX CONCURRENTLY` on its own (never inside a transaction block). A concurrent build interrupted midway leaves the index invalid: drop it and retry (check `pg_index` and `pg_index.indisvalid`).
- A partitioned parent cannot take `CREATE INDEX CONCURRENTLY` (`cannot create index on partitioned table ... concurrently`). Build one index per partition with `CONCURRENTLY`, then `CREATE INDEX ... ON ONLY` on the parent and `ALTER INDEX ... ATTACH PARTITION` for each child; the parent index only becomes valid when every partition is attached.
- Write the migration as plain, idempotent SQL: `ADD COLUMN IF NOT EXISTS`, `CREATE INDEX IF NOT EXISTS`, and `DROP CONSTRAINT IF EXISTS` followed by `ADD CONSTRAINT`. Do not encode shape checks as `pg_catalog` introspection: they are easy to get wrong (a missing `NOT condeferred` accepts an `INITIALLY DEFERRED` foreign key) and they duplicate what the runbook verifies by hand. `IF NOT EXISTS` matches the name, not the definition, so the out-of-band procedure verifies the index shape and completeness.
- The runbook is the contract for a large instance: it builds and verifies the out-of-band work and then marks the migration step as applied (`INSERT INTO migrations (module, step) ...`), so the body does not run at startup. Verify the column, the pending rows, the index (valid, no predicate or expression, every partition attached) and the constraint shape before inserting the row; the marker is the only thing that skips the migration.
- A reference that a GC task resolves must be `DEFERRABLE INITIALLY IMMEDIATE`, never `INITIALLY DEFERRED`: the immediate check fires inside the transaction that catches the violation and retries the chunk; the deferred one fires at commit, outside the catch. A validated foreign key belongs out of band: `ADD FOREIGN KEY` runs as an `ALTER TABLE` and it scans the whole referencing table; `NOT VALID` on a partitioned table only exists since PostgreSQL 18.
- A backfill that removes a key an old reader uses (for example `metadata.storage-ref-id`, which the previous storage GC scans) must run with the old code stopped. Otherwise the old reader loses the reference and can delete a live object, and the rows it writes in the meantime miss the backfill.
- `ADD COLUMN` takes a brief `ACCESS EXCLUSIVE` even when `IF NOT EXISTS` skips it, and `ADD FOREIGN KEY` takes `ACCESS EXCLUSIVE` on the referencing table and `SHARE ROW EXCLUSIVE` on the referenced one. A migration accepts those locks; a deployment that cannot take them runs the runbook and marks the step as applied.
## See also

View File

@ -43,7 +43,6 @@
(def ^:dynamic *state* nil)
(def ^:dynamic *options* nil)
(def ^:dynamic *reference-file* nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; DEFAULTS
@ -159,7 +158,7 @@
[index obj & attrs]
(reduce (fn [index attr-fn]
(let [old-id (attr-fn obj)
new-id (if (::overwrite *options*) old-id (uuid/next))]
new-id (uuid/next)]
(assoc index old-id new-id)))
index
attrs))
@ -209,6 +208,7 @@
p.team_id,
coalesce(fd.backend, 'legacy-db') AS backend,
fd.metadata AS metadata,
fd.storage_object_id AS storage_object_id,
fd.data AS data
FROM file AS f
LEFT JOIN file_data AS fd ON (fd.file_id = f.id AND fd.id = f.id)
@ -218,27 +218,37 @@
(str sql:files-with-data " WHERE f.id = ?"))
(def sql:get-file-without-data
(str "WITH files AS (" sql:files-with-data ")"
"SELECT f.id,
f.project_id,
f.created_at,
f.modified_at,
f.deleted_at,
f.name,
f.is_shared,
f.has_media_trimmed,
f.revn,
f.ignore_sync_until,
f.comment_thread_seqn,
f.features,
f.version,
f.vern,
f.team_id
FROM files AS f
WHERE f.id = ?"))
"SELECT f.id,
f.project_id,
f.created_at,
f.modified_at,
f.deleted_at,
f.name,
f.is_shared,
f.has_media_trimmed,
f.revn,
f.ignore_sync_until,
f.comment_thread_seqn,
f.features,
f.version,
f.vern,
p.team_id
FROM file AS f
INNER JOIN project AS p ON (p.id = f.project_id)
WHERE f.id = ?")
(defn- migrate-file
[{:keys [::db/conn] :as cfg} {:keys [read-only?]} {:keys [id] :as file}]
"Apply the pending migrations to the file.
With `persist-after-migration?` the migrated map is also persisted, which is
only safe from a map read under the `file` row lock (see `get-file*`). The
returned map is then the reattached one: decoded data where the pages the
migration did not change keep their pointers and their fragment ids, plus
the `:storage-object-id` of the row the write left, so a caller that
persists again touches the current object. Without `persist-after-migration?`
the realized map is returned, which is what a read-only context can do.
`get-file*` realizes the result when the caller asks for it."
[cfg {:keys [id] :as file} {:keys [persist-after-migration?]}]
(fdata/with-tracked-pointers cfg id
(let [libs (delay (get-resolved-file-libraries cfg file))
;; Capture the pointer layout before realizing: the migration
@ -252,111 +262,186 @@
objects-map-added? (and (not objects-map-before?)
(contains? (:features realized) "fdata/objects-map"))]
(if (or read-only? (db/read-only? conn))
realized
(let [file (if objects-map-added?
realized
(fdata/reattach-unchanged original realized))]
(if persist-after-migration?
(let [file (if objects-map-added?
realized
(fdata/reattach-unchanged original realized))
written (update-file! cfg file)]
;; When the file is migrated, we break the rule of not
;; performing mutations on get operations and update the file
;; with all migrations applied. The caller still receives the
;; realized file: the read contract is plain data.
(update-file! cfg file)
(fmigr/resolve-applied-migrations cfg realized))))))
;; with all migrations applied. The reattached map is also what
;; the read returns: the caller realizes it only when it asks.
(assoc (fmigr/resolve-applied-migrations cfg file)
:storage-object-id (:storage-object-id written)))
realized))))
(defn- fetch-row
"Read the file row. With `load-data?` the file data columns come along, but
they are not resolved nor decoded (see `attach-file-data`). With
`load-migrations?` the applied migrations are resolved, which is what
`need-migration?` expects. A skip-locked read answers nil instead of raising
when the row is gone."
[{:keys [::db/conn] :as cfg} id
{:keys [include-deleted?
skip-locked?
lock-for-update?
lock-for-share?
throw-if-not-exists?
load-migrations?
load-data?]}]
(let [sql (if load-data?
sql:get-file
sql:get-file-without-data)
sql (cond
lock-for-update?
(str sql " FOR UPDATE of f")
lock-for-share?
(str sql " FOR SHARE of f")
:else
sql)
sql (if (and skip-locked? (or lock-for-share? lock-for-update?))
(str sql " SKIP LOCKED")
sql)
file (db/get-with-sql conn [sql id] {::db/throw-if-not-exists false
::db/remove-deleted (not include-deleted?)})
file (some-> file
(d/update-when :features db/decode-pgarray #{})
(d/update-when :metadata fdata/decode-metadata))
file (if (and file load-migrations?)
(fmigr/resolve-applied-migrations cfg file)
file)]
(or file
(when-not (or skip-locked? (not throw-if-not-exists?))
(ex/raise :type :not-found
:code :object-not-found
:hint "database object not found"
:table :file
:file-id id)))))
(defn- attach-file-data
"Resolve the data of an already read row and decode it when `decode?`. It
completes the map it receives instead of reading the row again. It does not
realize: `get-file*` owns that step, once per path."
[cfg file {:keys [decode?]}]
(let [file (fdata/resolve-file-data cfg file)]
(if decode?
(fdata/decode-file-data cfg file)
file)))
(defn- fetch-file
"Read the row with its data resolved and decoded, under the requested lock."
[cfg id options]
(when-let [file (fetch-row cfg id options)]
(attach-file-data cfg file options)))
(def ^:private
default-get-file-options
{:load-migrations? true
:throw-if-not-exists? true
:persist-after-migration? true
:load-data? true
:migrate? true
:decode? true})
(defn- get-file*
[{:keys [::db/conn] :as cfg} id
{:keys [migrate?
realize?
decode?
skip-locked?
include-deleted?
load-data?
throw-if-not-exists?
lock-for-update?
lock-for-share?]
:or {lock-for-update? false
lock-for-share? false
load-data? true
migrate? true
decode? true
include-deleted? false
throw-if-not-exists? true
realize? false}
:as options}]
[{:keys [::db/conn] :as cfg} id options]
(assert (db/connection? conn) "expected cfg with valid connection")
(when (and (not load-data?)
(or lock-for-share? lock-for-update? skip-locked?))
(throw (IllegalArgumentException. "locking is incompatible when `load-data?` is false")))
(let [sql
(if load-data?
sql:get-file
sql:get-file-without-data)
(let [{:keys [migrate?
realize?
decode?
load-data?
lock-for-share?
read-only?]
:as options}
(merge default-get-file-options options)
sql
(cond
lock-for-update?
(str sql " FOR UPDATE of f")
read-only?
(or read-only? (db/read-only? conn))]
lock-for-share?
(str sql " FOR SHARE of f")
(when (and realize? (or (not load-data?) (not decode?)))
(throw (IllegalArgumentException. "invalid options, you only can realize when loading data and decoding")))
:else
sql)
(when (and lock-for-share? load-data?)
(throw (IllegalArgumentException. "invalid options, `:lock-for-share?` is only allowed on row-only reads")))
sql
(if skip-locked?
(str sql " SKIP LOCKED")
sql)
(cond
;; The caller only wants the row: that read is the answer.
(not load-data?)
(fetch-row cfg id options)
file
(db/get-with-sql conn [sql id]
{::db/throw-if-not-exists false
::db/remove-deleted (not include-deleted?)})
(and migrate? decode? (not read-only?))
(when-let [file (fetch-row cfg id options)]
(if (fmg/need-migration? file)
(when-let [file (fetch-file cfg id (assoc options :lock-for-update? true))]
(cond-> file
(fmg/need-migration? file)
(as-> $ (migrate-file cfg $ options))
file
(-> file
(d/update-when :features db/decode-pgarray #{})
(d/update-when :metadata fdata/decode-metadata))]
realize?
(->> (fdata/realize cfg))))
(if file
(if load-data?
(let [file
(->> file
(fmigr/resolve-applied-migrations cfg)
(fdata/resolve-file-data cfg))
(let [file (attach-file-data cfg file options)]
(cond-> file
realize?
(->> (fdata/realize cfg))))))
will-migrate?
(and migrate? (fmg/need-migration? file))]
:else
(when-let [file (fetch-file cfg id options)]
(cond-> file
(and migrate? decode? (fmg/need-migration? file))
(as-> $ (migrate-file cfg $ (assoc options :persist-after-migration? false)))
(if decode?
(cond->> (fdata/decode-file-data cfg file)
(and realize? (not will-migrate?))
(fdata/realize cfg)
will-migrate?
(migrate-file cfg options))
file))
file)
(when-not (or skip-locked? (not throw-if-not-exists?))
(ex/raise :type :not-found
:code :object-not-found
:hint "database object not found"
:table :file
:file-id id)))))
realize?
(->> (fdata/realize cfg)))))))
(defn get-file
"Get file, resolve all features and apply migrations.
Runs inside a transaction: it joins the caller's when the cfg already
carries a connection and opens one otherwise, so the migration write
commits with the read. A read-only read (`:read-only?`) takes no lock and
writes nothing, so it runs on a plain connection instead of opening a
transaction of its own; with a cfg that already carries a connection it
still joins the caller's. Accepts a cfg map only: a bare pool or a
connection raises `IllegalArgumentException`.
Useful when you have plan to apply massive or not surgical
operations on file, because it removes the overhead of lazy fetching
and decoding."
and decoding.
Options:
- `:realize?` returns plain data instead of fragment pointers; it
requires `:load-data?` and `:decode?`.
- `:decode?` decodes the stored blob (default true).
- `:load-data?` reads the data columns (default true). A row-only read
(`false`) is the only mode that accepts `:lock-for-share?`.
- `:migrate?` applies the pending migrations on read (default true).
- `:load-migrations?` resolves the applied migrations on a row read
(default true).
- `:read-only?` applies the pending migrations in memory only and skips
the transaction. It does not take a lock.
- `:lock-for-update?`, `:skip-locked?`, `:include-deleted?` and
`:throw-if-not-exists?` are the usual read knobs. A lock needs a
read-write transaction from the caller: PostgreSQL rejects row locks in
a read-only transaction.
- `:persist-after-migration?` is internal: `get-file*` turns it off
for the in-memory migration of a read-only context. Do not pass it."
[cfg file-id & {:as opts}]
(db/run! cfg get-file* file-id opts))
(when-not (map? cfg)
(throw (IllegalArgumentException.
"expected cfg map, not a pool or a connection")))
(if (:read-only? opts)
(db/run! cfg get-file* file-id opts)
(db/tx-run! cfg get-file* file-id opts)))
(defn clean-file-features
[file]
@ -726,7 +811,12 @@
(let [library-ids (get-libraries cfg [file-id])
data (reduce (fn [data library-id]
(if-let [library (get-file cfg library-id :include-deleted? true)]
(cond-> (ctf/absorb-assets data (:data library))
;; The library is read without `:realize?`, so its
;; `:components` may be a pointer map. Bind the
;; library's own loader: the absorb walks the
;; components and would raise without one.
(cond-> (fdata/with-pointers cfg library-id
(ctf/absorb-assets data (:data library)))
(= library-id (cfo/get-tokens-source data))
(cfo/absorb-tokens-lib (:data library)))
data))
@ -809,18 +899,33 @@
(dissoc :metadata)
(dissoc :migrations)))
(defn file->response
"Strip the internal keys of a file map before it leaves the backend in a
response. The file data storage pointer is bookkeeping for the write path:
a `file-data` object is authentication-only, so a leaked id would let any
logged-in profile fetch the blob from `/assets/by-id`. The metadata key of
the old pointer is stripped too: a row the migration does not backfill keeps
it, and the metadata schema is open, so it would travel in the response."
[file]
(-> file
(dissoc :storage-object-id)
(d/update-when :metadata #(dissoc % :storage-ref-id))))
(defn- file->file-data-params
[{:keys [id] :as file} & {:as opts}]
[{:keys [id] :as file}]
(let [created-at (or (:created-at file) (ct/now))
modified-at (or (:modified-at file) created-at)]
(d/without-nils
{:id id
:type "main"
:file-id id
:data (:data file)
:metadata (:metadata file)
:created-at created-at
:modified-at modified-at})))
(-> (d/without-nils
{:id id
:type "main"
:file-id id
:data (:data file)
:metadata (:metadata file)
:created-at created-at
:modified-at modified-at})
;; The storage object the persisted row pointed at (nil for a new or
;; imported file). `upsert!` touches it before replacing the row.
(assoc :storage-object-id (:storage-object-id file)))))
(defn insert-file!
"Insert a new file into the database table. Expectes a not-encoded file.
@ -844,34 +949,63 @@
:cause cause)
(throw cause))))
(->> (file->file-data-params file)
;; An INSERT never replaces a persisted pointer: `duplicate-file` hands
;; the source file map here, and touching the source object would be a
;; write on a live object.
(->> (file->file-data-params (dissoc file :storage-object-id))
(fdata/upsert! cfg))
nil))
(defn update-file!
"Update an existing file on the database. Expects not encoded file."
[{:keys [::db/conn] :as cfg} {:keys [id] :as file} & {:as opts}]
"Update an existing file on the database. Expects a not-encoded file map,
as returned by `get-file`, and optionally the fields to change as keyword
args; they are merged into the file map before persisting.
(if (::reset-migrations? opts false)
(fmigr/reset-migrations! conn file)
(fmigr/upsert-migrations! conn file))
The storage object the persisted row pointed at travels in the map
(`:storage-object-id`), and `upsert!` touches it before replacing the row.
That is why the caller must pass the map it read instead of building a
partial one: nothing is queried here. The params only change mutable fields
of the file: the pointer and the identity (`:id`, `:file-id`) always come
from the read map.
(let [file
(encode-file cfg file)
Returns the map `fdata/upsert!` answers with: `:written` and the
`:storage-object-id` of the object this write created, so a caller that
persists again touches the current object instead of the replaced one."
[{:keys [::db/conn] :as cfg} file & {:as params}]
file-params
(file->params (dissoc file :id))
;; A map read with `:load-data? false` has no `:data`; persisting it would
;; wipe the file content. `ex/raise` instead of `assert`: the guard must
;; exist in the deployed binary, where `clojure.core/assert` is compiled
;; out.
(when-not (contains? file :data)
(ex/raise :type :internal
:code :missing-file-data
:hint "expected a file map read with data"
:file-id (:id file)))
file-data-params
(file->file-data-params file)]
(let [reset? (::reset-migrations? params false)
;; The pointer and the identity are bookkeeping of the persisted row,
;; not editable fields: they can only come from the read map. A pointer
;; in the params would skip the touch and leak the replaced blob; an
;; `:id` would retarget the UPDATE.
file (merge file (dissoc params ::reset-migrations?
:storage-object-id
:id
:file-id))]
(db/update! conn :file file-params
{:id id}
{::db/return-keys false})
(if reset?
(fmigr/reset-migrations! conn file)
(fmigr/upsert-migrations! conn file))
(fdata/upsert! cfg file-data-params)
nil))
(let [file (encode-file cfg file)
file-params (file->params (dissoc file :id))]
(db/update! conn :file file-params
{:id (:id file)}
{::db/return-keys false})
(fdata/upsert! cfg (file->file-data-params file)))))
(defn save-file!
"Applies all the final validations and perist the file, binfile
@ -884,8 +1018,7 @@
(let [file (-> file
(assoc :created-at timestamp)
(assoc :modified-at timestamp)
(cond-> (not (::overwrite cfg))
(assoc :ignore-sync-until (ct/plus timestamp (ct/duration {:seconds 5}))))
(assoc :ignore-sync-until (ct/plus timestamp (ct/duration {:seconds 5})))
(update :features
(fn [features]
(-> (::features cfg #{})
@ -902,9 +1035,7 @@
(when (ex/exception? result)
(l/error :hint "file schema validation error" :cause result))))
(if (::overwrite cfg)
(update-file! cfg file (assoc opts ::reset-migrations? true))
(insert-file! cfg file opts))))
(insert-file! cfg file opts)))
(def ^:private sql:get-file-libraries
"WITH RECURSIVE libs AS (

View File

@ -988,8 +988,7 @@
:old-id (str (:id item))
::l/sync? true)
(db/insert! conn :file-media-object params
::db/on-conflict-do-nothing? (::bfc/overwrite cfg))))
(db/insert! conn :file-media-object params)))
(doseq [[index item] (d/enumerate thumbnails)]
(let [media-id (bfc/lookup-index (:media-id item))
@ -1305,56 +1304,6 @@
{:file-ids file-ids
:resolution resolution})))
(defn- invalidate-thumbnails
[cfg file-id]
(let [storage (sto/resolve cfg ::db/reuse-conn true)
sql-1
(str "update file_tagged_object_thumbnail "
" set deleted_at = now() "
" where file_id=? returning media_id")
sql-2
(str "update file_thumbnail "
" set deleted_at = now() "
" where file_id=? returning media_id")]
(run! #(sto/touch-object! storage %)
(sequence
(keep :media-id)
(concat
(db/exec! cfg [sql-1 file-id])
(db/exec! cfg [sql-2 file-id]))))))
(defn- import-file-and-overwrite*
[{:keys [::manifest ::bfc/file-id] :as cfg}]
(when (not= 1 (count (:files manifest)))
(ex/raise :type :validation
:code :invalid-condition
:hint "unable to perform in-place update with binfile containing more than 1 file"
:manifest manifest))
(bfc/configure-import-transaction cfg)
(let [ref-file (bfc/get-minimal-file cfg file-id ::db/for-update true)
file (first (get manifest :files))
cfg (assoc cfg ::bfc/overwrite true)]
(vswap! bfc/*state* update :index assoc (:id file) file-id)
(binding [bfc/*options* cfg
bfc/*reference-file* ref-file]
(import-storage-objects cfg)
(import-file cfg file {:current 1 :total 1})
(invalidate-thumbnails cfg file-id)
(bfm/apply-pending-migrations! cfg)
{:file-ids [file-id]
:resolution {}})))
(defn- import-files
[{:keys [::bfc/timestamp ::bfc/input] :or {timestamp (ct/now)} :as cfg}]
@ -1405,9 +1354,7 @@
(tap-progress cfg {:section :manifest})
(binding [bfc/*state* (volatile! {:media [] :index {}})]
(if (::bfc/file-id cfg)
(db/tx-run! cfg import-file-and-overwrite*)
(db/tx-run! cfg import-files*)))))
(db/tx-run! cfg import-files*))))
;; --- PUBLIC API
@ -1476,6 +1423,12 @@
(defn import-files!
[{:keys [::bfc/input] :as cfg}]
(when (::bfc/file-id cfg)
(ex/raise :type :validation
:code :not-supported
:hint "in-place import is not supported"
:file-id (::bfc/file-id cfg)))
(assert
(and (uuid? (::bfc/profile-id cfg))
(uuid? (::bfc/project-id cfg)))

View File

@ -105,11 +105,16 @@
(dissoc file :legacy-data))
(defmethod resolve-file-data "storage"
[cfg {:keys [metadata] :as file}]
[cfg {:keys [storage-object-id] :as file}]
(let [storage (sto/resolve cfg ::db/reuse-conn true)
ref-id (:storage-ref-id metadata)
data (->> (sto/get-object storage ref-id)
(sto/get-object-bytes storage))]
sobject (or (sto/get-object storage storage-object-id)
(ex/raise :type :internal
:code :missing-storage-object
:hint "file data row has no readable storage object"
:file-id (or (:file-id file) (:id file))
:id (:id file)
:storage-object-id storage-object-id))
data (->> (sto/get-object-bytes storage sobject))]
(-> file
(assoc :data data)
(dissoc :legacy-data))))
@ -122,8 +127,8 @@
(def ^:private sql:insert-file-data
"INSERT INTO file_data (file_id, id, created_at, modified_at, deleted_at,
type, backend, metadata, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
type, backend, metadata, data, storage_object_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
(def ^:private sql:upsert-file-data
(str sql:insert-file-data
@ -132,104 +137,130 @@
deleted_at=?,
backend=?,
metadata=?,
data=?"))
data=?,
storage_object_id=?
WHERE file_data.storage_object_id IS NOT DISTINCT FROM ?"))
(defn- upsert-in-database
[cfg {:keys [id file-id created-at modified-at deleted-at type backend data metadata]}]
[cfg {:keys [id file-id created-at modified-at deleted-at type backend data metadata storage-object-id]} expected-storage-object-id]
(let [created-at (or created-at (ct/now))
metadata (some-> metadata db/json)
modified-at (or modified-at created-at)]
;; The metadata pointer is dead (the column is the only source of
;; truth). Clean it here, the single point where every branch
;; serializes the metadata, so no write can resurrect it.
metadata (some-> metadata (dissoc :storage-ref-id) (db/json))
modified-at (or modified-at created-at)
(db/exec-one! cfg [sql:upsert-file-data
file-id id
created-at
modified-at
deleted-at
type
backend
metadata
data
modified-at
deleted-at
backend
metadata
data])))
result
(db/exec-one! cfg [sql:upsert-file-data
file-id id
created-at
modified-at
deleted-at
type
backend
metadata
data
storage-object-id
modified-at
deleted-at
backend
metadata
data
storage-object-id
expected-storage-object-id])]
;; A zero count means the row exists with another pointer: the caller
;; read it before someone else replaced it. Every writer holds the `file`
;; row lock, so this is a protocol violation, not a race to retry.
(when-not (pos? (db/get-update-count result))
(ex/raise :type :internal
:code :stale-file-data-pointer
:hint "the file data row changed since it was read"
:file-id file-id
:id id))
result))
(defn- handle-persistence
[cfg {:keys [type backend id file-id data] :as params}]
(cond
(= backend "storage")
;; IMPORTANT: we strongly do not reuse the main connection that can
;; run inside a transaction because the storage upload process can
;; fail in the middle of uploading and leave garbage on the underlying
;; backend, if we participate in the main transaction and it aborts
;; we will lose all registry of the pending to reconcile blobs
;; what the storage subsystem registers in other parallel
;; transaction
(let [storage (sto/resolve cfg)
content (sto/content data)
sobject (sto/put-object! storage
{::sto/content content
::sto/touch true
:bucket "file-data"
:content-type "application/octet-stream"
:file-id file-id
:id id})
metadata (-> (:metadata params)
(assoc :storage-ref-id (:id sobject)))
params (-> params
(assoc :metadata metadata)
(assoc :data nil))]
(upsert-in-database cfg params))
(= backend "db")
(let [metadata (dissoc (:metadata params) :storage-ref-id)
params (assoc params :metadata metadata)]
(upsert-in-database cfg params))
(= backend "legacy-db")
(let [expected (:storage-object-id params)]
(cond
(= type "main")
(do
(db/delete! cfg :file-data
{:id id :file-id file-id :type "main"}
{::db/return-keys false})
(db/update! cfg :file
{:data data}
{:id file-id}
{::db/return-keys false}))
(= backend "storage")
;; IMPORTANT: we strongly do not reuse the main connection that can
;; run inside a transaction because the storage upload process can
;; fail in the middle of uploading and leave garbage on the underlying
;; backend, if we participate in the main transaction and it aborts
;; we will lose all registry of the pending to reconcile blobs
;; what the storage subsystem registers in other parallel
;; transaction
(let [storage (sto/resolve cfg)
content (sto/content data)
sobject (sto/put-object! storage
{::sto/content content
::sto/touch true
:bucket "file-data"
:content-type "application/octet-stream"
:file-id file-id
:id id})
params (-> params
(assoc :storage-object-id (:id sobject))
(assoc :data nil))]
{:result (upsert-in-database cfg params expected)
:storage-object-id (:id sobject)})
(= type "snapshot")
(do
(db/delete! cfg :file-data
{:id id :file-id file-id :type "snapshot"}
{::db/return-keys false})
;; every mutation of `file_change` moves `updated_at`: the partition
;; runbook uses it as the watermark of the delta passes
(db/update! cfg :file-change
{:data data
:updated-at (ct/now)}
{:file-id file-id :id id}
{::db/return-keys false}))
(= backend "db")
{:result (upsert-in-database cfg (assoc params :storage-object-id nil) expected)
:storage-object-id nil}
(= type "fragment")
(upsert-in-database cfg
(-> (dissoc params :metadata)
(assoc :backend "db")))
(= backend "legacy-db")
{:result
(cond
(= type "main")
(do
(db/delete! cfg :file-data
{:id id :file-id file-id :type "main"}
{::db/return-keys false})
(db/update! cfg :file
{:data data}
{:id file-id}
{::db/return-keys false}))
(= type "snapshot")
(do
(db/delete! cfg :file-data
{:id id :file-id file-id :type "snapshot"}
{::db/return-keys false})
;; every mutation of `file_change` moves `updated_at`: the partition
;; runbook uses it as the watermark of the delta passes
(db/update! cfg :file-change
{:data data
:updated-at (ct/now)}
{:file-id file-id :id id}
{::db/return-keys false}))
(= type "fragment")
(upsert-in-database cfg
(-> (dissoc params :metadata)
(assoc :backend "db")
(assoc :storage-object-id nil))
expected)
:else
(throw (RuntimeException. "not implemented")))
:storage-object-id nil}
:else
(throw (RuntimeException. "not implemented")))
(throw (IllegalArgumentException.
(str "backend '" backend "' not supported"))))))
:else
(throw (IllegalArgumentException.
(str "backend '" backend "' not supported")))))
(defn process-metadata
[cfg metadata]
(when-let [storage-id (:storage-ref-id metadata)]
(let [storage (sto/resolve cfg ::db/reuse-conn true)]
(sto/touch-object! storage storage-id))))
(defn touch-storage-object
"Mark a storage object as touched so the storage GC can reclaim it once
nothing references it anymore. Used when a file data row replaces or
deletes the object it pointed at. Expects a non-nil object id; callers
guard with `some->`/`some->>`."
[cfg storage-object-id]
(-> (sto/resolve cfg ::db/reuse-conn true)
(sto/touch-object! storage-object-id)))
(defn- default-backend
[backend]
@ -248,6 +279,10 @@
[:file-id ::sm/uuid]
[:backend {:optional true} [:enum "db" "legacy-db" "storage"]]
[:metadata {:optional true} ctf/schema:file-metadata]
;; The storage object the persisted row pointed at before this write; it is
;; the object to touch when the row replaces it. Required so a new caller
;; must decide it explicitly (nil for a new row) instead of leaking it.
[:storage-object-id [:maybe ::sm/uuid]]
[:data {:optional true} bytes?]
[:created-at {:optional true} ::ct/inst]
[:modified-at {:optional true} [:maybe ::ct/inst]]
@ -257,17 +292,28 @@
(sm/check-fn schema:update-params :hint "invalid params received for update"))
(defn upsert!
"Create or update file data"
"Create or update a file data row.
`:storage-object-id` is the storage object the persisted row pointed at
before this write (nil for a new row or a row that had none), not the
object the new content will live in: the write resolves that itself. The
previous object is marked as touched before the row is replaced, so the
storage GC can reclaim the blob once nothing references it.
The function does not query the row: the caller must hand the pointer it
read. Returns a map with `:written` (whether a row was written) and the
`:storage-object-id` of the object this write created, nil for the `db`
and `legacy-db` backends."
[cfg params & {:as opts}]
(let [params (-> (check-update-params params)
(update :backend default-backend))]
(some->> (:metadata params)
(process-metadata cfg))
(some->> (:storage-object-id params)
(touch-storage-object cfg))
(-> (handle-persistence cfg params)
(db/get-update-count)
(pos?))))
(let [{:keys [result storage-object-id]} (handle-persistence cfg params)]
{:written (pos? (db/get-update-count result))
:storage-object-id storage-object-id})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; POINTER-MAP
@ -281,7 +327,7 @@
;; previous pass marked must still load until `objects-gc` purges it.
(let [fragment (some-> (db/get* cfg :file-data
{:id id :file-id file-id :type "fragment"}
{::sql/columns [:data :backend :id :metadata]
{::sql/columns [:data :backend :file_id :id :metadata :storage_object_id]
::db/remove-deleted false})
(update :metadata decode-metadata))]
@ -308,9 +354,12 @@
(when (pmap/modified? item)
(l/trc :hint "persist pointer" :file-id (str file-id) :id (str id))
(let [content (-> item deref blob/encode)]
;; A modified pointer has a fresh id, so the fragment row is always a
;; new insert: there is no previous storage object to touch.
(upsert! cfg {:id id
:file-id file-id
:type "fragment"
:storage-object-id nil
:data content})))))
(defmacro with-pointers

View File

@ -42,7 +42,8 @@
c.data AS legacy_data,
fd.data AS data,
coalesce(fd.backend, 'legacy-db') AS backend,
fd.metadata AS metadata
fd.metadata AS metadata,
fd.storage_object_id AS storage_object_id
FROM file_change AS c
LEFT JOIN file_data AS fd ON (fd.file_id = c.file_id
AND fd.id = c.id
@ -65,12 +66,16 @@
(d/update-when :features db/decode-pgarray #{}))))
(def ^:private sql:get-minimal-file
;; `fd.storage_object_id` is load-bearing: `restore!` hands this map to
;; `update-file!` so the previous main object is touched before the row is
;; replaced. Removing it would leave the old blob unreclaimed with no error.
"SELECT f.id,
f.revn,
f.modified_at,
f.deleted_at,
fd.backend AS backend,
fd.metadata AS metadata
fd.metadata AS metadata,
fd.storage_object_id AS storage_object_id
FROM file AS f
LEFT JOIN file_data AS fd ON (fd.file_id = f.id AND fd.id = f.id)
WHERE f.id = ?")
@ -131,7 +136,8 @@
(defn get-snapshot
"Get a fully decoded snapshot for read-only preview or restoration.
Returns the snapshot map with decoded :data field, or nil when the file has
no snapshot with that id."
no snapshot with that id. The internal storage pointer of the row is not
part of the result."
[cfg file-id snapshot-id]
(let [now (ct/now)]
(some->> (db/get-with-sql cfg [sql:get-snapshot file-id snapshot-id now]
@ -139,7 +145,8 @@
::db/throw-if-not-exists false})
(decode-snapshot)
(fdata/resolve-file-data cfg)
(fdata/decode-file-data cfg))))
(fdata/decode-file-data cfg)
(bfc/file->response))))
(def ^:private sql:get-visible-snapshots
(str "WITH "
@ -293,6 +300,7 @@
{:id snapshot-id
:file-id (:id file)
:type "snapshot"
:storage-object-id nil
:data (blob/encode (:data file))
:created-at created-at
:deleted-at deleted-at})

View File

@ -123,7 +123,8 @@
(defn- get-resolved-file
[cfg file-id]
(bfc/get-file cfg file-id :migrate? false :decode? false))
(-> (bfc/get-file cfg file-id :migrate? false :decode? false)
(bfc/file->response)))
(defn prepare-download
[file filename]
@ -372,7 +373,6 @@
:profile-id profile-id
:project-id project-id)
cfg (assoc cfg
::bfc/overwrite false
::bfc/profile-id profile-id
::bfc/project-id project-id
::bfc/team-id (:id team)

View File

@ -541,7 +541,10 @@
:fn (mg/resource "app/migrations/sql/0158-del-forbidden-file-library-rels.sql")}
{:name "0158-partition-file-change"
:fn (mg/resource "app/migrations/sql/0158-partition-file-change.sql")}])
:fn (mg/resource "app/migrations/sql/0158-partition-file-change.sql")}
{:name "0159-add-file-data-storage-object-id"
:fn (mg/resource "app/migrations/sql/0159-add-file-data-storage-object-id.sql")}])
(defn apply-migrations!
[pool name migrations]

View File

@ -0,0 +1,65 @@
-- Turn the file data storage pointer into a column with a foreign key.
--
-- Until now the pointer lived in `file_data.metadata->>'storage-ref-id'`.
-- The storage GC parsed the JSON, and nothing stopped it from deleting the
-- blob of a live row. With the column and the foreign key the database
-- refuses that delete.
--
-- With the storage backend the release is a coordinated restart: the column is
-- the only source of truth, and the previous code cannot read the rows this
-- release writes. With the default `db` backend the new code writes the same
-- `file_data.data` column the previous code reads, so a rolling deploy is
-- safe.
--
-- This migration runs on a fresh database and on small instances. A large
-- instance builds the column and the index out of band, runs this same
-- backfill and foreign key with the instances stopped, and marks this step as
-- applied; the end state is identical. See
-- `operations/2.20.0-file-data-storage-object-id.md`.
--
-- `DEFERRABLE` follows the schema convention (all foreign keys of the project
-- are deferrable, so `th/database-reset` can delete table by table with
-- `SET CONSTRAINTS ALL DEFERRED`). It is `INITIALLY IMMEDIATE`, not
-- `DEFERRED`: the storage GC catches the violation inside the chunk
-- transaction and retries the chunk, and a deferred check would fire at
-- commit, outside that transaction, so the GC would never move past it.
ALTER TABLE file_data
ADD COLUMN IF NOT EXISTS storage_object_id uuid;
-- The CTE is MATERIALIZED so the uuid cast only sees rows that passed the
-- regex. A plain subquery can be inlined, and a corrupt value would reach the
-- cast and abort the migration.
WITH candidates AS MATERIALIZED (
SELECT file_id,
id,
(metadata->>'storage-ref-id')::uuid AS soid
FROM file_data
WHERE backend = 'storage'
AND storage_object_id IS NULL
AND (metadata->>'storage-ref-id') ~*
'^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$'
)
UPDATE file_data AS fd
SET storage_object_id = c.soid,
metadata = fd.metadata - 'storage-ref-id'
FROM candidates AS c
WHERE fd.file_id = c.file_id
AND fd.id = c.id
AND EXISTS (SELECT 1 FROM storage_object AS so WHERE so.id = c.soid);
-- The deletion check of the foreign key looks a row up by this column for
-- every deleted object; without the index it scans all partitions.
CREATE INDEX IF NOT EXISTS file_data__storage_object_id__idx
ON file_data (storage_object_id);
-- Rebuild the constraint so the definition is always the one above. This is
-- also how a constraint created by hand with the wrong shape (CASCADE, not
-- deferrable, or `INITIALLY DEFERRED`) gets repaired.
ALTER TABLE file_data
DROP CONSTRAINT IF EXISTS file_data_storage_object_id_fkey;
ALTER TABLE file_data
ADD CONSTRAINT file_data_storage_object_id_fkey
FOREIGN KEY (storage_object_id) REFERENCES storage_object(id)
ON DELETE NO ACTION DEFERRABLE INITIALLY IMMEDIATE;

View File

@ -192,7 +192,10 @@
(-> file
(assoc :page-name (dm/get-in data [:pages-index page-id :name]))
(assoc :page-id page-id)
(dissoc :data)))))
(dissoc :data)
;; The storage pointer is internal bookkeeping: it never leaves the
;; backend in a response.
(bfc/file->response)))))
;; FIXME: rename
(defn- get-comment-thread

View File

@ -43,7 +43,6 @@
[app.rpc.doc :as-alias doc]
[app.rpc.helpers :as rph]
[app.rpc.permissions :as perms]
[app.util.blob :as blob]
[app.util.events :as events]
[app.util.pointer-map :as pmap]
[app.util.services :as sv]
@ -222,7 +221,11 @@
(if (and (contains? (:features file) "fdata/objects-map")
(not (contains? (:features params) "fdata/objects-map")))
(feat.fdata/realize-objects cfg file)
file)))))
file)
;; The storage pointer is internal bookkeeping: it never leaves the
;; backend in a response.
(bfc/file->response file)))))
;; --- COMMAND QUERY: get-file-fragment (by id)
@ -231,7 +234,7 @@
[:id ::sm/uuid]
[:file-id ::sm/uuid]
[:created-at ::ct/inst]
[:content ::sm/any]])
[:data ::sm/any]])
(def schema:get-file-fragment
[:map {:title "get-file-fragment"}
@ -241,8 +244,17 @@
(defn- get-file-fragment
[cfg file-id fragment-id]
(some-> (db/get cfg :file-data {:file-id file-id :id fragment-id :type "fragment"})
(update :data blob/decode)))
;; Resolve through the file data backend: a fragment can live on cold
;; storage, and reading its row directly would hand `nil` to `blob/decode`.
;; Only the public fields leave the backend: the row also carries the
;; internal storage pointer and the backend metadata.
(when-let [row (db/get cfg :file-data {:file-id file-id
:id fragment-id
:type "fragment"})]
(let [fragment (->> row
(feat.fdata/resolve-file-data cfg)
(feat.fdata/decode-file-data cfg))]
(select-keys fragment (sm/keys schema:file-fragment)))))
(defn- check-fragment-scope!
"Checks that the fragment is reachable from the pages authorized by
@ -556,17 +568,23 @@
(let [file (bfc/get-file cfg id :load-data? false)
summary (t/decode-str result)]
(-> (assoc file :library-summary summary)
(dissoc :data)))))
(dissoc :data :migrations)
(bfc/file->response)))))
calculate-from-db
(fn []
(let [file (bfc/get-file cfg id)
result (feat.fdata/with-pointers cfg id
(calculate-library-summary file))]
;; The storage pointer is internal bookkeeping: this summary is an
;; RPC response and must not expose it. The applied migrations go
;; for the same reason: this endpoint is not where a client
;; completes a read, and `schema:file` declares the key optional.
(-> file
(assoc :library-summary result)
(dissoc :legacy-data)
(dissoc :data))))
(dissoc :data :migrations)
(bfc/file->response))))
persist-to-cache
(fn [{:keys [::rds/conn]} data cache-key]
@ -1007,13 +1025,10 @@
:library-id (str (:id ldata))
:file-id (str file-id))
(bfc/update-file! cfg {:id file-id
:features (:features file)
:migrations (:migrations file)
:revn (inc (:revn file))
:data (:data file)
:modified-at (ct/now)
:has-media-trimmed false}))))
(bfc/update-file! cfg file
:revn (inc (:revn file))
:modified-at (ct/now)
:has-media-trimmed false))))
(defn- get-referenced-files
[cfg library-id]
@ -1420,8 +1435,8 @@
(def ^:private sql:restore-storage-objects
;; Collect referenced storage ids first (UUID set), then join by PK.
;; Casting `storage_object.id` to text (or OR-ing that with `id IN`) forces
;; a scan of deleted rows; cast the JSON side instead.
;; `file_data` points at its object with the `storage_object_id` column, so
;; the reference is already a uuid and no JSON cast is needed.
"WITH ids AS (SELECT unnest(?::uuid[]) AS file_id),
refs AS (
SELECT fmo.media_id AS id
@ -1448,11 +1463,11 @@
WHERE fot.deleted_at IS NULL
AND fot.media_id IS NOT NULL
UNION
SELECT (fd.metadata->>'storage-ref-id')::uuid
SELECT fd.storage_object_id
FROM file_data AS fd
JOIN ids ON (ids.file_id = fd.file_id)
WHERE fd.deleted_at IS NULL
AND (fd.metadata->>'storage-ref-id') IS NOT NULL
AND fd.storage_object_id IS NOT NULL
)
UPDATE storage_object AS so
SET deleted_at = null

View File

@ -68,7 +68,10 @@
{:modified-at (ct/now)}
{:id project-id})
(bfc/get-file cfg (:id file))))))
;; The storage pointer is internal bookkeeping: it never leaves the
;; backend in a response.
(-> (bfc/get-file cfg (:id file))
(bfc/file->response))))))
(def ^:private schema:create-file
[:map {:title "create-file" :closed true}

View File

@ -126,12 +126,15 @@
;; every unpurged snapshot as a liveness root, and readers
;; (get-file-snapshot, restore!, reduce-snapshots) resolve pointers
;; on demand.
;; NOTE: the file is read with FOR SHARE inside this transaction so
;; NOTE: the file is read with FOR UPDATE inside this transaction so
;; snapshot creation serializes with a concurrent :file-gc pass
;; (which takes FOR UPDATE + SKIP LOCKED on the same row). Without
;; the lock, a version pinned mid-pass could reference fragment rows
;; the pass is recreating.
(let [file (bfc/get-file cfg file-id :lock-for-share? true)
;; (which takes FOR UPDATE + SKIP LOCKED on the same row) and with a
;; concurrent save. Without the lock, a version pinned mid-pass could
;; reference fragment rows the pass is recreating. The lock is
;; exclusive, not shared, because the migration-on-read path may
;; re-read the same row with FOR UPDATE; holding a shared lock while
;; asking for the exclusive one deadlocks two concurrent readers.
(let [file (bfc/get-file cfg file-id :lock-for-update? true)
project (db/get-by-id cfg :project (:project-id file))]
(-> cfg
@ -167,12 +170,14 @@
delay (ldel/get-deletion-delay team)
;; Create backup snapshot of the current state (committed immediately
;; independent of the restore outcome). The read takes FOR SHARE so a
;; independent of the restore outcome). The read takes FOR UPDATE so a
;; concurrent :file-gc pass (which holds FOR UPDATE + SKIP LOCKED on the
;; file row) either finishes first -- and we snapshot the new fragments --
;; or skips the file and retries later. Without the lock, the backup
;; could reference fragments the pass is about to mark as deleted,
;; breaking the backup permanently.
;; breaking the backup permanently. The lock is exclusive because the
;; migration-on-read path may re-read the row with FOR UPDATE: a shared
;; lock that upgrades deadlocks two concurrent readers.
;;
;; The backup read also provides the revn the guard below compares
;; against. An edit committed before this read is captured in the
@ -181,7 +186,7 @@
backup-revn
(db/tx-run! cfg
(fn [cfg]
(let [file (bfc/get-file cfg file-id :lock-for-share? true)]
(let [file (bfc/get-file cfg file-id :lock-for-update? true)]
(fsnap/create! cfg file
{:profile-id profile-id
:deleted-at (ct/in-future delay)

View File

@ -438,9 +438,15 @@
:modified-at (or timestamp (ct/now))}}))))
(defn get-file
"Get not-decoded file, only decodes the features set."
"Get not-decoded file, only decodes the features set.
The read takes the `file` row with FOR UPDATE: the save persists the
map it read, so it must hold the row from the read to the write. The
lock is exclusive, not shared, because the migration-on-read path may
re-read the same row with FOR UPDATE, and a shared lock that upgrades
deadlocks two concurrent readers."
[cfg id]
(bfc/get-file cfg id :decode? false :lock-for-share? true))
(bfc/get-file cfg id :decode? false :lock-for-update? true))
(defn persist-file!
"Function responsible of persisting already encoded file. Should be

View File

@ -88,7 +88,9 @@
fmeds)]
(db/insert! conn :file-media-object params ::db/return-keys false))
file)))
;; The storage pointer of the source file is internal bookkeeping: the
;; new file does not inherit it, and it never leaves the backend.
(bfc/file->response file))))
(def ^:private
schema:duplicate-file

View File

@ -770,6 +770,9 @@
(-> file
(dissoc :data)
(dissoc :deleted-at)
;; The storage pointer is internal bookkeeping: it never leaves the
;; backend in a response.
(bfc/file->response)
(assoc :page-id (-> file :data :pages first)))))
(def ^:private schema:create-team-access-request

View File

@ -129,7 +129,10 @@
(defn- get-view-only-bundle
[{:keys [::db/conn] :as cfg} {:keys [profile-id file-id share-id ::perms] :as params}]
(let [file (bfc/get-file cfg file-id)
(let [;; The storage pointer is internal bookkeeping: this bundle is an RPC
;; response and must not expose it.
file (-> (bfc/get-file cfg file-id)
(bfc/file->response))
project (db/get conn :project
{:id (:project-id file)}
@ -159,7 +162,8 @@
libs (->> (bfc/get-file-libraries conn file-id)
(mapv (fn [{:keys [id] :as lib}]
(merge lib (bfc/get-file cfg id)))))
(-> (merge lib (bfc/get-file cfg id))
(bfc/file->response)))))
;; A share link never grants pages of a linked library, so trim
;; each library to the components the allowed pages reference.

View File

@ -182,5 +182,5 @@
:created-by "system"}))
(let [file' (update file' :revn inc)]
(bfc/update-file! system file' opts)
(bfc/update-file! system file' ::bfc/reset-migrations? (::bfc/reset-migrations? opts))
true))))

View File

@ -118,6 +118,16 @@
[(ct/now) chunk-size]])]
(db/exec! conn (into [sql] params))))
(defn- server-error
"Return the PostgreSQL server error of a foreign key violation, or nil. It
carries the constraint and the referencing table, which is what the operator
needs: any `NO ACTION` foreign key on `storage_object` can block the delete,
not only the `file_data` one."
[cause]
(when (and (instance? org.postgresql.util.PSQLException cause)
(= "23503" (.getSQLState ^java.sql.SQLException cause)))
(.getServerErrorMessage ^org.postgresql.util.PSQLException cause)))
(defn- clean-deleted
"Processes the pending objects chunk by chunk with keyset pagination: each
chunk is one short transaction that reads and locks the next `chunk-size`
@ -127,11 +137,16 @@
marked as deleted.
A chunk that fails aborts its transaction: nothing of the chunk is deleted,
its locks are released, and it is logged and skipped. The cursor advances
to the `(deleted_at, id)` of the last row of each read chunk regardless of
the deletion result, so a failed chunk is not visited again in the same
run. There is no long-lived read transaction: each transaction lives only
as long as one chunk, letting the vacuum proceed between chunks. Rows
its locks are released, and it is logged and skipped. A chunk blocked by a
foreign key (SQLState 23503) keeps its log at error level with a hint and the
constraint and table the database reports, and is retried on the next run;
the reference must be fixed for the chunk to make progress. Any `NO ACTION`
foreign key on `storage_object` can block the delete, not only the one of
`file_data`. The cursor advances to the `(deleted_at, id)` of
the last row of each read chunk regardless of the deletion result, so a
failed chunk is not visited again in the same run. There is no long-lived
read transaction: each transaction lives only as long as one chunk, letting
the vacuum proceed between chunks. Rows
locked by a concurrent run are skipped and deferred to the next run; a
chunk that fails after a partial backend delete self-heals on the next
run (physical deletes are idempotent). Every `throttle-every` deleted
@ -155,9 +170,22 @@
;; afterwards is a JDBC no-op on the already
;; rolled-back connection.
(db/rollback! conn)
(l/err :hint "unexpected error on chunk deletion"
:ids (map :id rows)
:cause cause)
(if-let [serr (server-error cause)]
;; A NO ACTION foreign key refused a physical
;; delete: a live row of another table still
;; references an object marked for deletion.
;; That is a real anomaly (the reference scan
;; should have frozen it), so it stays an
;; error and the chunk is retried on the next
;; run until the reference is fixed.
(l/err :hint "chunk deletion blocked by a live reference; fix the reference and let the next run reclaim the chunk"
:ids (map :id rows)
:constraint (.getConstraint ^org.postgresql.util.ServerErrorMessage serr)
:table (.getTable ^org.postgresql.util.ServerErrorMessage serr)
:cause cause)
(l/err :hint "unexpected error on chunk deletion"
:ids (map :id rows)
:cause cause))
[rows {}])))))]
;; Reported only after the chunk commits: a rolled-back chunk leaves

View File

@ -108,16 +108,13 @@
(def sql:exists-file-data-refs
"SELECT EXISTS (
SELECT 1 FROM file_data
WHERE file_id = ?
AND id = ?
AND metadata->>'storage-ref-id' = ?::text
WHERE storage_object_id = ?
) AS has_refs")
(defn- has-file-data-refs?
[conn sobject]
(let [{:keys [file-id id]} (:metadata sobject)]
(-> (db/exec-one! conn [sql:exists-file-data-refs file-id id (:id sobject)])
(get :has-refs))))
(-> (db/exec-one! conn [sql:exists-file-data-refs (:id sobject)])
(get :has-refs)))
(def ^:private sql:mark-freeze-in-bulk
"UPDATE storage_object

View File

@ -613,7 +613,7 @@
ORDER BY deleted_at ASC")
(def ^:private sql:lock-file-data
"SELECT file_id, id, type, deleted_at, metadata, backend
"SELECT file_id, id, type, deleted_at, backend, storage_object_id
FROM file_data
WHERE (file_id, id) IN (SELECT file_id, id FROM unnest(?::uuid[], ?::uuid[]) AS u(file_id, id))
AND deleted_at IS NOT NULL
@ -630,11 +630,10 @@
(let [file-ids (db/create-array conn "uuid" (map :file-id rows))
ids (db/create-array conn "uuid" (map :id rows))]
(->> (db/exec! conn [sql:lock-file-data file-ids ids threshold])
(reduce (fn [total {:keys [file-id id type deleted-at metadata backend]}]
(reduce (fn [total {:keys [file-id id type deleted-at backend storage-object-id]}]
(some->> metadata
(fdata/decode-metadata)
(fdata/process-metadata cfg))
(some->> storage-object-id
(fdata/touch-storage-object cfg))
(l/trc :obj "file-data"
:id (str id)

View File

@ -28,18 +28,33 @@
(def ^:private sql:lock-file
;; NOTE: SKIP LOCKED only serializes against writers that also lock
;; the file row. Every file_data writer must therefore hold at least
;; FOR SHARE on it (the update RPC via lock-for-share?, file-gc via
;; FOR UPDATE); a writer skipping that lock would reopen the
;; lost-update race this lock closes.
;; the file row. Every file_data writer must therefore lock it too:
;; the update RPC and the snapshot paths via `lock-for-update?`, and
;; file-gc via FOR UPDATE. A writer skipping that lock would reopen
;; the lost-update race this lock closes.
"SELECT id FROM file WHERE id = ? AND deleted_at IS NULL FOR UPDATE SKIP LOCKED")
(defn- decode-row
"Normalize a `file_data` row read with `SELECT fd.*`: NULL columns are
absent (the db layer uses `next.jdbc.optional`) and jsonb metadata arrives
as a `PGobject`, while `fdata/upsert!` expects a decoded metadata map. A
JSON `null` decodes to nil, and the key has to disappear rather than travel
as `:metadata nil`, which the schema rejects."
[row]
(let [metadata (some-> (:metadata row) fdata/decode-metadata)]
(cond-> (dissoc row :metadata)
(some? metadata) (assoc :metadata metadata))))
(defn- offload-file-data
"Offload one hot-storage row to cold storage. Returns the row type
and the migrated bytes for the caller to aggregate."
[cfg {:keys [id file-id type data] :as fdata}]
(jobs/heartbeat cfg)
(fdata/upsert! cfg (assoc fdata :backend "storage"))
;; The pointer key is normalized here because a NULL `storage_object_id`
;; is omitted by the row builder; `decode-row` already normalized metadata.
(fdata/upsert! cfg (assoc fdata
:backend "storage"
:storage-object-id (:storage-object-id fdata)))
(let [size (if (bytes? data) (alength ^bytes data) 0)]
(l/trc :hint "file data row offloaded"
:file-id (str file-id)
@ -61,16 +76,19 @@
[{:keys [::db/conn] :as cfg} file-id]
(if (db/exec-one! conn [sql:lock-file file-id])
(let [{:keys [rows bytes by-type]}
(reduce (fn [stats fdata]
(let [{:keys [type size]} (offload-file-data cfg fdata)]
(-> stats
(update :rows inc)
(update :bytes + size)
(update-in [:by-type type]
(fn [{r :rows b :bytes :or {r 0 b 0}}]
{:rows (inc r) :bytes (+ b size)})))))
{:rows 0 :bytes 0 :by-type {}}
(db/plan conn [sql:get-file-data file-id]))]
(transduce
(map decode-row)
(completing
(fn [stats fdata]
(let [{:keys [type size]} (offload-file-data cfg fdata)]
(-> stats
(update :rows inc)
(update :bytes + size)
(update-in [:by-type type]
(fn [{r :rows b :bytes :or {r 0 b 0}}]
{:rows (inc r) :bytes (+ b size)}))))))
{:rows 0 :bytes 0 :by-type {}}
(db/plan conn [sql:get-file-data file-id]))]
(l/trc :hint "file data offloaded"
:file-id (str file-id)
:offloaded rows

View File

@ -801,6 +801,95 @@
(t/is (cfo/token-applied? token-radius shape [:r1 :r2 :r3 :r4]))
(t/is (cfo/token-applied? token-opacity shape [:opacity]))))))
(t/deftest embed-assets-loads-the-library-components
;; The library is read without `:realize?`, so its `:components` is an
;; unloaded pointer map: `absorb-assets` walks it with `vals`, which calls
;; `load!`, and that raises when no loader is bound. The absorb has to run
;; under the library's own loader. This is a pre-existing failure, not a
;; regression of the migration-on-read work: the migration path returns the
;; pointer already loaded by the reattach comparison.
(let [profile (th/create-profile* 1)
library (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared true})
file (th/create-file* 2 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
lib-page (first (get-in library [:data :pages]))
file-page (first (get-in file [:data :pages]))
component-id (uuid/random)
main-id (uuid/random)
copy-id (uuid/random)]
(th/link-file-to-library* {:file-id (:id file) :library-id (:id library)})
;; The library owns one component.
(update-file!
:file-id (:id library)
:profile-id (:id profile)
:changes
[{:type :add-obj
:page-id lib-page
:id main-id
:parent-id uuid/zero
:frame-id uuid/zero
:components-v2 true
:obj (cts/setup-shape
{:id main-id
:name "Board"
:frame-id uuid/zero
:parent-id uuid/zero
:type :frame
:main-instance true
:component-root true
:component-file (:id library)
:component-id component-id})}
{:type :add-component
:path ""
:name "Board"
:main-instance-id main-id
:main-instance-page lib-page
:id component-id
:anotation nil}])
;; The file instances it, so the absorb has a usage to embed.
(update-file!
:file-id (:id file)
:profile-id (:id profile)
:changes
[{:type :add-obj
:page-id file-page
:id copy-id
:parent-id uuid/zero
:frame-id uuid/zero
:components-v2 true
:obj (cts/setup-shape
{:id copy-id
:name "Board"
:frame-id uuid/zero
:parent-id uuid/zero
:type :frame
:main-instance false
:component-root true
:component-file (:id library)
:component-id component-id})}])
(t/testing "a plain library is absorbed"
(let [file-data (-> (bfc/get-file th/*system* (:id file) :realize? true) :data)
result (bfc/embed-assets th/*system* file-data (:id file))]
(t/is (contains? (:components result) component-id))))
(t/testing "a library that needed a migration is absorbed too"
;; The scenario the review reported. It works even without the loader,
;; because `reattach-unchanged` loads the pointers it puts back; it
;; stays pinned so a future reattach that stops loading does not
;; silently break the absorb.
(th/db-delete! :file-migration
{:file-id (:id library)
:name "0031-migrate-stroke-width-token-attr"})
(let [file-data (-> (bfc/get-file th/*system* (:id file) :realize? true) :data)
result (bfc/embed-assets th/*system* file-data (:id file))]
(t/is (contains? (:components result) component-id))))))
(t/deftest export-detach-libraries-preserves-own-tokens-and-status
(let [profile (th/create-profile* 1)
{:keys [library file page-id shape-id token-radius token-opacity]}
@ -1410,26 +1499,23 @@
(t/is (some? file-res))
(t/is (= 1 (count (:done file-res))))))))
(t/deftest link-later-overwrite-import-no-resolution
(t/deftest import-rejects-an-in-place-import
;; The in-place import was removed: it never carried the previous storage
;; pointer, so it could leave the replaced object unreclaimed. A caller that
;; still sets `::bfc/file-id` fails instead of importing as new files.
(let [{:keys [profile file-id team-id]} (import-sample-file)
output (tmp/tempfile :suffix ".zip")]
;; Export file with link-later
(v3/export-files!
(-> th/*system*
(assoc ::bfc/file-ids #{file-id})
(assoc ::bfc/export-type :link-later)
(assoc ::bfc/output (io/output-stream output))))
;; Import with overwrite (file-id set)
(let [result (-> th/*system*
output (tmp/tempfile :suffix ".zip")
cause (try
(-> th/*system*
(assoc ::bfc/project-id (:default-project-id profile))
(assoc ::bfc/profile-id (:id profile))
(assoc ::bfc/team-id team-id)
(assoc ::bfc/file-id file-id)
(assoc ::bfc/input output)
(v3/import-files!))]
;; Overwrite should have empty resolution
(t/is (= {} (:resolution result))))))
(v3/import-files!))
nil
(catch clojure.lang.ExceptionInfo cause cause))]
(t/is (= :not-supported (:code (ex-data cause))))))
;; -----------------------------------------------------------------------------
;; Category 2: Cross-Team Migration
@ -3082,17 +3168,51 @@
(:object-id thumb)))
(t/is (some? (:media-id thumb)))))))
(t/deftest get-file-without-data-rejects-locks
;; Locking is incompatible with `load-data? false`: the guard fires
;; before any query, so no DB row is needed. Regression test for the
;; `lock-for-share?`/`lock-for-share?` typo that left `lock-for-update?`
;; unchecked. NOTE: the guard is an unconditional `when`/`throw` in
;; `get-file*` (not an `assert`), so this test is not flag-dependent:
;; it behaves the same with or without `enable-backend-asserts`.
(doseq [opt [:lock-for-share? :lock-for-update? :skip-locked?]]
(t/deftest get-file-without-data-can-lock
;; Locking is legal without loading the data: the row-only query selects
;; directly from `file`, so `FOR UPDATE`/`FOR SHARE` apply to the row and
;; the lock lives until the enclosing transaction ends. `SKIP LOCKED` only
;; modifies a locking read, so on its own it is ignored. The SQL is pinned
;; because a plain `SELECT` also returns the row: the lock clause is what
;; serializes with the other writers.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})]
(doseq [[opt sql] {:lock-for-share? (str bfc/sql:get-file-without-data " FOR SHARE of f")
:lock-for-update? (str bfc/sql:get-file-without-data " FOR UPDATE of f")
:skip-locked? bfc/sql:get-file-without-data}]
(let [[row sqls] (th/read-recording-sql
#(bfc/get-file th/*system* (:id file) :load-data? false opt true))]
(t/is (= (:id file) (:id row)))
(t/is (nil? (:data row)))
(t/is (= [sql] sqls))))))
(t/deftest get-file-rejects-realize-without-data
;; `:realize?` walks the decoded data; asking for it without loading or
;; decoding the data is a caller bug. The guard fires before any query, so
;; no file row is needed.
(let [id (uuid/random)]
(t/is (thrown? IllegalArgumentException
(bfc/get-file th/*system* (uuid/random)
:load-data? false opt true)))))
(bfc/get-file th/*system* id :realize? true :decode? false)))
(t/is (thrown? IllegalArgumentException
(bfc/get-file th/*system* id :realize? true :load-data? false)))))
(t/deftest get-file-rejects-a-shared-lock-with-data
;; The probe inherits the caller's lock and the migration branch re-reads
;; with FOR UPDATE, so a shared lock on a data read is a lock upgrade. The
;; guard fires before any query, so no row is needed.
(t/is (thrown? IllegalArgumentException
(bfc/get-file th/*system* (uuid/random) :lock-for-share? true))))
(t/deftest get-file-rejects-a-bare-pool-or-connection
;; The read opens a transaction (unless it is read-only) and resolves the
;; cfg, so it takes a cfg map only: a bare pool or connection is a caller
;; bug. The guard is an `IllegalArgumentException`, not an `assert`, which
;; is elided when the backend runs without `:backend-asserts`.
(let [id (uuid/random)]
(t/is (thrown? IllegalArgumentException (bfc/get-file th/*pool* id)))
(with-open [conn (db/open th/*system*)]
(t/is (thrown? IllegalArgumentException (bfc/get-file conn id))))))
;; --- Library relations security tests

View File

@ -40,12 +40,13 @@
:kind fchanges/snapshot-kind
:updated-at past})
(t/is (true? (fdata/upsert! th/*system*
{:id id
:file-id (:id file)
:type "snapshot"
:backend "legacy-db"
:data payload})))
(t/is (true? (:written (fdata/upsert! th/*system*
{:id id
:file-id (:id file)
:type "snapshot"
:backend "legacy-db"
:storage-object-id nil
:data payload}))))
(let [row (th/db-get :file-change {:id id} {::db/remove-deleted false})]
(t/testing "the payload lands in the legacy column"
@ -53,3 +54,73 @@
(t/testing "the watermark moves to the moment of the mutation"
(t/is (pos? (compare (inst-ms (:updated-at row)) (inst-ms past))))))))
(t/deftest upsert-reports-the-pointer-it-created
;; The write reports the object it created, so a caller that persists again
;; touches the current pointer instead of the replaced one.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
data (byte-array [1 2 3])]
(let [out (db/tx-run! th/*system*
(fn [cfg]
(fdata/upsert! cfg {:id (:id file)
:file-id (:id file)
:type "main"
:backend "storage"
:storage-object-id nil
:data data})))]
(t/testing "a storage write reports the object it created"
(t/is (true? (:written out)))
(t/is (uuid? (:storage-object-id out)))
(t/is (= (:storage-object-id out)
(:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id (:id file)}))))))
(let [previous (:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id (:id file)}))
out (db/tx-run! th/*system*
(fn [cfg]
(fdata/upsert! cfg {:id (:id file)
:file-id (:id file)
:type "main"
:backend "db"
:storage-object-id previous
:data data})))]
(t/testing "a db write has no object to report"
(t/is (true? (:written out)))
(t/is (nil? (:storage-object-id out)))
(t/is (nil? (:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id (:id file)}))))))))
(t/deftest upsert-rejects-a-stale-pointer
;; The write only replaces the row whose pointer the caller read. A stale
;; map must fail instead of touching the wrong object and leaking the blob.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
data (byte-array [1 2 3])
before (th/db-get :file-data {:file-id (:id file) :id (:id file)})
cause (try
(db/tx-run! th/*system*
(fn [cfg]
(fdata/upsert! cfg {:id (:id file)
:file-id (:id file)
:type "main"
:backend "db"
:storage-object-id (uuid/next)
:data data})))
nil
(catch clojure.lang.ExceptionInfo cause cause))]
(t/is (= :stale-file-data-pointer (:code (ex-data cause))))
(let [after (th/db-get :file-data {:file-id (:id file) :id (:id file)})]
(t/testing "the row is untouched"
(t/is (= (:backend before) (:backend after)))
(t/is (= (:storage-object-id before) (:storage-object-id after)))
(t/is (= (vec (:data before)) (vec (:data after))))))))

View File

@ -0,0 +1,323 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS INC Sucursal en España SL
(ns backend-tests.file-data-test
(:require
[app.binfile.common :as bfc]
[app.common.time :as ct]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.features.fdata :as fdata]
[app.storage :as sto]
[app.util.blob :as blob]
[backend-tests.helpers :as th]
[clojure.test :as t]))
(t/use-fixtures :once th/state-init)
(t/use-fixtures :each th/database-reset)
;; The storage pointer of a `file_data` row is a column with a foreign key and
;; it is the only source of truth: the release is a coordinated restart and
;; the metadata no longer carries `storage-ref-id`.
(defn- find-object
[id]
(th/db-get :storage-object {:id id} {::db/remove-deleted false}))
(defn- put-object!
([bucket metadata content]
(sto/put-object! (::sto/storage th/*system*)
(merge {::sto/content content
:content-type "application/octet-stream"
:bucket bucket}
metadata)))
([bucket metadata]
(put-object! bucket metadata (sto/content "sobject"))))
(defn- create-file!
[]
(let [profile (th/create-profile* 1)]
(th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})))
(defn- upsert!
[params]
(db/tx-run! th/*system*
(fn [cfg]
(fdata/upsert! cfg params))))
(defn- resolve!
[row]
(db/tx-run! th/*system*
(fn [cfg]
(fdata/resolve-file-data cfg row))))
(t/deftest upsert-to-storage-writes-the-column
(let [file (create-file!)
data (blob/encode {:pages [] :pages-index {}})]
;; `main` always carries `id = file_id`: update the row the file already
;; has instead of inventing a second one.
(upsert! {:id (:id file)
:file-id (:id file)
:type "main"
:backend "storage"
:storage-object-id nil
:data data
:metadata {:generated-by "test"}})
(let [row (th/db-get :file-data {:file-id (:id file) :id (:id file)})
metadata (fdata/decode-metadata (:metadata row))
sobject (:storage-object-id row)]
(t/testing "the row points at the object with the column"
(t/is (= "storage" (:backend row)))
(t/is (nil? (:data row)))
(t/is (uuid? sobject)))
(t/testing "the metadata no longer carries the pointer"
(t/is (nil? (:storage-ref-id metadata)))
(t/is (= "test" (:generated-by metadata))))
(t/testing "the object is stored in the file-data bucket"
(t/is (= "file-data" (:bucket (meta (sto/get-object (::sto/storage th/*system*)
sobject))))))
(t/testing "the row resolves to the stored bytes"
(t/is (= (vec data) (vec (:data (resolve! row)))))))))
(t/deftest upsert-back-to-db-clears-the-column-and-touches-the-object
(let [file (create-file!)]
(upsert! {:id (:id file)
:file-id (:id file)
:type "main"
:backend "storage"
:storage-object-id nil
:data (blob/encode {:pages [] :pages-index {}})})
(let [sobject (:storage-object-id (th/db-get :file-data
{:file-id (:id file) :id (:id file)}))]
;; The caller passes the object the persisted row points at; `upsert!`
;; touches it before replacing the row. The dead metadata pointer must
;; not survive the write either.
(upsert! {:id (:id file)
:file-id (:id file)
:type "main"
:backend "db"
:storage-object-id sobject
:data (blob/encode {:pages [] :pages-index {}})
:metadata {:generated-by "test"
:storage-ref-id (uuid/next)}})
(let [row (th/db-get :file-data {:file-id (:id file) :id (:id file)})
metadata (fdata/decode-metadata (:metadata row))]
(t/testing "the hot row no longer references the object"
(t/is (= "db" (:backend row)))
(t/is (nil? (:storage-object-id row)))
(t/is (nil? (:storage-ref-id metadata)))
(t/is (= "test" (:generated-by metadata))))
(t/testing "the replaced object is touched for the storage GC"
(t/is (some? (:touched-at (find-object sobject)))))))))
(t/deftest resolve-file-data-uses-the-column-and-ignores-the-metadata
(let [file (create-file!)
data (blob/encode {:pages [] :pages-index {}})
obj (put-object! "file-data"
{:file-id (:id file) :id (:id file)}
(sto/content data))
;; A different, well-formed pointer in the metadata: it must be
;; ignored now that the column is the only source of truth.
other (put-object! "file-data"
{:file-id (uuid/next) :id (uuid/next)})]
(th/db-update! :file-data
{:backend "storage"
:data nil
:storage-object-id (:id obj)
:metadata (db/json {"storage-ref-id" (str (:id other))})}
{:file-id (:id file) :id (:id file)})
(t/testing "the column wins over the metadata"
(let [row (th/db-get :file-data {:file-id (:id file) :id (:id file)})]
(t/is (= (:id obj) (:storage-object-id row)))
(t/is (= (vec data) (vec (:data (resolve! row)))))))))
(t/deftest gc-touched-freezes-an-object-referenced-only-by-the-column
(let [file (create-file!)
;; The object metadata points at other ids: the freeze must come from
;; the column, not from the old metadata lookup.
sobject (put-object! "file-data"
{:file-id (uuid/next) :id (uuid/next)})]
(th/db-update! :storage-object
{:touched-at (ct/in-past {:hours 3})}
{:id (:id sobject)})
(th/db-update! :file-data
{:backend "storage"
:data nil
:storage-object-id (:id sobject)}
{:file-id (:id file) :id (:id file)})
(let [result (th/run-task! :storage-gc-touched {})]
(t/is (= 1 (:freeze result)))
(t/is (= 0 (:delete result)))
(t/is (nil? (:touched-at (find-object (:id sobject))))))))
(t/deftest update-file!-ignores-the-pointer-in-the-params
;; `:storage-object-id` is bookkeeping of the persisted row, not an editable
;; field: a param must not be able to drop the pointer and skip the touch.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})]
(th/run-task! :offload-file-data {:file-id (:id file)})
(th/run-task! :storage-gc-touched {:skip-delay true})
(let [sobject (:storage-object-id (th/db-get :file-data {:file-id (:id file)
:id (:id file)}))]
(t/is (uuid? sobject))
(t/is (nil? (:touched-at (find-object sobject))))
(db/tx-run! th/*system*
(fn [cfg]
(let [file (bfc/get-file cfg (:id file)
:migrate? false
:lock-for-update? true)]
(bfc/update-file! cfg file
:storage-object-id nil
:modified-at (ct/now)))))
(t/testing "the previous object is still touched"
(t/is (some? (:touched-at (find-object sobject))))))))
(t/deftest resolve-file-data-reports-a-missing-storage-object
(let [file (create-file!)]
(th/db-update! :file-data
{:backend "storage"
:data nil
:storage-object-id nil}
{:file-id (:id file) :id (:id file)})
(let [cause (try
(db/tx-run! th/*system*
(fn [cfg]
(->> (th/db-get :file-data {:file-id (:id file)
:id (:id file)})
(fdata/resolve-file-data cfg))))
nil
(catch clojure.lang.ExceptionInfo cause cause))]
(t/is (some? cause))
(t/is (= :missing-storage-object (:code (ex-data cause))))
(t/is (= (:id file) (:file-id (ex-data cause)))))))
(t/deftest load-pointer-reports-the-file-when-the-object-is-gone
(let [file (create-file!)
fragment (first (th/db-query :file-data {:file-id (:id file)
:type "fragment"}))
sobject (put-object! "file-data"
{:file-id (:id file) :id (:id fragment)})]
(t/is (uuid? (:id fragment)))
;; The foreign key accepts the row (the object exists); a soft-deleted
;; object is simply unreadable, which is the case the error reports.
(th/db-update! :storage-object
{:deleted-at (ct/in-past "1h")}
{:id (:id sobject)})
(th/db-update! :file-data
{:backend "storage"
:data nil
:storage-object-id (:id sobject)}
{:file-id (:id file) :id (:id fragment)})
(let [cause (try
(db/tx-run! th/*system*
(fn [cfg]
(fdata/load-pointer cfg (:id file) (:id fragment))))
nil
(catch clojure.lang.ExceptionInfo cause cause))
data (ex-data cause)]
(t/is (some? cause))
(t/is (= :missing-storage-object (:code data)))
(t/is (= (:id file) (:file-id data)))
(t/is (= (:id fragment) (:id data))))))
(t/deftest update-file!-rejects-a-map-without-data
;; A map read with `:load-data? false` has no `:data` and no storage pointer;
;; persisting it would wipe the content and skip the touch. The guard is an
;; explicit raise, not an assert, so it also exists in production.
(let [file (create-file!)
cause (try
(db/tx-run! th/*system*
(fn [cfg]
(bfc/update-file! cfg (bfc/get-file cfg (:id file)
:load-data? false))))
nil
(catch clojure.lang.ExceptionInfo cause cause))]
(t/is (some? cause))
(t/is (= :missing-file-data (:code (ex-data cause))))))
(t/deftest update-file!-ignores-the-identity-in-the-params
;; The params change mutable fields only: `:id` cannot retarget the UPDATE.
(let [file (create-file!)
other (uuid/next)
when (ct/inst "2020-01-01T00:00:00Z")]
(db/tx-run! th/*system*
(fn [cfg]
(let [file (bfc/get-file cfg (:id file)
:migrate? false
:lock-for-update? true)]
(bfc/update-file! cfg file :id other :modified-at when))))
(t/testing "the read file is updated"
(t/is (= when (:modified-at (th/db-get :file {:id (:id file)})))))
(t/testing "the id in the params is ignored"
(t/is (nil? (th/db-get :file {:id other}))))))
(t/deftest update-file!-touches-the-previous-object-on-a-storage-write
;; With `:file-data-backend` = "storage", every ordinary save replaces the
;; object of the row: the previous one must be touched so the storage GC can
;; reclaim it. The storage -> db and db -> storage directions are covered
;; above; this pins the configuration where storage is the default.
(with-redefs [cf/get (th/config-get-mock {:file-data-backend "storage"})]
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
previous (:storage-object-id (th/db-get :file-data
{:file-id (:id file) :id (:id file)}))]
(t/is (uuid? previous))
;; A new object is born touched; clear the mark so the assertion below
;; proves the save is what touches it.
(th/db-update! :storage-object {:touched-at nil} {:id previous})
(t/is (nil? (:touched-at (find-object previous))))
(db/tx-run! th/*system*
(fn [cfg]
(let [file (bfc/get-file cfg (:id file)
:migrate? false
:lock-for-update? true)]
(bfc/update-file! cfg file :modified-at (ct/now)))))
(let [row (th/db-get :file-data {:file-id (:id file) :id (:id file)})
current (:storage-object-id row)]
(t/testing "the row points at a new object"
(t/is (uuid? current))
(t/is (not= previous current)))
(t/testing "the previous object is touched for the storage GC"
(t/is (some? (:touched-at (find-object previous)))))))))

View File

@ -0,0 +1,365 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS INC Sucursal en España SL
(ns backend-tests.file-migration-read-test
"Persisting the migrations applied on read is an optimization of the read:
the read already returns migrated data, so the write must never overwrite a
row written after that read, and it must keep a single decoded copy of the
file in the heap."
(:require
[app.binfile.common :as bfc]
[app.common.features :as cfeat]
[app.common.files.migrations :as fmg]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.features.fdata :as fdata]
[app.features.file-migrations :as fmigr]
[app.rpc :as-alias rpc]
[app.util.pointer-map :as pmap]
[backend-tests.helpers :as th]
[clojure.test :as t]))
(t/use-fixtures :once th/state-init)
(t/use-fixtures :each th/database-reset)
(def ^:private migration-name
"0031-migrate-stroke-width-token-attr")
(defn- create-file!
[]
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared false})]
{:profile-id (:id profile)
:file-id (:id file)
:page-id (first (:pages (:data (bfc/get-file th/*system* (:id file)))))}))
(defn- force-migration!
"Make the next read see a pending migration, the way the snapshot tests do:
the version matches, so only a missing row triggers the migration."
[file-id]
(th/db-delete! :file-migration
{:file-id file-id
:name migration-name}))
(defn- file-data-row
[file-id]
(th/db-get :file-data {:file-id file-id :id file-id}))
(defn- storage-object
[id]
(th/db-get :storage-object {:id id} {::db/remove-deleted false}))
(defn- save!
"Run a real save request so the test exercises the same write path a client
takes, not a hand-built row."
[profile-id file-id revn changes]
(th/command! {::th/type :update-file
::rpc/profile-id profile-id
:id file-id
:session-id (uuid/random)
:revn revn
:vern 0
:features (cfeat/get-enabled-features cf/flags)
:changes changes}))
(t/deftest migrate-on-read-does-not-overwrite-a-concurrent-save
;; A save commits after the read that saw the pending migration. The read
;; must decide again on the map it takes under the `file` row lock, so it
;; writes nothing: the save survives, `revn` never goes back (a client whose
;; revn is higher than the stored one cannot save again) and the object the
;; save left stays referenced instead of becoming a frozen orphan.
(with-redefs [cf/get (th/config-get-mock {:file-data-backend "storage"})]
(let [{:keys [profile-id file-id page-id]} (create-file!)
shape-id (uuid/random)
fired? (atom false)
replaced (atom nil)
saved-at (atom nil)
saved-revn (atom nil)]
(force-migration! file-id)
(with-redefs [fmigr/resolve-applied-migrations
(let [orig fmigr/resolve-applied-migrations]
(fn [cfg file]
(let [result (orig cfg file)]
(when (compare-and-set! fired? false true)
;; The save commits once the read has already
;; seen the pending migration. It applies the
;; migration on its own and records it.
(let [out (save! profile-id file-id 0
[(th/add-rect-change page-id shape-id)])]
(t/is (nil? (:error out))))
(let [row (file-data-row file-id)]
(reset! replaced (:storage-object-id row))
(reset! saved-revn (:revn (th/db-get :file {:id file-id})))
(reset! saved-at (:modified-at (th/db-get :file {:id file-id}))))
;; Freeze the object the save left, as the storage
;; GC would if it saw it before a stale write
;; replaced the row again: a write that does not
;; touch it leaks the blob forever.
(th/db-update! :storage-object
{:touched-at nil}
{:id @replaced}))
result)))]
(let [returned (db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id)))
row (th/db-get :file {:id file-id})
persisted (db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id
:migrate? false
:realize? true)))]
(t/testing "the save survives the read"
(t/is (= @saved-revn (:revn returned)))
(t/is (= @saved-revn (:revn row)))
(t/is (= @saved-at (:modified-at row)))
(t/is (some? (get-in persisted [:data :pages-index page-id :objects shape-id]))))
(t/testing "the read writes nothing and the file ends migrated"
(t/is (not (fmg/need-migration? returned)))
(t/is (= @replaced (:storage-object-id (file-data-row file-id))))
(t/is (seq (th/db-query :file-migration
{:file-id file-id
:name migration-name}))))
(t/testing "the next save of the same client does not conflict"
(let [out (save! profile-id file-id @saved-revn
[(th/add-rect-change page-id (uuid/random))])]
(t/is (nil? (:error out))))))))))
(t/deftest migration-already-applied-by-another-reader-is-not-persisted
;; Two readers see the migration pending; the first to get the lock migrates
;; and persists. The second must re-check on its locked read and write
;; nothing (a second write would create another object for the same data).
(with-redefs [cf/get (th/config-get-mock {:file-data-backend "storage"})]
(let [{:keys [file-id]} (create-file!)
fired? (atom false)
pointer (atom nil)]
(force-migration! file-id)
(with-redefs [fmg/need-migration?
(let [orig fmg/need-migration?]
(fn [file]
(let [result (orig file)]
(when (and result (compare-and-set! fired? false true))
;; The other reader wins the lock, migrates and
;; persists before this one gets it.
(db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id)))
(reset! pointer (:storage-object-id (file-data-row file-id))))
result)))]
(db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id)))
(t/testing "the reader that lost the race does not write"
(t/is (uuid? @pointer))
(t/is (= @pointer (:storage-object-id (file-data-row file-id)))))
(t/testing "the file ends migrated"
(t/is (seq (th/db-query :file-migration
{:file-id file-id
:name migration-name}))))))))
(t/deftest migration-read-loads-the-file-data-once
;; The probe decides with a row read without data, so the migration path
;; keeps a single decoded copy of the file in the heap (a large file can be
;; hundreds of MB and a second copy can exhaust it).
(let [{:keys [file-id]} (create-file!)
reads (atom 0)]
(force-migration! file-id)
(with-redefs [fdata/resolve-file-data
(let [orig fdata/resolve-file-data]
(fn [cfg file]
(when (= file-id (:id file))
(swap! reads inc))
(orig cfg file)))]
(db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id)))
(t/is (= 1 @reads)))))
(t/deftest realize-runs-once-per-read-path
;; `fdata/realize` is a full walk of the decoded data. The read owns it once
;; per path; the migration path pays it twice on purpose, once inside
;; `migrate-file` (the chain needs plain data) and once on its result.
(let [{:keys [file-id]} (create-file!)
calls (atom 0)
read! (fn [opts]
(reset! calls 0)
(with-redefs [fdata/realize
(let [orig fdata/realize]
(fn [cfg file]
(swap! calls inc)
(orig cfg file)))]
(db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id opts)))))]
(t/testing "a plain read realizes once"
(read! {:realize? true})
(t/is (= 1 @calls)))
(t/testing "a read-only read realizes once"
(read! {:realize? true :read-only? true})
(t/is (= 1 @calls)))
(t/testing "the migration path realizes twice"
(force-migration! file-id)
(read! {:realize? true})
(t/is (= 2 @calls)))))
(t/deftest row-only-read-resolves-the-applied-migrations-on-demand
;; A row-only read resolves the applied migrations by default, because the
;; row can be completed later and the caller may need them; the explicit
;; opt-out leaves them out.
(let [{:keys [file-id]} (create-file!)
with-migrations (bfc/get-file th/*system* file-id :load-data? false)
without (bfc/get-file th/*system* file-id
:load-data? false
:load-migrations? false)]
(t/is (seq (:migrations with-migrations)))
(t/is (nil? (:migrations without)))))
(t/deftest migrating-read-returns-the-pointer-it-persisted
;; The map a migrating read returns must carry the pointer of the row it
;; left: a caller that writes with it touches that object instead of the
;; replaced one. The storage GC freezes a referenced object, so a write
;; that misses it leaks the blob forever.
(with-redefs [cf/get (th/config-get-mock {:file-data-backend "storage"})]
(let [{:keys [file-id]} (create-file!)]
(force-migration! file-id)
(let [file (db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id)))
left (:storage-object-id (file-data-row file-id))]
(t/testing "the read reports the pointer of the persisted row"
(t/is (uuid? left))
(t/is (= left (:storage-object-id file))))
;; Freeze the object while the row still references it, as the storage
;; GC does; the later write must touch it (see the concurrent-save
;; test for the same technique).
(th/db-update! :storage-object {:touched-at nil} {:id left})
(db/tx-run! th/*system*
(fn [cfg] (bfc/update-file! cfg file)))
(let [row (file-data-row file-id)]
(t/testing "the write replaces the row and touches the object it left"
(t/is (not= left (:storage-object-id row)))
(t/is (some? (:touched-at (storage-object left))))))))))
(t/deftest read-completes-with-a-single-row-read
;; The common read is one row read (with its data columns) and
;; `attach-file-data` completes it.
(let [{:keys [file-id page-id]} (create-file!)
[file sqls] (th/read-recording-sql
#(db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id))))]
(t/is (= [bfc/sql:get-file] sqls))
(t/is (some? (get-in file [:data :pages-index page-id])))))
(t/deftest read-resolves-the-applied-migrations-once
;; The common read resolves the applied migrations once. The migration path
;; resolves them again on the locked re-read (it must decide on the fresh
;; row) and once more after persisting (to return the applied set); no path
;; resolves them twice without a reason.
(let [{:keys [file-id]} (create-file!)
calls (atom 0)
read! (fn []
(reset! calls 0)
(with-redefs [fmigr/resolve-applied-migrations
(let [orig fmigr/resolve-applied-migrations]
(fn [cfg file]
(swap! calls inc)
(orig cfg file)))]
(db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id)))))]
(read!)
(t/is (= 1 @calls))
(force-migration! file-id)
(read!)
(t/is (= 3 @calls))))
(t/deftest migration-read-rereads-the-row-under-lock
;; The first read decides; only when a migration is pending the row is read
;; again, and that second read takes the `file` row lock.
(let [{:keys [file-id]} (create-file!)]
(force-migration! file-id)
(let [[_ sqls] (th/read-recording-sql
#(db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id))))]
(t/is (= [bfc/sql:get-file
(str bfc/sql:get-file " FOR UPDATE of f")]
sqls)))))
(t/deftest read-only-migration-never-writes
;; A read-only context migrates in memory: no lock, no row write and no
;; storage write. The pending migration stays pending.
(with-redefs [cf/get (th/config-get-mock {:file-data-backend "storage"})]
(let [{:keys [file-id page-id]} (create-file!)
pointer (:storage-object-id (file-data-row file-id))]
(force-migration! file-id)
(let [returned (db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id :read-only? true)))]
(t/testing "the read returns migrated, realized data"
(t/is (not (pmap/pointer-map? (get-in returned [:data :pages-index page-id])))))
(t/testing "nothing is persisted"
(t/is (= pointer (:storage-object-id (file-data-row file-id))))
(t/is (empty? (th/db-query :file-migration
{:file-id file-id
:name migration-name}))))))))
(t/deftest read-only-cfg-migration-never-writes
;; A cfg marked `::db/read-only` migrates in memory too: `db/tx-run!` opens
;; the transaction read-only, `get-file*` sees the connection read-only and
;; takes the no-persist branch. The config flag that fills this key is
;; legacy, but the key is set by hand (objects-gc, the REPL), so the read
;; must keep working under it.
(with-redefs [cf/get (th/config-get-mock {:file-data-backend "storage"})]
(let [{:keys [file-id page-id]} (create-file!)
pointer (:storage-object-id (file-data-row file-id))]
(force-migration! file-id)
(let [returned (db/tx-run! (assoc th/*system* ::db/read-only true)
(fn [cfg] (bfc/get-file cfg file-id)))]
(t/testing "the read returns migrated data"
(t/is (not (pmap/pointer-map? (get-in returned [:data :pages-index page-id])))))
(t/testing "nothing is persisted"
(t/is (= pointer (:storage-object-id (file-data-row file-id))))
(t/is (empty? (th/db-query :file-migration
{:file-id file-id
:name migration-name}))))))))
(t/deftest read-only-read-does-not-open-a-transaction
;; A read-only read takes no lock and writes nothing, so `get-file` runs it
;; on a plain connection instead of opening a transaction of its own. The
;; redefinition proves both directions: the same call without the option
;; does open one.
(let [{:keys [file-id]} (create-file!)]
(with-redefs [db/tx-run! (fn [& _]
(throw (ex-info "opened a transaction" {})))]
(t/is (some? (bfc/get-file th/*system* file-id :read-only? true)))
(t/is (thrown? clojure.lang.ExceptionInfo
(bfc/get-file th/*system* file-id))))))

View File

@ -837,7 +837,8 @@
(t/deftest migration-keeps-unchanged-page-fragments
;; Applying a pending migration on read keeps the fragment ids of the
;; pages the migration does not change; a page it changes gets a new
;; id. The caller still receives realized data, not pointers.
;; id. The read returns decoded data with pointers for the pages the
;; migration does not change; `:realize?` is what returns it plain.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
@ -865,7 +866,9 @@
(let [returned (db/tx-run! th/*system*
(fn [cfg] (bfc/get-file cfg file-id)))]
(t/is (not (pmap/pointer-map? (get-in returned [:data :pages-index page-a]))))
;; The migration changed page-b, so it comes plain; page-a keeps
;; its pointer (and its fragment id) until someone realizes it.
(t/is (pmap/pointer-map? (get-in returned [:data :pages-index page-a])))
(t/is (not (pmap/pointer-map? (get-in returned [:data :pages-index page-b]))))
(t/is (not (fmg/need-migration? returned)))

View File

@ -368,8 +368,8 @@
:or {session-id (uuid/next) revn 0}}]
(-> system
(assoc ::files.update/timestamp (ct/now))
(db/tx-run! (fn [{:keys [::db/conn] :as system}]
(let [file (files.update/get-file conn file-id)]
(db/tx-run! (fn [system]
(let [file (files.update/get-file system file-id)]
(#'files.update/update-file* system
{:id file-id
:revn revn
@ -842,6 +842,19 @@
[& params]
(apply db/get* *pool* params))
(defn read-recording-sql
"Run `f` and return [result sqls], where `sqls` are the SQL statements of
every `db/get-with-sql` call. Those are exactly the file reads of
`binfile.common/get-file`: the fragment loads go through `db/get*`."
[f]
(let [sqls (atom [])]
(with-redefs [db/get-with-sql
(let [orig db/get-with-sql]
(fn [ds sql & opts]
(swap! sqls conj (first sql))
(apply orig ds sql opts)))]
[(f) @sqls])))
(defn sleep
[ms-or-duration]
(Thread/sleep (inst-ms (ct/duration ms-or-duration))))

View File

@ -10,7 +10,9 @@
resolve the pointer-mapped pages with the file's own loader."
(:require
[app.http.debug :as debug]
[app.storage :as sto]
[backend-tests.helpers :as th]
[clojure.string :as str]
[clojure.test :as t]
[yetti.response :as-alias yres]))
@ -27,3 +29,28 @@
(t/is (= 200 (::yres/status result)))
(t/is (= "NO VALIDATION ERRORS FOUND" (::yres/body result)))))
(t/deftest debug-download-does-not-expose-the-storage-object-id
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared false})
sobject (sto/put-object! (::sto/storage th/*system*)
{::sto/content (sto/content "sobject")
:content-type "application/octet-stream"
:bucket "file-data"
:file-id (:id file)
:id (:id file)})
_ (th/db-update! :file-data {:storage-object-id (:id sobject)}
{:file-id (:id file)
:id (:id file)})
handler (deref #'debug/download-file-data)
result (handler th/*system* {:params {:file-id (str (:id file))
:download true}})
body (String. ^bytes (::yres/body result))]
(t/is (= 200 (::yres/status result)))
(t/is (str/includes? (get-in result [::yres/headers "content-disposition"])
"attachment"))
(t/is (not (str/includes? body "storage-object-id")))
(t/is (not (str/includes? body "storage_object_id")))))

View File

@ -6,7 +6,9 @@
(ns backend-tests.migrations-test
(:require
[app.common.uuid :as uuid]
[app.db :as db]
[app.features.fdata :as fdata]
[app.migrations :as migrations]
[app.util.migrations :as mg]
[backend-tests.helpers :as th]
@ -15,6 +17,7 @@
[clojure.test :as t]))
(t/use-fixtures :once th/state-init)
(t/use-fixtures :each th/database-reset)
(t/deftest migrations-registry-satisfies-steps-spec
(t/testing "every entry is a {:name :fn} step (guards against stray forms)"
@ -51,6 +54,18 @@
(map :conname)
set))
(defn- foreign-key-flags
"The deferral and delete-action flags of one foreign key. `condeferred` is
true only for `INITIALLY DEFERRED`."
[table name]
(-> (th/db-exec! ["SELECT condeferrable, condeferred, confdeltype, convalidated
FROM pg_constraint
WHERE contype = 'f'
AND conname = ?
AND conrelid = ?::regclass"
name table])
first))
(t/deftest job-table-exists-with-expected-columns
(t/is (= #{; dispatch/lifecycle columns
"id" "name" "tenant" "queue" "label" "priority" "scheduled_at"
@ -216,3 +231,205 @@
(t/is (not (contains? triggers "job__modified_at__tgr"))))
(t/testing "deletion protection is the only trigger on job"
(t/is (= #{"deletion_protection__tgr"} triggers)))))
;; --- File data storage reference (migration 0159)
(def ^:private file-data-migration
(mg/resource "app/migrations/sql/0159-add-file-data-storage-object-id.sql"))
(defn- apply-file-data-migration!
[]
(db/tx-run! (::db/pool th/*system*)
(fn [{:keys [::db/conn]}]
(file-data-migration conn))))
(t/deftest file-data-storage-object-reference-is-a-deferrable-no-action-fk
(t/testing "the pointer column exists"
(t/is (contains? (table-columns "file_data") "storage_object_id")))
(t/testing "the index that serves the FK check and the GC scan exists"
(t/is (contains? (table-indexes "file_data")
"file_data__storage_object_id__idx")))
(t/testing "the reference does not cascade"
(t/is (contains? (table-foreign-keys "file_data")
["file_data_storage_object_id_fkey" "a"])))
(t/testing "the reference is DEFERRABLE but checked immediately"
;; The storage GC catches the violation inside the chunk transaction. An
;; `INITIALLY DEFERRED` check fires at commit, outside the catch, and the
;; sweep would never move past the blocked chunk.
(t/is (= {:condeferrable true
:condeferred false
:confdeltype "a"
:convalidated true}
(foreign-key-flags "file_data"
"file_data_storage_object_id_fkey")))))
(t/deftest deleting-a-referenced-storage-object-fails
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
sobject (:id (th/db-insert! :storage-object {:backend "fs"}))
data-id (uuid/next)]
(th/db-insert! :file-data
{:file-id (:id file)
:id data-id
:type "snapshot"
:backend "storage"
:storage-object-id sobject})
(t/testing "a live reference refuses the physical delete"
(let [cause (try
(th/db-exec! ["DELETE FROM storage_object WHERE id = ?" sobject])
nil
(catch java.sql.SQLException cause cause))]
(t/is (some? cause))
(t/is (= "23503" (.getSQLState cause)))))
(th/db-delete! :file-data {:file-id (:id file) :id data-id})
(t/testing "without the reference the delete succeeds"
(th/db-exec! ["DELETE FROM storage_object WHERE id = ?" sobject])
(t/is (nil? (th/db-get :storage-object {:id sobject}))))))
(t/deftest file-data-migration-backfills-and-is-idempotent
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
sobject (:id (th/db-insert! :storage-object {:backend "fs"}))
data-id (uuid/next)]
(th/db-insert! :file-data
{:file-id (:id file)
:id data-id
:type "snapshot"
:backend "storage"
:metadata (db/json {"storage-ref-id" (str sobject)})})
(t/testing "the backfill copies the metadata pointer into the column"
(apply-file-data-migration!)
(t/is (= sobject (:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id data-id})))))
(t/testing "the backfill removes the dead metadata pointer"
(let [row (th/db-get :file-data {:file-id (:id file) :id data-id})
metadata (fdata/decode-metadata (:metadata row))]
(t/is (nil? (:storage-ref-id metadata)))))
(t/testing "a second application changes nothing"
(let [before (th/db-get :file-data {:file-id (:id file) :id data-id})]
(apply-file-data-migration!)
(t/is (= before (th/db-get :file-data {:file-id (:id file)
:id data-id})))))))
(t/deftest file-data-migration-guards-corrupt-and-orphan-pointers
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
sobject (:id (th/db-insert! :storage-object {:backend "fs"}))
valid-id (uuid/next)
corrupt-id (uuid/next)
orphan-id (uuid/next)
other-id (uuid/next)]
(th/db-insert! :file-data
{:file-id (:id file) :id valid-id :type "snapshot" :backend "storage"
:metadata (db/json {"storage-ref-id" (str sobject)})})
(th/db-insert! :file-data
{:file-id (:id file) :id corrupt-id :type "snapshot" :backend "storage"
:metadata (db/json {"storage-ref-id" "not-a-uuid"})})
(th/db-insert! :file-data
{:file-id (:id file) :id orphan-id :type "snapshot" :backend "storage"
:metadata (db/json {"storage-ref-id" (str (uuid/next))})})
(th/db-insert! :file-data
{:file-id (:id file) :id other-id :type "snapshot" :backend "db"
:metadata (db/json {"storage-ref-id" (str sobject)})})
(t/testing "the migration applies without aborting"
(t/is (true? (apply-file-data-migration!))))
(t/testing "a valid pointer is backfilled"
(t/is (= sobject (:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id valid-id})))))
(t/testing "a non-uuid value stays NULL"
(t/is (nil? (:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id corrupt-id})))))
(t/testing "a pointer to a missing object stays NULL"
(t/is (nil? (:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id orphan-id})))))
(t/testing "rows of other backends are not touched"
(t/is (nil? (:storage-object-id (th/db-get :file-data
{:file-id (:id file)
:id other-id})))))))
(t/deftest file-data-migration-creates-a-missing-index
;; In the test database the index already exists, so the creation branch is
;; only reachable by dropping it first. It is the branch a fresh deployment
;; runs.
(th/db-exec! ["DROP INDEX file_data__storage_object_id__idx"])
(t/is (not (contains? (table-indexes "file_data")
"file_data__storage_object_id__idx")))
(t/is (true? (apply-file-data-migration!)))
(t/is (contains? (table-indexes "file_data")
"file_data__storage_object_id__idx")))
(t/deftest file-data-migration-rebuilds-a-wrong-foreign-key
;; The migration owns the definition. A constraint created by hand with
;; CASCADE would delete the referencing rows instead of refusing the delete,
;; so it is replaced with the NO ACTION one.
(th/db-exec! ["ALTER TABLE file_data
DROP CONSTRAINT file_data_storage_object_id_fkey"])
(try
(th/db-exec! ["ALTER TABLE file_data
ADD CONSTRAINT file_data_storage_object_id_fkey
FOREIGN KEY (storage_object_id) REFERENCES storage_object(id)
ON DELETE CASCADE DEFERRABLE"])
(t/is (true? (apply-file-data-migration!)))
(t/is (= "a" (:confdeltype
(foreign-key-flags "file_data"
"file_data_storage_object_id_fkey"))))
(finally
(apply-file-data-migration!))))
(t/deftest file-data-migration-rebuilds-a-non-deferrable-foreign-key
;; Without DEFERRABLE the constraint breaks `SET CONSTRAINTS ALL DEFERRED`
;; and `database-reset`; the migration recreates it deferrable.
(th/db-exec! ["ALTER TABLE file_data
DROP CONSTRAINT file_data_storage_object_id_fkey"])
(try
(th/db-exec! ["ALTER TABLE file_data
ADD CONSTRAINT file_data_storage_object_id_fkey
FOREIGN KEY (storage_object_id) REFERENCES storage_object(id)
ON DELETE NO ACTION"])
(t/is (true? (apply-file-data-migration!)))
(t/is (true? (:condeferrable
(foreign-key-flags "file_data"
"file_data_storage_object_id_fkey"))))
(finally
(apply-file-data-migration!))))
(t/deftest file-data-migration-rebuilds-a-deferred-foreign-key
;; An `INITIALLY DEFERRED` check fires at commit, outside the
;; `storage-gc-deleted` chunk transaction, so the sweep would never move past
;; a blocked chunk. The migration must leave the check immediate.
(th/db-exec! ["ALTER TABLE file_data
DROP CONSTRAINT file_data_storage_object_id_fkey"])
(try
(th/db-exec! ["ALTER TABLE file_data
ADD CONSTRAINT file_data_storage_object_id_fkey
FOREIGN KEY (storage_object_id) REFERENCES storage_object(id)
ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED"])
(t/is (true? (apply-file-data-migration!)))
(t/is (false? (:condeferred
(foreign-key-flags "file_data"
"file_data_storage_object_id_fkey"))))
(finally
(apply-file-data-migration!))))

View File

@ -287,6 +287,34 @@
(t/is (nil? (th/db-get :team {:id (:id team)} {::db/remove-deleted false})))
(t/is (empty? (:call-args-list @audit-mock))))))
(t/deftest gc-deletes-file-data-and-touches-its-storage-object
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
sobject (sto/put-object! (::sto/storage th/*system*)
{::sto/content (sto/content "file-data")
:content-type "application/octet-stream"
:bucket "file-data"
:file-id (:id file)
:id (:id file)})]
;; `main` always carries `id = file_id`: mark the real row as deleted
;; instead of inventing a second main row.
(th/db-update! :file-data
{:backend "storage"
:data nil
:storage-object-id (:id sobject)
:deleted-at (ct/in-past "30m")}
{:file-id (:id file) :id (:id file)})
(th/run-task! :objects-gc {})
(t/testing "the row is purged"
(t/is (nil? (th/db-get :file-data {:file-id (:id file) :id (:id file)}))))
(t/testing "the storage object is touched for the storage GC"
(t/is (some? (:touched-at (th/db-get :storage-object {:id (:id sobject)})))))))
(t/deftest gc-emits-events-only-for-committed-chunks
(with-mocks [audit-mock {:target 'app.loggers.audit/submit :return nil}]
(with-redefs [cf/flags (conj cf/flags :audit-log)]

View File

@ -62,6 +62,42 @@
(t/is (every? #(= "storage" (:backend %)) after))
(t/is (every? #(nil? (:data %)) after)))))
(t/deftest offloads-a-file-data-row-with-metadata
;; `SELECT fd.*` returns jsonb metadata as a `PGobject`; the offload has to
;; decode it before `fdata/upsert!` validates the row. Imported files carry
;; metadata, so without the normalization the job never offloads them.
(let [profile (th/create-profile* 1)
file (create-file 1 profile)]
(th/db-update! :file-data
{:metadata (db/json {"generated-by" "offload-test"})}
{:file-id (:id file) :id (:id file)})
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})
row (th/db-get :file-data {:file-id (:id file) :id (:id file)})]
(t/is (pos? (:offloaded result)))
(t/is (= "storage" (:backend row)))
(t/is (uuid? (:storage-object-id row)))
(t/is (= {:generated-by "offload-test"}
(fdata/decode-metadata (:metadata row)))))))
(t/deftest offloads-a-file-data-row-with-a-json-null-metadata
;; A jsonb `null` decodes to nil; the key must disappear from the row instead
;; of travelling as `:metadata nil`, which the update schema rejects.
(let [profile (th/create-profile* 1)
file (create-file 1 profile)]
(th/db-exec! ["UPDATE file_data SET metadata = 'null'::jsonb
WHERE file_id = ? AND id = ?"
(:id file) (:id file)])
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})
row (th/db-get :file-data {:file-id (:id file) :id (:id file)})]
(t/is (pos? (:offloaded result)))
(t/is (= "storage" (:backend row)))
(t/is (uuid? (:storage-object-id row)))
(t/is (nil? (:metadata row))))))
(t/deftest skips-file-locked-by-another-transaction
(let [profile (th/create-profile* 1)
file (create-file 1 profile)
@ -385,36 +421,65 @@
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (pos? (:offloaded result))))
(t/testing "live snapshot rows moved to cold storage"
(let [snapshots (th/db-query :file-data {:file-id (:id file)
:type "snapshot"
:deleted-at nil})]
(t/is (pos? (count snapshots)))
(t/is (every? #(= "storage" (:backend %)) snapshots))
(t/is (every? #(nil? (:data %)) snapshots))))
(th/run-task! :storage-gc-touched {:skip-delay true})
(t/testing "snapshots are still listed"
(let [out (th/command! {::th/type :get-file-snapshots
::rpc/profile-id (:id profile)
:file-id (:id file)})]
(t/is (nil? (:error out)))
(t/is (some #(= "before-offload" (:label %)) (:result out)))))
;; The main row points at a cold object, and the storage GC froze it
;; because the row still references it. The restore must touch it before
;; replacing the row, or the blob is never reclaimed.
(let [sobject (:storage-object-id (th/db-get :file-data {:file-id (:id file)
:id (:id file)}))]
(t/is (uuid? sobject))
(t/is (nil? (:touched-at (th/db-get :storage-object {:id sobject}
{::db/remove-deleted false}))))
(t/testing "live snapshot rows moved to cold storage"
(let [snapshots (th/db-query :file-data {:file-id (:id file)
:type "snapshot"
:deleted-at nil})]
(t/is (pos? (count snapshots)))
(t/is (every? #(= "storage" (:backend %)) snapshots))
(t/is (every? #(nil? (:data %)) snapshots))))
(t/testing "snapshots are still listed"
(let [out (th/command! {::th/type :get-file-snapshots
::rpc/profile-id (:id profile)
:file-id (:id file)})]
(t/is (nil? (:error out)))
(t/is (some #(= "before-offload" (:label %)) (:result out)))))
(t/testing "snapshot restores from cold storage"
(let [snap-id (->> (:result (th/command! {::th/type :get-file-snapshots
::rpc/profile-id (:id profile)
:file-id (:id file)}))
(filter #(= "before-offload" (:label %)))
first
:id)
out (th/command! {::th/type :restore-file-snapshot
:id)]
(t/is (some? snap-id))
(t/testing "snapshot preview does not expose the storage pointer"
(let [out (th/command! {::th/type :get-file-snapshot
::rpc/profile-id (:id profile)
:file-id (:id file)
:id snap-id})]
(t/is (some? snap-id))
(t/is (nil? (:error out)))
(t/is (some? (get-in (get-file-data profile (:id file))
[:pages-index page-id :objects shape-id])))))))
(t/is (nil? (:error out)))
(t/is (not (contains? (:result out) :storage-object-id)))))
(t/testing "snapshot restores from cold storage"
(let [out (th/command! {::th/type :restore-file-snapshot
::rpc/profile-id (:id profile)
:file-id (:id file)
:id snap-id})]
(t/is (nil? (:error out)))
(t/is (some? (get-in (get-file-data profile (:id file))
[:pages-index page-id :objects shape-id]))))))
(t/testing "the replaced main object is touched for the storage GC"
(t/is (some? (:touched-at (th/db-get :storage-object {:id sobject}
{::db/remove-deleted false})))))
(t/testing "the main row is back on hot storage without the old pointer"
(let [row (th/db-get :file-data {:file-id (:id file) :id (:id file)})]
(t/is (= "db" (:backend row)))
(t/is (nil? (:storage-object-id row))))))))
(t/deftest write-after-offload-returns-to-hot-storage
(let [profile (th/create-profile* 1 {:is-active true})
@ -483,11 +548,7 @@
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (pos? (:offloaded result))))
(let [ref-ids (into #{}
(comp (map :metadata)
(map fdata/decode-metadata)
(keep :storage-ref-id))
(db-rows (:id file)))]
(let [ref-ids (into #{} (keep :storage-object-id) (db-rows (:id file)))]
(t/is (pos? (count ref-ids)))
(t/is (every? some? (map #(sto/get-object storage %) ref-ids)))

View File

@ -91,8 +91,8 @@
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
data-id (uuid/next)
;; file-data objects carry the ids of their row: the GC resolves the
;; reference with that pair.
;; the row points at its object through `storage_object_id`; the
;; metadata ids are informational for diagnostics
sobject (:id (put-object! "file-data" {:file-id (:id file)
:id data-id}))]
@ -103,7 +103,7 @@
:type "main"
:backend "fs"
:deleted-at (ct/in-past {:days 1})
:metadata (db/json {"storage-ref-id" (str sobject)})})
:storage-object-id sobject})
(mark-object! sobject)
(restore-file! (:id file))

View File

@ -15,6 +15,7 @@
[app.rpc.commands.comments :as comments]
[app.rpc.cond :as cond]
[app.rpc.quotes :as-alias quotes]
[app.storage :as sto]
[backend-tests.helpers :as th]
[clojure.test :as t]
[datoteka.fs :as fs]
@ -1058,3 +1059,28 @@
:team-id (:id team)})]
(t/is (th/success? out))
(t/is (= 0 (count (:result out))))))))
(t/deftest internal-file-map-for-comments-omits-the-storage-object-id
;; The comments module builds its file map through `comments/get-file`; the
;; storage pointer is internal bookkeeping and must not travel in it. The
;; RPC responses never embed the file map, so this pins the internal choke
;; point instead.
(let [profile (th/create-profile* 1 {:is-active true})
team (th/create-team* 1 {:profile-id (:id profile)})
project (th/create-project* 1 {:team-id (:id team)
:profile-id (:id profile)})
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:id project)})
page-id (get-in file [:data :pages 0])
sobject (sto/put-object! (::sto/storage th/*system*)
{::sto/content (sto/content "sobject")
:content-type "application/octet-stream"
:bucket "file-data"
:file-id (:id file)
:id (:id file)})
_ (th/db-update! :file-data {:storage-object-id (:id sobject)}
{:file-id (:id file)
:id (:id file)})
result ((deref #'comments/get-file) th/*system* (:id file) page-id)]
(t/is (not (contains? result :storage-object-id)))))

View File

@ -291,10 +291,11 @@
nil {:data (:data preview)}))]
(t/is (= preview-data live)))))
(t/deftest user-snapshot-of-file-needing-migration-is-materialized
;; A file with pending migrations cannot share fragments: the
;; migration path realizes the data, so the stored snapshot holds
;; plain maps. This pins the shape so it cannot drift silently.
(t/deftest user-snapshot-of-file-needing-migration-shares-fragments
;; A file with pending migrations is migrated on read before the snapshot
;; is taken. The read keeps the pointers of the pages the migration does
;; not change, so the snapshot shares those fragments with the live file
;; like any other snapshot instead of storing a materialized copy.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
@ -309,7 +310,11 @@
snap-id (:id (:result out))
snap (fsnap/get-snapshot th/*system* file-id snap-id)]
(t/is (uuid? snap-id))
(t/is (empty? (fdata/get-used-pointer-ids (:data snap))))
(let [snap-pointers (fdata/get-used-pointer-ids (:data snap))
live-pointers (fdata/get-used-pointer-ids
(:data (bfc/get-file th/*system* file-id)))]
(t/is (seq snap-pointers))
(t/is (every? live-pointers snap-pointers)))
;; ...while preview keeps working on the migrated content.
(let [preview (th/command! {::th/type :get-file-snapshot
::rpc/profile-id (:id profile)
@ -402,29 +407,69 @@
(t/is (nil? (:error out)))
(t/is (true? (:result out)))))))
(t/deftest snapshot-creation-reads-the-file-row-for-update
;; The read inherits the caller's lock, and the migration-on-read path may
;; re-read the same row with FOR UPDATE. A shared lock would be an upgrade,
;; and two concurrent readers can deadlock there. The read of the command
;; takes the exclusive lock.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared false})
[out sqls] (th/read-recording-sql
#(th/command! {::th/type :create-file-snapshot
::rpc/profile-id (:id profile)
:file-id (:id file)
:label "pinned"}))]
(t/is (nil? (:error out)))
(t/is (uuid? (get-in out [:result :id])))
(t/is (= [(str bfc/sql:get-file " FOR UPDATE of f")]
sqls))))
(t/deftest restore-backup-reads-the-file-row-for-update
;; The backup read is the same reader as the snapshot creation, so it also
;; takes the exclusive lock: the migration-on-read re-read cannot upgrade a
;; shared one and deadlock with a concurrent reader.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared false})
snap-id (:id (:result (th/command! {::th/type :create-file-snapshot
::rpc/profile-id (:id profile)
:file-id (:id file)
:label "v1"})))
[out sqls] (th/read-recording-sql
#(th/command! {::th/type :restore-file-snapshot
::rpc/profile-id (:id profile)
:file-id (:id file)
:id snap-id}))]
(t/is (nil? (:error out)))
(t/is (some #(= (str bfc/sql:get-file " FOR UPDATE of f") %) sqls))
(t/is (not-any? #(str/includes? % "FOR SHARE") sqls))))
(t/deftest snapshot-creation-serializes-with-file-gc
;; A user snapshot shares fragment rows with the live file, so its
;; creation must serialize with a concurrent :file-gc pass (which
;; takes FOR UPDATE + SKIP LOCKED on the file row): creation holds
;; FOR SHARE, the GC skips locked files instead of racing it.
;; FOR UPDATE, the GC skips locked files instead of racing it.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared false})
file-id (:id file)]
(t/testing "gc skips a file locked for share"
(t/testing "gc skips a file locked for update"
(db/tx-run! th/*system*
(fn [cfg]
;; Hold FOR SHARE to commit, like create-file-snapshot does.
(bfc/get-file cfg file-id :lock-for-share? true)
;; Hold FOR UPDATE to commit, like create-file-snapshot does.
(bfc/get-file cfg file-id :lock-for-update? true)
;; The GC uses SKIP LOCKED on a different connection, so it
;; must skip instead of blocking or marking.
(t/is (not (th/run-task! :file-gc {:file-id file-id}))))))
(t/testing "creation cannot slip between gc scan and mark"
;; Deterministic interleaving: pause the GC right after its
;; snapshot scan, then create a snapshot. With the FOR SHARE lock
;; snapshot scan, then create a snapshot. With the FOR UPDATE lock
;; the creation waits at the read and sees post-GC fragment ids;
;; without it, it reads pre-GC ids and pins a fragment the pass
;; is about to mark.
@ -451,7 +496,7 @@
(t/is (= true (deref scan-started 10000 ::timeout)))
(let [created (future (do-create))]
;; The creation must not reach the insert while the GC
;; pass holds the file row: with FOR SHARE it waits at the
;; pass holds the file row: with FOR UPDATE it waits at the
;; read instead of snapshotting pre-GC fragment ids.
(t/is (= ::timeout (deref reached-insert 10000 ::timeout)))
(deliver release-scan true)
@ -487,7 +532,7 @@
(t/deftest restore-backup-serializes-with-file-gc
;; The backup snapshot taken by restore shares fragment rows with
;; the live file, so its creation must serialize with a concurrent
;; :file-gc pass, like ::create-file-snapshot does: with FOR SHARE
;; :file-gc pass, like ::create-file-snapshot does: with FOR UPDATE
;; held by the GC pass, the restore waits at the locked read instead
;; of snapshotting pre-GC fragment ids that the pass is about to
;; mark as deleted.

View File

@ -23,6 +23,7 @@
[app.features.fdata :as fdata]
[app.http :as http]
[app.loggers.audit :as-alias audit]
[app.redis :as rds]
[app.rpc :as-alias rpc]
[app.rpc.commands.files :as files]
[app.storage :as sto]
@ -68,7 +69,8 @@
(let [result (:result out)]
(t/is (uuid? file-id))
(t/is (= (:name data) (:name result)))
(t/is (= proj-id (:project-id result)))))
(t/is (= proj-id (:project-id result)))
(t/is (not (contains? result :storage-object-id)))))
(t/testing "rename file"
(let [data {::th/type :rename-file
@ -923,6 +925,68 @@
(t/is (nil? (:error out)))
(t/is (false? (-> out :result :is-shared))))))
(t/deftest unsharing-a-library-touches-the-consumer-storage-object
;; Regression: the absorption used to build a partial file map that dropped
;; `:storage-object-id`, so the offloaded blob of the consumer was never
;; touched and the storage GC could not reclaim it.
(let [profile (th/create-profile* 1 {:is-active true})
library (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared true})
consumer (th/create-file* 2 {:profile-id (:id profile)
:project-id (:default-project-id profile)})]
(th/link-file-to-library* {:file-id (:id consumer)
:library-id (:id library)})
(th/run-task! :offload-file-data {:file-id (:id consumer)})
(th/run-task! :storage-gc-touched {:skip-delay true})
(let [sobject (:storage-object-id (th/db-get :file-data {:file-id (:id consumer)
:id (:id consumer)}))]
(t/is (uuid? sobject))
(t/is (nil? (:touched-at (th/db-get :storage-object {:id sobject}
{::db/remove-deleted false}))))
(let [out (th/command! {::th/type :set-file-shared
::rpc/profile-id (:id profile)
:id (:id library)
:is-shared false})]
(t/is (nil? (:error out)))
(t/testing "the absorbed file rewrites its data and touches the old object"
(let [row (th/db-get :file-data {:file-id (:id consumer) :id (:id consumer)})]
(t/is (= "db" (:backend row)))
(t/is (nil? (:storage-object-id row)))
(t/is (some? (:touched-at (th/db-get :storage-object {:id sobject}
{::db/remove-deleted false}))))))))))
(t/deftest get-file-does-not-expose-the-storage-pointer
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})]
(th/run-task! :offload-file-data {:file-id (:id file)})
(t/is (uuid? (:storage-object-id (th/db-get :file-data {:file-id (:id file)
:id (:id file)}))))
;; A row the migration does not backfill keeps the old pointer in the
;; metadata. The metadata schema is open, so it would travel in the
;; response unless `file->response` strips it.
(th/db-update! :file-data
{:metadata (db/json {"storage-ref-id" (str (uuid/next))})}
{:file-id (:id file) :id (:id file)})
(let [out (th/command! {::th/type :get-file
::rpc/profile-id (:id profile)
:id (:id file)})]
(t/is (nil? (:error out)))
(t/is (= (:id file) (-> out :result :id)))
(t/testing "the internal storage object id never reaches the client"
(t/is (not (contains? (:result out) :storage-object-id))))
(t/testing "a residual metadata pointer does not reach the client"
(t/is (not (contains? (:metadata (:result out)) :storage-ref-id)))))))
(t/deftest permissions-checks-link-to-library-1
(let [profile1 (th/create-profile* 1)
profile2 (th/create-profile* 2)
@ -1606,14 +1670,13 @@
(t/is (every? #(nil? (:data %)) rows))
(t/is (every? #(= "storage" (:backend %)) rows)))
(let [file (-> (th/db-get :file-data {:id (:id file) :type "main"})
(update :metadata fdata/decode-metadata))
(let [file (th/db-get :file-data {:id (:id file) :type "main"})
storage (sto/resolve th/*system*)]
;; (pp/pprint file)
(t/is (= "storage" (:backend file)))
(t/is (nil? (:data file)))
(let [sobj (sto/get-object storage (-> file :metadata :storage-ref-id))]
(let [sobj (sto/get-object storage (:storage-object-id file))]
(vreset! sobject sobj)
;; (pp/pprint (meta sobj))
(t/is (= "file-data" (:bucket (meta sobj))))
@ -3049,6 +3112,36 @@
:id slink-id})]
(t/is (nil? (:error out)))))))
(t/deftest get-file-fragment-returns-only-public-fields
(let [profile (th/create-profile* 1 {:is-active true})
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
fragment (first (th/db-query :file-data {:file-id (:id file)
:type "fragment"}))]
(t/is (uuid? (:id fragment)))
(t/testing "a fragment on hot storage resolves"
(let [out (th/command! {::th/type :get-file-fragment
::rpc/profile-id (:id profile)
:file-id (:id file)
:fragment-id (:id fragment)})]
(t/is (nil? (:error out)))
(let [result (:result out)]
(t/is (contains? result :data))
(t/is (= #{:id :file-id :created-at :data}
(set (keys result)))))))
(t/testing "a fragment moved to cold storage still resolves"
(th/run-task! :offload-file-data {:file-id (:id file)})
(let [out (th/command! {::th/type :get-file-fragment
::rpc/profile-id (:id profile)
:file-id (:id file)
:fragment-id (:id fragment)})]
(t/is (nil? (:error out)))
(t/is (contains? (:result out) :data))
(t/is (not (contains? (:result out) :storage-object-id)))))))
(t/deftest share-link-fragment-access-denied
(let [owner (th/create-profile* 1 {:is-active true})
viewer (th/create-profile* 2 {:is-active true})
@ -3272,3 +3365,71 @@
:team-id (:default-team-id profile)}))]
(t/is (th/success? out))
(t/is (= #{(:id file2)} (into #{} (map :id) (:result out))))))
(t/deftest get-team-shared-files-does-not-expose-the-storage-pointer
(let [profile (th/create-profile* 1 {:is-active true})
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared true})]
(th/run-task! :offload-file-data {:file-id (:id file)})
(let [out (th/command! {::th/type :get-team-shared-files
::rpc/profile-id (:id profile)
:team-id (:default-team-id profile)})
result (:result out)]
(t/is (nil? (:error out)))
(t/is (= #{(:id file)} (into #{} (map :id) result)))
(t/is (every? #(not (contains? % :storage-object-id)) result)))))
(t/deftest save-reads-the-file-row-for-update
;; The save persists the map it read, so the read holds the `file` row from
;; the read to the write, with the exclusive lock: the migration-on-read
;; re-read cannot upgrade a shared one and deadlock with another reader.
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared false})
page-id (first (get-in file [:data :pages]))
[_ sqls] (th/read-recording-sql
#(update-file! :profile-id (:id profile)
:file-id (:id file)
:revn 0
:changes [(th/add-rect-change page-id (uuid/random))]))]
(t/is (some #(= (str bfc/sql:get-file " FOR UPDATE of f") %) sqls))
(t/is (not-any? #(str/includes? % "FOR SHARE") sqls))))
(t/deftest get-team-shared-files-does-not-return-the-applied-migrations
;; The applied migrations are read bookkeeping for the write path: this
;; summary is not where a client completes a read, so both cache paths strip
;; the key. The recorded SQL proves which path ran: a miss reads the file, a
;; hit reads the row only.
(let [profile (th/create-profile* 1 {:is-active true})
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared true})
shared (fn []
(th/command! {::th/type :get-team-shared-files
::rpc/profile-id (:id profile)
:team-id (:default-team-id profile)}))]
;; Redis is not reset between tests and the helper builds deterministic
;; file ids: drop the entry so the first call is a real cache miss.
(rds/run! th/*system*
(fn [{:keys [::rds/conn]}]
(rds/del conn (files/file-summary-cache-key (:id file)))))
(with-redefs [cf/flags (conj cf/flags :redis-cache)]
(let [[miss sqls-miss] (th/read-recording-sql shared)
[hit sqls-hit] (th/read-recording-sql shared)]
(t/is (= [bfc/sql:get-file] sqls-miss))
(t/is (= [bfc/sql:get-file-without-data] sqls-hit))
(t/testing "the cache miss does not carry the applied migrations"
(t/is (nil? (:error miss)))
(t/is (= #{(:id file)} (into #{} (map :id) (:result miss))))
(t/is (every? #(not (contains? % :migrations)) (:result miss))))
(t/testing "the cache hit does not carry the applied migrations"
(t/is (nil? (:error hit)))
(t/is (= (into #{} (map :id) (:result miss))
(into #{} (map :id) (:result hit))))
(t/is (every? #(not (contains? % :migrations)) (:result hit))))))))

View File

@ -177,6 +177,39 @@
(let [rows (th/db-query :file {:project-id (:id project)})]
(t/is (= 3 (count rows))))))))
(t/deftest duplicate-file-does-not-touch-the-source-storage-object
(let [profile (th/create-profile* 1 {:is-active true})
project (th/create-project* 1 {:team-id (:default-team-id profile)
:profile-id (:id profile)})
file1 (th/create-file* 1 {:profile-id (:id profile)
:project-id (:id project)})]
(th/run-task! :offload-file-data {:file-id (:id file1)})
(th/run-task! :storage-gc-touched {:skip-delay true})
(let [sobject (:storage-object-id (th/db-get :file-data {:file-id (:id file1)
:id (:id file1)}))]
(t/is (uuid? sobject))
(t/is (nil? (:touched-at (th/db-get :storage-object {:id sobject}
{::db/remove-deleted false}))))
(let [out (th/command! {::th/type :duplicate-file
::rpc/profile-id (:id profile)
:file-id (:id file1)})]
(t/is (nil? (:error out)))
(t/is (not (contains? (:result out) :storage-object-id)))
(t/testing "duplication does not write to the source object"
(t/is (nil? (:touched-at (th/db-get :storage-object {:id sobject}
{::db/remove-deleted false})))))
(let [file-id (:id (:result out))
row (th/db-get :file-data {:file-id file-id :id file-id})]
(t/testing "the new file does not inherit the source pointer"
(t/is (= "db" (:backend row)))
(t/is (nil? (:storage-object-id row)))
(t/is (bytes? (:data row)))))))))
(t/deftest duplicate-file-with-deleted-relations
(let [storage (-> (:app.storage/storage th/*system*)
(configure-storage-backend))

View File

@ -1371,6 +1371,10 @@
file (th/create-file* 1 {:profile-id (:id owner)
:project-id (:id proj)})
;; Cold storage makes the file map carry the internal pointer, so the
;; response assertion below is meaningful.
_ (th/run-task! :offload-file-data {:file-id (:id file)})
data {::th/type :create-team-access-request
::rpc/profile-id (:id requester)
:file-id (:id file)}]
@ -1383,7 +1387,8 @@
:requester-id (:id requester)})]
(t/is (th/success? out))
(t/is (= 1 (:call-count @mock)))
(t/is (= 1 (count requests))))
(t/is (= 1 (count requests)))
(t/is (not (contains? (:result out) :storage-object-id))))
;; request again fails
(th/reset-mock! mock)

View File

@ -910,3 +910,38 @@
(t/is (= #{comp-b}
(set (keys (get-in by-id [(:id lib2) :data :components])))))
(t/is (= [] (get-in by-id [(:id lib2) :data :pages])))))))
(t/deftest view-only-bundle-does-not-expose-the-storage-pointer
;; Both the file and its libraries are moved to cold storage, so their file
;; maps carry the internal pointer unless the response strips it.
(let [owner (th/create-profile* 1 {:is-active true})
proj-id (:default-project-id owner)
file (th/create-file* 1 {:profile-id (:id owner)
:project-id proj-id
:is-shared false})
lib (th/create-file* 2 {:profile-id (:id owner)
:project-id proj-id
:is-shared true})
page-id (get-in file [:data :pages 0])
_ (th/link-file-to-library* {:file-id (:id file)
:library-id (:id lib)})
slink (th/command! {::th/type :create-share-link
::rpc/profile-id (:id owner)
:file-id (:id file)
:pages #{page-id}
:who-comment "team"
:who-inspect "all"})
slink-id (get-in slink [:result :id])]
(th/run-task! :offload-file-data {:file-id (:id file)})
(th/run-task! :offload-file-data {:file-id (:id lib)})
(let [out (th/command! {::th/type :get-view-only-bundle
:share-id slink-id
:file-id (:id file)})
result (:result out)]
(t/is (nil? (:error out)))
(t/is (seq (:libraries result)))
(t/is (not (contains? (:file result) :storage-object-id)))
(t/is (every? #(not (contains? % :storage-object-id))
(:libraries result))))))

View File

@ -6,6 +6,7 @@
(ns backend-tests.storage-gc-deleted-test
(:require
[app.common.logging :as l]
[app.common.time :as ct]
[app.common.uuid :as uuid]
[app.db :as db]
@ -155,3 +156,75 @@
(t/testing "the objects after the failed chunk are gone"
(t/is (every? #(nil? (find-object (:id %))) recent)))))
(defn- blocked-by-file-data!
"Puts an object referenced by a `file_data` row, so the `NO ACTION`
foreign key of `storage_object_id` refuses the physical delete."
[file-id]
(let [blocked (put-object! (ct/in-past "30m"))]
;; `main` always carries `id = file_id`: point the real row at the object
;; instead of inventing a second main row.
(th/db-update! :file-data
{:backend "storage"
:data nil
:storage-object-id (:id blocked)}
{:file-id file-id :id file-id})
blocked))
(def ^:private blocked-chunk-hint
"chunk deletion blocked by a live reference; fix the reference and let the next run reclaim the chunk")
(defn- blocked-chunk-log
"The first captured error record with the blocked-chunk hint, waiting for it
because logging is asynchronous."
[records]
(let [deadline (+ (System/currentTimeMillis) 30000)]
(loop []
(let [record (first (filter (fn [record]
(and (= :error (::l/level record))
(= blocked-chunk-hint
(get (::l/props record) :hint))))
@records))]
(cond
record record
(> (System/currentTimeMillis) deadline) nil
:else (do (Thread/sleep 10) (recur)))))))
(t/deftest file-data-reference-blocks-its-chunk
(let [profile (th/create-profile* 1)
file (th/create-file* 1 {:profile-id (:id profile)
:project-id (:default-project-id profile)})
;; The blocked object goes first in `deleted_at` order, so it lands in
;; the first chunk with the objects that fill it up. The last object
;; lands in the next chunk: it proves the run kept going.
blocked (blocked-by-file-data! (:id file))
others (mapv (fn [_] (put-object! (ct/in-past "20m"))) (range (dec chunk-size)))
last-id (:id (put-object! (ct/in-past "5m")))
records (atom [])
_ (add-watch l/log-record ::capture
(fn [_ _ _ record] (swap! records conj record)))
result (try
(th/run-task! :storage-gc-deleted {})
(finally
(remove-watch l/log-record ::capture)))]
(t/testing "the run finishes and only the object of the second chunk is deleted"
(t/is (= 1 (:deleted result))))
(t/testing "the object referenced by the file data row is still alive"
(t/is (some? (find-object (:id blocked)))))
(t/testing "the other objects of the failed chunk are still alive"
(t/is (every? #(some? (find-object (:id %))) others)))
(t/testing "the blocked chunk names the constraint that blocks it"
(let [record (blocked-chunk-log records)]
(t/is (some? record))
(t/is (= "file_data_storage_object_id_fkey"
(get (::l/props record) :constraint)))
(t/is (= "file_data" (get (::l/props record) :table)))))
(t/testing "the object of the next chunk is gone"
(t/is (nil? (find-object last-id))))))

View File

@ -95,7 +95,6 @@
(def schema:file-metadata
[:map {:title "Metadata"}
[:storage-ref-id {:optional true} ::sm/uuid]
[:generated-by {:optional true} :string]
[:referer {:optional true} :string]])

View File

@ -95,6 +95,52 @@ Examples:
**NOTE**: if table name has more than one word, we still use <code class="language-text">-</code> as a separator.
### Large tables
A migration runs inside a single transaction, so it cannot use `CONCURRENTLY`,
and a `CREATE INDEX` in a migration locks the table against writes until the
whole run commits.
Write the migration as plain, idempotent SQL: `ADD COLUMN IF NOT EXISTS`,
`CREATE INDEX IF NOT EXISTS`, and `DROP CONSTRAINT IF EXISTS` followed by
`ADD CONSTRAINT`. Do not encode shape checks as `pg_catalog` introspection.
They are easy to get wrong (forgetting `NOT condeferred` accepts an
`INITIALLY DEFERRED` foreign key, which moves the integrity check to commit) and
they duplicate what the runbook can verify by hand.
On a large table, build the column and the index out of band before deploying,
with `CREATE INDEX CONCURRENTLY` on its own (never inside a transaction block).
A partitioned table cannot take `CREATE INDEX CONCURRENTLY` on the parent: build
the index on each partition, create the parent index with
`CREATE INDEX ... ON ONLY`, and attach every partition with
`ALTER INDEX ... ATTACH PARTITION`. An interrupted concurrent build leaves the
index `INVALID`: drop it and retry. `CREATE INDEX IF NOT EXISTS` matches the
name, not the definition, so the runbook verifies `pg_index.indisvalid`, that
the index has no predicate or expression, and that every partition is attached.
A validated foreign key is the other expensive DDL: `ADD FOREIGN KEY` runs as an
`ALTER TABLE`, so it takes `ACCESS EXCLUSIVE` on the referencing table and
`SHARE ROW EXCLUSIVE` on the referenced one, and it scans the whole referencing
table. `NOT VALID` on a partitioned table is only available since PostgreSQL 18.
A reference that a GC task resolves must be `DEFERRABLE INITIALLY IMMEDIATE`,
never `INITIALLY DEFERRED`: the immediate check fires inside the transaction
that catches the violation and retries; the deferred one fires at commit,
outside the catch.
The runbook ends by verifying the end state (column, pending rows, index and
constraint shape) and marking the migration step as applied
(`INSERT INTO migrations (module, step) ...`), so the body does not run at
startup. The marker is the only thing that skips the migration.
A backfill that removes a key an old reader uses (for example a JSONB pointer
that the previous GC scans) must run with the old code stopped. Otherwise the
old reader loses the reference and can delete a live object, and the rows it
writes in the meantime miss the backfill.
`ADD COLUMN` takes a brief `ACCESS EXCLUSIVE` even when it changes nothing. A
migration accepts that lock; a deployment that cannot take it runs the runbook
and marks the step as applied.
If you need to have a global overview of the all schema of the database you can extract it
using postgresql:

View File

@ -0,0 +1,285 @@
# 2.20.0 — File data storage object foreign key
Runbook for the release that moves the file data storage pointer out of
`file_data.metadata->>'storage-ref-id'` and into a column,
`file_data.storage_object_id`, with a foreign key to `storage_object(id)`.
## When to run this
The migration `0159-add-file-data-storage-object-id` does the whole job on a
fresh database and on small instances: it adds the column, backfills the
pointer, creates the index and the foreign key.
A large instance builds everything online and keeps the stopped window as
short as possible:
- the column, the index and the foreign key are built online, without stopping
the service;
- the backfill runs in the stopped window **only if** the metadata pointer
exists; when the storage backend was never enabled there is nothing to
backfill and the new binaries roll out like any other deploy;
- the step is then marked as applied in the `migrations` table, so the
migration body does not run at startup.
The coordinated restart is required only when the instance uses the storage
backend (`PENPOT_FILE_DATA_BACKEND=storage`) or still has rows that carry the
metadata pointer. The previous code writes and reads `metadata.storage-ref-id`,
the new code reads the column, and a rolling deploy would mix both. With the
default `db` backend and no row carrying the pointer (see the pre-flight
query), the previous and the new code read the same `file_data.data` column, so
a rolling deploy is safe.
**Do not run the backfill while the previous version is serving** when
`PENPOT_FILE_DATA_BACKEND` is configured to `storage`, or when the table still
has rows with the metadata pointer. The previous code writes the pointer only to
`metadata.storage-ref-id`, and its storage GC reads the reference from there.
Removing the key while that code runs leaves the rows it writes without a
pointer (unreadable after the deploy), and it can make the GC delete an object
that a live row still references. When the pre-flight query returns 0 there is
nothing to backfill and this risk does not apply.
## 0. Pre-flight
```sql
SELECT version(); -- 16.x: `NOT VALID` foreign keys on a partitioned table need 18
SELECT count(*) FROM pg_inherits
WHERE inhparent = 'file_data'::regclass; -- 16
-- Whether the storage backend was ever enabled. When this is 0 there is no
-- pointer in the metadata and step 6 is skipped.
SELECT count(*) FROM file_data
WHERE backend = 'storage' AND jsonb_exists(metadata, 'storage-ref-id');
-- Every online ALTER uses a short lock timeout and is retried, so a long
-- transaction cannot make it queue and block the table behind it.
SELECT pid, state, now() - xact_start AS age, left(query, 60)
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
AND now() - xact_start > interval '1 minute';
```
## 1. Column
```sql
BEGIN;
SET LOCAL lock_timeout = '3s';
ALTER TABLE file_data
ADD COLUMN storage_object_id uuid NULL;
COMMIT;
```
Skip this step if the column already exists. The change is catalog-only (a
nullable column without a default), so it takes `ACCESS EXCLUSIVE` for an
instant. If it fails with `lock timeout`, wait for a quieter moment and retry:
it did not block anything.
## 2. One index per partition, concurrently
```sql
CREATE INDEX CONCURRENTLY file_data_00__storage_object_id__idx
ON file_data_00 (storage_object_id);
-- ... up to file_data_15
```
Run each statement in autocommit: `CREATE INDEX CONCURRENTLY` cannot run inside
a transaction block. An interrupted build leaves the index `INVALID`: drop it
and retry.
```sql
SELECT c.relname, i.indisvalid
FROM pg_index AS i
JOIN pg_class AS c ON c.oid = i.indexrelid
WHERE c.relname LIKE 'file_data_%storage_object_id%'
ORDER BY c.relname;
```
## 3. Parent index and partition attachment
```sql
CREATE INDEX file_data__storage_object_id__idx
ON ONLY file_data (storage_object_id);
ALTER INDEX file_data__storage_object_id__idx
ATTACH PARTITION file_data_00__storage_object_id__idx;
-- ... up to file_data_15
```
The step creates the index unconditionally: if an index with that name already
exists, drop it and rebuild it. Verify the result before continuing:
```sql
SELECT i.indisvalid, i.indpred IS NULL AS plain, i.indexprs IS NULL AS no_expression
FROM pg_index AS i
WHERE i.indexrelid = 'file_data__storage_object_id__idx'::regclass;
-- t | t | t
SELECT count(*) FROM pg_inherits
WHERE inhparent = 'file_data__storage_object_id__idx'::regclass;
-- 16
```
## 4. Foreign key, online
```sql
BEGIN;
SET LOCAL lock_timeout = '3s';
ALTER TABLE file_data
ADD CONSTRAINT file_data_storage_object_id_fkey
FOREIGN KEY (storage_object_id) REFERENCES storage_object(id)
ON DELETE NO ACTION DEFERRABLE INITIALLY IMMEDIATE;
COMMIT;
```
The column is NULL until step 6, so the validation finds nothing to check and
the `SHARE ROW EXCLUSIVE` lock (it blocks writes, not reads) is brief. Retry on
`lock timeout`. If the constraint already exists, do not add it again: verify
its shape with the query in step 7. Drop it first only if the shape is wrong.
Creating it here, before the backfill, keeps the full validation scan out of
the stopped window: the backfill validates each row it writes.
`INITIALLY IMMEDIATE` is required. The storage GC catches the violation inside
the chunk transaction and retries the chunk; an `INITIALLY DEFERRED` check
fires at commit, outside that transaction, and the GC would never move past a
blocked chunk.
## 5. Stop every instance
Coordinated restart when the pre-flight count is not 0: stop all of them before
the next step. No rolling deploy. When the count is 0 there is nothing to
backfill: run steps 1-4 online, run the verification (step 7) and mark the step
as applied (step 8) without stopping the service.
## 6. Backfill, only if the metadata pointer exists
Skip this step when the pre-flight count is 0: the storage backend was never
enabled, no row carries the pointer, and the new code reads all file data from
the `data` column.
```sql
WITH candidates AS MATERIALIZED (
SELECT file_id,
id,
(metadata->>'storage-ref-id')::uuid AS soid
FROM file_data
WHERE backend = 'storage'
AND storage_object_id IS NULL
AND (metadata->>'storage-ref-id') ~*
'^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$'
)
UPDATE file_data AS fd
SET storage_object_id = c.soid,
metadata = fd.metadata - 'storage-ref-id'
FROM candidates AS c
WHERE fd.file_id = c.file_id
AND fd.id = c.id
AND EXISTS (SELECT 1 FROM storage_object AS so WHERE so.id = c.soid);
```
The `MATERIALIZED` CTE keeps the uuid cast away from values that did not pass
the regex: without it PostgreSQL can inline the subquery and cast a corrupt
value, aborting the statement. The foreign key already exists, so every written
row is validated here instead of in a separate full scan.
## 7. Verify
Do not mark the migration as applied until every check passes.
```sql
-- Column.
SELECT data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'file_data'
AND column_name = 'storage_object_id';
-- uuid | YES
-- Rows that will be unreadable. Must be 0. The backfill only fills pointers it
-- can resolve, so a non-zero count means pointers that were already corrupt or
-- orphan: inspect them and accept them before continuing. With the backfill
-- skipped this must still be 0, or the storage backend was enabled after all.
-- A row pointing at a storage_object with deleted_at set is legitimate and
-- restorable, not unreadable: the backfill fills it on purpose and the
-- restore flow revives the object, so it is not counted here.
SELECT count(*) FROM file_data
WHERE backend = 'storage' AND storage_object_id IS NULL;
-- Index: valid, plain, with every partition attached.
SELECT i.indisvalid, i.indpred IS NULL AS plain, i.indexprs IS NULL AS no_expression
FROM pg_index AS i
WHERE i.indexrelid = 'file_data__storage_object_id__idx'::regclass;
SELECT count(*) FROM pg_inherits
WHERE inhparent = 'file_data__storage_object_id__idx'::regclass; -- 16
-- Foreign key: deferrable, checked immediately, no action, validated.
SELECT condeferrable, condeferred, confdeltype, convalidated
FROM pg_constraint
WHERE conname = 'file_data_storage_object_id_fkey'
AND conrelid = 'file_data'::regclass;
-- t | f | a | t
```
## 8. Mark the migration as applied
Only after step 7 passes:
```sql
INSERT INTO migrations (module, step)
VALUES ('main', '0159-add-file-data-storage-object-id')
ON CONFLICT (module, step) DO NOTHING;
```
Check it:
```sql
SELECT module, step, created_at FROM migrations
WHERE module = 'main' AND step = '0159-add-file-data-storage-object-id';
```
The row is the only thing that skips the migration at startup. Without it, the
migration runs at the next start and repeats the backfill and the foreign key.
## 9. Start the new instances
Start every instance you stopped in step 5. When the pre-flight count was 0
nothing was stopped, and the rolling deploy simply finishes.
## Post-deploy checks
```sql
SELECT conname, condeferrable, condeferred, confdeltype, convalidated
FROM pg_constraint
WHERE conname = 'file_data_storage_object_id_fkey';
SELECT count(*) FROM file_data
WHERE backend = 'storage' AND storage_object_id IS NULL;
-- The delete check must use the index, not a sequential scan.
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
DELETE FROM storage_object WHERE id = '<uuid of a deleted object with no references>';
ROLLBACK;
```
## Rollback
Before step 8:
```sql
ALTER TABLE file_data
DROP CONSTRAINT IF EXISTS file_data_storage_object_id_fkey;
-- A partitioned index cannot be dropped with CONCURRENTLY; the plain drop
-- takes a brief ACCESS EXCLUSIVE.
DROP INDEX file_data__storage_object_id__idx;
ALTER TABLE file_data DROP COLUMN storage_object_id;
```
After step 8 the backfill has already removed the metadata key that the
previous code reads, so a rollback to the previous binaries is **not
supported** when the instance uses the storage backend: the files offloaded by
the new code would be unreadable, and the recovery is a data restore, not a
binary switch. With the default `db` backend and no storage rows, the previous
binaries read the same `data` column and the rollback is a plain binary switch.