penpot/backend/src/app/storage.clj
Andrey Antukh 9abcfebf60
✨ Run binfile import and export as durable jobs (#12056)
* ✨ Run binfile import and export as durable jobs

Import and export of `.penpot` files become durable jobs: two commands
create them and answer at once with a job id the caller follows, while
a worker of the `binfile` queue does the work. Each job keeps its own
ledger (owner, params frozen at creation, result, progress history and
an expiry), and the legacy commands and their SSE keep working.

Why: both operations ran inside the request. A large import held it
open for minutes, progress only existed while the caller kept the
stream open, and a client that went away left work nobody recorded,
retried or could cancel. The unified `job` substrate already dispatched,
leased, retried and logged events, but it had no user-facing ledger.

How:
- The substrate gains the pieces a user-facing job needs: optional
  job-def metadata (family, resource-role), an expiry on submit, the
  owner in the runner context, and job resources in their own bucket,
  written with the profile of the job and never deduplicated.
- One generic command per family: the caller names the job and sends its
  business params, the registry checks the family, the job-def decodes
  and validates, and permission and quota are checked first.
- Progress taps of the core become milestones of the job: a shared stage
  vocabulary with self-contained counters, throttled heartbeats, and an
  interrupt that stops the run inside its own transaction on cancel.
- Cancel reaches pending and running jobs from both modals, and closing
  a modal mid-run cancels the job it was following.
- The export re-checks the read permission at run time and answers with
  the package descriptor; the import re-checks the edition permission,
  runs the core in a transaction so a cancellation rolls it back, and
  releases the consumed package and its temporary copy.

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

* ♻️ Handle externally-cancelled binfile jobs end to end

The `cancelled` outcome of a job nobody followed no longer hangs its
screens: the data layers emit an explicit terminal message for it.

- The export emits `{:cancelled true}` per file and the modal paints a
  neutral cancelled row instead of success; a message without an
  artifact never reaches the download branch.
- The import closes every entry with a dedicated cancelled message
  through the existing error rendering, so the wizard completes.
- Both flows are pinned by data-layer tests, including the red state
  they replace.

Also in this change: the progress-contract comment of the management
API, early business-params validation in create-import-job (before
assembling the upload), a `release-resource` helper without fabricated
job ids, a note on the heartbeat write cost, and a memory cleanup.

AI-assisted-by: muse-spark-1.3-contributor

* ♻️ Pre-translate the cancelled import message

The cancelled entry of the import wizard carried its message as a key
for the UI to translate, which needed a rehash marker comment. Like
its neighboring errors, it now translates eagerly in the data layer:
the literal call keeps rehash clean with no marker, and the tests
assert through the same call instead of the raw key.

AI-assisted-by: muse-spark-1.3-contributor

* ♻️ Move cancelled strings under generic labels keys

The dashboard-specific cancelled key never shipped: before use it moves
under `labels.*` next to the generic strings both flows already use,
with Spanish translations following the established wording.

AI-assisted-by: muse-spark-1.3-contributor

* ✨ Add minor improvements

* ♻️ Rename export job command to create-export-binfile-job

Export now has one command per job type, the shape the :export-assets
command needs: create-export-binfile-job freezes exactly the
:export-binfile job, so :name no longer travels in the body and only
:params does. Import keeps the generic envelope.

submit-job reads the queue from the job-def metadata ::jobs/queue-name
(falling back to :binfile), read by the command and never by the
substrate, so a job-def can route its work to another queue without a
change in the command.

The rename reaches the frontend and the tests: the binfile export is
asked for under its own name, and the exporter service keeps
create-export-job.

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

* ✨ Polish the import and export status rows

The status row of a file already carries what the file is doing, so the
generic "Uploading file…"/"Downloading file…" lines are gone: the
import wizard drops its own (the export one went with the jobs
refactor), along with the now-unused style.

In the export, every file is queued up front, even the ones whose job
is created only after the previous one is over, and a file stays queued
until its first milestone: a worker picking the job up no longer ends
the queue. The queued text is a step smaller than the milestone.

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

* 🐛 Show the cancelled export and fix the import error

The cancelled export was unreachable: mark-file-cancelled sets :loading
false and the label lived inside the loading branch, so a cancelled
file only painted a neutral notification. The terminal state now
carries the label, and the export flags lose the `?` suffix
(predicates keep it; a data prop is not a question).

The import wizard rendered (:error entry) through tr, but every
producer writes user-facing text (a hint or a translated label), never
a key: it renders the text as-is now, and the dynamic-key ignores and
the stale comment are gone.

The total-text-limit comment no longer references the 200MiB it
replaced; the value is 500MiB in develop already.

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

* ♻️ Reflect the real job params in the creation commands

The creation commands declared their params as an open empty map, so the
RPC contract and the generated docs said nothing about them. Each command
now imports the schema from the job namespace
(`export-binfile/schema:params`, `import-binfile/schema:create-params`),
and the RPC validates the business params before the command runs. The
job-def still owns the params and re-validates the assembled ones at run
time. The commands no longer decode the params again: the RPC did it.

Import joins export as one command per job type: `create-import-job`
becomes `create-import-binfile-job`, its body no longer carries `:name`
and the job-def is resolved by name like export's. Its creation schema
keeps the version optional, because the command reads it from the package
header when the caller does not say it, and fills the manifest metadata
kept for audit.

A version out of range is now refused by the schema (`:params-validation`)
instead of the command's own `:unsupported-version` check, which is gone.

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

* 🐛 Stop the test system from running job runners

The test system is main/system-config plus main/worker-config with a
few components dissoc'ed. The runners of default, webhook and cron were
listed by hand; the binfile runner added with the durable binfile jobs
was not, so a real penpot/job-runner/binfile/0 thread ran during the
whole suite.

That runner races the tests that drive the loop by hand (run-batch plus
run-worker-loop): it takes the job the test just dispatched and
completes it, and the test then reads a state it did not produce. That
is the reported flake of binfile-jobs-integration-test, whose middle
assertion waits for a runner of another queue to not take the job. It
only reproduced in CI: in the devenv PENPOT_TENANT makes the tenant
baked into main/worker-config differ from the one the test builds, so
the two used different queue keys locally.

Drop every [<profile> :app.worker/runner] by key shape instead of
listing the known queues, so a new queue cannot bring the race back.

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

* ✨ Upload the package one chunk at a time and as a percentage

The upload milestone counts chunks, not units of work, so the row wrote
"Uploading the package 3/9" over a file the user had uploaded once: it
read as if nine packages were on their way. Write the stage as a
percentage of the file instead ("Uploading file… (33%)"), and make the
English text of the stage say file, not package.

The chunks also go one at a time now (concat-all instead of merge-all
with two in flight), so the percentage moves in a straight line instead
of jumping. upload-blob-chunked is the generic uploader, so media and
font uploads become sequential too.

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

* 🌐 Complete the Spanish catalogue

es.po was 25 keys short of en.po: the 15 that the durable binfile jobs
introduced (14 jobs.progress.stage.* and labels.queued) plus 10 gaps
that predate them (errors.connection-error, errors.save-retrying, the
find shortcuts, workspace.header.retrying,
workspace.tokens.stroke-width and the mcp session labels).

sync -l es then sorts the entries, syncs the #: comments from en and
drops the 7 dashboard.import.progress.* keys en no longer has. The
msgid sets of en and es are now identical (0 missing, 0 extra).

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

* ♻️ Move the job status keys into the jobs namespace

The three status words the durable import and export rows render were
filed under labels.*, next to the generic labels bucket, while their
progress stages live under jobs.progress.stage.*: the strings of one
feature sat in two places.

Rename them so the whole job vocabulary is one namespace:

  labels.queued           -> jobs.queued
  labels.export-cancelled -> jobs.export-cancelled
  labels.import-cancelled -> jobs.import-cancelled

No other locale has these keys yet, so the rename costs no translation.
The convention (a key names the feature that renders it; labels.* holds
the generic reusable words) is written down in the frontend/translations
memory.

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

* 🔥 Remove the translation keys nothing references

Six keys of en.po (and of es.po, which now mirrors it) have no (tr ...)
call site left in frontend/src or common/src, and no literal reference
either:

  labels.uploading-file    a duplicate of jobs.progress.stage.upload
                           since the upload stage says "Uploading file…"
  labels.downloading-file  dead since the durable jobs replaced the old
                           import and export progress rows
  inspect.attributes.stroke.alignment.center
  inspect.attributes.stroke.alignment.inner
  inspect.attributes.stroke.alignment.outer
  workspace.toolbar.mcp-connect-here

The first two are leftovers of the durable binfile jobs, the other four
predate them. Both catalogues keep an identical msgid set afterwards.

AI-assisted-by: deepseek-v4.1-flash
2026-10-07 11:52:48 +02:00

418 lines
14 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 app.storage
"Objects storage abstraction layer."
(:refer-clojure :exclude [resolve])
(:require
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.logging :as l]
[app.common.schema :as sm]
[app.common.time :as ct]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.metrics :as mtx]
[app.storage.fs :as sfs]
[app.storage.impl :as impl]
[app.storage.s3 :as ss3]
[app.storage.schema :as stsch]
[cuerdas.core :as str]
[datoteka.fs :as fs]
[integrant.core :as ig])
(:import
java.io.InputStream))
(defn get-legacy-backend
[]
(when-let [name (cf/get :assets-storage-backend)]
(l/wrn :hint "using deprecated configuration, please read 2.11 release notes"
:href "https://github.com/penpot/penpot/releases/tag/2.11.0")
(case name
:assets-fs :fs
:assets-s3 :s3
nil)))
(def default-bucket
stsch/default-bucket)
(def tempfile-bucket
"Bucket name for temporary file uploads (10-minute expiry)."
stsch/tempfile-bucket)
(def upload-session-bucket
"Bucket name for chunked-upload chunks."
stsch/upload-session-bucket)
(def job-resource-bucket
"Bucket for storage objects referenced by job.resource_id (the
unified jobs substrate): transient artifacts owned by their job row,
reclaimed by storage-gc-touched (via the jobs GC touch) once no job
row references them anymore."
stsch/job-resource-bucket)
(def valid-buckets
stsch/metadata-buckets)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Storage Module State
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private schema:backends
[:map-of :keyword
[:maybe
[:or ::ss3/backend ::sfs/backend]]])
(def ^:private valid-backends?
(sm/validator schema:backends))
(def ^:private schema:storage
[:map {:title "storage"}
[::backends schema:backends]
[::backend [:enum :s3 :fs]]
[::mtx/metrics ::mtx/metrics]
::db/pool])
(def valid-storage?
(sm/validator schema:storage))
(sm/register! ::storage schema:storage)
(defmethod ig/assert-key ::storage
[_ params]
(assert (db/pool? (::db/pool params)) "expected valid database pool")
(assert (valid-backends? (::backends params)) "expected valid backends map"))
(defmethod ig/init-key ::storage
[_ {:keys [::backends ::db/pool] :as cfg}]
(let [backend (or (get-legacy-backend)
(cf/get :objects-storage-backend)
:fs)
backends (d/without-nils backends)]
(l/dbg :hint "initialize"
:default (d/name backend)
:available (str/join "," (map d/name (keys backends))))
(-> (d/without-nils cfg)
(assoc ::backends backends)
(assoc ::backend backend)
(assoc ::db/pool pool))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Database Objects
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-metadata
[params]
(reduce-kv (fn [res k _]
(if (qualified-keyword? k)
(dissoc res k)
res))
params
params))
;; Matches both metadata encodings while Transit rows still exist. The
;; UNION ALL keeps each branch indexable: migration 0068 covers the legacy
;; "~:" keys and 0156 covers the plain JSON keys. Phase 3 drops the legacy
;; branch once no "~:" rows remain.
(def ^:private sql:get-database-object-by-hash
"(
select * from storage_object
where (metadata->>'~:hash') = ?
and (metadata->>'~:bucket') = ?
and backend = ?
and deleted_at is null
and status = 'valid'
limit 1
) union all (
select * from storage_object
where (metadata->>'hash') = ?
and (metadata->>'bucket') = ?
and backend = ?
and deleted_at is null
and status = 'valid'
limit 1
) limit 1")
;; NOTE: metadata is left encoded; row->storage-object is responsible for
;; decoding it.
(defn- get-database-object-by-hash
[connectable backend bucket hash]
(let [backend (name backend)]
(db/exec-one! connectable [sql:get-database-object-by-hash
hash bucket backend
hash bucket backend])))
(defn- promote-object!
[storage object]
(let [ds (db/get-connectable storage)
res (-> (db/update! ds :storage-object
{:status "valid"}
{:id (:id object)}
{::db/return-keys false})
(db/get-update-count))]
(when-not (pos? res)
;; The pending row disappeared while the blob was being written
;; (e.g. reclaimed by :storage-pending-gc); make it observable.
(l/wrn :hint "unable to promote storage object, pending row not found"
:id (str (:id object))))
res))
(defn row->storage-object [res]
(let [mdata (or (some-> (:metadata res) (stsch/decode-metadata)) {})]
(impl/storage-object
(:id res)
(:size res)
(:created-at res)
(:deleted-at res)
(:touched-at res)
(keyword (:backend res))
mdata)))
(def ^:private sql:get-storage-object
"SELECT *
FROM storage_object
WHERE id = ?
AND (deleted_at IS NULL)
AND status = 'valid'")
(defn- get-database-object
[conn id]
(some-> (db/exec-one! conn [sql:get-storage-object id])
(row->storage-object)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; API
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn object->relative-path
[{:keys [id] :as obj}]
(impl/id->path id))
(defn file-url->path
[url]
(when url
(fs/path (java.net.URI. (str url)))))
(dm/export impl/content)
(dm/export impl/wrap-with-hash)
(dm/export impl/object?)
(defn- emit-op!
"Record a logical storage operation. Recording never fails: metrics
must not change storage behavior."
([storage op bucket]
(emit-op! storage op bucket nil))
([storage op bucket object]
(mtx/run! (::mtx/metrics storage)
:id :storage-operations :inc 1
:labels [op
(mtx/label bucket "unknown")
(mtx/label (or (some-> object :backend) (::backend storage))
"unknown")])))
(defn- emit-dedup!
"Record a deduplication outcome. Recording never fails."
[storage result bucket]
(mtx/run! (::mtx/metrics storage)
:id :storage-dedup :inc 1
:labels [(name result) (mtx/label bucket "unknown")]))
(defn get-object
[storage id]
(assert (valid-storage? storage))
(let [ds (db/get-connectable storage)]
(get-database-object ds id)))
(defn put-object!
"Creates a new object with the provided content."
[{:keys [::backend ::db/pool] :as storage}
{:keys [::content ::expired-at ::touched-at ::touch] :as params}]
(assert (valid-storage? storage))
(assert (impl/content? content) "expected an instance of content")
(let [id (or (::id params) (uuid/random))
mdata (cond-> (get-metadata params)
(satisfies? impl/IContentHash content)
(assoc :hash (impl/get-hash content)))
touched-at (if touch
(or touched-at (ct/now))
touched-at)
backend' (impl/resolve-backend storage backend)
bucket (:bucket mdata)
;; `job-resource` objects belong to one profile, so they are
;; never shared: a dedup hit would hand the artifact of one
;; profile to the job of another.
dedupable? (and (::deduplicate? params)
(:hash mdata)
(some? bucket)
(not= tempfile-bucket bucket)
(not= upload-session-bucket bucket)
(not= job-resource-bucket bucket))
hit (when dedupable?
(get-database-object-by-hash pool backend bucket (:hash mdata)))]
;; NOTE: for now we don't reuse the deleted objects, but in futute
;; we can consider reusing deleted objects if we found a duplicated
;; one and is marked for deletion but still not deleted.
;; PHASE 1: deduplication lookup (see `dedupable?` and `hit` above).
(if-some [hit hit]
;; PHASE 2: an existing reference is found: reuse or repair it.
;; The `exists` op is emitted only after a successful probe so every
;; count stays paired with its `hit`/`repair` outcome.
(if (impl/exists-object? backend' hit)
;; PHASE 2a: healthy reference. Optionally refresh touched_at
;; and reuse the object as it is.
(do
(emit-op! storage "exists" bucket)
(emit-dedup! storage :hit bucket)
(when touch
(db/update! pool :storage-object
{:touched-at touched-at}
{:id (:id hit)}
{::db/return-keys false}))
(row->storage-object (cond-> hit touch (assoc :touched-at touched-at))))
;; PHASE 2b: the referenced blob is missing (a stale/broken row).
;; Repair the reference in place: rewrite the incoming content
;; under the same id, restoring the blob for all existing
;; references to it. If the write fails, the exception propagates
;; and the row stays live and valid, so a later matching upload
;; retries the heal.
(let [object (row->storage-object hit)]
(l/wrn :hint "blob not found on reusing storage object"
:id (:id object)
:backend (name backend))
(impl/put-object backend' object content)
(emit-op! storage "exists" bucket)
(emit-op! storage "repair" bucket)
(emit-dedup! storage :repair bucket)
(promote-object! storage object)
object))
;; PHASE 3: no dedup hit: create a fresh object. The row is
;; inserted in 'pending' state so it is not visible to the normal
;; lifecycle (dedup, gc, reads) until the blob has been written
;; and the object promoted to 'valid'.
(let [row (db/insert! pool :storage-object
{:id id
:size (impl/get-size content)
:backend (name backend)
:metadata (stsch/encode-metadata mdata)
:deleted-at expired-at
:touched-at touched-at
:status "pending"})
object (row->storage-object row)]
(impl/put-object backend' object content)
(emit-op! storage "put" bucket)
(emit-dedup! storage (if dedupable? :miss :skip) bucket)
(promote-object! storage object)
object))))
(defn touch-object!
"Mark object as touched. Takes the object id (UUID). The metric labels
come from the updated row itself (RETURNING); no row, no metric."
[storage id]
(assert (valid-storage? storage))
(let [ds (db/get-connectable storage)
res (db/update! ds :storage-object
{:touched-at (ct/now)}
{:id id}
{::db/return-keys [:id :backend :metadata]})]
(when-some [object (some-> res row->storage-object)]
(emit-op! storage "touch" (-> object meta :bucket) object))
(some? res)))
(defn get-object-data
"Return an input stream instance of the object content."
^InputStream
[storage object]
(assert (valid-storage? storage))
(when (or (nil? (:expired-at object))
(ct/is-after? (:expired-at object) (ct/now)))
(let [result (-> (impl/resolve-backend storage (:backend object))
(impl/get-object-data object))]
(emit-op! storage "get-data" (-> object meta :bucket) object)
result)))
(defn get-object-bytes
"Returns a byte array of object content."
[storage object]
(assert (valid-storage? storage))
(when (or (nil? (:expired-at object))
(ct/is-after? (:expired-at object) (ct/now)))
(let [result (-> (impl/resolve-backend storage (:backend object))
(impl/get-object-bytes object))]
(emit-op! storage "get-bytes" (-> object meta :bucket) object)
result)))
(defn get-object-url
([storage object]
(get-object-url storage object nil))
([storage object options]
(assert (valid-storage? storage))
(when (or (nil? (:expired-at object))
(ct/is-after? (:expired-at object) (ct/now)))
(-> (impl/resolve-backend storage (:backend object))
(impl/get-object-url object options)))))
(defn get-object-path
"Get the Path to the object. Only works with `:fs` type of
storages."
[storage object]
(assert (valid-storage? storage))
(let [backend (impl/resolve-backend storage (:backend object))]
(when (and (= :fs (::type backend))
(or (nil? (:expired-at object))
(ct/is-after? (:expired-at object) (ct/now))))
(-> (impl/get-object-url backend object nil) file-url->path))))
(defn del-object!
"Mark the object as deleted (soft delete: the backend content is
removed by the GC). Takes the object id (UUID). Only a live row
(deleted_at IS NULL) is deleted, so a repeated call is a no-op that
returns false. The metric labels come from the updated row itself
(RETURNING); no row, no metric."
[storage id]
(assert (valid-storage? storage))
(let [ds (db/get-connectable storage)
res (db/update! ds :storage-object
{:deleted-at (ct/now)}
["id = ? AND deleted_at IS NULL" id]
{::db/return-keys [:id :backend :metadata]})]
(when-some [object (some-> res row->storage-object)]
(emit-op! storage "del" (-> object meta :bucket) object))
(some? res)))
(dm/export impl/calculate-hash)
(dm/export impl/get-hash)
(dm/export impl/get-size)
(defn configure
[storage connection]
(assert (db/connection? connection))
(assert (valid-storage? storage))
(assoc storage ::db/conn connection))
(defn resolve
"Resolves the storage instance with preconfigured backend. You can
specify to reuse the database connection from provided
cfg/system (default false)."
[cfg & {:as opts}]
(let [storage (::storage cfg)]
(if (::db/reuse-conn opts false)
(configure storage (db/get-connection cfg))
storage)))