penpot/backend/test/backend_tests/offload_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

673 lines
27 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 SUBSIDIARY SL
(ns backend-tests.offload-file-data-test
(:require
[app.binfile.common :as bfc]
[app.binfile.v3 :as v3]
[app.common.features :as cfeat]
[app.common.time :as ct]
[app.common.types.shape :as cts]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.features.fdata :as fdata]
[app.jobs :as jobs]
[app.jobs.metrics :as metrics]
[app.main :as main]
[app.metrics :as mtx]
[app.metrics.definition :as-alias mdef]
[app.rpc :as-alias rpc]
[app.storage :as sto]
[app.storage.tmp :as tmp]
[app.tasks.offload-file-data :as offload]
[backend-tests.helpers :as th]
[clojure.test :as t]
[datoteka.io :as io]
[integrant.core :as ig])
(:import
io.prometheus.client.Counter
io.prometheus.client.Counter$Child))
(t/use-fixtures :once th/state-init)
(t/use-fixtures :each th/database-reset)
(defn- db-rows
[file-id]
(th/db-query :file-data {:file-id file-id}))
(defn- create-file
[i profile]
(th/create-file* i {:profile-id (:id profile)
:project-id (:default-project-id profile)
:is-shared false}))
(t/deftest offloads-file-data-to-storage
(let [profile (th/create-profile* 1)
file (create-file 1 profile)
before (db-rows (:id file))]
(t/is (pos? (count before)))
(t/is (every? #(= "db" (:backend %)) before))
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (= (count before) (:offloaded result)))
(t/is (zero? (:skipped result))))
(let [after (db-rows (:id file))]
(t/is (= (count before) (count after)))
(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)
before (db-rows (:id file))
locked (promise)
release (promise)
holder (future
(db/tx-run! th/*system*
(fn [{:keys [::db/conn]}]
(db/exec-one! conn ["SELECT id FROM file WHERE id = ? FOR UPDATE" (:id file)])
(deliver locked true)
@release
:held)))]
(t/is (= true (deref locked 10000 ::timeout)))
(try
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (= 0 (:offloaded result)))
(t/is (= 1 (:skipped result))))
(finally
(deliver release true)
(deref holder 10000 ::timeout)))
(let [after (db-rows (:id file))]
(t/is (= (count before) (count after)))
(t/is (every? #(= "db" (:backend %)) after)))))
(t/deftest skips-missing-and-deleted-files
(let [result (th/run-task! :offload-file-data {:file-id (uuid/next)})]
(t/is (= 0 (:offloaded result)))
(t/is (= 1 (:skipped result))))
(let [profile (th/create-profile* 1)
file (create-file 1 profile)
_ (th/db-update! :file {:deleted-at (ct/now)} {:id (:id file)})
before (db-rows (:id file))
result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (= 0 (:offloaded result)))
(t/is (= 1 (:skipped result)))
(let [after (db-rows (:id file))]
(t/is (= (count before) (count after)))
(t/is (every? #(= "db" (:backend %)) after)))))
(defn- row-bytes
[{:keys [data]}]
(if (bytes? data)
(alength ^bytes data)
0))
(t/deftest summary-reports-rows-and-bytes
(let [profile (th/create-profile* 1)
file (create-file 1 profile)
before (db-rows (:id file))
expected-bytes (reduce + 0 (map row-bytes before))]
(t/is (pos? (count before)))
(t/is (every? some? (map :data before)))
(t/is (pos? expected-bytes))
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (= (count before) (:offloaded result)))
(t/is (= expected-bytes (:bytes result)))
(t/is (zero? (:skipped result))))
;; A second run is a no-op: nothing left on the hot storage.
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (= 0 (:offloaded result)))
(t/is (= 0 (:bytes result)))
(t/is (zero? (:skipped result))))))
(t/deftest storage-failure-aborts-only-that-file
(let [profile (th/create-profile* 1)
file-a (create-file 1 profile)
file-b (create-file 2 profile)
real-put @#'sto/put-object!
failing (fn [storage params]
(if (= (:file-id params) (:id file-a))
(throw (ex-info "storage is down" {:file-id (:id file-a)}))
(real-put storage params)))]
;; The failing file aborts as a whole: every row stays on hot storage.
(with-redefs [sto/put-object! failing]
(t/is (thrown? Exception
(th/run-task! :offload-file-data {:file-id (:id file-a)}))))
(let [rows-a (db-rows (:id file-a))]
(t/is (pos? (count rows-a)))
(t/is (every? #(= "db" (:backend %)) rows-a))
(t/is (every? some? (map :data rows-a))))
;; The other file is independent and offloads while storage is down for A.
(with-redefs [sto/put-object! failing]
(let [result (th/run-task! :offload-file-data {:file-id (:id file-b)})]
(t/is (pos? (:offloaded result)))
(t/is (pos? (:bytes result)))
(t/is (zero? (:skipped result)))))
(t/is (every? #(= "storage" (:backend %)) (db-rows (:id file-b))))
;; Once storage recovers, a retry converges with no leftovers on hot.
(let [result (th/run-task! :offload-file-data {:file-id (:id file-a)})]
(t/is (pos? (:offloaded result)))
(t/is (pos? (:bytes result)))
(t/is (zero? (:skipped result))))
(let [rows-a (db-rows (:id file-a))]
(t/is (every? #(= "storage" (:backend %)) rows-a))
(t/is (every? #(nil? (:data %)) rows-a)))))
(defn- make-metrics
[]
(ig/init-key :app.metrics/metrics
{:default (select-keys main/default-metrics
[:file-data-offload-rows
:file-data-offload-bytes
:file-data-offload-timing])}))
(defn- offload-cfg
[metrics]
(-> th/*system*
(assoc ::mtx/metrics metrics)
(assoc ::sto/storage (assoc (::sto/storage th/*system*)
::mtx/metrics metrics))))
(defn- counter-value
[metrics id labels]
(let [collector (mtx/get-collector metrics id)
instance (::mdef/instance collector)
child (.labels ^Counter instance (into-array String labels))]
(.get ^Counter$Child child)))
(def ^:private known-types
["main" "snapshot" "fragment"])
(defn- total-counter
[metrics id]
(reduce + 0 (map #(counter-value metrics id [%]) known-types)))
(t/deftest metric-definitions-are-pinned
(let [defs main/default-metrics]
(t/is (= "penpot_file_data_offload_rows_total"
(get-in defs [:file-data-offload-rows ::mdef/name])))
(t/is (= ["type"]
(get-in defs [:file-data-offload-rows ::mdef/labels])))
(t/is (= :counter
(get-in defs [:file-data-offload-rows ::mdef/type])))
(t/is (= "penpot_file_data_offload_bytes_total"
(get-in defs [:file-data-offload-bytes ::mdef/name])))
(t/is (= ["type"]
(get-in defs [:file-data-offload-bytes ::mdef/labels])))
(t/is (= :counter
(get-in defs [:file-data-offload-bytes ::mdef/type])))
(t/is (= "penpot_file_data_offload_timing_ms"
(get-in defs [:file-data-offload-timing ::mdef/name])))
(t/is (= ["result"]
(get-in defs [:file-data-offload-timing ::mdef/labels])))
(t/is (= :histogram
(get-in defs [:file-data-offload-timing ::mdef/type])))
(t/is (= [1 10 50 100 500 1000 5000 10000 30000 60000 300000]
(get-in defs [:file-data-offload-timing ::mdef/buckets])))))
(t/deftest success-emits-rows-and-bytes
(let [metrics (make-metrics)
profile (th/create-profile* 1)
file (create-file 1 profile)
result (offload/execute-offload-file-data (offload-cfg metrics)
{:file-id (:id file)})]
(t/is (pos? (:offloaded result)))
(t/is (= (double (:offloaded result))
(total-counter metrics :file-data-offload-rows)))
(t/is (= (double (:bytes result))
(total-counter metrics :file-data-offload-bytes)))
(t/is (pos? (counter-value metrics :file-data-offload-rows ["main"])))
(t/is (pos? (total-counter metrics :file-data-offload-rows)))))
(t/deftest skip-records-skip-and-nothing-else
(let [durations (volatile! [])
rows (volatile! [])
bytes (volatile! [])]
(with-redefs [metrics/record-offload-duration (fn [_ result _] (vswap! durations conj result) nil)
metrics/record-offload-rows (fn [_ type amount] (vswap! rows conj [type amount]) nil)
metrics/record-offload-bytes (fn [_ type amount] (vswap! bytes conj [type amount]) nil)]
(let [result (offload/execute-offload-file-data th/*system* {:file-id (uuid/next)})]
(t/is (= 0 (:offloaded result)))
(t/is (= 1 (:skipped result)))))
(t/is (= [:skip] @durations))
(t/is (empty? @rows))
(t/is (empty? @bytes))))
(t/deftest error-records-error-and-rethrows
(let [profile (th/create-profile* 1)
file (create-file 1 profile)
durations (volatile! [])
real-put @#'sto/put-object!]
(with-redefs [sto/put-object! (fn [_ _] (throw (ex-info "storage is down" {})))
metrics/record-offload-duration (fn [_ result _] (vswap! durations conj result) nil)]
(t/is (thrown? Exception
(offload/execute-offload-file-data th/*system* {:file-id (:id file)}))))
(t/is (= [:error] @durations))
;; Nothing was migrated: the whole file aborted.
(t/is (every? #(= "db" (:backend %)) (db-rows (:id file))))))
(t/deftest missing-metrics-raises
(let [params {::db/pool th/*pool*
::sto/storage (::sto/storage th/*system*)}]
(t/is (thrown? AssertionError
(ig/assert-key :app.tasks.offload-file-data/job-def params)))
(t/is (nil? (ig/assert-key :app.tasks.offload-file-data/job-def
(assoc params ::mtx/metrics (:app.metrics/metrics th/*system*)))))))
(t/deftest submit-validates-params-upfront
(let [cfg th/*system*]
(t/testing "valid params submit a durable job"
(t/is (uuid? (jobs/submit cfg {::jobs/name :offload-file-data
::jobs/params {:file-id (uuid/next)}}))))
(t/testing "invalid params fail at submit instead of burning retries"
(t/is (thrown? Exception
(jobs/submit cfg {::jobs/name :offload-file-data
::jobs/params {}})))
(t/is (thrown? Exception
(jobs/submit cfg {::jobs/name :offload-file-data
::jobs/params {:file-id "not-a-uuid"}}))))))
(t/deftest file-gc-without-flag-does-not-enqueue-offload
(t/is (not (contains? cf/flags :tiered-file-data-storage)))
(let [profile (th/create-profile* 1)
file (create-file 1 profile)]
(t/is (true? (th/run-task! :file-gc {:file-id (:id file)})))
(th/run-pending-jobs)
(t/testing "no offload job was enqueued"
(t/is (empty? (th/db-query :job {:name "offload-file-data"}))))
(t/testing "every row stays on hot storage"
(let [rows (db-rows (:id file))]
(t/is (pos? (count rows)))
(t/is (every? #(= "db" (:backend %)) rows))
(t/is (every? some? (map :data rows)))))))
(defn- update-file!
[& {:keys [profile-id file-id changes revn] :or {revn 0}}]
(let [params {::th/type :update-file
::rpc/profile-id profile-id
:id file-id
:session-id (uuid/random)
:revn revn
:vern 0
:features cfeat/supported-features
:changes changes}
out (th/command! params)]
(t/is (nil? (:error out)))
(:result out)))
(defn- add-page-with-rect
[profile file page-id shape-id]
(update-file!
:file-id (:id file)
:profile-id (:id profile)
:changes
[{:type :add-page
:name "test"
:id page-id}
{:type :add-obj
:page-id page-id
:id shape-id
:parent-id uuid/zero
:frame-id uuid/zero
:components-v2 true
:obj (cts/setup-shape
{:id shape-id
:name "rect"
:frame-id uuid/zero
:parent-id uuid/zero
:type :rect})}]))
(defn- get-file-data
[profile file-id]
(let [out (th/command! {::th/type :get-file
::rpc/profile-id (:id profile)
:id file-id})]
(t/is (nil? (:error out)))
(get-in out [:result :data])))
(t/deftest offloaded-file-reads-identically
(let [profile (th/create-profile* 1 {:is-active true})
file (create-file 1 profile)
page-id (uuid/next)
shape-id (uuid/next)]
(add-page-with-rect profile file page-id shape-id)
(let [before-bfc (:data (bfc/get-file th/*system* (:id file) {:realize? true}))
before-rpc (get-file-data profile (:id file))]
(t/is (some? (get-in before-bfc [:pages-index page-id :objects shape-id])))
(t/is (= before-bfc before-rpc))
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (pos? (:offloaded result)))
(t/is (every? #(= "storage" (:backend %)) (remove :deleted-at (db-rows (:id file))))))
(t/testing "direct read resolves cold storage transparently"
(t/is (= before-bfc
(:data (bfc/get-file th/*system* (:id file) {:realize? true})))))
(t/testing "rpc read resolves cold storage transparently"
(t/is (= before-rpc (get-file-data profile (:id file))))))))
(t/deftest snapshot-survives-offload
(let [profile (th/create-profile* 1 {:is-active true})
file (create-file 1 profile)
page-id (uuid/next)
shape-id (uuid/next)]
(add-page-with-rect profile file page-id shape-id)
(let [out (th/command! {::th/type :create-file-snapshot
::rpc/profile-id (:id profile)
:file-id (:id file)
:label "before-offload"})]
(t/is (nil? (:error out)))
(t/is (uuid? (get-in out [:result :id]))))
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (pos? (:offloaded result))))
(th/run-task! :storage-gc-touched {:skip-delay true})
;; 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)))))
(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)]
(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 (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})
file (create-file 1 profile)
page-id (uuid/next)
shape-id (uuid/next)]
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (pos? (:offloaded result))))
(let [main (th/db-get :file-data {:file-id (:id file) :type "main"})]
(t/is (= "storage" (:backend main)))
(t/is (nil? (:data main))))
(add-page-with-rect profile file page-id shape-id)
(t/testing "the new main row is back on hot storage"
(let [main (th/db-get :file-data {:file-id (:id file) :type "main"})]
(t/is (= "db" (:backend main)))
(t/is (bytes? (:data main)))))
(t/testing "the written content reads back"
(t/is (some? (get-in (get-file-data profile (:id file))
[:pages-index page-id :objects shape-id]))))))
(t/deftest export-import-roundtrip-after-offload
(let [profile (th/create-profile* 1 {:is-active true})
file (create-file 1 profile)
page-id (uuid/next)
shape-id (uuid/next)]
(add-page-with-rect profile file page-id shape-id)
(let [before (:data (bfc/get-file th/*system* (:id file) {:realize? true}))
_ (th/run-task! :offload-file-data {:file-id (:id file)})
output (tmp/tempfile :suffix ".zip")]
(v3/export-files!
(-> th/*system*
(assoc ::bfc/file-ids #{(:id file)})
(assoc ::bfc/export-type :detach-libraries)
(assoc ::bfc/output (io/output-stream output))))
(let [result (-> th/*system*
(assoc ::bfc/project-id (:default-project-id profile))
(assoc ::bfc/profile-id (:id profile))
(assoc ::bfc/team-id (:default-team-id profile))
(assoc ::bfc/input output)
(v3/import-files!))
imported (:data (bfc/get-file th/*system* (first (:file-ids result))
{:realize? true}))]
(t/is (= 1 (count (:file-ids result))))
(t/is (= (set (keys (:pages-index before)))
(set (keys (:pages-index imported)))))
(t/is (= (get-in before [:pages-index page-id :name])
(get-in imported [:pages-index page-id :name])))
(t/is (some? (get-in imported [:pages-index page-id :objects shape-id])))))))
(t/deftest deleted-offloaded-file-is-fully-purged
(let [storage (sto/resolve th/*system*)
profile (th/create-profile* 1 {:is-active true})
file (create-file 1 profile)
page-id (uuid/next)]
(add-page-with-rect profile file page-id (uuid/next))
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (pos? (:offloaded result))))
(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)))
(let [out (th/command! {::th/type :delete-file
::rpc/profile-id (:id profile)
:id (:id file)})]
(t/is (nil? (:error out))))
(th/run-pending-jobs)
(let [res (binding [ct/*clock* (ct/fixed-clock (ct/in-future {:days 8}))]
(th/run-task! :objects-gc {}))]
(t/is (pos? (:processed res))))
(t/testing "every file data row is gone"
(t/is (empty? (db-rows (:id file)))))
;; The touches above landed 8 days in the future, so the touched
;; collector needs a clock past them plus its deletion delay.
(let [res (binding [ct/*clock* (ct/fixed-clock (ct/in-future {:days 9}))]
(th/run-task! :storage-gc-touched {}))]
(t/is (pos? (:delete res))))
(t/testing "every referenced storage object is reclaimed"
(let [objects (mapv #(sto/get-object storage %) ref-ids)]
(t/is (every? nil? objects)))))))
(t/deftest file-gc-with-stale-revn-enqueues-nothing
(let [profile (th/create-profile* 1)
file (create-file 1 profile)
before (db-rows (:id file))
stale (inc (or (:revn file) 0))]
(t/is (not (th/run-task! :file-gc {:file-id (:id file) :revn stale})))
(th/run-pending-jobs)
(t/testing "no offload job was enqueued"
(t/is (empty? (th/db-query :job {:name "offload-file-data"}))))
(t/testing "every row stays on hot storage"
(let [after (db-rows (:id file))]
(t/is (= (count before) (count after)))
(t/is (every? #(= "db" (:backend %)) after))))))
(t/deftest concurrent-edit-and-offload-stay-coherent
(let [profile (th/create-profile* 1 {:is-active true})
file (create-file 1 profile)
page-1 (uuid/next)
shape-1 (uuid/next)
page-2 (uuid/next)
shape-2 (uuid/next)]
(add-page-with-rect profile file page-1 shape-1)
(let [locked (promise)
release (promise)
holder (future
(db/tx-run! th/*system*
(fn [{:keys [::db/conn]}]
(db/exec-one! conn ["SELECT id FROM file WHERE id = ? FOR UPDATE" (:id file)])
(deliver locked true)
@release
:held)))
_ (t/is (= true (deref locked 10000 ::timeout)))
updater (future
(add-page-with-rect profile file page-2 shape-2))]
(try
;; Give the updater time to block on the held row lock.
(th/sleep 500)
(t/is (not (realized? updater)))
(t/testing "offload skips while the row is locked"
(let [result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (= 0 (:offloaded result)))
(t/is (= 1 (:skipped result)))))
(finally
(deliver release true)))
(t/is (not= ::timeout (deref holder 10000 ::timeout)))
(t/is (not= ::timeout (deref updater 30000 ::timeout))))
(t/testing "the blocked edit won as a whole"
(t/is (some? (get-in (get-file-data profile (:id file))
[:pages-index page-2 :objects shape-2]))))
(t/testing "a later offload migrates the new bytes, never stale ones"
(let [current (get-file-data profile (:id file))
result (th/run-task! :offload-file-data {:file-id (:id file)})]
(t/is (pos? (:offloaded result)))
(t/is (= current (get-file-data profile (:id file))))))))
(t/deftest partial-failure-leaves-reclaimable-orphans
(let [profile (th/create-profile* 1)
file (create-file 1 profile)
_ (t/is (>= (count (db-rows (:id file))) 2))
calls (volatile! 0)
orphans (volatile! [])
real-put @#'sto/put-object!
mock (fn [storage params]
(if (= (:file-id params) (:id file))
(let [n (vswap! calls inc)]
(if (= 1 n)
(let [object (real-put storage params)]
(vswap! orphans conj (:id object))
object)
(throw (ex-info "storage is down" {}))))
(real-put storage params)))]
(with-redefs [sto/put-object! mock]
(t/is (thrown? Exception
(th/run-task! :offload-file-data {:file-id (:id file)}))))
(t/testing "the aborted file keeps every row on hot storage"
(let [rows (db-rows (:id file))]
(t/is (every? #(= "db" (:backend %)) rows))
(t/is (every? some? (map :data rows)))))
(t/testing "the orphaned blob is reclaimed once old enough"
(t/is (= 1 (count @orphans)))
(let [storage (sto/resolve th/*system*)]
(t/is (some? (sto/get-object storage (first @orphans))))
(let [res (binding [ct/*clock* (ct/fixed-clock (ct/in-future {:hours 3}))]
(th/run-task! :storage-gc-touched {}))]
(t/is (pos? (:delete res))))
(t/is (nil? (sto/get-object storage (first @orphans))))))))