Merge remote-tracking branch 'origin/staging' into develop

This commit is contained in:
Andrey Antukh 2026-11-24 22:48:49 +01:00
commit d94518ec41
36 changed files with 1715 additions and 112 deletions

View File

@ -47,8 +47,10 @@ hard blocker: fix the message and re-check it before reporting success.
```
If it fails, amend the message (`git commit --amend`) until it passes. Do
not finish with a failing checker.
5. The `AI-assisted-by` trailer value is provided by the calling context — use
it verbatim.
5. When adding an `AI-assisted-by` trailer, use the canonical model ID from
the calling context as a bare lowercase slug (for example,
`gpt-6.1-terra`), without a provider prefix or display name. Do not guess
the ID.
## Constraints

View File

@ -38,7 +38,9 @@ the user agrees.
`:emoji:` title, the `**Note:**` line, and the `## What` / `## Why` /
`## How` sections. Derive them from the commits and the issue body when
there is one. Repeat the `AI-assisted-by:` trailer once per model that
worked on the branch. Put the body in a temp file to avoid shell quoting.
worked on the branch, using the bare canonical model ID under the rules in
`mem:workflow/creating-commits` (for example, `gpt-6.1-terra`). Put the
body in a temp file to avoid shell quoting.
2. Decide whether the PR resolves an issue. If it does, include `Closes
#NNNN` in the body for human readers and pass `--issue NNNN` so the
command creates the GitHub link. If the user's invocation says `no issue`
@ -67,6 +69,8 @@ error. Do not ask the user and do not add pre-flight checks for this case.
1. Identify the PR: the number given by the user, or `gh pr list --head
<branch>`.
2. Write the new title and/or body following `mem:workflow/creating-prs`.
Preserve each model attribution using the same canonical model ID rules
as in Open mode.
3. Apply and verify:
```bash

View File

@ -8,6 +8,7 @@
- Browser ingest derives the actor from the session, never the event. Public `x-client` can influence `:initiator`; it is not an authorization signal. On backend RPCs `:initiator` comes from the authenticated shared-key context or defaults to `"app"`. Trusted management ingest authenticates the service and accepts the actor it reports; that does not prove the remote business operation and the audit event committed together.
- `source` identifies the channel, not the outcome. A browser event can be lost on shutdown, overflow or failure; HTTP success can mean an ingest error was logged rather than rows persisted. Do not use missing browser events as evidence that an action did not happen. Avoid browser copies of backend actions unless the UI observes something distinct; respect `skip-audit?` on resumed gestures.
- `audit/submit` propagates failures. The RPC wrapper may emit **after** the business transaction commits, so a failed audit response does not prove the mutation rolled back. When explicitly submitting inside a transaction, the failure can roll back the mutation with the event. `audit/insert` alone writes full rows; it does not fan out.
- The `:import-binfile` job submits `import-binfile` from its terminal hook in the transaction that records `completed`, `failed` or `cancelled`. Its props explicitly select `project-id`, `name`, `version`, `generated-by` and `referer` from job params, then add `job-id`, `team-id`, `status` and completed file ids/count; new job params do not automatically reach audit. New jobs freeze `team-id` at creation and both creation and terminal events use it for webhook routing; older jobs without it resolve the current project team as fallback. A queued cancellation also emits it; dispatcher-side `aborted` does not. The hook has no request context and omits handler-only elapsed time and package size. Import files commit earlier, and the `create-file` events use a separate transaction after that commit: a later audit or terminal failure cannot roll the files back, and a cancellation that wins late can coexist with committed files. The `job-id` joins the outcome to the job-creation event.
- `props` describes the action, `context` describes capture. Do not put secrets in either, including on paths that bypass the RPC wrapper's partial sanitization. `:client-event-origin` on backend RPCs explains the UI entry point; it is not the browser event's `:event-origin` or a substitute for business fields.
## Projection contracts

View File

@ -2,6 +2,7 @@
- Start at `app.binfile.common` for shared domain configuration, `app.binfile.jobs` for the job adapter, `app.rpc.commands.jobs` for the public envelope, and `app.binfile.v1`/`app.binfile.v3` for the formats. For cross-module model changes see `mem:common/data-model-change-checklist`; for durable execution see `mem:backend/jobs`.
- Keep legacy RPC and job configuration aligned on frozen IDs, team features and import size limits. The import creation request is not the stored job params: the server can determine the format from the upload, and audit uses manifest metadata, not file contents.
- Import job creation freezes the project's `team-id` in its internal params while holding the project row lock and rechecking edit permission; the client cannot supply it. The import and `move-project` take the same row lock before checking team and permissions, so a move waits for an import and a queued job refuses to import after the project moves. The lock lasts through the import transaction; unrelated projects are independent. Jobs created before the field existed keep the old permission behavior and use the current project team as audit fallback. New creation and terminal audit events use the frozen team. Old workers with the former closed schema cannot process new params during a mixed-version rollout.
- Revalidate permissions when jobs run, not just when submitting: access can be revoked while queued. Import runs inside a transaction so an interruption cannot leave half a file. The job adapter stops on the heartbeat interrupt and checks again after the final tap; do not publish success if cancellation fell between the last tap and return. An upload not adopted by a job must be released; adopted import packages and temporary copies must be released on terminal outcomes.
- Keep the progress stage vocabulary shared across formats. Each tap carries its outer scopes, with no dependency on an earlier tap; throttling can drop intermediate events. Do not put source IDs or names into public progress. Normalize format-specific return shapes in the adapter rather than making the caller know the format.
- A v1 package can list a file twice (legacy export included libraries without deduping). Consume both objects of every entry to keep the stream aligned, but import and report the first occurrence only.

View File

@ -9,6 +9,7 @@
- A job-def closes over its own dependencies. A handler receives context and business params, never the runner cfg. A job-def must not reference `::jobs/defs` through Integrant: the registry already depends on the definitions. Don't add routing or retry state to public context; it belongs to dispatch or execution, not the job's business contract.
- `submit` joins the caller transaction because creation is part of the caller's work. Claim, retry and terminal transitions own their transactions because they report work the caller cannot roll back. A job must commit before an independent claimant can see it. A transition writes its event with the state change; a no-op writes neither event nor metric. Keep job foreign keys deferrable.
- A job-def can supply `::jobs/on-terminal`, called with the transition transaction cfg and a semantic job map after a successful `complete`, `fail` or `cancel`: `:status` is the terminal string, `:params` is decoded, `:result` is decoded for completion and `:error` is present for failure. Its writes and the transition commit together; a throw rolls both back. Dispatcher `aborted` sweeps do not call it. The import job uses the hook for its `import-binfile` audit event; the import and `create-file` writes are earlier independent transactions, so a terminal audit failure does not undo imported files. See `mem:audit-log`.
- Submit keys include tenant, name, queue and label; rely on the partial unique indexes, not a read-before-write check. `skip-if-active` excludes live exclusive jobs; dedupe discards a conflict with a `new` job; debounce refreshes that pending row and retains its ID. Use an explicit non-blank label for dedupe or debounce. Opted-in jobs do not conflict with plain jobs just because they share a label. Submit accepts at most one of these options.
- Cron claims its `scheduled_task` row with `FOR UPDATE SKIP LOCKED` to coordinate the tick while the transaction is open. The exclusive job insert prevents overlap across ticks and backends; the row lock alone cannot. Worker runners, dispatcher and cron do not start on a read-only pool.
- Postgres owns the lifecycle; Redis delivery is not proof of a claim. Dispatch and recovery must stay tenant-scoped. Lost scheduled jobs and expired running jobs are terminal, not requeued; sending them back to `new` can violate dedupe. Long-running work must heartbeat; a beat that finds a terminal or missing job raises an internal interruption, not a retryable failure. Progress can be throttled, so each milestone must make sense without the previous one.

View File

@ -2,6 +2,7 @@
- Start at `app.rpc.permissions` and the owning file, team, project and comment commands. Permission failures normally answer `:not-found` to avoid exposing resource existence. Invitation management deliberately answers `:validation` / `:insufficient-permissions` instead.
- File and project roles require live team membership; leaving or removing a member clears team-scoped roles. The organization-owner fallback grants read-only access without membership only for live resources. Soft-delete filtering in `db/get*` requires `deleted_at` in the selected columns. WebSocket rechecks depend on the same rules; see `mem:backend/websocket-subscriptions`.
- `move-project` locks its project row before resolving the source team, checking permissions and enumerating files. Binfile job creation and import take the same lock when freezing or validating the destination team; a move can wait for the whole import transaction, subject to database timeouts. This only serializes paths that take that lock, not every file creation or legacy import.
- Share-link authorization is page-scoped for comments, viewer bundles and file fragments. A view-only bundle includes only live components transitively referenced by the permitted output, including linked-library dependencies; do not derive those dependencies from excluded pages or deleted components. Root-level fragments are not authorized by a share link. Membership bundles have different scope.
- Invitation management is team-admin only; owner-role invitation tokens require the team owner. With `:admin-console`, `check-send-invitations-policy` gates changes and token issuance through a strict Nitrate lookup, but listing remains team-admin only. The policy lookup runs outside the DB transaction. For registration with an invitation see `mem:backend/auth-sso`.
- Comment checks include login state and file/team policy. Preserve share-link page checks before mutation and avoid bypassing existing permission helpers, including their not-found behavior. For webhook and audit emission see `mem:audit-log`.

View File

@ -48,8 +48,8 @@ that breaks them is wrong, even if the code is right.
- Exceptions inside the body (do not wrap these): `Signed-off-by:`, `Co-authored-by:`, `AI-assisted-by:` trailers, and lines carrying a URL.
**AI-assisted-by trailer rules:**
- Use only the model name, e.g. `mimo-v2.5`, `deepseek-v4-flash`
- Do NOT add prefixes like `opencode-go/` — use the bare model name
- Optional; when present, every trailer must use the bare canonical model ID as a lowercase slug, e.g. `gpt-6.1-terra`, `mimo-v2.5`, `deepseek-v4-flash`.
- Use lowercase ASCII letters and digits separated by single `-` or `.` characters; no provider prefix, display name, or guessed ID. `scripts/check-commit` checks the format, not whether the ID exists.
## Commit Type Emojis

View File

@ -77,6 +77,9 @@ PR descriptions follow this structure:
The "Note:" line is required at the top. Adjust if this is a manual (non-AI) PR.
When the PR requests a regular merge instead of a squash merge, its
`**Merge:**` line goes above the `**Note:**` line (see Merge Strategy).
For AI-assisted work, include one `AI-assisted-by:` trailer per model that
worked on the branch, using the canonical model ID rules in
`mem:workflow/creating-commits`. Preserve the attributions when updating a PR.
## Writing Principles

View File

@ -161,6 +161,11 @@
[::handler ::sm/fn]
[::decoder ::sm/fn]
[::validator ::sm/fn]
;; Runs in the winning complete/fail/cancel transaction with the cfg and
;; a terminal job map. Params and result are decoded, status is terminal,
;; and result or error is present only for its corresponding outcome.
;; A throw rolls the transition back; dispatcher aborts do not invoke it.
[::on-terminal {:optional true} ::sm/fn]
;; A result crosses a plain JSON column on its way out of the job, so a
;; uuid comes back as the text it is on disk and a uuid used as a map
;; key comes back as a keyword. A def that declares the schema of its
@ -567,6 +572,20 @@
(decode-json-col :result)
(decode-json-col :error)))
(defn- run-on-terminal
"Run the job definition's terminal hook in the transition transaction."
[cfg job terminal]
(when-let [job-def (get (get-defs cfg) (keyword (:name job)))]
(when-let [hook (::on-terminal job-def)]
(let [job (-> job
(dissoc :result :error)
(assoc :params (decode-params job-def (:params job)))
(merge terminal))
job (if (contains? terminal :result)
(update job :result #(decode-result job-def %))
job)]
(hook cfg job)))))
(defn- decode-result-of
"Decode the result of a row with the decoder of the job-def that owns it.
A kind the registry no longer knows (a retired job-def) answers with the
@ -1248,6 +1267,9 @@
(if (db/exec-one! conn [sql:complete-job (ct/now) (ct/now)
encoded resource-id job-id])
(do
(run-on-terminal tx-cfg job (cond-> {:status "completed"
:result result}
resource-id (assoc :resource-id resource-id)))
(insert-event tx-cfg
job-id "end" {:outcome "completed"})
(db/after-commit
@ -1264,7 +1286,7 @@
SET status='failed', modified_at=?, error=?
WHERE id=?
AND status IN ('running','retry')
RETURNING id")
RETURNING *")
(defn fail
"Mark a running job as failed and record the `end` event.
@ -1279,12 +1301,13 @@
affected rows."
[cfg job-id error]
(assert (mtx/instance cfg) "missing ::mtx/metrics on the jobs cfg")
(let [job (get-job cfg job-id)
encoded (db/json (check-job-error error))
(let [encoded (db/json (check-job-error error))
n (db/tx-run! (db/own-transaction cfg)
(fn [{:keys [::db/conn] :as tx-cfg}]
(if (db/exec-one! conn [sql:fail-job (ct/now) encoded job-id])
(if-let [job (some-> (db/exec-one! conn [sql:fail-job (ct/now) encoded job-id])
decode-row)]
(do
(run-on-terminal tx-cfg job {:status "failed" :error error})
(insert-event tx-cfg
job-id "end" {:outcome "failed"})
(db/after-commit
@ -1301,7 +1324,7 @@
SET status='cancelled', modified_at=?
WHERE id=?
AND status IN ('new','scheduled','retry','running')
RETURNING id")
RETURNING *")
(defn cancel
"Cancel a pending or running job (new/scheduled/retry/running) and
@ -1313,11 +1336,12 @@
and writes no event. Returns the number of affected rows."
[cfg job-id]
(assert (mtx/instance cfg) "missing ::mtx/metrics on the jobs cfg")
(let [job (get-job cfg job-id)
n (db/tx-run! (db/own-transaction cfg)
(let [n (db/tx-run! (db/own-transaction cfg)
(fn [{:keys [::db/conn] :as tx-cfg}]
(if (db/exec-one! conn [sql:cancel-job (ct/now) job-id])
(if-let [job (some-> (db/exec-one! conn [sql:cancel-job (ct/now) job-id])
decode-row)]
(do
(run-on-terminal tx-cfg job {:status "cancelled"})
(insert-event tx-cfg
job-id "end" {:outcome "cancelled"})
(db/after-commit

View File

@ -273,10 +273,20 @@
:filename "package.penpot"
:mtype "application/zip"})]
(try
(let [summary (get-job-summary cfg (submit-job cfg job-def :import-binfile params profile-id
:resource-id (:resource-id staged)))]
(let [{:keys [summary team-id]}
(db/tx-run! cfg
(fn [tx-cfg]
(let [project (projects/get-project-for-update tx-cfg project-id)
_ (projects/check-edition-permissions! tx-cfg profile-id project-id)
team-id (:team-id project)
params (assoc params :team-id team-id)
job-id (submit-job tx-cfg job-def :import-binfile params profile-id
:resource-id (:resource-id staged))]
{:summary (get-job-summary tx-cfg job-id)
:team-id team-id})))]
(with-meta summary
{::audit/props {:job-id (:id summary)
:team-id team-id
:generated-by (:generated-by manifest)
:referer referer}}))

View File

@ -419,6 +419,8 @@
- Permission exceptions if user lacks required permissions
- Team compatibility exceptions if teams are incompatible"
[{:keys [::db/conn] :as cfg} {:keys [profile-id team-id project-id] :as params}]
;; Lock before reading or validating; retain get-by-id's not-found behavior.
(proj/get-project-for-update cfg project-id)
(let [project (db/get-by-id conn :project project-id {:columns [:id :team-id]})
pids (->> (db/query conn :project {:team-id (:team-id project)} {:columns [:id]})
(map :id)

View File

@ -81,6 +81,12 @@
(def check-read-permissions!
(perms/make-check-fn has-read-permissions?))
(defn get-project-for-update
"Lock a project against concurrent updates for the caller's transaction."
[cfg project-id]
(db/exec-one! cfg ["SELECT id, team_id FROM project WHERE id = ? FOR NO KEY UPDATE"
project-id]))
;; --- QUERY: Get projects
(def ^:private sql:projects

View File

@ -12,13 +12,17 @@
[app.binfile.jobs :as bfj]
[app.binfile.v1 :as bf.v1]
[app.binfile.v3 :as bf.v3]
[app.common.data :as d]
[app.common.exceptions :as ex]
[app.common.schema :as sm]
[app.common.time :as ct]
[app.db :as db]
[app.jobs :as jobs]
[app.jobs.storage :as js]
[app.loggers.audit :as audit]
[app.loggers.webhooks :as-alias webhooks]
[app.metrics :as mtx]
[app.rpc :as-alias rpc]
[app.rpc.commands.projects :as projects]
[app.rpc.commands.teams :as teams]
[app.storage :as sto]
@ -30,6 +34,7 @@
format version and the manifest metadata kept for audit."
[:map {:title "import-binfile-params" :closed true}
[:project-id ::sm/uuid]
[:team-id {:optional true} ::sm/uuid]
[:name [:or [:string {:max 250}]
[:map-of ::sm/uuid [:string {:max 250}]]]]
[:version [:enum 1 3]]
@ -117,61 +122,111 @@
{:id project-id}
{::db/return-keys false}))
(defn- import-files
"Run the core inside a transaction, so a cancellation detected between
units rolls the whole import back, and check the result against its
schema inside that same transaction: a result the contract does not
accept rolls the import back instead of leaving half of a file
imported."
[cfg context params input]
(let [profile-id (:profile-id context)
project-id (:project-id params)]
(db/tx-run! cfg (fn [tx-cfg]
(let [project (projects/get-project-for-update tx-cfg project-id)
_ (bfj/check-active tx-cfg context)
_ (projects/check-edition-permissions! tx-cfg profile-id project-id)
team (teams/get-team tx-cfg :profile-id profile-id
:project-id project-id)]
(when (and (:team-id params)
(not= (:team-id params) (:team-id project)))
(ex/raise :type :validation
:code :import-team-changed
:hint "the destination project changed teams"))
;; the core joins this transaction: it is the one
;; that decides whether the whole import is kept or
;; rolled back
(-> (bfc/import-cfg tx-cfg {:profile-id profile-id
:project-id project-id
:team team
:name (:name params)
:input input})
(bfj/check-active context)
(bfj/run context
(fn [cfg]
(let [result (case (int (:version params))
1 (bf.v1/import-files! cfg)
3 (bf.v3/import-files! cfg)
(ex/raise :type :validation
:code :unsupported-version
:hint "unsupported binfile version"
:version (:version params)))]
(touch-project cfg project-id)
result)))
(assoc :name (:name params))
(assoc :version (:version params))
(check-result)
(as-> result {:team team :result result})))))))
(defn- submit-import-event
"Submit the `import-binfile` audit event with the outcome of the job.
The event shares the terminal transition's transaction. The job runs
outside any request, so the event carries no request context."
[cfg {:keys [params status result] :as job}]
(let [{:keys [project-id team-id name version generated-by referer]} params
;; Fallback for older jobs without a team-id; remove in 2.21.0.
team-id (or team-id (:team-id (db/get* cfg :project {:id project-id})))
file-ids (:file-ids result)
props (cond-> {:project-id project-id
:name name
:version version
:generated-by generated-by
:referer referer
:job-id (:id job)
:team-id team-id
:status status}
(= status "completed")
(assoc :file-ids file-ids :file-count (count file-ids)))]
(audit/submit cfg {:type "command"
:name "import-binfile"
:profile-id (:profile-id job)
:props (d/without-nils props)
:context {:triggered-by "import-binfile-job"}
::webhooks/event? true})))
(defn- submit-file-created-events
"The imported files get no event from their own command, so emit one per
file inside a single transaction, as the legacy RPC does."
[cfg context team file-ids]
(let [params {::rpc/profile-id (:profile-id context)}]
(db/tx-run! cfg (fn [cfg]
(doseq [file-id file-ids]
(audit/submit-file-created-event cfg params file-id
{:team-id (:id team)}))))))
(defn execute-import
"Plain handler, importable and testable without integrant.
The edition permission is checked again here, and not only when the job
was created: it can be revoked while the job waits in its queue. The
core runs inside a transaction, so a cancellation detected between units
rolls the whole import back, and the result is checked against its schema
inside that same transaction: a result the contract does not accept rolls
the import back instead of leaving half of a file imported. The substrate
checks the result again when the job is completed, which is the only net
for a job that does not validate its own result.
substrate checks the result again when the job is completed, which is
the only net for a job that does not validate its own result.
A completed import submits a `create-file` event per file it created.
The terminal hook submits the import outcome.
The package is the input of the job: it is released and its temporary
copy deleted once the job is terminal, whatever the outcome. A crash is
covered by the storage GC."
[cfg context params]
(let [profile-id (:profile-id context)
project-id (:project-id params)
input (js/load-input cfg context)]
(let [input (js/load-input cfg context)]
(try
(projects/check-edition-permissions! cfg profile-id project-id)
(let [{:keys [team result]} (import-files cfg context params input)]
(submit-file-created-events cfg context team (:file-ids result))
result)
(let [team (or (teams/get-team cfg
:profile-id profile-id
:project-id project-id)
(ex/raise :type :not-found
:code :project-not-found
:hint "the destination project is not available"
:profile-id profile-id
:project-id project-id))]
(db/tx-run! cfg (fn [tx-cfg]
;; the core joins this transaction: it
;; is the one that decides whether the
;; whole import is kept or rolled back
(-> (bfc/import-cfg tx-cfg {:profile-id profile-id
:project-id project-id
:team team
:name (:name params)
:input input})
(bfj/check-active context)
(bfj/run context
(fn [cfg]
(let [result (case (int (:version params))
1 (bf.v1/import-files! cfg)
3 (bf.v3/import-files! cfg)
(ex/raise :type :validation
:code :unsupported-version
:hint "unsupported binfile version"
:version (:version params)))]
(touch-project cfg project-id)
result)))
(assoc :name (:name params))
(assoc :version (:version params))
(check-result)))))
(finally
(fs/delete input)
(js/release-input cfg context)))))
@ -190,6 +245,7 @@
::jobs/schema schema:params
::jobs/handler (fn [context params]
(execute-import cfg context params))
::jobs/on-terminal submit-import-event
::jobs/decoder (sm/decoder schema:params sm/json-transformer)
::jobs/validator (sm/validator schema:params)
;; The resolution is keyed by file id: without the result schema the

View File

@ -0,0 +1,333 @@
;; 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.import-team-concurrency-test
(:require
[app.binfile.v3 :as v3]
[app.common.time :as ct]
[app.config :as cf]
[app.db :as db]
[app.jobs :as jobs]
[app.jobs.storage :as js]
[app.rpc.commands.management :as management]
[app.rpc.commands.projects :as projects]
[app.storage :as sto]
[app.worker :as worker]
[app.worker.dispatcher :as dispatcher]
[backend-tests.helpers :as th]
[clojure.java.io :as jio]
[clojure.test :as t]
[datoteka.io :as io]))
(t/use-fixtures :once th/state-init)
(t/use-fixtures :each (th/serial th/database-reset th/clean-storage))
(defn- await-result
[p]
(let [value (deref p 15000 ::timeout)]
(when (= ::timeout value)
(throw (ex-info "Timed out waiting for concurrent operation" {})))
value))
(defn- get-pid
[cfg]
(:pid (db/exec-one! cfg ["SELECT pg_backend_pid() AS pid"])))
(defn- await-blocked
[pid]
(let [deadline (+ (System/nanoTime) 10000000000)]
(loop []
(let [row (db/exec-one! th/*system*
["SELECT cardinality(pg_blocking_pids(?)) > 0 AS blocked" pid])]
(cond
(:blocked row) true
(< (System/nanoTime) deadline) (recur)
:else (throw (ex-info "Database operation did not block" {:pid pid})))))))
(defn- setup-import
[profile project-id team-id]
(let [path (-> "backend_tests/test_files/svg-attrs-camel-case.penpot"
io/resource jio/file)
staged (js/put-resource th/*system* (:id profile)
{:content (sto/content path)
:filename "package.penpot"
:mtype "application/zip"})
params (cond-> {:project-id project-id :name "imported" :version 3}
team-id (assoc :team-id team-id))
job-id (th/create-job* :import-binfile {:profile-id (:id profile)
:resource-id (:resource-id staged)})]
(th/db-update! :job {:params (db/json params)} {:id job-id})
{:id job-id :params params}))
(defn- run-import
[{:keys [id params]}]
(jobs/invoke (assoc th/*system*
::jobs/name :import-binfile
::jobs/params params
::jobs/context (jobs/make-context (jobs/get-job th/*system* id)))))
(defn- get-files
[project-id]
(th/db-exec! ["SELECT id FROM file WHERE project_id = ? AND deleted_at IS NULL"
project-id]))
(defn- move
[cfg profile-id project-id team-id]
(management/move-project cfg {:profile-id profile-id
:project-id project-id
:team-id team-id}))
(t/deftest move-waits-for-import-to-commit
(let [profile (th/create-profile* 1)
project (th/create-project* 1 {:profile-id (:id profile)
:team-id (:default-team-id profile)})
destination (th/create-team* 1 {:profile-id (:id profile)})
job (setup-import profile (:id project) (:default-team-id profile))
entered (promise)
release (promise)
move-pid (promise)
original v3/import-files!]
(with-redefs [v3/import-files! (fn [cfg]
(deliver entered true)
(await-result release)
(original cfg))]
(let [import (future (run-import job))]
(try
(await-result entered)
(let [moving (future
(db/tx-run! th/*system*
(fn [cfg]
(deliver move-pid (get-pid cfg))
(move cfg (:id profile) (:id project) (:id destination)))))]
(try
(t/is (true? (await-blocked (await-result move-pid))))
(t/is (= (:default-team-id profile)
(:team-id (th/db-get :project {:id (:id project)}))))
(deliver release true)
(let [result (await-result import)]
(await-result moving)
(t/is (= (set (:file-ids result))
(set (map :id (get-files (:id project)))))))
(t/is (= (:id destination)
(:team-id (th/db-get :project {:id (:id project)}))))
(finally
(deliver release true)
(await-result moving))))
(finally
(deliver release true)
(await-result import)))))))
(t/deftest import-waits-for-move-and-rejects-the-new-team
(let [profile (th/create-profile* 1)
project (th/create-project* 1 {:profile-id (:id profile)
:team-id (:default-team-id profile)})
destination (th/create-team* 1 {:profile-id (:id profile)})
job (setup-import profile (:id project) (:default-team-id profile))
moved (promise)
release (promise)
import-pid (promise)
original projects/get-project-for-update
moving (future
(db/tx-run! th/*system*
(fn [cfg]
(move cfg (:id profile) (:id project) (:id destination))
(deliver moved true)
(await-result release))))]
(try
(await-result moved)
(with-redefs [projects/get-project-for-update
(fn [cfg id]
(deliver import-pid (get-pid cfg))
(original cfg id))]
(let [import (future (try (run-import job)
(catch Throwable cause cause)))]
(try
(t/is (true? (await-blocked (await-result import-pid))))
(deliver release true)
(await-result moving)
(t/is (= :import-team-changed (-> (await-result import) ex-data :code)))
(t/is (empty? (get-files (:id project))))
(finally
(deliver release true)
(await-result import)))))
(finally
(deliver release true)
(await-result moving)))))
(t/deftest moved-import-without-destination-access-returns-not-found
(let [profile (th/create-profile* 1)
project (th/create-project* 1 {:profile-id (:id profile)
:team-id (:default-team-id profile)})
destination (th/create-team* 1 {:profile-id (:id profile)})
job (setup-import profile (:id project) (:default-team-id profile))]
(db/tx-run! th/*system*
#(move % (:id profile) (:id project) (:id destination)))
(th/db-exec! ["DELETE FROM team_profile_rel WHERE team_id = ? AND profile_id = ?"
(:id destination) (:id profile)])
(let [error (try (run-import job)
(catch Throwable cause cause))]
(t/is (= :not-found (:type (ex-data error))))
(t/is (= :object-not-found (:code (ex-data error))))
(t/is (empty? (get-files (:id project)))))))
(t/deftest import-waits-for-move-rollback-and-succeeds
(let [profile (th/create-profile* 1)
project (th/create-project* 1 {:profile-id (:id profile)
:team-id (:default-team-id profile)})
destination (th/create-team* 1 {:profile-id (:id profile)})
job (setup-import profile (:id project) (:default-team-id profile))
moved (promise)
release (promise)
import-pid (promise)
original projects/get-project-for-update
moving (future
(try
(db/tx-run! th/*system*
(fn [cfg]
(move cfg (:id profile) (:id project) (:id destination))
(deliver moved true)
(await-result release)
(throw (ex-info "Rollback move" {:rollback true}))))
(catch Throwable cause cause)))]
(try
(await-result moved)
(with-redefs [projects/get-project-for-update
(fn [cfg id]
(deliver import-pid (get-pid cfg))
(original cfg id))]
(let [import (future (run-import job))]
(try
(t/is (true? (await-blocked (await-result import-pid))))
(deliver release true)
(t/is (true? (-> (await-result moving) ex-data :rollback)))
(let [result (await-result import)]
(t/is (seq (:file-ids result)))
(t/is (= (set (:file-ids result))
(set (map :id (get-files (:id project)))))))
(t/is (= (:default-team-id profile)
(:team-id (th/db-get :project {:id (:id project)}))))
(finally
(deliver release true)
(await-result import)))))
(finally
(deliver release true)
(await-result moving)))))
(defn- blocked-terminal-import
[legacy terminal]
(let [profile (th/create-profile* 1)
project-id (:default-project-id profile)
job (setup-import profile project-id (when-not legacy (:default-team-id profile)))
locked (promise)
release (promise)
import-pid (promise)
original projects/get-project-for-update
holder (future
(db/tx-run! th/*system*
(fn [cfg]
(db/exec-one! cfg ["SELECT id FROM project WHERE id = ? FOR NO KEY UPDATE"
project-id])
(deliver locked true)
(await-result release))))]
(try
(await-result locked)
(with-redefs [projects/get-project-for-update
(fn [cfg id]
(deliver import-pid (get-pid cfg))
(original cfg id))]
(let [import (future (try (run-import job)
(catch Throwable cause cause)))]
(try
(t/is (true? (await-blocked (await-result import-pid))))
(if (= terminal :cancelled)
(t/is (= 1 (await-result (future (jobs/cancel th/*system* (:id job))))))
(do
(th/db-update! :job {:modified-at (ct/minus (ct/now)
(ct/plus (cf/get-jobs-lease)
(ct/duration {:minutes 1})))}
{:id (:id job)})
(db/tx-run! th/*system*
(fn [cfg]
(#'dispatcher/mark-orphan-jobs
(assoc cfg ::dispatcher/timestamp (ct/now)
::worker/tenant (cf/get :tenant)))))))
(t/is (= (name terminal) (:status (jobs/get-job th/*system* (:id job)))))
(deliver release true)
(await-result holder)
(t/is (= :job-interrupted (-> (await-result import) ex-data :code)))
(t/is (empty? (get-files project-id)))
(t/is (zero? (jobs/complete th/*system* :job-id (:id job)
:result {:file-ids [] :name "imported" :version 3})))
(finally
(deliver release true)
(await-result import)))))
(finally
(deliver release true)
(await-result holder)))))
(t/deftest cancellation-of-a-blocked-import
(blocked-terminal-import false :cancelled))
(t/deftest cancellation-of-a-blocked-legacy-import
(blocked-terminal-import true :cancelled))
(t/deftest lease-expiry-of-a-blocked-import
(blocked-terminal-import false :aborted))
(defn- cancel-running-import
[legacy]
(let [profile (th/create-profile* 1)
project-id (:default-project-id profile)
job (setup-import profile project-id (when-not legacy (:default-team-id profile)))
entered (promise)
release (promise)
lock-pid (promise)
original v3/import-files!]
(with-redefs [v3/import-files!
(fn [cfg]
(let [result (original cfg)
files (db/exec! cfg ["SELECT id FROM file WHERE project_id = ? AND deleted_at IS NULL"
project-id])]
(deliver entered (count files))
(await-result release)
result))]
(let [import (future (try (run-import job)
(catch Throwable cause cause)))]
(try
(t/is (pos? (await-result entered)))
(let [waiter (future
(db/tx-run! th/*system*
(fn [cfg]
(deliver lock-pid (get-pid cfg))
(db/exec-one! cfg ["SELECT id FROM project WHERE id = ? FOR NO KEY UPDATE"
project-id]))))
cancel (atom nil)]
(try
(t/is (true? (await-blocked (await-result lock-pid))))
(reset! cancel (future (jobs/cancel th/*system* (:id job))))
(t/is (= 1 (await-result @cancel)))
(t/is (= "cancelled" (:status (jobs/get-job th/*system* (:id job)))))
(deliver release true)
(let [error (await-result import)]
(t/is (= :interrupt (:type (ex-data error))))
(t/is (= :job-interrupted (:code (ex-data error)))))
(await-result waiter)
(t/is (empty? (get-files project-id)))
(finally
(deliver release true)
(await-result import)
(await-result waiter)
(when @cancel
(await-result @cancel)))))
(finally
(deliver release true)
(await-result import)))))))
(t/deftest cancellation-of-a-running-import
(cancel-running-import false))
(t/deftest cancellation-of-a-running-legacy-import
(cancel-running-import true))

View File

@ -0,0 +1,230 @@
;; 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
(ns backend-tests.import-terminal-rpc-test
(:require
[app.common.transit :as transit]
[app.config :as cf]
[app.db :as db]
[app.jobs :as jobs]
[app.jobs.storage :as js]
[app.loggers.audit :as audit]
[app.loggers.webhooks :as webhooks]
[app.rpc :as-alias rpc]
[app.rpc.commands.management :as management]
[app.storage :as sto]
[backend-tests.helpers :as th]
[clojure.java.io :as jio]
[clojure.test :as t]
[datoteka.io :as io]))
(t/use-fixtures :once th/state-init)
(t/use-fixtures :each (th/serial th/database-reset th/clean-storage))
(def ^:private real-audit-submit audit/submit)
(defn- create-import-job
[profile & {:keys [team-id]}]
(let [id (th/create-job* :import-binfile {:profile-id (:id profile)})]
(th/db-update! :job {:status "new"
:params (db/json (cond-> {:project-id (:default-project-id profile)
:name "imported"
:version 3
:generated-by "test"}
team-id (assoc :team-id team-id)))}
{:id id})
id))
(defn- get-import-events
[]
(->> (th/db-exec! ["SELECT * FROM audit_log WHERE name = 'import-binfile' AND source = 'backend'"])
(mapv #(update % :props db/decode-transit-pgobject))))
(t/deftest cancelling-a-queued-import-through-rpc-persists-one-terminal-event
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true]
(let [profile (th/create-profile* 1)
job-id (create-import-job profile)
cancel #(th/command! {::th/type :cancel-job
::rpc/profile-id (:id profile)
:id job-id})]
(t/is (th/success? (cancel)))
(t/is (th/success? (cancel)))
(t/is (= "cancelled" (:status (jobs/get-job th/*system* job-id))))
(let [events (get-import-events)
event (first events)
props (:props event)]
(t/is (= 1 (count events)))
(t/is (= (:id profile) (:profile-id event)))
(t/is (= job-id (:job-id props)))
(t/is (= (:default-team-id profile) (:team-id props)))
(t/is (= "cancelled" (:status props)))
(t/is (= 3 (:version props)))
(t/is (= "test" (:generated-by props)))
(t/is (not (contains? props :file-ids)))
(t/is (not (contains? props :file-count)))))))
(t/deftest management-terminal-rpcs-run-the-registered-import-hook
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true]
(let [profile (th/create-profile* 1)
completed-id (create-import-job profile)
failed-id (create-import-job profile)
result {:file-ids [] :name "imported" :version 3}
error {:type :internal :code :processing-error :hint "failed"}]
(doseq [id [completed-id failed-id]]
(t/is (pos? (jobs/claim th/*system* id (:scheduled-at (jobs/get-job th/*system* id))))))
(let [completed (th/management-command! {::th/type :complete-job
:job-id completed-id
:result result})
failed (th/management-command! {::th/type :fail-job
:job-id failed-id
:error error})
events (get-import-events)
by-job (into {} (map (juxt #(get-in % [:props :job-id]) identity)) events)]
(t/is (nil? (:error completed)))
(t/is (nil? (:error failed)))
(t/is (= "completed" (:status (jobs/get-job th/*system* completed-id))))
(t/is (= "failed" (:status (jobs/get-job th/*system* failed-id))))
(t/is (= 2 (count events)))
(t/is (= "completed" (get-in by-job [completed-id :props :status])))
(t/is (= 0 (get-in by-job [completed-id :props :file-count])))
(t/is (= "failed" (get-in by-job [failed-id :props :status])))
(t/is (not (contains? (get-in by-job [failed-id :props]) :file-ids)))))))
(t/deftest cancelling-a-moved-import-routes-to-its-frozen-team
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/webhooks-enabled? true]
(let [profile (th/create-profile* 1)
original-id (:default-team-id profile)
destination (th/create-team* 1 {:profile-id (:id profile)})
original (th/create-webhook* {:team-id original-id})
_ (th/create-webhook* {:team-id (:id destination)})
job-id (create-import-job profile :team-id original-id)]
(th/db-update! :project {:team-id (:id destination)}
{:id (:default-project-id profile)})
(t/is (th/success? (th/command! {::th/type :cancel-job
::rpc/profile-id (:id profile)
:id job-id})))
(let [events (get-import-events)
event (first events)
rows (th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"])
blobs (map #(db/decode-json-pgobject (:params %)) rows)
blob (first (filter #(= "import-binfile"
(:name (transit/decode-str (:event-blob %))))
blobs))]
(t/is (= 1 (count events)))
(t/is (= original-id (get-in event [:props :team-id])))
(t/is (some? blob))
(when blob
(webhooks/process-event-impl th/*system* blob)
(let [deliveries (th/db-exec! ["SELECT * FROM job WHERE name = 'run-webhook'"])
params (map #(db/decode-json-pgobject (:params %)) deliveries)
delivery (first params)
payload (some-> delivery :event transit/decode-str)]
(t/is (= 1 (count deliveries)))
(t/is (= (str (:id original)) (get-in delivery [:config :id])))
(t/is (= original-id (get-in payload [:props :team-id])))
(t/is (= job-id (get-in payload [:props :job-id])))))))))
(t/deftest failed-import-after-move-routes-to-its-frozen-team
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/webhooks-enabled? true]
(let [profile (th/create-profile* 1)
original-id (:default-team-id profile)
project (th/create-project* 1 {:profile-id (:id profile)
:team-id original-id})
project-id (:id project)
destination (th/create-team* 1 {:profile-id (:id profile)})
original (th/create-webhook* {:team-id original-id})
_ (th/create-webhook* {:team-id (:id destination)})
path (-> "backend_tests/test_files/svg-attrs-camel-case.penpot"
io/resource jio/file)
staged (js/put-resource th/*system* (:id profile)
{:content (sto/content path)
:filename "package.penpot"
:mtype "application/zip"})
job-id (th/create-job* :import-binfile {:profile-id (:id profile)
:resource-id (:resource-id staged)})
params {:project-id project-id :team-id original-id
:name "imported" :version 3}]
(th/db-update! :job {:params (db/json params)} {:id job-id})
(db/tx-run! th/*system*
#(management/move-project % {:profile-id (:id profile)
:project-id project-id
:team-id (:id destination)}))
(let [error (try
(jobs/invoke (assoc th/*system*
::jobs/name :import-binfile
::jobs/params params
::jobs/context (jobs/make-context (jobs/get-job th/*system* job-id))))
(catch Throwable cause cause))]
(t/is (= :import-team-changed (-> error ex-data :code)))
(t/is (= 1 (jobs/fail th/*system* job-id
{:type :validation :code :import-team-changed
:hint "the destination project changed teams"}))))
(t/is (= "failed" (:status (jobs/get-job th/*system* job-id))))
(t/is (empty? (th/db-exec! ["SELECT id FROM file WHERE project_id = ? AND deleted_at IS NULL"
project-id])))
(let [events (get-import-events)
blobs (map #(db/decode-json-pgobject (:params %))
(th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"]))
blob (first (filter #(= "import-binfile"
(:name (transit/decode-str (:event-blob %))))
blobs))]
(t/is (= 1 (count events)))
(t/is (= "failed" (get-in (first events) [:props :status])))
(t/is (= original-id (get-in (first events) [:props :team-id])))
(t/is (some? blob))
(when blob
(webhooks/process-event-impl th/*system* blob)
(let [deliveries (th/db-exec! ["SELECT * FROM job WHERE name = 'run-webhook'"])
delivery (some-> deliveries first :params db/decode-json-pgobject)
payload (some-> delivery :event transit/decode-str)]
(t/is (= 1 (count deliveries)))
(t/is (= (str (:id original)) (get-in delivery [:config :id])))
(t/is (= original-id (get-in payload [:props :team-id])))
(t/is (= job-id (get-in payload [:props :job-id])))))))))
(t/deftest cancelling-a-legacy-moved-import-uses-the-current-team
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true]
(let [profile (th/create-profile* 1)
destination (th/create-team* 1 {:profile-id (:id profile)})
job-id (create-import-job profile)]
(th/db-update! :project {:team-id (:id destination)}
{:id (:default-project-id profile)})
(t/is (th/success? (th/command! {::th/type :cancel-job
::rpc/profile-id (:id profile)
:id job-id})))
(let [events (get-import-events)]
(t/is (= 1 (count events)))
(t/is (= (:id destination) (get-in (first events) [:props :team-id])))))))
(t/deftest cancelling-a-moved-import-does-not-fall-back-to-destination-webhooks
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/webhooks-enabled? true]
(let [profile (th/create-profile* 1)
destination (th/create-team* 1 {:profile-id (:id profile)})
_ (th/create-webhook* {:team-id (:id destination)})
job-id (create-import-job profile :team-id (:default-team-id profile))]
(th/db-update! :project {:team-id (:id destination)}
{:id (:default-project-id profile)})
(t/is (th/success? (th/command! {::th/type :cancel-job
::rpc/profile-id (:id profile)
:id job-id})))
(let [rows (th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"])
blobs (map #(db/decode-json-pgobject (:params %)) rows)
blob (first (filter #(= "import-binfile"
(:name (transit/decode-str (:event-blob %))))
blobs))]
(t/is (some? blob))
(when blob
(webhooks/process-event-impl th/*system* blob)
(t/is (empty? (th/db-exec! ["SELECT id FROM job WHERE name = 'run-webhook'"]))))))))

View File

@ -163,6 +163,62 @@
nil)
(-purge [_ _] nil)))
(t/deftest terminal-hooks-run-in-the-winning-transaction
(doseq [[status transition terminal-status result error]
[["running" (fn [cfg id] (jobs/complete cfg :job-id id :result {:value 1}))
"completed" {:value 1} nil]
["running" (fn [cfg id] (jobs/fail cfg id test-error))
"failed" nil test-error]
["new" jobs/cancel "cancelled" nil nil]]]
(let [seen (atom [])
defs (assoc-in (get-job-defs) [:echo ::jobs/on-terminal]
(fn [tx-cfg job]
(swap! seen conj job)
(db/exec-one! tx-cfg ["UPDATE job SET label = ? WHERE id = ?"
"hook-ran" (:id job)])))
cfg (make-cfg defs)
params (make-params)
id (jobs/submit cfg {::jobs/name :echo ::jobs/params params})]
(th/db-exec! ["UPDATE job SET status = ? WHERE id = ?" status id])
(t/is (= 1 (transition cfg id)))
(t/is (= 0 (transition cfg id)))
(t/is (= 1 (count @seen)))
(t/is (= id (:id (first @seen))))
(t/is (= params (:params (first @seen))))
(t/is (= terminal-status (:status (first @seen))))
(t/is (= result (:result (first @seen))))
(t/is (= error (:error (first @seen))))
(t/is (= (= terminal-status "completed") (contains? (first @seen) :result)))
(t/is (= (= terminal-status "failed") (contains? (first @seen) :error)))
(t/is (= "hook-ran" (:label (jobs/get-job cfg id)))))))
(t/deftest terminal-hook-failure-rolls-back-transition-and-writes
(doseq [[status transition]
[["running" (fn [cfg id] (jobs/complete cfg :job-id id :result nil))]
["running" (fn [cfg id] (jobs/fail cfg id test-error))]
["new" jobs/cancel]]]
(let [defs (assoc-in (get-job-defs) [:echo ::jobs/on-terminal]
(fn [tx-cfg job]
(db/exec-one! tx-cfg ["UPDATE job SET label = ? WHERE id = ?"
"rolled-back" (:id job)])
(throw (ex-info "hook failed" {}))))
cfg (make-cfg defs)
id (jobs/submit cfg {::jobs/name :echo ::jobs/params (make-params)})]
(th/db-exec! ["UPDATE job SET status = ? WHERE id = ?" status id])
(t/is (some? (raised #(transition cfg id))))
(t/is (= status (:status (jobs/get-job cfg id))))
(t/is (not= "rolled-back" (:label (jobs/get-job cfg id))))
(t/is (empty? (get-outcomes id))))))
(t/deftest terminal-transitions-allow-a-missing-definition-or-hook
(doseq [remove-definition [false true]]
(let [defs (get-job-defs)
cfg (make-cfg defs)
id (jobs/submit cfg {::jobs/name :echo ::jobs/params (make-params)})
cfg (if remove-definition (assoc cfg ::jobs/defs {}) cfg)]
(t/is (= 1 (jobs/cancel cfg id)))
(t/is (= ["cancelled"] (get-outcomes id))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TESTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

View File

@ -12,14 +12,19 @@
[app.binfile.v3 :as v3]
[app.common.exceptions :as ex]
[app.common.time :as ct]
[app.common.transit :as transit]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.jobs :as jobs]
[app.loggers.audit :as-alias audit]
[app.jobs.storage :as js]
[app.loggers.audit :as audit]
[app.loggers.webhooks :as webhooks]
[app.rpc :as-alias rpc]
[app.rpc.climit :as-alias climit]
[app.rpc.commands.jobs :as cmd-jobs]
[app.rpc.commands.management :as management]
[app.rpc.commands.projects :as projects]
[app.rpc.quotes :as-alias quotes]
[app.storage :as sto]
[app.storage.tmp :as tmp]
@ -42,6 +47,8 @@
"A real penpot export, the same fixture the binfile tests read."
"backend_tests/test_files/svg-attrs-camel-case.penpot")
(def ^:private real-audit-submit audit/submit)
(defn- import-fixture!
"A file in the default project of the profile, imported from the
fixture through the core."
@ -470,6 +477,7 @@
(let [job-def (jobs/get-job-def (::jobs/defs th/*system*) :import-binfile)
params (jobs/decode-params job-def (:params job))]
(t/is (= (:default-project-id profile) (:project-id params)))
(t/is (= (:default-team-id profile) (:team-id params)))
(t/is (= "imported" (:name params)))
(t/is (= 3 (:version params)))
(t/is (string? (:generated-by params)))))
@ -477,7 +485,213 @@
(t/testing "the audit points at the job and the manifest, not the package"
(let [props (::audit/props (meta (:result out)))]
(t/is (= (:id result) (:job-id props)))
(t/is (= #{:job-id :generated-by :referer} (set (keys props)))))))))
(t/is (= (:default-team-id profile) (:team-id props)))
(t/is (= #{:job-id :team-id :generated-by :referer} (set (keys props))))
(t/is (not (contains? result :team-id))))))))
(t/deftest create-import-binfile-job-rejects-a-client-supplied-team
(let [profile (th/create-profile* 1)
session-id (upload-chunked! profile)
before (live-storage-objects)
out (create-import-binfile-job
(:id profile) (:default-project-id profile)
:upload-id session-id
:params {:project-id (:default-project-id profile)
:name "imported"
:team-id (uuid/next)})]
(t/is (not (th/success? out)))
(t/is (= :params-validation (th/ex-code (:error out))))
(t/is (zero? (count-jobs)))
(t/is (= before (live-storage-objects)))
(t/is (nil? (:deleted-at (session-row session-id))))))
(t/deftest create-import-binfile-job-routes-its-audit-to-the-frozen-team
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/webhooks-enabled? true]
(let [profile (th/create-profile* 1)
original-id (:default-team-id profile)
destination (th/create-team* 1 {:profile-id (:id profile)})
original (th/create-webhook* {:team-id original-id})
_ (th/create-webhook* {:team-id (:id destination)})
upload-id (upload-chunked! profile)
names {(uuid/next) "Renamed file"}
given {:project-id (:default-project-id profile) :name names}
out (create-import-binfile-job (:id profile) (:default-project-id profile)
:upload-id upload-id :params given)
job-id (:id (:result out))]
(t/is (th/success? out))
(th/db-update! :project {:team-id (:id destination)}
{:id (:default-project-id profile)})
;; The test system does not install the RPC audit wrapper. Prepare the
;; event after the move, as that wrapper does after the command returns.
(let [[mdata _] (get (::rpc/methods th/*system*) :create-import-binfile-job)
request (reify
yetti.request/IRequest
(get-header [_ _] nil)
(remote-addr [_] "127.0.0.1"))
params (with-meta {::rpc/profile-id (:id profile)
::rpc/request-id (uuid/next)
::rpc/request-at (ct/now)
:upload-id upload-id
:params given}
{:app.http/request request})
event (audit/prepare-rpc-event (assoc th/*system* ::rpc/module "main"
::rpc/type "command")
mdata params (:result out))]
(audit/submit th/*system* event))
(let [rows (th/db-exec! ["SELECT * FROM job WHERE name = 'process-webhook-event'"])
blobs (map #(db/decode-json-pgobject (:params %)) rows)
blob (first (filter #(= "create-import-binfile-job"
(:name (transit/decode-str (:event-blob %))))
blobs))]
(t/is (some? blob))
(when blob
(webhooks/process-event-impl th/*system* blob)
(let [deliveries (th/db-exec! ["SELECT * FROM job WHERE name = 'run-webhook'"])
params (map #(db/decode-json-pgobject (:params %)) deliveries)
delivery (first params)
payload (some-> delivery :event transit/decode-str)
props (:props payload)]
(t/is (= 1 (count deliveries)))
(t/is (= (str (:id original)) (get-in delivery [:config :id])))
(t/is (= original-id (:team-id props)))
(t/is (= job-id (:job-id props)))
(t/is (= (cond-> {:upload-id upload-id
:params given
:team-id original-id
:job-id job-id}
(some? (:generated-by (::audit/props (meta (:result out)))))
(assoc :generated-by (:generated-by (::audit/props (meta (:result out)))))
(some? (:referer (::audit/props (meta (:result out)))))
(assoc :referer (:referer (::audit/props (meta (:result out))))))
props))))))))
(defn- await-concurrent
[p]
(let [value (deref p 15000 ::timeout)]
(when (= ::timeout value)
(throw (ex-info "Timed out waiting for concurrent operation" {})))
value))
(defn- await-db-blocked
[pid]
(let [deadline (+ (System/nanoTime) 10000000000)]
(loop []
(cond
(:blocked (db/exec-one! th/*system*
["SELECT cardinality(pg_blocking_pids(?)) > 0 AS blocked" pid]))
true
(< (System/nanoTime) deadline) (recur)
:else (throw (ex-info "Database operation did not block" {:pid pid}))))))
(t/deftest create-import-after-move-rechecks-permission-and-releases-resource
(let [owner (th/create-profile* 1)
actor (th/create-profile* 2)
project (th/create-project* 1 {:profile-id (:id owner)
:team-id (:default-team-id owner)})
destination (th/create-team* 1 {:profile-id (:id owner)})
_ (th/db-insert! :team-profile-rel {:team-id (:default-team-id owner)
:profile-id (:id actor)
:is-owner false
:is-admin false
:can-edit true})
upload-id (upload-chunked! actor)
before (live-storage-objects)
staged (promise)
proceed (promise)
moved (promise)
release (promise)
create-pid (promise)
put js/put-resource
lock projects/get-project-for-update]
(with-redefs [js/put-resource (fn [& args]
(let [resource (apply put args)]
(deliver staged resource)
(await-concurrent proceed)
resource))
projects/get-project-for-update
(fn [cfg id]
(when (realized? moved)
(deliver create-pid (:pid (db/exec-one! cfg ["SELECT pg_backend_pid() AS pid"]))))
(lock cfg id))]
(let [creating (future (create-import-binfile-job (:id actor) (:id project) :upload-id upload-id))]
(try
(await-concurrent staged)
(let [moving (future
(db/tx-run! th/*system*
(fn [cfg]
(management/move-project cfg {:profile-id (:id owner)
:project-id (:id project)
:team-id (:id destination)})
(deliver moved true)
(await-concurrent release))))]
(try
(await-concurrent moved)
(deliver proceed true)
(t/is (true? (await-db-blocked (await-concurrent create-pid))))
(deliver release true)
(await-concurrent moving)
(let [out (await-concurrent creating)]
(t/is (not (th/success? out)))
(t/is (= :not-found (th/ex-type (:error out))))
(t/is (zero? (count-jobs)))
(t/is (= before (live-storage-objects)))
(t/is (some? (:deleted-at (session-row upload-id)))))
(finally
(deliver proceed true)
(deliver release true)
(await-concurrent moving))))
(finally
(deliver proceed true)
(deliver release true)
(await-concurrent creating)))))))
(t/deftest move-waits-for-import-job-submission
(let [profile (th/create-profile* 1)
project (th/create-project* 1 {:profile-id (:id profile)
:team-id (:default-team-id profile)})
destination (th/create-team* 1 {:profile-id (:id profile)})
upload-id (upload-chunked! profile)
entered (promise)
release (promise)
move-pid (promise)
submit jobs/submit]
(with-redefs [jobs/submit (fn [cfg params]
(when (= :import-binfile (::jobs/name params))
(deliver entered true)
(await-concurrent release))
(submit cfg params))]
(let [creating (future (create-import-binfile-job (:id profile) (:id project) :upload-id upload-id))]
(try
(await-concurrent entered)
(let [moving (future
(db/tx-run! th/*system*
(fn [cfg]
(deliver move-pid (:pid (db/exec-one! cfg ["SELECT pg_backend_pid() AS pid"])))
(management/move-project cfg {:profile-id (:id profile)
:project-id (:id project)
:team-id (:id destination)}))))]
(try
(t/is (true? (await-db-blocked (await-concurrent move-pid))))
(deliver release true)
(let [out (await-concurrent creating)
job (jobs/get-job th/*system* (:id (:result out)))
job-def (jobs/get-job-def (::jobs/defs th/*system*) :import-binfile)
params (jobs/decode-params job-def (:params job))]
(t/is (th/success? out))
(t/is (= (:default-team-id profile) (:team-id params)))
(t/is (= (:default-team-id profile)
(:team-id (::audit/props (meta (:result out))))))
(t/is (some? (:resource-id job))))
(await-concurrent moving)
(t/is (= (:id destination) (:team-id (th/db-get :project {:id (:id project)}))))
(finally
(deliver release true)
(await-concurrent moving))))
(finally
(deliver release true)
(await-concurrent creating)))))))
(t/deftest create-import-binfile-job-assembles-the-chunks-of-its-upload
(let [profile (th/create-profile* 1)

View File

@ -16,6 +16,7 @@
[app.db :as db]
[app.http :as http]
[app.rpc :as-alias rpc]
[app.rpc.commands.management :as management]
[app.storage :as sto]
[backend-tests.helpers :as th]
[backend-tests.storage-test :refer [configure-storage-backend]]
@ -665,6 +666,35 @@
(let [rows (th/db-query :file-library-rel {:file-id (:id file2)})]
(t/is (zero? (count rows)))))))
(t/deftest move-project-locks-before-validating
(let [profile (th/create-profile* 1 {:is-active true})
project-id (:default-project-id profile)
locked (promise)
release (promise)
holder (future
(db/tx-run! th/*system*
(fn [{:keys [::db/conn]}]
(db/exec-one! conn ["SELECT id FROM project WHERE id = ? FOR NO KEY UPDATE"
project-id])
(deliver locked true)
(deref release 10000 ::timeout))))]
(try
(t/is (= true (deref locked 10000 ::timeout)))
(let [error (try
(db/tx-run! th/*system*
(fn [{:keys [::db/conn] :as cfg}]
(db/exec-one! conn ["SET LOCAL lock_timeout = '100ms'"])
(management/move-project
cfg {:profile-id (:id profile)
:project-id project-id
:team-id (:default-team-id profile)})))
nil
(catch java.sql.SQLException cause cause))]
(t/is (= "55P03" (some-> error .getSQLState))))
(finally
(deliver release true)
(t/is (not= ::timeout (deref holder 10000 ::timeout)))))))
(t/deftest move-project
(let [profile (th/create-profile* 1 {:is-active true})
team (th/create-team* 1 {:profile-id (:id profile)})

View File

@ -9,14 +9,18 @@
it leaves behind when it fails."
(:require
[app.binfile.common :as bfc]
[app.binfile.jobs :as bfj]
[app.binfile.v1 :as v1]
[app.binfile.v3 :as v3]
[app.common.uuid :as uuid]
[app.config :as cf]
[app.db :as db]
[app.jobs :as jobs]
[app.jobs.storage :as js]
[app.loggers.audit :as audit]
[app.storage :as sto]
[app.storage.tmp :as tmp]
[app.tasks.import-binfile :as import-binfile]
[backend-tests.helpers :as th]
[clojure.java.io :as jio]
[clojure.test :as t]
@ -85,6 +89,21 @@
[]
(seq (.list (jio/file tmp/default-tmp-dir))))
(def ^:private real-audit-submit audit/submit)
(defn- get-audit-events
[event-name]
(->> (th/db-exec! ["SELECT * FROM audit_log WHERE name = ? AND source = 'backend'"
event-name])
(mapv #(update % :props db/decode-transit-pgobject))))
(defn- create-import-job
[profile params resource-id]
(let [job-id (th/create-job* :import-binfile {:profile-id (:id profile)
:resource-id resource-id})]
(th/db-update! :job {:params (db/json params)} {:id job-id})
job-id))
(defn- project-modified-at
[project-id]
(:modified-at (th/db-get :project {:id project-id})))
@ -186,6 +205,17 @@
(t/testing "and the package is released"
(t/is (some? (:deleted-at (input-row (:resource-id staged))))))))
(t/deftest an-import-refuses-a-project-that-changed-teams
(let [profile (th/create-profile* 1)
project-id (:default-project-id profile)
staged (stage-package! profile (fixture-path))
params {:project-id project-id :team-id (uuid/next)
:name "imported" :version 3}
job-id (create-import-job profile params (:resource-id staged))
before (project-files project-id)]
(t/is (thrown? Throwable (run-import job-id params)))
(t/is (= before (project-files project-id)))))
(t/deftest an-import-cancelled-while-it-runs-leaves-nothing-behind
(let [profile (th/create-profile* 1)
staged (stage-package! profile (fixture-path))
@ -265,3 +295,188 @@
(t/testing "and the import is rolled back: the destination keeps no files"
(t/is (= before (project-files project-id)))))))
(t/deftest import-audit-excludes-unlisted-job-params
(let [profile (th/create-profile* 1)
event (atom nil)
job {:id (uuid/next)
:profile-id (:id profile)
:status "cancelled"
:params {:project-id (:default-project-id profile)
:name "imported"
:version 3
:future-param "not for audit"}}]
(with-redefs [audit/submit (fn [_ submitted] (reset! event submitted))]
(#'import-binfile/submit-import-event th/*system* job))
(t/is (= {:project-id (:default-project-id profile)
:name "imported"
:version 3
:job-id (:id job)
:status "cancelled"
:team-id (:default-team-id profile)}
(:props @event)))))
(t/deftest a-completed-import-submits-its-audit-events
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile)
:name "imported" :version 3
:referer "penpot" :generated-by "penpot/2.20.0"}
staged (stage-package! profile (fixture-path))
job-id (create-import-job profile params (:resource-id staged))
result (run-import job-id params)
file-id (first (:file-ids result))]
(t/is (empty? (get-audit-events "import-binfile")))
(t/is (= 1 (jobs/complete th/*system* :job-id job-id :result result)))
(t/is (zero? (jobs/complete th/*system* :job-id job-id :result result)))
(let [[event :as events] (get-audit-events "import-binfile")
[created :as created-events] (get-audit-events "create-file")]
(t/is (= 1 (count events)))
(t/is (= "command" (:type event)))
(t/is (= (:id profile) (:profile-id event)))
(t/is (= {:status "completed" :job-id job-id
:project-id (:default-project-id profile)
:team-id (:default-team-id profile)
:name "imported" :version 3 :referer "penpot"
:generated-by "penpot/2.20.0"
:file-ids [file-id] :file-count 1}
(:props event)))
(t/is (= 1 (count created-events)))
(t/is (= file-id (-> created :props :id)))
(t/is (= (:id profile) (:profile-id created)))
(t/is (= (:default-team-id profile) (-> created :props :team-id)))))))
(t/deftest a-failed-import-submits-its-terminal-outcome
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile) :name "imported" :version 3}
staged (stage-package! profile (fixture-path))
job-id (create-import-job profile params (:resource-id staged))]
(with-redefs [v3/import-files! (fn [_] (throw (ex-info "boom" {:type :internal})))]
(t/is (thrown? Throwable (run-import job-id params))))
(t/is (= 1 (jobs/fail th/*system* job-id {:type :internal :code :unexpected-error :hint "import failed"})))
(t/is (zero? (jobs/fail th/*system* job-id {:type :internal :code :unexpected-error :hint "import failed"})))
(let [[event :as events] (get-audit-events "import-binfile")]
(t/is (= 1 (count events)))
(t/is (= (:id profile) (:profile-id event)))
(t/is (= "failed" (-> event :props :status)))
(t/is (= job-id (-> event :props :job-id)))
(t/is (not (contains? (:props event) :file-ids)))
(t/is (not (contains? (:props event) :file-count))))
(t/is (empty? (get-audit-events "create-file"))))))
(t/deftest a-queued-cancellation-submits-one-outcome-without-loading-input
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile) :name "imported" :version 3}
job-id (create-import-job profile params nil)]
(th/db-update! :job {:status "new"} {:id job-id})
(t/is (= 1 (jobs/cancel th/*system* job-id)))
(t/is (zero? (jobs/cancel th/*system* job-id)))
(t/is (zero? (jobs/complete th/*system* :job-id job-id :result nil)))
(let [[event :as events] (get-audit-events "import-binfile")]
(t/is (= 1 (count events)))
(t/is (= (:id profile) (:profile-id event)))
(t/is (= "cancelled" (-> event :props :status)))
(t/is (= job-id (-> event :props :job-id)))
(t/is (not (contains? (:props event) :file-ids)))
(t/is (not (contains? (:props event) :file-count))))
(t/is (empty? (get-audit-events "create-file"))))))
(t/deftest cancellation-after-the-last-check-can-leave-imported-files
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile) :name "imported" :version 3}
staged (stage-package! profile (fixture-path))
job-id (create-import-job profile params (:resource-id staged))
run bfj/run
result (with-redefs [bfj/run (fn [cfg context f]
(let [result (run cfg context f)]
(jobs/cancel th/*system* job-id)
result))]
(run-import job-id params))]
(t/is (= "cancelled" (:status (jobs/get-job th/*system* job-id))))
(t/is (zero? (jobs/complete th/*system* :job-id job-id :result result)))
(t/is (= (set (:file-ids result))
(set (map :id (project-files (:default-project-id profile))))))
(t/is (= ["cancelled"] (mapv #(get-in % [:props :status])
(get-audit-events "import-binfile"))))
(t/is (= 1 (count (get-audit-events "create-file")))))))
(t/deftest file-created-events-require-full-audit-persistence
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? false
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile) :name "imported" :version 3}
staged (stage-package! profile (fixture-path))
job-id (create-import-job profile params (:resource-id staged))
result (run-import job-id params)]
(t/is (= 1 (count (:file-ids result))))
(t/is (empty? (get-audit-events "create-file"))))))
(t/deftest a-terminal-audit-failure-does-not-undo-the-committed-import
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile) :name "imported" :version 3}
staged (stage-package! profile (fixture-path))
job-id (create-import-job profile params (:resource-id staged))
result (run-import job-id params)]
(with-redefs [audit/submit (fn [cfg event]
(real-audit-submit cfg event)
(throw (ex-info "audit failure" {})))]
(t/is (thrown-with-msg? Exception #"audit failure"
(jobs/complete th/*system* :job-id job-id :result result))))
(t/is (= "running" (:status (jobs/get-job th/*system* job-id))))
(t/is (empty? (get-audit-events "import-binfile")))
(t/is (= (set (:file-ids result))
(set (map :id (project-files (:default-project-id profile))))))
(t/is (= 1 (count (get-audit-events "create-file")))))))
(t/deftest a-file-created-audit-failure-leaves-the-imported-file-committed
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile) :name "imported" :version 3}
staged (stage-package! profile (fixture-path))
job-id (create-import-job profile params (:resource-id staged))]
(with-redefs [audit/submit (fn [cfg event]
(real-audit-submit cfg event)
(throw (ex-info "audit failure" {})))]
(t/is (thrown-with-msg? Exception #"audit failure" (run-import job-id params))))
(t/is (= 1 (count (project-files (:default-project-id profile)))))
(t/is (empty? (get-audit-events "create-file")))
(t/is (empty? (get-audit-events "import-binfile"))))))
(t/deftest an-aborted-import-does-not-report-a-cancellation
(with-redefs [audit/submit real-audit-submit
cf/audit-persist? true
cf/telemetry-enabled? false
cf/webhooks-enabled? false]
(let [profile (th/create-profile* 1)
params {:project-id (:default-project-id profile) :name "imported" :version 3}
staged (stage-package! profile (fixture-path))
job-id (create-import-job profile params (:resource-id staged))]
(th/db-update! :job {:status "aborted"} {:id job-id})
(t/is (thrown? Throwable (run-import job-id params)))
(t/is (zero? (jobs/cancel th/*system* job-id)))
(t/is (empty? (get-audit-events "import-binfile")))
(t/is (empty? (get-audit-events "create-file"))))))

View File

@ -406,6 +406,26 @@
(t/testing "recent running job is not touched"
(t/is (= "running" (:status (get-row fresh)))))))
(t/deftest dispatcher-aborts-do-not-run-terminal-hooks
(let [calls (atom [])
cfg (assoc (mk-cfg)
::jobs/defs
{:test-job {::jobs/decoder identity
::jobs/on-terminal
(fn [_ job]
(swap! calls conj job))}})
lost (mk-job {:status "scheduled"
:modified-at (ct/minus (ct/now)
(ct/duration {:minutes 6}))})
orphan (mk-job {:status "running"
:modified-at (ct/minus (ct/now)
(ct/plus (cf/get-jobs-lease)
(ct/duration {:minutes 1})))})]
(wdisp/run-batch cfg)
(t/is (= "aborted" (:status (get-row lost))))
(t/is (= "aborted" (:status (get-row orphan))))
(t/is (= [] @calls))))
(t/deftest dispatcher-orphan-sweep-records-the-terminal-counter
(let [metrics (make-orphan-metrics)
cfg (assoc (mk-cfg) ::mtx/metrics metrics)

View File

@ -507,6 +507,7 @@
:fill-color-ref-file
:fill-color-gradient
:strokes
:stroke-style
:stroke-alignment
:stroke-width

View File

@ -407,6 +407,18 @@
:changed-item-index index)]
(dwsh/update-shapes ids #(update-shape-stroke-color % index color) options)))))))
(defn update-shape-stroke-attrs
"Update the style attributes of the stroke on the specified `position`.
When the shape has no stroke there, a default one is created: a stroke
built from style attributes alone would have no color, which is not a
valid stroke."
[shape position attrs]
(let [stroke (or (get-in shape [:strokes position]) cts/default-stroke)]
(-> shape
(update :strokes #(or % []))
(assoc-in [:strokes position]
(merge stroke (build-stroke-style-attrs stroke) attrs)))))
(defn change-stroke-attrs
([ids attrs index] (change-stroke-attrs ids attrs index nil))
([ids attrs index options]
@ -419,16 +431,7 @@
:changed-item-index index)]
(rx/of (dwsh/update-shapes
ids
(fn [shape]
(let [stroke (get-in shape [:strokes index])
style-attrs (build-stroke-style-attrs stroke)
attrs (merge stroke style-attrs attrs)]
(cond-> shape
(not (contains? shape :strokes))
(assoc :strokes [])
:always
(assoc-in [:strokes index] attrs))))
#(update-shape-stroke-attrs % index attrs)
options)))))))
;; --- Stroke side width
@ -880,7 +883,11 @@
ptk/WatchEvent
(watch [_ state _]
(when-let [color (some-> state :colorpicker get-color-from-colorpicker-state)]
(on-change color)))))
;; A gradient without stops or coordinates is not a valid color;
;; applying it would send an invalid shape to the backend.
(when (or (nil? (:gradient color))
(clr/valid-color? color))
(on-change color))))))
(defn initialize-colorpicker
[on-change tab]
@ -952,7 +959,11 @@
(assoc :current-color (split-color-components (dissoc data :gradient))))
(dissoc :editing-stop)
(dissoc :gradient)
(dissoc :stops))))))))))
(dissoc :stops)
;; The color is no longer a gradient (e.g. after an
;; undo), so leave the gradient tab too.
(cond-> (contains? #{:linear-gradient :radial-gradient} (:type state))
(assoc :type (if (:image data) :image :color))))))))))))
(defn update-colorpicker-gradient-opacity
[opacity]

View File

@ -374,6 +374,16 @@
(ptk/data-event :layout/update {:ids ids})
(dwu/commit-undo-transaction undo-id))))))
(defn update-shape-layout
"Patch the layout attributes of `shape` with `changes`. A padding always
keeps its four sides: after patching, a missing or nil side becomes 0."
[shape changes]
(let [shape (d/patch-object shape changes)]
(cond-> shape
(map? (:layout-padding shape))
(update :layout-padding #(merge {:p1 0 :p2 0 :p3 0 :p4 0}
(d/without-nils %))))))
(defn update-layout
([ids changes] (update-layout ids changes nil))
([ids changes options]
@ -385,7 +395,7 @@
keys
set)]
(rx/of (dwu/start-undo-transaction undo-id)
(dwsh/update-shapes ids (d/patch-object changes)
(dwsh/update-shapes ids #(update-shape-layout % changes)
(cond-> options
(seq padding-attrs)
(assoc :changed-sub-attr padding-attrs)))

View File

@ -88,15 +88,20 @@
base-id (:parent-id base)
frame-id (or frame-id
(if (or selected-frame? (empty? selected)
(not= :frame (dm/get-in objects [base-id :type])))
(ctst/top-nested-frame objects position)
base-id))
keep-parent? (not (or selected-frame? (empty? selected) (nil? base)))
parent-id (if (or selected-frame? (empty? selected) (nil? base))
frame-id
base-id)
frame-id (or frame-id
(cond
(not keep-parent?)
(ctst/top-nested-frame objects position)
(= :frame (dm/get-in objects [base-id :type]))
base-id
:else
(dm/get-in objects [base-id :frame-id])))
parent-id (if keep-parent? base-id frame-id)
[new-shape new-children]
(sb/create-svg-shapes id svg-data position objects frame-id parent-id selected true)

View File

@ -300,6 +300,16 @@
(update :workspace-editor-state dissoc id)
(update :workspace-new-text-shapes disj id))))))
(defn editor-shape-content
"The `:content` of the text `shape` after editing it with the legacy
editor: the `exported` editor content with the root attrs of the
shape. The editor keeps paragraph data as it was set, nil values
included, so the result goes through `ensure-valid-text-content` like
the other commit paths."
[exported shape]
(ensure-valid-text-content
(d/merge exported (dissoc (:content shape) :children))))
(defn finalize-editor-state
[id update-name?]
(ptk/reify ::finalize-editor-state
@ -316,8 +326,7 @@
new-shape? (contains? (:workspace-new-text-shapes state) id)]
(if (ted/content-has-text? content)
(if (features/active-feature? state "render-wasm/v1")
(let [content (d/merge (ted/export-content content)
(dissoc (:content shape) :children))
(let [content (editor-shape-content (ted/export-content content) shape)
new-size (dwwt/get-wasm-text-new-size shape content)]
(rx/merge
(rx/of (update-editor-state shape nil))
@ -337,8 +346,7 @@
(ctm/change-size shape (:width new-size) (:height new-size))))))
{:undo-group (when new-shape? id)})))))
(let [content (d/merge (ted/export-content content)
(dissoc (:content shape) :children))
(let [content (editor-shape-content (ted/export-content content) shape)
modifiers (get-in state [:workspace-text-modifier id])]
(rx/merge
(rx/of (update-editor-state shape nil))

View File

@ -220,14 +220,6 @@
(f))
#js {:once true}))
(defn text-editor-wasm?
[]
(or (contains? cf/flags :feature-text-editor-wasm)
(let [runtime-features (get @st/state :features-runtime)
enabled-features (get @st/state :features)]
(or (contains? runtime-features "text-editor-wasm/v1")
(contains? enabled-features "text-editor-wasm/v1")))))
(def ^:const UUID-U8-SIZE 16)
(def ^:const UUID-U32-SIZE (/ UUID-U8-SIZE 4))
@ -2293,8 +2285,6 @@
(cond-> 0
(dbg/enabled? :wasm-viewbox)
(bit-or 2r00000000000000000000000000000001)
(text-editor-wasm?)
(bit-or 2r00000000000000000000000000000100)
(contains? cf/flags :render-wasm-info)
(bit-or 2r00000000000000000000000000001000)))

View File

@ -6,7 +6,9 @@
(ns frontend-tests.data.workspace-colors-test
(:require
[app.common.schema :as sm]
[app.common.types.color :as cc]
[app.common.types.shape :as cts]
[app.common.uuid :as uuid]
[app.main.data.workspace.colors :as dwc]
[app.main.ui.workspace.colorpicker.hsl :as hsl]
@ -50,6 +52,27 @@
(t/is (thrown? js/Error
(ptk/event? (dwc/add-fill #{uuid/zero} color4 1))))))
(t/deftest update-shape-stroke-attrs-changes-an-existing-stroke
(let [shape {:strokes [{:stroke-color "#000000" :stroke-opacity 1
:stroke-width 1 :stroke-style :solid
:stroke-alignment :inner}]}
result (dwc/update-shape-stroke-attrs shape 0 {:stroke-width 4})]
(t/is (= {:stroke-color "#000000" :stroke-opacity 1
:stroke-width 4 :stroke-style :solid
:stroke-alignment :inner}
(get-in result [:strokes 0])))))
(t/deftest update-shape-stroke-attrs-creates-a-stroke-with-color
;; Regression for https://github.com/penpot/penpot/issues/12463.
;; A stroke built from style attributes alone has no color, so the
;; backend rejects the shape as invalid.
(let [result (dwc/update-shape-stroke-attrs {:type :bool} 0 {:stroke-width 4})
stroke (get-in result [:strokes 0])]
(t/is (= 1 (count (:strokes result))))
(t/is (= "#000000" (:stroke-color stroke)))
(t/is (= 4 (:stroke-width stroke)))
(t/is (sm/validate cts/schema:stroke stroke))))
(t/deftest update-colorpicker-color-skips-add-recent-on-incomplete-image-state
;; Regression for https://github.com/penpot/penpot/issues/8443.
@ -158,3 +181,67 @@
:app.main.data.workspace.colors/change-stroke-color 1
:app.main.data.workspace.undo/commit-undo-transaction 1}
(frequencies @types)))))
(def ^:private gradient-colorpicker
{:type :linear-gradient
:editing-stop 0
:gradient {:type :linear :start-x 0.5 :start-y 0 :end-x 0.5 :end-y 1 :width 1}
:stops [{:color "#000000" :opacity 1 :offset 0}
{:color "#000000" :opacity 0 :offset 1}]
:current-color {:color "#000000" :opacity 1 :offset 0}})
(t/deftest update-colorpicker-leaves-gradient-tab-on-plain-color
;; Regression for https://github.com/penpot/penpot/issues/12463.
;; Undoing a gradient with the colorpicker open sends a plain color.
;; The colorpicker dropped the stops but stayed in gradient mode, so
;; adding a stop built a gradient without coordinates or colors.
(doseq [type [:linear-gradient :radial-gradient]]
(t/testing (name type)
(let [state {:colorpicker (assoc gradient-colorpicker :type type)}
event (dwc/update-colorpicker {:color "#000000" :opacity 1})
result (:colorpicker (ptk/update event state))]
(t/is (= :color (:type result)))
(t/is (nil? (:stops result)))
(t/is (nil? (:gradient result)))))))
(t/deftest update-colorpicker-switches-to-image-tab-on-image-color
(let [state {:colorpicker gradient-colorpicker}
image {:id uuid/zero :width 10 :height 10 :mtype "image/png"}
event (dwc/update-colorpicker {:image image :opacity 1})
result (:colorpicker (ptk/update event state))]
(t/is (= :image (:type result)))))
(t/deftest update-colorpicker-keeps-color-tab-on-plain-color
(let [state {:colorpicker {:type :color
:current-color {:color "#000000" :opacity 1}}}
event (dwc/update-colorpicker {:color "#ff0000" :opacity 1})
result (:colorpicker (ptk/update event state))]
(t/is (= :color (:type result)))
(t/is (= "#ff0000" (get-in result [:current-color :color])))))
(t/deftest colorpicker-onchange-runner-skips-invalid-gradient
(let [calls (atom [])
runner (#'dwc/colorpicker-onchange-runner #(swap! calls conj %))
empty-gradient {:colorpicker {:type :linear-gradient
:stops [{:offset 0.5}]}}]
(ptk/watch runner empty-gradient nil)
(t/is (empty? @calls))
(ptk/watch runner {:colorpicker gradient-colorpicker} nil)
(t/is (= 1 (count @calls)))
(t/is (= [{:color "#000000" :opacity 1 :offset 0}
{:color "#000000" :opacity 0 :offset 1}]
(get-in (first @calls) [:gradient :stops])))))
(t/deftest colorpicker-onchange-runner-applies-plain-and-image-colors
;; The guard only drops invalid gradients: colors without a gradient
;; must still reach `on-change`.
(let [calls (atom [])
runner (#'dwc/colorpicker-onchange-runner #(swap! calls conj %))
image {:id uuid/zero :width 10 :height 10 :mtype "image/png"}]
(ptk/watch runner {:colorpicker {:type :color
:current-color {:color "#ff0000" :opacity 1}}} nil)
(ptk/watch runner {:colorpicker {:type :image
:current-color {:image image :opacity 1}}} nil)
(t/is (= 2 (count @calls)))
(t/is (= "#ff0000" (:color (first @calls))))
(t/is (= image (:image (second @calls))))))

View File

@ -0,0 +1,62 @@
;; 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 frontend-tests.data.workspace-shape-layout-test
(:require
[app.common.schema :as sm]
[app.common.types.shape.layout :as ctl]
[app.main.data.workspace.shape-layout :as dwsl]
[cljs.test :as t :include-macros true]))
(def ^:private valid-layout-padding?
(sm/lazy-validator ctl/schema:layout-attrs))
(t/deftest update-shape-layout-patches-one-padding-side
(let [shape {:layout :flex
:layout-padding-type :multiple
:layout-padding {:p1 1 :p2 2 :p3 3 :p4 4}}
result (dwsl/update-shape-layout shape {:layout-padding {:p1 12}})]
(t/is (= {:p1 12 :p2 2 :p3 3 :p4 4} (:layout-padding result)))))
(t/deftest update-shape-layout-completes-a-missing-padding
;; Regression for https://github.com/penpot/penpot/issues/12463.
;; A layout without padding (made through the API) saved `{:p1 12}`
;; after setting one side, and the backend rejected the shape.
(let [shape {:layout :flex :layout-padding-type :multiple}
result (dwsl/update-shape-layout shape {:layout-padding {:p1 12}})]
(t/is (= {:p1 12 :p2 0 :p3 0 :p4 0} (:layout-padding result)))
(t/is (valid-layout-padding? (select-keys result [:layout-padding])))))
(t/deftest update-shape-layout-leaves-padding-alone-for-other-changes
(let [shape {:layout :flex}
result (dwsl/update-shape-layout shape {:layout-gap {:row-gap 4}})]
(t/is (not (contains? result :layout-padding)))
(t/is (= {:row-gap 4} (:layout-gap result)))))
(t/deftest update-shape-layout-completes-a-padding-side-cleared-to-nil
(let [shape {:layout :flex
:layout-padding-type :multiple
:layout-padding {:p1 1 :p2 2 :p3 3 :p4 4}}
result (dwsl/update-shape-layout shape {:layout-padding {:p1 nil}})]
(t/is (= {:p1 0 :p2 2 :p3 3 :p4 4} (:layout-padding result)))
(t/is (valid-layout-padding? (select-keys result [:layout-padding])))))
(t/deftest update-shape-layout-removes-padding-when-the-whole-value-is-nil
(let [shape {:layout :flex
:layout-padding-type :multiple
:layout-padding {:p1 1 :p2 2 :p3 3 :p4 4}}
result (dwsl/update-shape-layout shape {:layout-padding nil})]
(t/is (not (contains? result :layout-padding)))))
(t/deftest update-shape-layout-completes-a-stored-partial-padding
;; A board saved with a partial padding before the fix is completed by
;; any later layout change, not only by a padding one.
(let [shape {:layout :flex
:layout-padding-type :multiple
:layout-padding {:p1 12}}
result (dwsl/update-shape-layout shape {:layout-gap {:row-gap 4}})]
(t/is (= {:p1 12 :p2 0 :p3 0 :p4 0} (:layout-padding result)))
(t/is (valid-layout-padding? (select-keys result [:layout-padding])))))

View File

@ -14,6 +14,7 @@
[app.common.test-helpers.shapes :as cths]
[app.common.types.modifiers :as ctm]
[app.common.types.shape :as cts]
[app.common.types.shape.text :as ctst]
[app.common.types.text :as txt]
[app.common.uuid :as uuid]
[app.main.data.workspace.texts :as dwt]
@ -642,6 +643,29 @@
(let [node {:type "paragraph" :children []}]
(t/is (= node (dwt/ensure-valid-text-content node))))))
;; ---------------------------------------------------------------------------
;; Tests: editor-shape-content (legacy editor commit)
;; ---------------------------------------------------------------------------
(t/deftest editor-shape-content-drops-nil-paragraph-attrs
(t/testing "a nil :text-decoration left in the paragraph data is dropped"
(let [exported {:type "root"
:children [{:type "paragraph-set"
:children [{:type "paragraph"
:key "1gt0a"
:font-family "sourcesanspro"
:text-decoration nil
:typography-ref-id nil
:children [{:text "hello"
:font-family "sourcesanspro"}]}]}]}
shape {:content {:type "root" :vertical-align "center" :children []}}
content (dwt/editor-shape-content exported shape)
para (get-in content [:children 0 :children 0])]
(t/is (ctst/valid-content? content))
(t/is (not (contains? para :text-decoration)))
(t/is (= "sourcesanspro" (:font-family para)))
(t/is (= "center" (:vertical-align content))))))
;; ---------------------------------------------------------------------------
;; Tests: merge-live-text-dimensions (Design tab / edition outline)
;; ---------------------------------------------------------------------------

View File

@ -5,6 +5,7 @@
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns frontend-tests.logic.pasting-in-containers-test
(:require
[app.common.data :as d]
[app.common.geom.point :as gpt]
[app.common.test-helpers.components :as cthc]
[app.common.test-helpers.compositions :as ctho]
@ -16,6 +17,7 @@
[app.common.types.component :as ctk]
[app.common.uuid :as uuid]
[app.main.data.workspace :as dw]
[app.main.data.workspace.groups :as dwgr]
[app.main.data.workspace.selection :as dws]
[app.main.data.workspace.shapes :as dwsh]
[app.main.data.workspace.svg-upload :as dwsvg]
@ -998,6 +1000,111 @@
(t/is (some? created'))
(t/is (= (:id frame-blue) (:parent-id created')))))))))
(defn- svg-upload-in-group-events
"Group `rect`, select it again inside the group and upload an SVG at
`position`."
[rect position]
(let [svg-data {:name "test.svg"
:attrs {:width 100 :height 100}
:content [{:tag :rect
:attrs {:x "10" :y "10" :width "20" :height "20"}}]}]
[(dws/select-shapes (d/ordered-set (:id rect)))
(dwgr/group-selected)
(dws/select-shapes (d/ordered-set (:id rect)))
(dwsvg/add-svg-shapes nil svg-data position nil)]))
(defn- check-svg-in-group
[new-state expected-frame-id]
(let [file' (ths/get-file-from-state new-state)
objects (:objects (cthf/current-page file'))
svg' (->> (vals objects)
(filter #(= (:name %) "test"))
first)
parent' (get objects (:parent-id svg'))]
;; The shape is created inside the group, with the group's frame
(t/is (some? svg'))
(t/is (= :group (:type parent')))
(t/is (= expected-frame-id (:frame-id svg')))
(t/is (= (:frame-id parent') (:frame-id svg')))
(cthf/validate-file! file')))
(t/deftest svg-upload-in-group-inside-board-uses-group-frame
"Uploading an SVG with a selection inside a grouped board child keeps the board as frame, even with the cursor outside it"
(t/async
done
(let [;; ==== Setup
file (-> (cthf/sample-file :file1)
(ctho/add-frame :board {:name "board" :x 0 :y 0 :width 500 :height 500})
(cths/add-sample-shape :rect1 :parent-label :board
:x 10 :y 10 :width 50 :height 50))
store (ths/setup-store file)
;; ==== Action
events (svg-upload-in-group-events (cths/get-shape file :rect1)
(gpt/point 2000 2000))]
(ths/run-store
store done events
(fn [new-state]
(check-svg-in-group new-state (:id (cths/get-shape file :board))))))))
(t/deftest svg-upload-in-group-at-root-uses-group-frame
"Uploading an SVG with a selection inside a group at the root keeps the root as frame, even with the cursor over a board"
(t/async
done
(let [;; ==== Setup
file (-> (cthf/sample-file :file1)
(ctho/add-frame :board {:name "board" :x 1000 :y 1000 :width 500 :height 500})
(cths/add-sample-shape :rect1 :x 10 :y 10 :width 50 :height 50))
store (ths/setup-store file)
;; ==== Action
events (svg-upload-in-group-events (cths/get-shape file :rect1)
(gpt/point 1200 1200))]
(ths/run-store
store done events
(fn [new-state]
(check-svg-in-group new-state uuid/zero))))))
(t/deftest svg-upload-in-board-keeps-parent-board
"Uploading an SVG with a shape selected directly in a board keeps that board as frame, even with the cursor over another board"
(t/async
done
(let [;; ==== Setup
file (-> (cthf/sample-file :file1)
(ctho/add-frame :board-a {:name "board-a" :x 0 :y 0 :width 500 :height 500})
(ctho/add-frame :board-b {:name "board-b" :x 1000 :y 1000 :width 500 :height 500})
(cths/add-sample-shape :rect1 :parent-label :board-a
:x 10 :y 10 :width 50 :height 50))
store (ths/setup-store file)
;; ==== Action
svg-data {:name "test.svg"
:attrs {:width 100 :height 100}
:content [{:tag :rect
:attrs {:x "10" :y "10" :width "20" :height "20"}}]}
events [(dws/select-shapes (d/ordered-set (:id (cths/get-shape file :rect1))))
(dwsvg/add-svg-shapes nil svg-data (gpt/point 1200 1200) nil)]]
(ths/run-store
store done events
(fn [new-state]
(let [;; ==== Get
file' (ths/get-file-from-state new-state)
objects (:objects (cthf/current-page file'))
svg' (->> (vals objects)
(filter #(= (:name %) "test"))
first)
board-a (cths/get-shape file :board-a)]
;; ==== Check
(t/is (some? svg'))
(t/is (= (:id board-a) (:frame-id svg')))
(t/is (= (:id board-a) (:parent-id svg')))
(cthf/validate-file! file')))))))
(t/deftest props-paste-with-unloaded-page-is-noop
"Pasting props while the page is not loaded is ignored instead of crashing"
(t/async

View File

@ -54,6 +54,7 @@
[frontend-tests.data.workspace-pages-test]
[frontend-tests.data.workspace-path-edition-test]
[frontend-tests.data.workspace-reflow-test]
[frontend-tests.data.workspace-shape-layout-test]
[frontend-tests.data.workspace-shortcuts-test]
[frontend-tests.data.workspace-sync-text-wasm-test]
[frontend-tests.data.workspace-texts-test]
@ -298,6 +299,7 @@
'frontend-tests.data.workspace-pages-test
'frontend-tests.data.workspace-path-edition-test
'frontend-tests.data.workspace-reflow-test
'frontend-tests.data.workspace-shape-layout-test
'frontend-tests.data.workspace-shortcuts-test
'frontend-tests.data.workspace-sync-text-wasm-test
'frontend-tests.data.workspace-texts-test

View File

@ -10,6 +10,7 @@
[app.config :as cf]
[app.main.ui.workspace.sidebar.options.menus.stroke :as stroke]
[app.main.ui.workspace.sidebar.options.rows.stroke-row :as stroke-row]
[app.main.ui.workspace.sidebar.options.shapes.multiple :as multiple]
[clojure.test :as t :include-macros true]))
(def ^:private per-side-flags (conj cf/flags :stroke-per-side))
@ -93,3 +94,31 @@
{:stroke-width-top "sw" :stroke-width-left "other"} true)))
(t/is (nil? (stroke-row/stroke-width-input-token
{:stroke-width-left "other"} true)))))
(def ^:private solid-stroke
{:stroke-color "#000000"
:stroke-opacity 1
:stroke-width 1
:stroke-style :solid
:stroke-alignment :inner})
(defn- multiple-stroke-values
[shapes]
(let [[_ids values _tokens] (multiple/get-attrs* shapes {} :stroke)]
values))
(t/deftest multiple-selection-reads-bool-strokes-test
;; Regression for https://github.com/penpot/penpot/issues/13263: the
;; menu ignored the bool strokes, showed the rect stroke as shared and
;; editing it created a stroke on the bool.
(t/testing "a bool without strokes and a rect with one are mixed"
(t/is (= :multiple
(:strokes (multiple-stroke-values
[{:id :bool-a :type :bool :strokes []}
{:id :rect-a :type :rect :strokes [solid-stroke]}])))))
(t/testing "bools with the same stroke share it"
(t/is (= [solid-stroke]
(:strokes (multiple-stroke-values
[{:id :bool-a :type :bool :strokes [solid-stroke]}
{:id :bool-b :type :bool :strokes [solid-stroke]}]))))))

View File

@ -57,26 +57,17 @@ pub fn render_wasm_label(render_state: &mut RenderState) {
let mut paint = skia::Paint::default();
paint.set_color(skia::Color::GRAY);
let mut str = if render_state.options.is_debug_visible() {
let str = if render_state.options.is_debug_visible() {
"WebGL rendering (debug)"
} else {
"WebGL rendering"
};
let dpr = render_state.options.dpr;
let (scalar, _) = get_resources().fonts.debug_font().measure_str(str, None);
let mut p = skia::Point::new(canvas_width - (20.0 * dpr) - scalar, 50.0 * dpr);
let debug_font = get_resources().fonts.debug_font();
let (scalar, _) = debug_font.measure_str(str, None);
let p = skia::Point::new(canvas_width - (20.0 * dpr) - scalar, 50.0 * dpr);
canvas.draw_str(str, p, debug_font, &paint);
if render_state.options.is_text_editor_v3() {
str = "Text Editor v3";
let (scalar, _) = get_resources().fonts.debug_font().measure_str(str, None);
p.x = canvas_width - (20.0 * dpr) - scalar;
p.y += 15.0 * dpr;
canvas.draw_str(str, p, debug_font, &paint);
}
}
pub fn render_debug_tiles_for_viewbox(render_state: &mut RenderState) {

View File

@ -1,7 +1,6 @@
// Render options flags
const DEBUG_VISIBLE: u32 = 0x01;
const PROFILE_REBUILD_TILES: u32 = 0x02;
const TEXT_EDITOR_V3: u32 = 0x04;
const SHOW_WASM_INFO: u32 = 0x08;
// Render performance options
@ -114,10 +113,6 @@ impl RenderOptions {
self.interactive_transform = enabled;
}
pub fn is_text_editor_v3(&self) -> bool {
self.flags & TEXT_EDITOR_V3 == TEXT_EDITOR_V3
}
pub fn show_wasm_info(&self) -> bool {
self.flags & SHOW_WASM_INFO == SHOW_WASM_INFO
}

View File

@ -74,6 +74,9 @@ NON_HUMAN_COAUTHOR_PATTERN = re.compile(
re.IGNORECASE,
)
AI_TRAILER_PATTERN = re.compile(r"^\s*ai-assisted-by\s*:(.*)$", re.IGNORECASE)
MODEL_ID_PATTERN = re.compile(r"[a-z0-9]+(?:[.-][a-z0-9]+)*")
URL_PATTERN = re.compile(r"https?://\S+")
# Git appends the staged diff after this marker for `git commit -v` and
@ -285,6 +288,26 @@ def check_co_authored_by(message):
)
def check_ai_assisted_by(message):
"""Validate every AI-assisted-by value as a bare lowercase model ID."""
offenders = []
for line_number, line in enumerate(message.split("\n"), start=1):
match = AI_TRAILER_PATTERN.match(line)
if match and not MODEL_ID_PATTERN.fullmatch(match.group(1).strip()):
offenders.append((line_number, line))
if not offenders:
return True, None
details = "\n".join(
f" line {line_number}: {line!r}"
for line_number, line in offenders
)
return False, (
"AI-assisted-by must use a bare lowercase canonical model ID slug "
"(for example, gpt-6.1-terra), without a provider prefix. "
"Offending line(s):\n" + details
)
# ═══════════════════════════════════════════════════════════════════════════════
def main():
@ -320,6 +343,7 @@ def main():
("Blank line after subject", check_body_blank_line),
("Body wrapped at 80 chars", check_body_line_length),
("Co-authored-by is human only", check_co_authored_by),
("AI-assisted-by uses a model ID slug", check_ai_assisted_by),
]
all_ok = True

View File

@ -17,6 +17,7 @@ import importlib.util
import io
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
@ -194,6 +195,53 @@ class CoAuthorTrailerTests(unittest.TestCase):
self.assert_ok(":bug: Fix crash\n\nBody.\n\nCo-developed-by: Someone <someone@example.com>\n")
class AIAssistedTrailerTests(unittest.TestCase):
def test_valid_and_absent_trailers(self):
for trailer in ("", "AI-assisted-by: gpt-6.1-terra",
"ai-assisted-by: deepseek-v4-flash",
"AI-assisted-by: gpt-6.1-terra\nAI-assisted-by: mimo-v2.5"):
with self.subTest(trailer=trailer):
ok, error = check_commit.check_ai_assisted_by(":bug: Fix crash\n\n" + trailer)
self.assertTrue(ok, error)
def test_invalid_values_are_reported(self):
for value in ("", "openai/gpt-6.1-terra", "GPT-6.1 Terra",
"gpt-6.1-terra extra", "-gpt", "gpt-", "gpt..6", "gpt_6"):
with self.subTest(value=value):
ok, error = check_commit.check_ai_assisted_by(
":bug: Fix crash\n\nAI-assisted-by: " + value
)
self.assertFalse(ok)
self.assertIn("line 3", error)
def test_each_trailer_is_checked_and_all_offenders_reported(self):
ok, error = check_commit.check_ai_assisted_by(
":bug: Fix crash\n\nAI-assisted-by: gpt-6.1-terra\n"
"AI-assisted-by: openai/gpt-6.1-terra\n"
"ai-assisted-by: GPT-6.1 Terra"
)
self.assertFalse(ok)
self.assertIn("line 4", error)
self.assertIn("line 5", error)
def test_cli_rejects_invalid_trailer(self):
with tempfile.TemporaryDirectory() as directory:
subprocess.run(["git", "init", "-q", directory], check=True)
subprocess.run(
["git", "-C", directory, "-c", "user.name=Test",
"-c", "user.email=test@example.com", "commit", "-q",
"--allow-empty", "-m", ":bug: Fix crash",
"-m", "AI-assisted-by: openai/gpt-6.1-terra"],
check=True,
)
result = subprocess.run(
[str(SCRIPT_PATH), "-c", "HEAD"], cwd=directory,
capture_output=True, text=True, check=False,
)
self.assertEqual(result.returncode, 1)
self.assertIn("AI-assisted-by", result.stderr)
class SubjectRulesRegressionTests(unittest.TestCase):
"""Guard the pre-existing validators against accidental breakage."""