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

404 lines
18 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.binfile-jobs-test
"The binfile work of a job: the shared adapter that runs it with its
progress reported as job events, and the two job-defs that expose it."
(:require
[app.binfile.common :as bfc]
[app.binfile.jobs :as bfj]
[app.binfile.v3 :as v3]
[app.common.time :as ct]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.jobs :as jobs]
[app.jobs.storage :as js]
[app.rpc.commands.teams :as teams]
[app.storage :as sto]
[app.storage.tmp :as tmp]
[app.util.events :as events]
[backend-tests.helpers :as th]
[clojure.java.io :as jio]
[clojure.test :as t]
[datoteka.fs :as fs]
[datoteka.io :as io]))
(t/use-fixtures :once th/state-init)
(t/use-fixtures :each th/database-reset)
(def ^:private fixture
"A real penpot export, the same fixture the binfile tests read."
"backend_tests/test_files/svg-attrs-camel-case.penpot")
(defn- fixture-path
[]
(-> fixture io/resource jio/file))
(defn- import-fixture!
"A file in the default project of the profile, imported from the
fixture through the core."
[profile]
(-> 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 (fixture-path))
(v3/import-files!)))
(defn- make-job!
"A job row as the substrate writes it: running, owned by a profile and
holding a resource when the test needs one."
[profile-id resource-id]
(let [id (uuid/next)]
(th/db-insert! :job {:id id
:name "export-binfile"
:tenant (cf/get :tenant)
:queue "binfile"
:params (db/json {})
:priority 100
:max-retries 0
:retry-num 0
:status "running"
:profile-id profile-id
:resource-id resource-id
:scheduled-at (ct/now)
:created-at (ct/now)
:modified-at (ct/now)})
id))
(defn- job-cfg
"The system cfg as the runner hands it to a handler. The job id is NOT
bound here: the adapter takes it from the context, because the progress
bridge runs on a thread of its own."
[]
th/*system*)
(defn- job-context
[job-id]
(jobs/make-context (jobs/get-job th/*system* job-id)))
(defn- progress-events
"The progress events of a job, oldest first, with decoded payloads."
[job-id]
(->> (th/db-exec! ["SELECT payload FROM job_event
WHERE job_id = ? AND kind = 'progress'
ORDER BY created_at ASC, id ASC"
job-id])
(mapv #(jobs/decode-progress (:payload %)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ADAPTER
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(t/deftest export-through-the-adapter-produces-the-artifact
(let [profile (th/create-profile* 1)
file-id (first (:file-ids (import-fixture! profile)))
job-id (make-job! (:id profile) nil)
output (tmp/tempfile* :suffix ".penpot")]
(bfj/export-files (job-cfg) (job-context job-id)
{:ids #{file-id}
:export-type :detach-libraries
:output output})
(t/testing "the artifact is a penpot file with its manifest"
(t/is (fs/exists? output))
(t/is (= [file-id] (mapv :id (:files (v3/get-manifest th/*system* output))))))
(t/testing "the progress of the core became milestones of the job"
(let [events (progress-events job-id)]
(t/is (pos? (count events)))
(t/is (every? keyword? (map :stage events)))
(t/testing "the first one is the file in course, with its position"
(let [event (first events)]
(t/is (= :files (:stage event)))
(t/is (= {:current 1 :total 1} (get-in event [:counters :files])))))
(t/testing "and nothing else: the event is the stage and the counters"
(t/is (every? #(<= (count (keys %)) 2) events)))))))
(t/deftest import-through-the-adapter-imports-the-package
(let [profile (th/create-profile* 1)
team (teams/get-team th/*system*
:profile-id (:id profile)
:project-id (:default-project-id profile))
staged (js/put-resource th/*system* (:id profile)
{:content (sto/content (fixture-path))
:filename "package.penpot"
:mtype "application/zip"})
job-id (make-job! (:id profile) (:resource-id staged))
context (job-context job-id)
result (bfj/import-files (job-cfg) context
{:profile-id (:id profile)
:project-id (:default-project-id profile)
:team team
:name "imported"
:input (js/load-input th/*system* context)
:version 3})]
(t/testing "the package is imported in the destination project"
(t/is (= 1 (count (:file-ids result)))))
(t/testing "the job reported its progress"
(t/is (pos? (count (progress-events job-id)))))))
(t/deftest the-adapter-composes-a-milestone-per-tap
(let [profile (th/create-profile* 1)
file-id (first (:file-ids (import-fixture! profile)))
job-id (make-job! (:id profile) nil)
reports (atom [])]
;; the substrate throttles the durable events, so the whole stream of
;; milestones is only visible with the writes intercepted
(with-redefs [jobs/heartbeat (fn [_cfg & {:as options}]
(swap! reports conj (:progress options))
1)]
(bfj/export-files (job-cfg) (job-context job-id)
{:ids #{file-id}
:export-type :detach-libraries
:output (tmp/tempfile* :suffix ".penpot")}))
(t/testing "the file opens the run with its position"
(let [event (first @reports)]
(t/is (= :files (:stage event)))
(t/is (= {:current 1 :total 1} (get-in event [:counters :files])))))
(t/testing "the stages inside the file carry it as context, with their own counter"
(let [event (first (filter #(= :pages (:stage %)) @reports))]
(t/is (= {:current 1 :total 1} (get-in event [:counters :files])))
(t/is (pos? (get-in event [:counters :pages :current])))
(t/is (pos? (get-in event [:counters :pages :total])))))
(t/testing "a stage outside a file carries no file context"
(let [events (filter #(= :storage-objects (:stage %)) @reports)]
(t/is (pos? (count events)))
(t/is (every? #(nil? (get-in % [:counters :files])) events))))
(t/testing "and every milestone is a stage and its counters, and nothing else"
(t/is (every? #(<= (count (keys %)) 2) @reports)))))
(t/deftest a-tap-carries-the-outer-counters-in-course
(let [profile (th/create-profile* 1)
file-id (first (:file-ids (import-fixture! profile)))
job-id (make-job! (:id profile) nil)
taps (atom [])]
;; the taps themselves, before the adapter turns them into events
(with-redefs [events/tap (fn [_type data] (swap! taps conj data))]
(bfj/export-files (job-cfg) (job-context job-id)
{:ids #{file-id}
:export-type :detach-libraries
:output (tmp/tempfile* :suffix ".penpot")}))
(t/testing "the tap that opens the file carries the outer counters"
(let [tap (first (filter #(= :file (:section %)) @taps))]
(t/is (= {:files {:current 1 :total 1}} (:outer-counters tap)))))
(t/testing "every tap inside the file carries them as context"
(let [inner (filter #(some? (:file-id %)) @taps)]
(t/is (pos? (count inner)))
(t/is (every? #(= {:files {:current 1 :total 1}} (:outer-counters %)) inner))))
(t/testing "a tap outside a file carries no outer counters"
(let [outside (filter #(= :storage-object (:section %)) @taps)]
(t/is (pos? (count outside)))
(t/is (every? #(nil? (:outer-counters %)) outside))))))
(t/deftest a-milestone-merges-outer-counters-with-its-own
(let [milestone @#'bfj/milestone]
(t/testing "outer scopes survive next to the counter of the stage"
(t/is (= {:stage :pages
:counters {:teams {:current 1 :total 1}
:projects {:current 2 :total 2}
:files {:current 1 :total 4}
:pages {:current 2 :total 5}}}
(milestone {:section :page
:current 2 :total 5
:outer-counters {:teams {:current 1 :total 1}
:projects {:current 2 :total 2}
:files {:current 1 :total 4}}}))))
(t/testing "a file tap needs no own counter, the outer one is enough"
(t/is (= {:stage :files
:counters {:files {:current 1 :total 2}}}
(milestone {:section :file
:outer-counters {:files {:current 1 :total 2}}}))))))
(t/deftest entering-a-file-keeps-the-counters-of-the-outer-scopes
(let [cfg {::v3/outer-counters {:teams {:current 1 :total 1}}}
cfg' (@#'v3/with-outer-counter cfg :files {:current 2 :total 4})]
(t/is (= {:teams {:current 1 :total 1}
:files {:current 2 :total 4}}
(::v3/outer-counters cfg')))))
(t/deftest the-import-adapter-composes-the-same-milestones
(let [profile (th/create-profile* 1)
team (teams/get-team th/*system*
:profile-id (:id profile)
:project-id (:default-project-id profile))
staged (js/put-resource th/*system* (:id profile)
{:content (sto/content (fixture-path))
:filename "package.penpot"
:mtype "application/zip"})
job-id (make-job! (:id profile) (:resource-id staged))
context (job-context job-id)
reports (atom [])]
(with-redefs [jobs/heartbeat (fn [_cfg & {:as options}]
(swap! reports conj (:progress options))
1)]
(bfj/import-files (job-cfg) context
{:profile-id (:id profile)
:project-id (:default-project-id profile)
:team team
:name "imported"
:input (js/load-input th/*system* context)
:version 3}))
(t/testing "the run opens with the manifest, which has no units to count"
(let [event (first @reports)]
(t/is (= :manifest (:stage event)))
(t/is (nil? (:counters event)))))
(t/testing "the file carries its position"
(let [event (first (filter #(= :files (:stage %)) @reports))]
(t/is (= {:current 1 :total 1} (get-in event [:counters :files])))))
(t/testing "a stage inside the file carries it as context, with its own counter"
(let [event (first (filter #(= :pages (:stage %)) @reports))]
(t/is (= {:current 1 :total 1} (get-in event [:counters :files])))
(t/is (pos? (get-in event [:counters :pages :current])))
(t/is (pos? (get-in event [:counters :pages :total])))))
(t/testing "and every milestone is a stage and its counters, and nothing else"
(t/is (every? #(<= (count (keys %)) 2) @reports)))))
(t/deftest a-job-that-is-no-longer-active-stops-the-work
(let [profile (th/create-profile* 1)
file-id (first (:file-ids (import-fixture! profile)))
job-id (make-job! (:id profile) nil)
context (job-context job-id)]
(t/testing "a running job is active"
(t/is (nil? (bfj/check-active th/*system* context))))
(t/testing "a cancelled job is not"
(th/db-update! :job {:status "cancelled"} {:id job-id})
(let [cause (try (bfj/check-active th/*system* context) nil
(catch Throwable raised raised))]
(t/is (= :interrupt (th/ex-type cause)))
(t/is (= "cancelled" (:status (ex-data cause))))))
(t/testing "so the export stops at its next progress point"
(let [output (tmp/tempfile* :suffix ".penpot")
cause (try
(bfj/export-files (job-cfg) context
{:ids #{file-id}
:export-type :detach-libraries
:output output})
nil
(catch Throwable raised raised))]
(t/is (= :interrupt (th/ex-type cause)))
(t/is (zero? (count (progress-events job-id))))))
(t/testing "a job that already completed is not active either"
(th/db-update! :job {:status "completed"} {:id job-id})
(let [cause (try (bfj/check-active th/*system* context) nil
(catch Throwable raised raised))]
(t/is (= :interrupt (th/ex-type cause)))))
(t/testing "and neither is a job row that is gone"
(th/db-force-delete :job {:id job-id})
(let [cause (try (bfj/check-active th/*system* context) nil
(catch Throwable raised raised))]
(t/is (= :interrupt (th/ex-type cause)))
(t/is (= "gone" (:status (ex-data cause))))))))
(t/deftest an-interrupted-beat-stops-the-core-at-its-tap
(let [steps (atom [])
context {:id (uuid/next)}
cause (ex-info "the job is no longer active"
{:type :interrupt :code :job-interrupted})]
(with-redefs [jobs/heartbeat (fn [& _] (throw cause))]
(let [raised (try (@#'bfj/with-progress th/*system* context
(fn []
(swap! steps conj :before)
;; the sink calls the beat
;; inline, so its interrupt
;; aborts the run here
(events/tap :progress {:section :file})
(swap! steps conj :after)))
nil
(catch Throwable stopped stopped))]
(t/is (= :interrupt (:type (ex-data raised))))
(t/is (= :job-interrupted (:code (ex-data raised))))
(t/is (= [:before] @steps)
"the core stopped at its next tap, the step after never ran")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; JOB-DEFS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(t/deftest the-binfile-jobs-follow-the-substrate-contract
(let [defs (::jobs/defs th/*system*)]
(t/testing "the export job produces the resource of a user job"
(let [def (jobs/get-job-def defs :export-binfile)]
(t/is (= :export (::jobs/family def)))
(t/is (= :output (::jobs/resource-role def)))
(t/is (fn? (::jobs/handler def)))))
(t/testing "the import job consumes the resource of the job"
(let [def (jobs/get-job-def defs :import-binfile)]
(t/is (= :import (::jobs/family def)))
(t/is (= :input (::jobs/resource-role def)))
(t/is (fn? (::jobs/handler def)))))
(t/testing "the params are a closed contract"
(let [def (jobs/get-job-def defs :export-binfile)
file-id (uuid/next)]
(t/is (true? ((::jobs/validator def)
{:file-ids #{file-id} :export-type :detach-libraries})))
(t/testing "a job id never travels in params"
(t/is (false? ((::jobs/validator def)
{:file-ids #{file-id} :export-type :detach-libraries
:job-id (uuid/next)}))))))))
(t/deftest the-export-handler-runs-through-the-registry
(let [profile (th/create-profile* 1)
file-id (first (:file-ids (import-fixture! profile)))
job-id (make-job! (:id profile) nil)
result (jobs/invoke (-> th/*system*
(assoc ::jobs/name :export-binfile)
(assoc ::jobs/params {:file-ids #{file-id}
:export-type :detach-libraries})
(assoc ::jobs/context (job-context job-id))))]
(t/testing "the handler answers with the completion envelope of the job"
(t/is (uuid? (:resource-id result)))
(t/is (some? (get-in result [:result :resource-uri]))))
(t/testing "the handler reported progress without knowing the job id"
(t/is (pos? (count (progress-events job-id)))))))
(t/deftest the-import-handler-runs-through-the-registry
(let [profile (th/create-profile* 1)
staged (js/put-resource th/*system* (:id profile)
{:content (sto/content (fixture-path))
:filename "package.penpot"
:mtype "application/zip"})
job-id (make-job! (:id profile) (:resource-id staged))
result (jobs/invoke (-> th/*system*
(assoc ::jobs/name :import-binfile)
(assoc ::jobs/params {:project-id (:default-project-id profile)
:name "imported"
:version 3})
(assoc ::jobs/context (job-context job-id))))]
(t/testing "the package of the job was imported"
(t/is (pos? (count (:file-ids result)))))
(t/testing "the handler reported progress without knowing the job id"
(t/is (pos? (count (progress-events job-id)))))))