penpot/backend/src/app/tasks/delete_object.clj
Álvaro Tejero Cantero ee9067e154
✨ Apply the branch review vocabulary and drop the pinned revision
Apply the designer's answers on the wording of branch reviews:

- A verdict is two buttons, Approve and Request changes. A stale
  verdict reads Approved an earlier version or Requested changes on
  an earlier version, and Send appears only with a comment.
- Close review everywhere, Branch review in titles, Merges for the
  merge list, Mark as viewed for compare marks, and Merge into main.
- Publishing goes, with the pinned revision it moved. Reviewers see
  the live branch, a verdict goes stale once the branch is saved
  after it, and the review viewer plays the live branch. Migration
  0819 drops the pinned columns and hands their snapshots to the
  snapshot clean-up.
- The frontend takes the branch-review names: namespaces, state
  keys, events, i18n prefixes, and the branch-compare namespace for
  the compare panel.

A failed branch count no longer stays an error after a listing
succeeds: the listing's size stands in for the count.

AI-assisted-by: claude-opus-5-5
2026-11-24 15:00:25 +01:00

333 lines
13 KiB
Clojure

;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) KALEIDOS SUBSIDIARY SL
(ns app.tasks.delete-object
"A generic task for object deletion cascade handling"
(:require
[app.common.logging :as l]
[app.common.schema :as sm]
[app.common.time :as ct]
[app.db :as db]
[app.db.sql :as-alias sql]
[app.features.file-snapshots :as fsnap]
[app.jobs :as jobs]
[app.loggers.audit :as audit]
[app.rpc.commands.files :as files]
[app.rpc.commands.profile :as profile]
[app.storage :as sto]
[integrant.core :as ig]))
(def ^:dynamic *team-deletion* false)
(def ^:dynamic *cascade*
"Accumulates the ids marked deleted by the current cascade execution,
grouped by entity. Bound by the task entry point; nil on direct calls
(e.g. objects-gc, whose purges are announced by their own procs)."
nil)
(defn- record
[kind id]
(when (some? *cascade*)
(swap! *cascade* update kind conj id)))
(defn- top-exists?
"The cascade marks blindly, so an unknown top id would report phantom
rows. Every queue submission and SREPL call names a real row; only
check, never change behavior: a missing row just skips the run."
[{:keys [::db/conn]} {:keys [object id]}]
(let [object (when (some? object) (keyword (name object)))]
(if (contains? #{:team :project :file :profile} object)
(some? (db/get* conn object {:id id}
{::db/remove-deleted false
::sql/columns [:id]}))
true)))
(defmulti delete-object
(fn [_ props] (:object props)))
(defmethod delete-object :snapshot
[{:keys [::db/conn] :as cfg} {:keys [id file-id deleted-at]}]
(l/trc :obj "snapshot" :id (str id) :file-id (str file-id)
:deleted-at (ct/format-inst deleted-at))
(db/update! conn :file-change
{:deleted-at deleted-at
:updated-at (ct/now)}
{:id id :file-id file-id}
{::db/return-keys false})
(db/update! conn :file-data
{:deleted-at deleted-at}
{:id id :file-id file-id :type "snapshot"}
{::db/return-keys false}))
;; --- Branching: what a deleted file takes with it
;;
;; A file's row is the unit of storage and permission, so the objects GC
;; deletes it; its design reviews, threads, and tasks belong to the file
;; family and outlive it, except those of a branch no merge accepted.
(def ^:private sql:get-branch-edges
"SELECT fb.id AS edge_id,
fb.base_snapshot_id,
fb.source_file_id,
EXISTS (SELECT 1
FROM file_branch_merge AS fbm
WHERE fbm.file_branch_id = fb.id) AS merged
FROM file_branch AS fb
WHERE fb.branch_file_id = ?")
(def ^:private sql:delete-unmerged-branch-reviews
"DELETE FROM file_branch_review AS r
WHERE r.file_branch_id = ?
AND NOT EXISTS (SELECT 1
FROM file_branch_merge AS fbm
WHERE fbm.review_id = r.id)")
(defn- delete-unmerged-branch
"Delete what belonged to a branch that no merge accepted, before its
file row goes: the threads written on it (their messages and read marks
cascade), the tasks still on it, its reviews with their verdicts and
activity, the merge base it was derived from, and the branch edge.
A merged branch keeps all of it. Its merge moved only the threads that
hold an open task or that were written outside a review; a thread it
leaves behind stays on the branch file, and the purge only nulls its
`file_id`. Its edge and the review the merge names stay as the record
of the merge, read long after the file is gone, and its merge base was
released when it merged. Must run in the caller transaction."
[{:keys [::db/conn] :as cfg}
{:keys [file-id edge-id source-file-id base-snapshot-id deleted-at]}]
;; a task names its thread with a `SET NULL` key, so the threads go
;; first and the tasks are still found by their file afterwards
(db/delete! conn :comment-thread {:file-id file-id} {::db/return-keys false})
(db/delete! conn :file-task {:file-id file-id} {::db/return-keys false})
(db/exec-one! conn [sql:delete-unmerged-branch-reviews edge-id])
;; the merge base is a change row of the source, pinned while the
;; branch is open; it dies with the branch, or the source file row
;; could not be collected either
(when (some? base-snapshot-id)
(fsnap/delete! cfg
:id base-snapshot-id
:file-id source-file-id
:deleted-at deleted-at))
(db/delete! conn :file-branch {:id edge-id} {::db/return-keys false}))
(def ^:private sql:get-file-branches
"SELECT id, branch_file_id
FROM file_branch
WHERE source_file_id = ?
AND branch_file_id IS NOT NULL
AND deleted_at IS NULL")
(defmethod delete-object :file
[{:keys [::db/conn] :as cfg} {:keys [id deleted-at file-ids]}]
(when-let [file (db/get* conn :file {:id id}
{::db/remove-deleted false
::sql/columns [:id :is-shared]})]
(l/trc :obj "file" :id (str id)
:deleted-at (ct/format-inst deleted-at))
;; Branching: keep the branch metadata in sync when the deleted file
;; IS a branch copy (deleted through paths other than
;; delete-file-branch, e.g. a project deletion) ...
(db/update! conn :file-branch
{:deleted-at deleted-at}
{:branch-file-id id}
{::db/return-keys false})
;; ... and settle what the branch owned. A branch no merge accepted
;; takes its threads, tasks, reviews, and the edge itself with it; a
;; merged branch keeps them, and the edge outlives the file, so the
;; compare marks of either branch are deleted here: the cascade from
;; the edge only reaches the marks of a branch whose edge goes.
(doseq [{:keys [edge-id merged] :as edge} (db/exec! conn [sql:get-branch-edges id])]
(db/delete! conn :file-branch-change-mark
{:file-branch-id edge-id}
{::db/return-keys false})
(when-not merged
(delete-unmerged-branch cfg (assoc edge
:file-id id
:deleted-at deleted-at))))
;; ... and when it is the SOURCE of branches, cascade the logical
;; deletion to them: branch files are hidden from every listing, so
;; once the source is gone nothing else could ever reach (or GC)
;; them. Branches stack under `:branch-stacking`, so a branch file
;; can be a source too: this follows the chain of edges to its end
;; and a grandchild branch is deleted with the file its chain starts
;; from. A parent that merged re-parented its children, so they are
;; not in this branch list and survive it.
(doseq [branch (db/exec! conn [sql:get-file-branches id])]
(db/update! conn :file-branch
{:deleted-at deleted-at}
{:id (:id branch)}
{::db/return-keys false})
(delete-object cfg {:object :file
:id (:branch-file-id branch)
:deleted-at deleted-at}))
(db/update! conn :file
{:deleted-at deleted-at
:is-shared false}
{:id id}
{::db/return-keys false})
(when (and (:is-shared file)
(not *team-deletion*))
;; NOTE: we don't prevent file deletion on absorb operation failure
(try
(db/tx-run! cfg files/absorb-library id :file-ids file-ids)
(catch Throwable cause
(l/warn :hint "error on absorbing library"
:file-id id
:cause cause))))
;; Mark file change to be deleted, but only the rows that do not carry a
;; date yet. A revision is born already scheduled for deletion one hour
;; later, and rewriting its date here would push it out to the trash
;; lifetime; the collector would still take it, just much later than it
;; should.
(db/update! conn :file-change
{:deleted-at deleted-at
:updated-at (ct/now)}
{:file-id id :deleted-at nil}
{::db/return-keys false})
;; Mark file data fragment to be deleted
(db/update! conn :file-data
{:deleted-at deleted-at}
{:file-id id}
{::db/return-keys false})
;; Mark file media objects to be deleted
(db/update! conn :file-media-object
{:deleted-at deleted-at}
{:file-id id}
{::db/return-keys false})
;; Mark thumbnails to be deleted
(db/update! conn :file-thumbnail
{:deleted-at deleted-at}
{:file-id id}
{::db/return-keys false})
(db/update! conn :file-tagged-object-thumbnail
{:deleted-at deleted-at}
{:file-id id}
{::db/return-keys false})
(record :files id)))
(defmethod delete-object :project
[{:keys [::db/conn] :as cfg} {:keys [id deleted-at]}]
(l/trc :obj "project" :id (str id)
:deleted-at (ct/format-inst deleted-at))
(db/update! conn :project
{:deleted-at deleted-at}
{:id id}
{::db/return-keys false})
(doseq [file (db/query conn :file
{:project-id id}
{::db/columns [:id :deleted-at]})]
(delete-object cfg (assoc file
:object :file
:deleted-at deleted-at)))
(record :projects id))
(defmethod delete-object :team
[{:keys [::db/conn] :as cfg} {:keys [id deleted-at]}]
(l/trc :obj "team" :id (str id)
:deleted-at (ct/format-inst deleted-at))
(db/update! conn :team
{:deleted-at deleted-at}
{:id id}
{::db/return-keys false})
(db/update! conn :team-font-variant
{:deleted-at deleted-at}
{:team-id id}
{::db/return-keys false})
(binding [*team-deletion* true]
(doseq [project (db/query conn :project
{:team-id id}
{::db/columns [:id :deleted-at]})]
(delete-object cfg (assoc project
:object :project
:deleted-at deleted-at))))
(record :teams id))
(defmethod delete-object :profile
[{:keys [::db/conn] :as cfg} {:keys [id deleted-at]}]
(l/trc :obj "profile" :id (str id)
:deleted-at (ct/format-inst deleted-at))
(db/update! conn :profile
{:deleted-at deleted-at}
{:id id}
{::db/return-keys false})
(doseq [team (profile/get-owned-teams conn id)]
(jobs/heartbeat cfg)
(delete-object cfg (assoc team
:object :team
:deleted-at deleted-at))))
(defmethod delete-object :default
[_cfg props]
(l/wrn :obj (:object props) :hint "not implementation found"))
(def schema:delete-object-params
[:map
[:object [:enum :snapshot :team :project :profile :file]]
[:deleted-at ::ct/inst]
[:id ::sm/uuid]
[:file-id {:optional true} ::sm/uuid]
[:file-ids {:optional true} [:vector ::sm/uuid]]])
(defn execute-delete-object
"Plain job handler: run the delete-object multimethod on the provided
params inside a single transaction, tracking the cascade and reporting
it as an audit event when anything was marked."
[cfg params]
(db/tx-run! cfg
(fn [cfg]
(when (top-exists? cfg params)
(binding [*cascade* (atom {:teams [] :projects [] :files []})]
(delete-object cfg params)
(let [{:keys [teams projects files]} @*cascade*]
(when (or (seq teams) (seq projects) (seq files))
(audit/submit cfg {:name "delete-object-with-cascade"
:type "action"
:props {:object (:object params)
:id (:id params)
:deleted-at (:deleted-at params)
:cascade {:team-ids teams
:project-ids projects
:file-ids files}}
:context {:triggered-by "delete-object"}}))))))))
(defmethod ig/assert-key ::job-def
[_ params]
(assert (db/pool? (::db/pool params)) "expected a valid database pool")
(assert (sto/valid-storage? (::sto/storage params)) "expected valid storage to be provided"))
(defmethod ig/init-key ::job-def
[_ cfg]
{::jobs/name :delete-object
::jobs/schema schema:delete-object-params
::jobs/handler
(fn [_context params]
(execute-delete-object cfg params))
::jobs/decoder (sm/decoder schema:delete-object-params sm/json-transformer)
::jobs/validator (sm/validator schema:delete-object-params)})