penpot/backend/test/backend_tests/file_data_test.clj
Andrey Antukh e23ca02aa2
✨ 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
2026-11-14 19:27:18 +01:00

324 lines
13 KiB
Clojure

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