From 96b89436e376f43a10fec85497bece6d04ef69fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Tejero=20Cantero?= Date: Wed, 18 Nov 2026 00:07:13 +0100 Subject: [PATCH] :bug: Fix the backend findings of the design-review tasks review Fix the findings left after merging the design-review tasks (#12939): - Purging a profile that authored a task no longer fails on the foreign-key order: the chunk defers the file_task keys. - The review activity folds every row on the server instead of the newest 2000, and objects-gc compacts each finished sitting. - Marking the tasks of a deleted layer lost has no layer cap: objects above 500, or invalid ones, are not kept for restore. The client reports a failure instead of hiding it. - Task creation and the merge's task move take the branch file row lock, so no task is left behind. A deleted branch refuses new tasks, and main's clients hear about moved tasks. - Task change messages carry the session and the changed rows. A client ignores its own and patches its list for others. - A carried open task whose layer did not reach main lands on the layer's immediate parent, else on an area with the layer's bounds. - Only a task's author may delete it, and the deletion writes a deleted event. - Relinking a task moves the thread created with it. - Merges and updates from main write their revision row with its kind. AI-assisted-by: claude-opus-5-5 --- backend/src/app/rpc/commands/files_branch.clj | 41 +- .../app/rpc/commands/files_pull_request.clj | 102 ++++- backend/src/app/rpc/commands/files_task.clj | 369 +++++++++++++---- backend/src/app/tasks/objects_gc.clj | 152 ++++++- .../test/backend_tests/objects_gc_test.clj | 139 +++++++ .../backend_tests/rpc_file_branch_test.clj | 42 ++ .../rpc_file_pull_request_test.clj | 72 ++++ .../test/backend_tests/rpc_file_task_test.clj | 379 +++++++++++++++++- .../src/app/main/data/workspace/review.cljs | 17 +- .../src/app/main/data/workspace/tasks.cljs | 61 ++- .../app/main/ui/workspace/review/details.cljs | 10 +- .../app/main/ui/workspace/review/tasks.cljs | 16 +- .../data/workspace_tasks_test.cljs | 58 +++ .../ui/review_details_test.cljs | 24 ++ frontend/translations/en.po | 12 + frontend/translations/es.po | 12 + 16 files changed, 1362 insertions(+), 144 deletions(-) diff --git a/backend/src/app/rpc/commands/files_branch.clj b/backend/src/app/rpc/commands/files_branch.clj index e85e9da959..8d3f7892a1 100644 --- a/backend/src/app/rpc/commands/files_branch.clj +++ b/backend/src/app/rpc/commands/files_branch.clj @@ -32,6 +32,7 @@ [app.db :as db] [app.db.sql :as-alias sql] [app.features.fdata :as fdata] + [app.features.file-changes :as fchanges] [app.features.file-snapshots :as fsnap] [app.features.logical-deletion :as ldel] [app.jobs :as jobs] @@ -1218,7 +1219,7 @@ :hint "select at least one change to merge")) finish-branch! - (fn [ts] + (fn [ts merged-data] ;; record the merge, mark the branch merged and ;; delete it and its file in this same transaction ;; (no client-driven second call, no window where a @@ -1228,15 +1229,29 @@ ;; lines below close. (let [merge-id (record-merge! conn branch {:profile-id profile-id :comment comment - :created-at ts})] - ;; the tasks of the branch outlive it: the open ones - ;; keep going on main, the closed ones are its history - (ftask/move-branch-tasks cfg {:branch-file-id branch-file-id - :main-id main-id - :merge-id merge-id - :branch-name (:name branch) - :profile-id profile-id - :notify-assignees notify-assignees})) + :created-at ts}) + ;; the tasks of the branch outlive it: the open + ;; ones keep going on main (on the layer the + ;; merge left them), the closed ones are its + ;; history + moved (ftask/move-branch-tasks cfg {:branch-file-id branch-file-id + :main-id main-id + :merge-id merge-id + :branch-name (:name branch) + :profile-id profile-id + :notify-assignees notify-assignees + :merged-data merged-data + :branch-data branch-data + :base-data base-data})] + ;; main's open clients patch their task list + (when (seq moved) + (vswap! messages conj + {:topic main-id + :message (ftask/tasks-change-message + conn {:file-id main-id + :profile-id profile-id + :session-id session-id + :task-ids (map :id moved)})}))) (db/update! conn :file-branch {:status "merged" :merged-at ts @@ -1285,7 +1300,7 @@ ;; Nothing to integrate (branch matches main): close the ;; branch without touching main. (let [ts (ct/now)] - (finish-branch! ts) + (finish-branch! ts (:data main-file)) (audited {:status :merged :revn (:revn main-file) :source-file-id main-id} tpoint :merge)) @@ -1353,6 +1368,7 @@ (db/insert! conn :file-change {:id (uuid/next) :session-id session-id + :kind fchanges/revision-kind :profile-id profile-id :created-at ts :updated-at ts @@ -1374,7 +1390,7 @@ (when (contains? cf/flags :redis-cache) (fupd/invalidate-caches! cfg merged)) - (finish-branch! ts) + (finish-branch! ts (:data merged)) (vswap! messages conj {:topic main-id @@ -1745,6 +1761,7 @@ (db/insert! conn :file-change {:id (uuid/next) :session-id session-id + :kind fchanges/revision-kind :profile-id profile-id :created-at ts :updated-at ts diff --git a/backend/src/app/rpc/commands/files_pull_request.clj b/backend/src/app/rpc/commands/files_pull_request.clj index 7f54e004dd..a28147ef85 100644 --- a/backend/src/app/rpc/commands/files_pull_request.clj +++ b/backend/src/app/rpc/commands/files_pull_request.clj @@ -21,6 +21,7 @@ [app.common.data :as d] [app.common.exceptions :as ex] [app.common.features :as-alias cfeat] + [app.common.files.review-activity :as ra] [app.common.schema :as sm] [app.common.time :as ct] [app.common.uri :as uri] @@ -524,34 +525,101 @@ [:map {:title "get-pull-request-activity"} [:id ::sm/uuid]]) -(def ^:private max-activity-rows - "The newest saves the activity of a review reads. A review that runs - for months keeps its history; the list shows the recent part of it." - 2000) +(def ^:private activity-fetch-size + "Rows the server-side cursor of the activity holds at once." + 500) (def ^:private sql:get-pull-request-activity - "SELECT a.id, a.profile_id, a.revn, a.entries, a.created_at + "SELECT a.id, a.profile_id, a.entries, a.created_at FROM file_pull_request_activity AS a WHERE a.pull_request_id = ? - ORDER BY a.created_at DESC - LIMIT ?") + ORDER BY a.created_at ASC, a.id ASC") + +(defn- starts-sitting? + "Whether `row` is too late to join the sitting of the row before it, + so the rows read so far hold whole sittings." + [prev row] + (and (some? prev) + (> (- (inst-ms (:created-at row)) + (inst-ms (:created-at prev))) + ra/default-session-gap-ms))) + +(def ^:private empty-activity + {:sittings [] :buffer [] :people #{} :last-save nil}) + +(defn- fold-sitting + "Fold the sitting in course into the sittings read so far, oldest + first." + [{:keys [buffer sittings] :as acc}] + (if (empty? buffer) + acc + (-> acc + (assoc :sittings (into sittings (reverse (ra/sessions buffer)))) + (assoc :buffer [])))) + +(defn- add-activity-row + "Fold one activity row, read oldest first, into the sittings, the + people who saved and the newest save." + ([acc] acc) + ([acc row] + (-> (if (starts-sitting? (:last-save acc) row) + (fold-sitting acc) + acc) + (update :buffer conj row) + (assoc :last-save (select-keys row [:created-at :profile-id])) + (update :people conj (:profile-id row))))) + +(defn- sitting-rows + "The net entries of `sittings` as activity rows, the shape + `net-entries` reads. A sitting is the fold of its own rows, so folding + the sittings folds every row of the review: the fold sorts the rows by + the moment of the change each one carries. Each wrapped row keeps that + moment and the person who made the change, which is what the fold + reports as `:profile-id` and `:changed-at`." + [sittings] + (into [] + (mapcat (fn [{:keys [profile-id entries]}] + (map (fn [{:keys [changed-at] :as entry}] + {:profile-id profile-id + :created-at changed-at + :entries [entry]}) + entries))) + sittings)) + +(defn- get-activity + "The activity of a review, folded from every row of it: what each + layer ends up as, the sittings of saves, how many people saved and + the newest save. Rows are read oldest first and folded one sitting at + a time, so a long history is never held in memory at once." + [conn pr-id] + (let [acc (transduce (map (fn [row] (update row :entries blob/decode))) + add-activity-row + empty-activity + (db/plan conn [sql:get-pull-request-activity pr-id] + {:fetch-size activity-fetch-size})) + folded (fold-sitting acc) + sittings (vec (reverse (:sittings folded)))] + {:entries (ra/net-entries (sitting-rows sittings)) + :sessions sittings + :people (count (disj (:people folded) nil)) + :last-save (:last-save folded)})) (sv/defmethod ::get-pull-request-activity "What the saves of the branch did to its layers since the design review - opened: one row per save, newest first, each with who saved and its - entries (`app.common.files.review-activity/entries`). The client folds - them into the activity list." + opened, folded on the server: `:entries` what each layer ends up as + (`app.common.files.review-activity/net-entries`), `:sessions` the + sittings of saves the activity lists, `:people` how many people saved + and `:last-save` the newest save. Every row of the review is read, so + the oldest change still counts in what a layer ends up as." {::doc/added "2.16" ::sm/params schema:get-pull-request-activity} [cfg {:keys [::rpc/profile-id id]}] (check-pull-requests-enabled!) - (db/run! cfg - (fn [{:keys [::db/conn] :as cfg}] - (let [pr (get-pull-request* conn id)] - (files/check-read-permissions! cfg profile-id (:target-file-id pr)) - (into [] - (map (fn [row] (update row :entries blob/decode))) - (db/exec! conn [sql:get-pull-request-activity id max-activity-rows])))))) + (db/tx-run! (assoc cfg ::db/read-only true) + (fn [{:keys [::db/conn] :as cfg}] + (let [pr (get-pull-request* conn id)] + (files/check-read-permissions! cfg profile-id (:target-file-id pr)) + (get-activity conn id))))) ;; --- COMMAND QUERY: get-pull-request-bundle diff --git a/backend/src/app/rpc/commands/files_task.clj b/backend/src/app/rpc/commands/files_task.clj index 62b274c83a..d656fa3757 100644 --- a/backend/src/app/rpc/commands/files_task.clj +++ b/backend/src/app/rpc/commands/files_task.clj @@ -22,9 +22,11 @@ (:require [app.common.data :as d] [app.common.exceptions :as ex] + [app.common.files.helpers :as cfh] [app.common.geom.point :as gpt] [app.common.schema :as sm] [app.common.time :as ct] + [app.common.types.shape :as cts] [app.common.uri :as uri] [app.common.uuid :as uuid] [app.config :as cf] @@ -109,19 +111,97 @@ :hint "the assignee must be a member of the team" :profile-id assignee-id))))) +(def ^:private sql:select-tasks + "SELECT t.id, + t.file_id, + t.pull_request_id, + coalesce(fpr.title, t.review_title) AS review_title, + fpr.status AS review_status, + t.thread_id, + t.comment_id, + ct.seqn AS thread_seqn, + t.title, + t.status, + t.assignee_id, + t.created_by, + t.page_id, + t.frame_id, + t.shape_id, + t.lost_shape_name, + t.position, + t.merge_id, + t.branch_name, + t.status_changed_at, + t.status_changed_by, + t.created_at, + t.updated_at + FROM file_task AS t + LEFT JOIN file_pull_request AS fpr ON (fpr.id = t.pull_request_id) + LEFT JOIN comment_thread AS ct ON (ct.id = t.thread_id)") + +(def ^:private sql:get-file-tasks + (str sql:select-tasks + " WHERE t.file_id = ? + AND t.deleted_at IS NULL + ORDER BY t.created_at ASC")) + +(def ^:private sql:get-file-tasks-by-id + (str sql:select-tasks + " WHERE t.file_id = ? + AND t.id = ANY(?) + AND t.deleted_at IS NULL + ORDER BY t.created_at ASC")) + +(defn tasks-change-message + "The message that tells the open clients of `file-id` that its tasks + `task-ids` changed. It carries their rows as `get-file-tasks` lists + them (a deleted task has none) and the session that made the change: + that session skips it, the others patch their list with it. Read it + inside the transaction of the change." + [conn {:keys [file-id profile-id session-id task-ids]}] + (let [task-ids (vec task-ids)] + {:type :file-tasks-change + :file-id file-id + :profile-id profile-id + :session-id session-id + :task-ids task-ids + :tasks (if (seq task-ids) + (into [] + (map decode-row) + (db/exec! conn [sql:get-file-tasks-by-id file-id + (db/create-array conn "uuid" task-ids)])) + [])})) + (defn- run-and-notify "Run `f` in a transaction, then tell the open clients of `file-id` that - its tasks changed: the message leaves once the transaction committed, - so a client that reloads on it reads the committed state." - [{:keys [::mbus/msgbus] :as cfg} file-id profile-id f] - (let [result (db/tx-run! cfg f)] - (mbus/pub! msgbus - :topic file-id - :message {:type :file-tasks-change - :file-id file-id - :profile-id profile-id}) + the tasks `get-ids` names in the result of `f` changed + (`tasks-change-message`). The message is read in the transaction and + leaves once it committed, so it carries the committed state." + [{:keys [::mbus/msgbus] :as cfg} {:keys [file-id] :as context} get-ids f] + (let [[result message] + (db/tx-run! cfg (fn [{:keys [::db/conn] :as cfg}] + (let [result (f cfg)] + [result (tasks-change-message conn (assoc context :task-ids (get-ids result)))])))] + (mbus/pub! msgbus :topic file-id :message message) result)) +(def ^:private sql:lock-file + "SELECT id, deleted_at FROM file WHERE id = ? FOR UPDATE") + +(defn- lock-file + "Lock the row of `file-id` and refuse a deleted file. Task creation and + the move of the tasks of a merged branch (`move-branch-tasks`) take + this lock: a task created during a merge either lands before the merge + reads the tasks of the branch, or waits and finds the branch file + deleted." + [conn file-id] + (let [file (db/exec-one! conn [sql:lock-file file-id])] + (when (or (nil? file) (some? (:deleted-at file))) + (ex/raise :type :not-found + :code :object-not-found + :hint "the file of the task does not exist or was deleted" + :file-id file-id)))) + ;; --- Helpers: emails (defn- format-task-url @@ -159,37 +239,6 @@ [:map {:title "get-file-tasks"} [:file-id ::sm/uuid]]) -(def ^:private sql:get-file-tasks - "SELECT t.id, - t.file_id, - t.pull_request_id, - coalesce(fpr.title, t.review_title) AS review_title, - fpr.status AS review_status, - t.thread_id, - t.comment_id, - ct.seqn AS thread_seqn, - t.title, - t.status, - t.assignee_id, - t.created_by, - t.page_id, - t.frame_id, - t.shape_id, - t.lost_shape_name, - t.position, - t.merge_id, - t.branch_name, - t.status_changed_at, - t.status_changed_by, - t.created_at, - t.updated_at - FROM file_task AS t - LEFT JOIN file_pull_request AS fpr ON (fpr.id = t.pull_request_id) - LEFT JOIN comment_thread AS ct ON (ct.id = t.thread_id) - WHERE t.file_id = ? - AND t.deleted_at IS NULL - ORDER BY t.created_at ASC") - (defn get-file-tasks [conn file-id] (into [] (map decode-row) (db/exec! conn [sql:get-file-tasks file-id]))) @@ -313,12 +362,13 @@ message it was made from (`thread-id` and `comment-id`), or the first message of a new thread that carries its title. A task created in a design review belongs to it. The assignee, when there is one, must be - a member of the team and is told by email." + a member of the team and is told by email. A deleted file takes no + task: a merge deletes its branch file (see `lock-file`)." {::doc/added "2.16" ::webhooks/event? true ::sm/params schema:create-task} - [cfg {:keys [::rpc/profile-id file-id title page-id frame-id shape-id position assignee-id - pull-request-id thread-id comment-id] :as params}] + [cfg {:keys [::rpc/profile-id ::rpc/session-id file-id title page-id frame-id shape-id position + assignee-id pull-request-id thread-id comment-id] :as params}] (check-tasks-enabled) (when (str/blank? title) (ex/raise :type :validation @@ -326,8 +376,10 @@ :hint "task title cannot be blank")) (files/check-read-permissions! cfg profile-id file-id) (run-and-notify - cfg file-id profile-id + cfg {:file-id file-id :profile-id profile-id :session-id session-id} + (comp vector :id) (fn [{:keys [::db/conn] :as cfg}] + (lock-file conn file-id) (let [team-id (perms/get-team-id-for-file conn file-id) review (when pull-request-id (or (db/exec-one! conn [sql:get-open-review-of-file pull-request-id file-id]) @@ -382,7 +434,7 @@ task; a new assignee is told by email." {::doc/added "2.16" ::sm/params schema:update-task} - [cfg {:keys [::rpc/profile-id id title] :as params}] + [cfg {:keys [::rpc/profile-id ::rpc/session-id id title] :as params}] (check-tasks-enabled) (when (and (some? title) (str/blank? title)) (ex/raise :type :validation @@ -391,7 +443,8 @@ (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] (files/check-read-permissions! cfg profile-id (:file-id task)) (run-and-notify - cfg (:file-id task) profile-id + cfg {:file-id (:file-id task) :profile-id profile-id :session-id session-id} + (comp vector :id) (fn [{:keys [::db/conn] :as cfg}] (let [task (get-task conn id {::sql/for-update true}) team-id (perms/get-team-id-for-file conn (:file-id task)) @@ -425,12 +478,13 @@ {::doc/added "2.16" ::webhooks/event? true ::sm/params schema:set-task-status} - [cfg {:keys [::rpc/profile-id id status]}] + [cfg {:keys [::rpc/profile-id ::rpc/session-id id status]}] (check-tasks-enabled) (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] (files/check-read-permissions! cfg profile-id (:file-id task)) (run-and-notify - cfg (:file-id task) profile-id + cfg {:file-id (:file-id task) :profile-id profile-id :session-id session-id} + (comp vector :id) (fn [{:keys [::db/conn]}] (let [task (get-task conn id {::sql/for-update true}) from (:status task) @@ -454,6 +508,53 @@ :status-changed-at ts :status-changed-by profile-id)))))) +;; --- Helpers: the thread created with a task + +(def ^:private sql:get-first-comment + "SELECT id FROM comment + WHERE thread_id = ? + ORDER BY created_at ASC, id ASC + LIMIT 1") + +(defn- created-with-task? + "The thread of `task` was created with it: the message of the task is + the first message of the thread. A thread a task was made from later + keeps its own place." + [conn {:keys [thread-id comment-id]}] + (and (some? thread-id) + (some? comment-id) + (= comment-id (:id (db/exec-one! conn [sql:get-first-comment thread-id]))))) + +(defn- move-task-thread + "Point the thread created with `task` where the task points now: at the + layer `shape-id`; with no layer, at the rectangle `area` of the canvas, + or at the spot `position` when there is no area either." + [conn task {:keys [frame-id shape-id area position]}] + (when (created-with-task? conn task) + (db/update! conn :comment-thread + (cond + (some? shape-id) + {:frame-id frame-id + :shape-id shape-id + :anchor-type "layer" + :area nil} + + (some? area) + {:frame-id frame-id + :shape-id nil + :anchor-type "area" + :area (db/tjson area) + :position (db/pgpoint position)} + + :else + {:frame-id frame-id + :shape-id nil + :anchor-type "canvas" + :area nil + :position (db/pgpoint position)}) + {:id (:thread-id task)} + {::db/return-keys false}))) + ;; --- COMMAND: relink-task (def ^:private schema:relink-task @@ -467,24 +568,28 @@ (sv/defmethod ::relink-task "Point a task at another layer. A task whose layer was deleted stops - being lost." + being lost. The thread created with the task follows it; a thread the + task was made from keeps its place." {::doc/added "2.16" ::sm/params schema:relink-task} - [cfg {:keys [::rpc/profile-id id page-id frame-id shape-id shape-name]}] + [cfg {:keys [::rpc/profile-id ::rpc/session-id id page-id frame-id shape-id shape-name]}] (check-tasks-enabled) (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] (files/check-read-permissions! cfg profile-id (:file-id task)) (run-and-notify - cfg (:file-id task) profile-id + cfg {:file-id (:file-id task) :profile-id profile-id :session-id session-id} + (comp vector :id) (fn [{:keys [::db/conn]}] - (let [changes {:page-id page-id + (let [task (get-task conn id {::sql/for-update true}) + changes {:page-id page-id :frame-id frame-id :shape-id shape-id :lost-shape-name nil :updated-at (ct/now)}] (db/update! conn :file-task changes {:id id} {::db/return-keys false}) + (move-task-thread conn task changes) (insert-event conn id profile-id "relinked" {:shape-id shape-id :shape-name shape-name}) - (merge (get-task conn id) changes)))))) + (merge task changes)))))) ;; --- COMMAND: mark-tasks-layer-deleted @@ -496,13 +601,32 @@ [:frame-id ::sm/uuid] [:frame-name {:optional true} [:maybe [:string {:max 250}]]] ;; the layer as it was (the shape and its children), what "restore - ;; layer" puts back - [:objects {:optional true} [:vector {:max 500} :map]]]) + ;; layer" puts back; kept only up to `max-restore-objects` + [:objects {:optional true} [:vector :map]]]) (def ^:private schema:mark-tasks-layer-deleted [:map {:title "mark-tasks-layer-deleted" :closed true} [:file-id ::sm/uuid] - [:layers [:vector {:min 1 :max 200} schema:deleted-layer]]]) + [:layers [:vector {:min 1} schema:deleted-layer]]]) + +(def ^:private max-restore-objects + "The most objects of a deleted layer its event keeps for a restore." + 500) + +(def ^:private valid-restore-object? + (sm/lazy-validator cts/schema:shape-attrs)) + +(defn- restore-objects + "The objects of a deleted layer its event keeps, what a restore puts + back as real layers: none above `max-restore-objects`, and none when + one of them is not a valid shape. The client sends them without their + children ids (`:shapes`), which a restore rebuilds. Without them the + task is lost all the same and no restore is offered." + [objects] + (when (and (seq objects) + (<= (count objects) max-restore-objects) + (every? #(valid-restore-object? (update % :shapes (fnil identity []))) objects)) + objects)) (def ^:private sql:get-tasks-of-layers "SELECT * FROM file_task @@ -517,33 +641,36 @@ "Tell the server that layers with open tasks were deleted: each task moves to the board that held its layer and keeps the name of the lost layer until it is linked to another one. The event of each task keeps - the deleted layer, so it can be restored later. Returns the tasks it - moved." + the deleted layer, so it can be restored later, when the layer is small + and valid enough (`restore-objects`). Returns the tasks it moved." {::doc/added "2.16" ::sm/params schema:mark-tasks-layer-deleted} - [cfg {:keys [::rpc/profile-id file-id layers]}] + [cfg {:keys [::rpc/profile-id ::rpc/session-id file-id layers]}] (check-tasks-enabled) (files/check-read-permissions! cfg profile-id file-id) (run-and-notify - cfg file-id profile-id + cfg {:file-id file-id :profile-id profile-id :session-id session-id} + #(map :id %) (fn [{:keys [::db/conn]}] (let [by-shape (d/index-by :shape-id layers) ids (db/create-array conn "uuid" (vec (keys by-shape))) tasks (into [] (map decode-row) (db/exec! conn [sql:get-tasks-of-layers file-id ids])) + kept (update-vals by-shape (comp restore-objects :objects)) ts (ct/now)] (into [] (map (fn [{:keys [id shape-id] :as task}] - (let [{:keys [shape-name frame-id frame-name objects]} (get by-shape shape-id) + (let [{:keys [shape-name frame-id frame-name]} (get by-shape shape-id) + objects (get kept shape-id) changes {:lost-shape-name shape-name :frame-id frame-id :updated-at ts}] (db/update! conn :file-task changes {:id id} {::db/return-keys false}) (insert-event conn id profile-id "layer-deleted" - {:shape-id shape-id - :shape-name shape-name - :frame-id frame-id - :frame-name frame-name - :objects objects}) + (cond-> {:shape-id shape-id + :shape-name shape-name + :frame-id frame-id + :frame-name frame-name} + (some? objects) (assoc :objects objects))) (merge task changes)))) tasks))))) @@ -559,12 +686,13 @@ task): the task points at it again." {::doc/added "2.16" ::sm/params schema:mark-task-layer-restored} - [cfg {:keys [::rpc/profile-id id frame-id]}] + [cfg {:keys [::rpc/profile-id ::rpc/session-id id frame-id]}] (check-tasks-enabled) (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] (files/check-read-permissions! cfg profile-id (:file-id task)) (run-and-notify - cfg (:file-id task) profile-id + cfg {:file-id (:file-id task) :profile-id profile-id :session-id session-id} + (comp vector :id) (fn [{:keys [::db/conn]}] (let [changes {:lost-shape-name nil :frame-id frame-id @@ -582,22 +710,34 @@ [:id ::sm/uuid]]) (sv/defmethod ::delete-task - "Delete a task. Its thread stays: the message the task lived in goes - on as a plain comment." + "Delete a task. Only its author may; anybody who can read the file may + still move it to won't do. A `deleted` event, written before the task + goes, records who deleted it. Its thread stays: the message the task + lived in goes on as a plain comment." {::doc/added "2.16" ::sm/params schema:delete-task} - [cfg {:keys [::rpc/profile-id id]}] + [cfg {:keys [::rpc/profile-id ::rpc/session-id id]}] (check-tasks-enabled) (let [task (db/run! cfg (fn [{:keys [::db/conn]}] (get-task conn id)))] (files/check-read-permissions! cfg profile-id (:file-id task)) + (when (not= profile-id (:created-by task)) + (ex/raise :type :validation + :code :not-allowed + :hint "only the author of a task may delete it" + :task-id id)) (run-and-notify - cfg (:file-id task) profile-id + cfg {:file-id (:file-id task) :profile-id profile-id :session-id session-id} + (constantly [id]) (fn [{:keys [::db/conn]}] - (db/update! conn :file-task - {:deleted-at (ct/now) :updated-at (ct/now)} - {:id id} - {::db/return-keys false}) - nil)))) + (let [task (get-task conn id {::sql/for-update true}) + ts (ct/now)] + ;; the event first: a deleted task is not found any more + (insert-event conn id profile-id "deleted" {:title (:title task)}) + (db/update! conn :file-task + {:deleted-at ts :updated-at ts} + {:id id} + {::db/return-keys false}) + nil))))) ;; --- Review counts @@ -692,18 +832,79 @@ (uri/map->query-string {:file-id main-id :team-id team-id})])}))))) +(defn- find-shape + [data page-id shape-id] + (get-in data [:pages-index page-id :objects shape-id])) + +(defn- task-landing + "Where an open task of a merged branch lands on main when the merge did + not carry its layer: on the immediate parent of the layer when main has + it, otherwise on the area of the canvas the layer covered. The layer is + read from the branch document, or from the merge base when the branch + deleted it; when neither has it, the task keeps its spot of the canvas. + Nil when the task stays as it is: it is closed, points at the canvas, + its layer reached main, or its page did not." + [{:keys [merged-data branch-data base-data]} {:keys [page-id shape-id status position]}] + (when (and (some? shape-id) + (not (contains? closed-statuses status)) + (contains? (:pages-index merged-data) page-id) + (nil? (find-shape merged-data page-id shape-id))) + (let [layer (or (find-shape branch-data page-id shape-id) + (find-shape base-data page-id shape-id)) + parent (some->> (:parent-id layer) (find-shape merged-data page-id))] + (cond + (and (some? parent) (not (cfh/root? parent))) + {:shape-id (:id parent) + :shape-name (:name parent) + :frame-id (if (cfh/frame-shape? parent) (:id parent) (:frame-id parent))} + + (some? layer) + (let [{:keys [x y width height]} (:selrect layer)] + {:frame-id uuid/zero + :area {:x x :y y :width width :height height} + ;; the top right corner, where the mark of a task goes + :position (gpt/point (+ x width) y)}) + + :else + {:frame-id uuid/zero + :position position})))) + +(defn- land-task + "Point `task` where `task-landing` puts it, its thread created with it + too, and record it as a `relinked` event." + [conn profile-id task {:keys [shape-id shape-name frame-id area position] :as landing}] + (db/update! conn :file-task + (cond-> {:shape-id shape-id + :frame-id frame-id + :lost-shape-name nil} + (some? position) (assoc :position (db/pgpoint position))) + {:id (:id task)} + {::db/return-keys false}) + (move-task-thread conn task landing) + (insert-event conn (:id task) profile-id "relinked" + (if (some? shape-id) + {:shape-id shape-id :shape-name shape-name} + {:shape-id nil :area area}))) + (defn move-branch-tasks "Move every task of the branch file into main, inside the merge transaction: the open ones keep going on main, the closed ones stay as the history of the branch. Each task keeps the names it shows (the review title is refreshed from its pull request, which goes away with the branch), records the merge and gets a `moved-to-main` event. The - threads of the tasks move with them. When `notify-assignees` is set, - the assignees of the open tasks are told by email. Returns the moved - tasks." + threads of the tasks move with them. An open task whose layer the merge + did not carry lands where `task-landing` says, with a `relinked` event, + reading the layer in `merged-data`, `branch-data` and `base-data`. When + `notify-assignees` is set, the assignees of the open tasks are told by + email. Returns the moved tasks. + + The branch file row is locked before the tasks are read, as task + creation locks it (`lock-file`): a task created meanwhile is either + read here or refused once the merge deleted the branch file." [{:keys [::db/conn] :as cfg} - {:keys [branch-file-id main-id merge-id branch-name profile-id notify-assignees]}] - (let [tasks (db/exec! conn [sql:get-branch-tasks branch-file-id])] + {:keys [branch-file-id main-id merge-id branch-name profile-id notify-assignees] :as params}] + (db/exec-one! conn [sql:lock-file branch-file-id]) + (let [tasks (into [] (map decode-row) (db/exec! conn [sql:get-branch-tasks branch-file-id]))] (when (seq tasks) (let [reviews (->> (keep :pull-request-id tasks) (distinct) @@ -722,7 +923,9 @@ {:id id} {::db/return-keys false}) (insert-event conn (:id task) profile-id "moved-to-main" - {:merge-id merge-id :branch-name branch-name})) + {:merge-id merge-id :branch-name branch-name}) + (when-let [landing (task-landing params task)] + (land-task conn profile-id task landing))) (when notify-assignees (let [main (db/get conn :file {:id main-id} {::sql/columns [:name]})] (send-tasks-moved-emails cfg diff --git a/backend/src/app/tasks/objects_gc.clj b/backend/src/app/tasks/objects_gc.clj index 8f4ff44a98..79bc49017b 100644 --- a/backend/src/app/tasks/objects_gc.clj +++ b/backend/src/app/tasks/objects_gc.clj @@ -8,6 +8,7 @@ "A maintenance task that performs a general purpose garbage collection of deleted or unreachable objects." (:require + [app.common.files.review-activity :as ra] [app.common.logging :as l] [app.common.schema :as sm] [app.common.time :as ct] @@ -18,6 +19,7 @@ [app.loggers.audit :as audit] [app.storage :as sto] [app.tasks.delete-object :as dobj] + [app.util.blob :as blob] [integrant.core :as ig])) ;; Each proc below streams its pending keys with `db/plan`, a server-side @@ -132,6 +134,136 @@ (db/plan conn [sql:get-upload-sessions threshold stalled-threshold threshold] {:fetch-size 5})))))) +;; A save of a branch under review records one activity row, and the table +;; grows for the life of the review. The rows of one person's sitting (the +;; same review and profile, no gap longer than `ra/default-session-gap-ms`) +;; fold into one row once the sitting is finished: its entries concatenate +;; in order, its last revn and timestamp stay. The reading side replays +;; entries in order, so the fold leaves `net-entries` unchanged. + +(def ^:private sql:get-review-activity-groups + "SELECT pull_request_id, profile_id + FROM file_pull_request_activity + WHERE created_at <= ? + GROUP BY pull_request_id, profile_id + ORDER BY max(created_at) ASC") + +;; The profile comparison treats two nulls as equal, so the rows of a +;; purged author (the cascade set `profile_id` null) group together too. +;; +;; No SKIP LOCKED here, unlike the other chunks: skipping a row in the +;; middle of a sitting would make its neighbours look adjacent, and folding +;; them in that order would change the entries the reader replays. Wait for +;; the other transaction instead, so the sitting is read whole. +(def ^:private sql:lock-review-activity + "SELECT id, revn, entries, created_at + FROM file_pull_request_activity + WHERE pull_request_id = ? + AND profile_id IS NOT DISTINCT FROM ?::uuid + AND created_at <= ? + ORDER BY created_at ASC, id ASC + FOR UPDATE") + +(def ^:private sql:get-next-review-activity + "SELECT created_at + FROM file_pull_request_activity + WHERE pull_request_id = ? + AND profile_id IS NOT DISTINCT FROM ?::uuid + AND created_at > ? + ORDER BY created_at ASC, id ASC + LIMIT 1") + +(defn- split-sittings + "Cut `rows`, oldest first, into sittings: runs with no gap longer than + `gap-ms` between two rows." + [rows gap-ms] + (reduce (fn [sittings row] + (let [sitting (peek sittings)] + (if (and (some? sitting) + (<= (- (inst-ms (:created-at row)) + (inst-ms (:created-at (peek sitting)))) + gap-ms)) + (conj (pop sittings) (conj sitting row)) + (conj sittings [row])))) + [] + rows)) + +(defn- drop-unfinished + "Drop the last sitting when the row after the cutoff still joins it: the + sitting is still running, so leave it whole and fold it in a later run." + [sittings next-row gap-ms] + (if (and (some? next-row) + (seq sittings) + (<= (- (inst-ms (:created-at next-row)) + (inst-ms (:created-at (peek (peek sittings))))) + gap-ms)) + (pop sittings) + sittings)) + +(defn- fold-review-activity-pair + "Folds every finished sitting of one review and profile into one row." + [conn [pull-request-id profile-id] cutoff gap-ms] + (let [rows (db/exec! conn [sql:lock-review-activity + pull-request-id profile-id cutoff]) + next-row (db/exec-one! conn [sql:get-next-review-activity + pull-request-id profile-id cutoff]) + sittings (-> (split-sittings rows gap-ms) + (drop-unfinished next-row gap-ms))] + (reduce (fn [total sitting] + (if (= 1 (count sitting)) + total + (let [last-row (peek sitting) + entries (into [] + (mapcat (comp blob/decode :entries)) + sitting)] + (db/update! conn :file-pull-request-activity + {:entries (blob/encode entries)} + {:id (:id last-row)} + {::db/return-keys false}) + (doseq [row (butlast sitting)] + (db/delete! conn :file-pull-request-activity + {:id (:id row)} + {::db/return-keys false})) + (+ total (dec (count sitting)))))) + 0 + sittings))) + +(defn- delete-review-activity-chunk + "Folds the finished sittings of a chunk of review and profile pairs." + [cfg pairs] + (try + (db/tx-run! cfg + (fn [{:keys [::db/conn ::cutoff ::gap-ms]}] + (reduce (fn [total pair] + (+ total (fold-review-activity-pair conn pair cutoff gap-ms))) + 0 + pairs))) + (catch Throwable cause + (l/err :obj "review-activity" + :hint "error on chunk deletion, skipping it" + :chunk pairs + :cause cause) + 0))) + +(defn- delete-review-activity + [{:keys [::threshold ::chunk-size] :as cfg}] + (let [gap-ms ra/default-session-gap-ms + cfg (assoc cfg + ::gap-ms gap-ms + ::cutoff (ct/minus threshold gap-ms)) + rf (fn ([total] total) + ([total chunk] + (let [deleted (delete-review-activity-chunk cfg chunk)] + (jobs/heartbeat cfg) + (+ total deleted))))] + (db/tx-run! (assoc cfg ::db/read-only true) + (fn [{:keys [::db/conn ::cutoff]}] + (transduce (comp (map (juxt :pull-request-id :profile-id)) + (partition-all chunk-size)) + rf 0 + (db/plan conn [sql:get-review-activity-groups cutoff] + {:fetch-size 5})))))) + (def ^:private sql:get-profiles "SELECT id FROM profile WHERE deleted_at IS NOT NULL @@ -146,12 +278,28 @@ FOR UPDATE SKIP LOCKED") +(def ^:private sql:defer-task-keys + "SET CONSTRAINTS file_task_thread_id_fkey, + file_task_comment_id_fkey, + file_task_assignee_id_fkey, + file_task_created_by_fkey, + file_task_status_changed_by_fkey + DEFERRED") + (defn- delete-profiles-chunk [cfg ids] (try (db/tx-run! cfg (fn [{:keys [::db/conn ::threshold ::sto/storage] :as cfg}] (db/exec-one! conn ["SET LOCAL rules.deletion_protection TO off"]) + ;; One profile can be the author, the assignee and the + ;; last mover of the same task: the cascading actions + ;; update that row more than once, and Postgres rechecks + ;; every non-null key of a row this transaction already + ;; wrote, before the other actions clear the keys of the + ;; thread and the message the cascades delete. Wait for + ;; the commit, when only the final row is checked. + (db/exec-one! conn [sql:defer-task-keys]) (let [ids (db/create-array conn "uuid" ids)] (->> (db/exec! conn [sql:lock-profiles ids threshold]) (reduce (fn [total {:keys [id photo-id deleted-at]}] @@ -777,8 +925,10 @@ ;; NOTE: upload sessions go first: deleting a profile cascades to its ;; sessions, which would hit the upload_session_chunk NO ACTION foreign - ;; key while mappings still exist. + ;; key while mappings still exist. Review activity folds before the + ;; profile purge, which nulls the author of the rows. total (+ (delete-upload-sessions cfg) + (delete-review-activity cfg) (delete-profiles cfg) (delete-file-media-objects cfg) (delete-file-object-thumbnails cfg) diff --git a/backend/test/backend_tests/objects_gc_test.clj b/backend/test/backend_tests/objects_gc_test.clj index 462cbc5f5a..89444bbf07 100644 --- a/backend/test/backend_tests/objects_gc_test.clj +++ b/backend/test/backend_tests/objects_gc_test.clj @@ -6,6 +6,7 @@ (ns backend-tests.objects-gc-test (:require + [app.common.geom.point :as gpt] [app.common.logging :as l] [app.common.time :as ct] [app.common.uuid :as uuid] @@ -15,6 +16,7 @@ [app.rpc :as-alias rpc] [app.storage :as sto] [app.tasks.objects-gc :as ogc] + [app.util.blob :as blob] [backend-tests.helpers :as th] [clojure.test :as t] [mockery.core :refer [with-mocks]])) @@ -162,6 +164,143 @@ (t/is (= deleted-at (:deleted-at (th/db-get :team {:id (:default-team-id profile)} {::db/remove-deleted false}))))))) +(defn- create-review! + "An open review of a branch of `file`: the branch and pull request rows + the review activity points at." + [profile file] + (let [branch (th/create-file* 2 {:profile-id (:id profile) + :project-id (:default-project-id profile)}) + _ (th/db-update! :file {:is-branch true} {:id (:id branch)}) + br (th/db-insert! :file-branch + {:id (uuid/next) + :branch-file-id (:id branch) + :source-file-id (:id file) + :base-revn 0 + :created-by (:id profile) + :name "feature-checkout"})] + (th/db-insert! :file-pull-request + {:id (uuid/next) + :file-branch-id (:id br) + :source-file-id (:id branch) + :target-file-id (:id file) + :title "Checkout redesign" + :created-by (:id profile)}))) + +(defn- insert-activity! + [profile review revn entries created-at] + (th/db-insert! :file-pull-request-activity + {:id (uuid/next) + :pull-request-id (:id review) + :profile-id (:id profile) + :revn revn + :entries (blob/encode entries) + :created-at created-at})) + +(t/deftest gc-folds-the-activity-rows-of-a-finished-sitting + ;; The rows of one sitting concatenate into its last row, in order, so + ;; the reading side replays the same entries; the last revn and the last + ;; timestamp stay. A sitting whose last row is newer than the gap is + ;; still open and keeps its rows. + (let [profile (th/create-profile* 1) + file (th/create-file* 1 {:profile-id (:id profile) + :project-id (:default-project-id profile)}) + review (create-review! profile file) + shape-id (uuid/next) + entries (fn [kind] + [{:id shape-id + :page-id (:id file) + :name "Pay button" + :type :rect + :kind kind}]) + now (ct/now) + _ (insert-activity! profile review 1 (entries :added) + (ct/minus now {:minutes 120})) + _ (insert-activity! profile review 2 (entries :modified) + (ct/minus now {:minutes 110})) + row3 (insert-activity! profile review 3 (entries :modified) + (ct/minus now {:minutes 100})) + row4 (insert-activity! profile review 4 (entries :modified) + (ct/minus now {:minutes 10})) + + result (th/run-task! :objects-gc {})] + + (t/is (pos? (:processed result))) + + (let [rows (sort-by :created-at + (th/db-query :file-pull-request-activity + {:pull-request-id (:id review)}))] + (t/testing "the sitting folds into its last row and the open one stays" + (t/is (= 2 (count rows))) + (t/is (= [(:id row3) (:id row4)] (mapv :id rows)))) + + (t/testing "the folded row concatenates the entries in order" + (t/is (= (into [] cat [(entries :added) (entries :modified) (entries :modified)]) + (blob/decode (:entries (first rows)))))) + + (t/testing "the folded row keeps the last revn and timestamp" + (t/is (= 3 (:revn (first rows)))) + (t/is (= (:created-at row3) (:created-at (first rows))))) + + (t/testing "the open sitting is untouched" + (t/is (= 4 (:revn (second rows)))) + (t/is (= (:created-at row4) (:created-at (second rows)))) + (t/is (= (entries :modified) (blob/decode (:entries (second rows))))))))) + +(t/deftest a-task-that-names-its-author-does-not-block-the-profile-purge + ;; A profile that authored a task, was assigned it and moved it is hit by + ;; three SET NULL actions on the same row during the purge, which also + ;; deletes the thread and the message the task points at. Postgres + ;; rechecks the row's keys before those actions clear them; deferring the + ;; keys to the commit lets every action run first. + (with-redefs [cf/flags (conj cf/flags :branching)] + (let [author (th/create-profile* 1 {:is-active true}) + file (th/create-file* 1 {:profile-id (:id author) + :project-id (:default-project-id author)}) + page-id (-> (th/command! {::th/type :get-file + ::rpc/profile-id (:id author) + :id (:id file)}) + :result :data :pages first) + task (-> (th/command! {::th/type :create-task + ::rpc/profile-id (:id author) + :file-id (:id file) + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 0) + :title "Use the secondary token"}) + :result)] + + (t/is (some? (:id task))) + + (th/db-update! :file-task {:assignee-id (:id author)} {:id (:id task)}) + (let [out (th/command! {::th/type :set-task-status + ::rpc/profile-id (:id author) + :id (:id task) + :status "done"})] + (t/is (nil? (:error out)))) + (th/db-update! :profile {:deleted-at (ct/in-past "30m")} {:id (:id author)}) + + (let [deleted-at (:deleted-at (th/db-get :profile {:id (:id author)} + {::db/remove-deleted false})) + cfg {::db/pool th/*pool* + ::sto/storage (::sto/storage th/*system*) + ::ogc/threshold deleted-at} + total (#'ogc/delete-profiles-chunk cfg [(:id author)])] + + (t/testing "the chunk purges the profile instead of skipping it" + (t/is (= 1 total)) + (t/is (nil? (th/db-get :profile {:id (:id author)} + {::db/remove-deleted false})))) + + (t/testing "the task survives with its links and author cleared" + (let [row (th/db-get :file-task {:id (:id task)} + {::db/remove-deleted false})] + (t/is (some? row)) + (t/is (nil? (:thread-id row))) + (t/is (nil? (:comment-id row))) + (t/is (nil? (:created-by row))) + (t/is (nil? (:assignee-id row))) + (t/is (nil? (:status-changed-by row))))))))) + (t/deftest blocked-chunk-does-not-stop-the-run ;; Chunks of one file: the blocked file takes down its own chunk and nothing ;; else, so the clean file of the next chunk is still deleted and the run diff --git a/backend/test/backend_tests/rpc_file_branch_test.clj b/backend/test/backend_tests/rpc_file_branch_test.clj index b2a8de9297..34d37745f2 100644 --- a/backend/test/backend_tests/rpc_file_branch_test.clj +++ b/backend/test/backend_tests/rpc_file_branch_test.clj @@ -17,6 +17,7 @@ [app.common.uuid :as uuid] [app.config :as cf] [app.db :as db] + [app.features.file-changes :as fchanges] [app.msgbus :as mbus] [app.rpc :as-alias rpc] [app.rpc.commands.files-branch :as fbranch] @@ -3316,3 +3317,44 @@ :direction :branch->main})] (t/is (= :not-found (th/ex-type (:error out)))) (t/is (= :branch-not-found (th/ex-code (:error out))))))))) + +(t/deftest merge-and-update-from-main-record-revision-rows + ;; the revision rows the merge and the update from main write carry + ;; their kind, as the save path's do: a kind-filtered read sees them + (with-redefs [cf/flags (conj cf/flags :branching)] + (let [profile (th/create-profile* 1 {:is-active true}) + file (th/create-file* 1 {:profile-id (:id profile) + :project-id (:default-project-id profile)}) + create (:result (th/command! {::th/type :create-file-branch + ::rpc/profile-id (:id profile) + :file-id (:id file) + :name "kinds"})) + branch-id (:id create) + branch-file-id (:branch-file-id create) + kinds-of (fn [file-id session-id] + (mapv :kind (th/db-exec! ["SELECT kind FROM file_change + WHERE file_id = ? AND session_id = ?" + file-id session-id])))] + (apply-change* profile (:id file) + {:type :add-color :color {:id (uuid/random) :name "Main" :color "#00ff00" :opacity 1}}) + + (t/testing "the update from main" + (let [session-id (uuid/random) + out (th/command! {::th/type :update-branch-from-main + ::rpc/profile-id (:id profile) + ::rpc/session-id session-id + :branch-id branch-id})] + (t/is (nil? (:error out))) + (t/is (= [fchanges/revision-kind] (kinds-of branch-file-id session-id))))) + + (t/testing "the merge" + (apply-change* profile branch-file-id + {:type :add-color :color {:id (uuid/random) :name "Branch" :color "#0000ff" :opacity 1}}) + (let [session-id (uuid/random) + out (th/command! {::th/type :merge-file-branch + ::rpc/profile-id (:id profile) + ::rpc/session-id session-id + :branch-id branch-id})] + (t/is (nil? (:error out))) + (t/is (= :merged (-> out :result :status))) + (t/is (= [fchanges/revision-kind] (kinds-of (:id file) session-id)))))))) diff --git a/backend/test/backend_tests/rpc_file_pull_request_test.clj b/backend/test/backend_tests/rpc_file_pull_request_test.clj index e0d504c26b..b9aa60b812 100644 --- a/backend/test/backend_tests/rpc_file_pull_request_test.clj +++ b/backend/test/backend_tests/rpc_file_pull_request_test.clj @@ -15,6 +15,7 @@ [app.email :as eml] [app.msgbus :as mbus] [app.rpc :as-alias rpc] + [app.util.blob :as blob] [backend-tests.helpers :as th] [clojure.string :as str] [clojure.test :as t])) @@ -797,3 +798,74 @@ (t/is (empty? @seen)) (t/is (empty? (th/db-query :file-pull-request {:file-branch-id (:id branch)}))))))) + +(t/deftest activity-folds-every-row-not-the-newest-window + (with-redefs [cf/flags (pr-flags)] + (let [author (th/create-profile* 1 {:is-active true}) + file (th/create-file* 1 {:profile-id (:id author) + :project-id (:default-project-id author)}) + page-id (-> (th/command! {::th/type :get-file + ::rpc/profile-id (:id author) + :id (:id file)}) + :result :data :pages first) + branch (create-branch* author file "feature") + pr-id (-> (create-pr* author (:id branch) {}) :result :id) + paid-id (uuid/random) + board-id (uuid/random) + promo-id (uuid/random) + start (ct/now) + + paid {:id paid-id :page-id page-id :name "Pay" :type :rect + :frame-id board-id :frame-name "Checkout" :kind :added} + promo {:id promo-id :page-id page-id :name "Promo" :type :rect + :frame-id board-id :frame-name "Checkout" :kind :added} + moved {:id board-id :page-id page-id :name "Checkout" :type :frame + :frame-id uuid/zero :frame-name nil :kind :modified + :attrs {:x [0 10]}} + changed (assoc paid :name "Pay now" :kind :modified + :attrs {:name ["Pay" "Pay now"]}) + + row + (fn [revn at entries] + [(uuid/next) pr-id (:id author) revn + (blob/encode entries) + at]) + + ;; 2001 saves: the oldest one adds the layers and the newest + ;; one renames one of them and deletes the other. The saves in + ;; between keep the first one outside a 2000-row window, and a + ;; gap longer than a sitting opens a second sitting, so the + ;; fold crosses one. + rows + (into [(row 0 start [paid promo])] + (concat (map (fn [i] + (row i + (ct/plus start (ct/duration {:hours 2 :seconds i})) + [moved])) + (range 1 2000)) + [(row 2000 + (ct/plus start (ct/duration {:hours 2 :seconds 2000})) + [changed (assoc promo :kind :deleted)])]))] + + (db/insert-many! th/*pool* :file-pull-request-activity + [:id :pull-request-id :profile-id :revn :entries :created-at] + rows + {::db/return-keys false}) + + (let [out (th/command! {::th/type :get-pull-request-activity + ::rpc/profile-id (:id author) + :id pr-id}) + result (:result out) + entry (->> (:entries result) + (some #(when (= paid-id (:id %)) %)))] + (t/is (nil? (:error out))) + (t/is (= :added (:kind entry)) + "the oldest save still counts in what the layer ends up as") + (t/is (= "Pay now" (:name entry)) + "the layer keeps the name of its last change") + (t/is (not-any? #(= promo-id (:id %)) (:entries result)) + "a layer added and then deleted is no change") + (t/is (= 2 (count (:entries result)))) + (t/is (= 2 (count (:sessions result)))) + (t/is (= 1 (:people result))) + (t/is (= (:id author) (-> result :last-save :profile-id))))))) diff --git a/backend/test/backend_tests/rpc_file_task_test.clj b/backend/test/backend_tests/rpc_file_task_test.clj index fefe1de104..5639dd6d8d 100644 --- a/backend/test/backend_tests/rpc_file_task_test.clj +++ b/backend/test/backend_tests/rpc_file_task_test.clj @@ -7,12 +7,14 @@ (ns backend-tests.rpc-file-task-test (:require [app.common.features :as cfeat] + [app.common.files.branch-merge :as bm] [app.common.geom.point :as gpt] [app.common.types.shape :as cts] [app.common.uuid :as uuid] [app.config :as cf] [app.db :as db] [app.email :as eml] + [app.msgbus :as mbus] [app.rpc :as-alias rpc] [backend-tests.helpers :as th] [clojure.test :as t])) @@ -224,13 +226,14 @@ (update-file* author branch-file-id [{:type :mod-obj :page-id page-id :id rect-id :operations [{:type :set :attr :name :val "Pay"}]}]) - (let [[row :as rows] (:result (th/command! {::th/type :get-pull-request-activity - ::rpc/profile-id (:id author) - :id (:id review)}))] - (t/is (= 1 (count rows))) - (t/is (= (:id author) (:profile-id row))) + (let [result (:result (th/command! {::th/type :get-pull-request-activity + ::rpc/profile-id (:id author) + :id (:id review)}))] (t/is (= [{:id rect-id :kind :modified :attrs {:name ["Pay button" "Pay"]}}] - (mapv #(select-keys % [:id :kind :attrs]) (:entries row)))))))) + (mapv #(select-keys % [:id :kind :attrs]) (:entries result)))) + (t/is (= (:id author) (-> result :last-save :profile-id))) + (t/is (= 1 (:people result))) + (t/is (= 1 (count (:sessions result)))))))) (t/deftest merge-moves-the-tasks-and-their-threads-into-main (with-redefs [cf/flags (task-flags) @@ -424,3 +427,367 @@ (mapv :id (:result (th/command! {::th/type :get-file-tasks ::rpc/profile-id (:id author) :file-id branch-file-id})))))))) + +;; --- Messages to the open clients + +(defn- capture-messages + "Run `f` and return the msgbus messages it published." + [f] + (let [seen (atom [])] + (with-redefs [mbus/pub! (fn [_ & {:keys [topic message]}] + (swap! seen conj {:topic topic :message message}))] + (f)) + @seen)) + +(defn- tasks-change-of + [messages topic] + (some #(when (and (= topic (:topic %)) + (= :file-tasks-change (-> % :message :type))) + (:message %)) + messages)) + +(t/deftest task-change-messages-name-the-session-and-the-task + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id rect-id branch-file-id]} (setup-review) + session-id (uuid/random) + task (atom nil) + messages (capture-messages + #(reset! task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id rect-id + ::rpc/session-id session-id})))) + message (tasks-change-of messages branch-file-id)] + (t/is (= session-id (:session-id message))) + (t/is (= [(:id @task)] (:task-ids message))) + (t/is (= [(:title @task)] (mapv :title (:tasks message)))) + + (t/testing "a deleted task is named without a row" + (let [message (-> (capture-messages + #(th/command! {::th/type :delete-task + ::rpc/profile-id (:id author) + :id (:id @task)})) + (tasks-change-of branch-file-id))] + (t/is (= [(:id @task)] (:task-ids message))) + (t/is (empty? (:tasks message)))))))) + +(t/deftest the-merge-tells-main-that-its-tasks-changed + (with-redefs [cf/flags (task-flags) + eml/send-template (fn [_ _] nil)] + (let [{:keys [author page-id rect-id file branch branch-file-id]} (setup-review) + task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id rect-id})) + _ (update-file* author branch-file-id + [{:type :mod-obj :page-id page-id :id rect-id + :operations [{:type :set :attr :name :val "Pay"}]}]) + messages (capture-messages + #(t/is (nil? (:error (th/command! {::th/type :merge-file-branch + ::rpc/profile-id (:id author) + :branch-id (:id branch)}))))) + message (tasks-change-of messages (:id file))] + (t/is (some? message)) + (t/is (= [(:id task)] (:task-ids message))) + (t/is (= [(:id file)] (mapv :file-id (:tasks message))))))) + +;; --- Creating a task while the branch merges + +(t/deftest a-task-created-during-the-merge-does-not-stay-on-the-branch + ;; the merge reads the tasks of the branch, then deletes the branch + ;; file: a task created in between must not be left on the deleted + ;; file. The hook runs another session's creation once the merge has + ;; moved the tasks, and waits for it, but not past the lock the merge + ;; holds. + (with-redefs [cf/flags (task-flags) + eml/send-template (fn [_ _] nil)] + (let [{:keys [author page-id rect-id branch branch-file-id]} (setup-review) + orig-update db/update! + created (atom nil)] + (update-file* author branch-file-id + [{:type :mod-obj :page-id page-id :id rect-id + :operations [{:type :set :attr :name :val "Pay"}]}]) + (with-redefs [db/update! + (fn [conn table params & more] + (when (and (= :file-branch table) + (= "merged" (:status params)) + (compare-and-set! created nil ::started)) + (let [creation (future (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id rect-id + :title "Late task"}))] + (reset! created creation) + (deref creation 2000 nil))) + (apply orig-update conn table params more))] + (t/is (nil? (:error (th/command! {::th/type :merge-file-branch + ::rpc/profile-id (:id author) + :branch-id (:id branch)}))))) + (let [out (deref @created 10000 ::timeout)] + (t/is (= :object-not-found (-> out :error ex-data :code)))) + (t/is (empty? (th/db-exec! ["SELECT id FROM file_task WHERE file_id = ?" branch-file-id])))))) + +;; --- Where a carried task lands when the merge leaves its layer out + +(defn- add-shape* + [profile file-id page-id {:keys [id parent-id frame-id] :as attrs}] + (update-file* profile file-id + [{:type :add-obj + :page-id page-id + :id id + :parent-id parent-id + :frame-id frame-id + :obj (cts/setup-shape attrs)}])) + +(defn- setup-board-branch + "A file whose main holds a board with a rect inside, and a branch of + it. Returns the ids the tests need." + [] + (let [author (th/create-profile* 1 {:is-active true}) + file (th/create-file* 1 {:profile-id (:id author) + :project-id (:default-project-id author)}) + page-id (page-id-of author (:id file)) + board-id (uuid/random) + rect-id (uuid/random)] + (add-shape* author (:id file) page-id + {:id board-id :name "Checkout" :type :frame + :x 0 :y 0 :width 400 :height 800 + :parent-id uuid/zero :frame-id uuid/zero}) + (add-shape* author (:id file) page-id + {:id rect-id :name "Pay button" :type :rect + :x 20 :y 600 :width 300 :height 48 + :parent-id board-id :frame-id board-id}) + (let [branch (:result (th/command! {::th/type :create-file-branch + ::rpc/profile-id (:id author) + :file-id (:id file) + :name "feature-login"}))] + {:author author + :file file + :page-id page-id + :board-id board-id + :rect-id rect-id + :branch branch + :branch-file-id (:branch-file-id branch)}))) + +(defn- add-promo* + "Add on the branch a board with a rect inside, which main lacks. + Returns their ids." + [author branch-file-id page-id] + (let [promo-id (uuid/random) + badge-id (uuid/random)] + (add-shape* author branch-file-id page-id + {:id promo-id :name "Promo" :type :frame + :x 500 :y 0 :width 400 :height 800 + :parent-id uuid/zero :frame-id uuid/zero}) + (add-shape* author branch-file-id page-id + {:id badge-id :name "Badge" :type :rect + :x 520 :y 600 :width 300 :height 48 + :parent-id promo-id :frame-id promo-id}) + {:promo-id promo-id :badge-id badge-id})) + +(defn- merge-excluding* + [profile branch page-id shape-ids] + (th/command! {::th/type :merge-file-branch + ::rpc/profile-id (:id profile) + :branch-id (:id branch) + :excluded (into #{} + (map #(bm/change-key {:kind :shape :page-id page-id :id %})) + shape-ids)})) + +(defn- task-events* + [profile task-id] + (:result (th/command! {::th/type :get-task-events + ::rpc/profile-id (:id profile) + :id task-id}))) + +(t/deftest a-carried-task-lands-on-the-layer-its-parent-has-on-main + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author file page-id board-id rect-id branch branch-file-id]} (setup-board-branch) + task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :frame-id board-id + :shape-id rect-id}))] + ;; the branch deletes the rect: the merge does not carry it + (update-file* author branch-file-id [{:type :del-obj :page-id page-id :id rect-id}]) + (t/is (nil? (:error (th/command! {::th/type :merge-file-branch + ::rpc/profile-id (:id author) + :branch-id (:id branch)})))) + (let [row (th/db-get :file-task {:id (:id task)}) + thread (th/db-get :comment-thread {:id (:thread-id task)})] + (t/is (= (:id file) (:file-id row))) + (t/is (= board-id (:shape-id row))) + (t/is (= board-id (:frame-id row))) + (t/is (nil? (:lost-shape-name row))) + (t/testing "the thread created with the task follows it" + (t/is (= "layer" (:anchor-type thread))) + (t/is (= board-id (:shape-id thread))))) + (t/testing "the landing is an event naming the layer" + (let [event (last (task-events* author (:id task)))] + (t/is (= "relinked" (:type event))) + (t/is (= {:shape-id board-id :shape-name "Checkout"} (:payload event)))))))) + +(t/deftest the-merge-parent-fallback-uses-the-branch-parent + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id branch branch-file-id]} (setup-board-branch) + {:keys [promo-id badge-id]} (add-promo* author branch-file-id page-id) + task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :frame-id promo-id + :shape-id badge-id}))] + ;; the merge carries the new board and leaves the rect out: the rect + ;; exists on the branch only, so its parent comes from the branch + (t/is (nil? (:error (merge-excluding* author branch page-id [badge-id])))) + (let [row (th/db-get :file-task {:id (:id task)})] + (t/is (= promo-id (:shape-id row))) + (t/is (= promo-id (:frame-id row))))))) + +(t/deftest a-carried-task-with-nothing-left-lands-on-an-area + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id board-id branch branch-file-id]} (setup-board-branch) + {:keys [promo-id badge-id]} (add-promo* author branch-file-id page-id) + task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :frame-id promo-id + :shape-id badge-id}))] + ;; something else merges: the board of main is renamed + (update-file* author branch-file-id + [{:type :mod-obj :page-id page-id :id board-id + :operations [{:type :set :attr :name :val "Checkout v2"}]}]) + ;; leaving the new board out leaves its rect out with it + (t/is (nil? (:error (merge-excluding* author branch page-id [promo-id])))) + (let [row (th/db-get :file-task {:id (:id task)}) + thread (th/db-get :comment-thread {:id (:thread-id task)}) + area (db/decode-transit-pgobject (:area thread))] + (t/is (nil? (:shape-id row))) + (t/is (= uuid/zero (:frame-id row))) + ;; the mark sits on the top right corner of the lost layer + (t/is (= {:x 820.0 :y 600.0} (into {} (db/decode-pgpoint (:position row))))) + (t/is (= "area" (:anchor-type thread))) + (t/is (nil? (:shape-id thread))) + (t/is (= [520.0 600.0 300.0 48.0] + (mapv #(double (get area %)) [:x :y :width :height])))) + (let [event (last (task-events* author (:id task)))] + (t/is (= "relinked" (:type event))) + (t/is (some? (-> event :payload :area))))))) + +;; --- Deleted layers of any size + +(t/deftest a-task-on-a-board-larger-than-the-snapshot-cap-is-still-marked-lost + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id rect-id branch-file-id]} (setup-review) + small-id (uuid/random) + bogus-id (uuid/random) + create (fn [shape-id] + (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id shape-id}))) + large (create rect-id) + small (create small-id) + bogus (create bogus-id) + children (map (fn [_] + (cts/setup-shape {:id (uuid/random) :name "Item" :type :rect + :parent-id rect-id :frame-id rect-id})) + (range 501)) + out (th/command! {::th/type :mark-tasks-layer-deleted + ::rpc/profile-id (:id author) + :file-id branch-file-id + :layers [{:shape-id rect-id + :shape-name "Pay button" + :frame-id uuid/zero + :objects (into [(cts/setup-shape + {:id rect-id :name "Pay button" :type :frame + :parent-id uuid/zero :frame-id uuid/zero})] + children)} + {:shape-id small-id + :shape-name "Badge" + :frame-id uuid/zero + :objects [(cts/setup-shape + {:id small-id :name "Badge" :type :rect + :parent-id uuid/zero :frame-id uuid/zero})]} + ;; not a shape: no restore may make it a layer + {:shape-id bogus-id + :shape-name "Bogus" + :frame-id uuid/zero + :objects [{:id bogus-id :type :rect}]}]}) + payload (fn [task] + (->> (task-events* author (:id task)) + (filter #(= "layer-deleted" (:type %))) + (last) + :payload))] + (t/is (nil? (:error out))) + (t/is (= 3 (count (:result out)))) + (t/testing "every task is lost" + (t/is (= "Pay button" (:lost-shape-name (th/db-get :file-task {:id (:id large)})))) + (t/is (= "Badge" (:lost-shape-name (th/db-get :file-task {:id (:id small)})))) + (t/is (= "Bogus" (:lost-shape-name (th/db-get :file-task {:id (:id bogus)}))))) + (t/testing "the event keeps the layer only when small and valid" + (t/is (not (contains? (payload large) :objects))) + (t/is (= [small-id] (mapv :id (:objects (payload small))))) + (t/is (not (contains? (payload bogus) :objects))))))) + +;; --- Deleting a task + +(t/deftest only-the-author-may-delete-a-task-and-it-leaves-an-event + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author reviewer page-id branch-file-id]} (setup-review) + task (:result (create-task* author {:file-id branch-file-id :page-id page-id})) + delete (fn [profile] + (th/command! {::th/type :delete-task + ::rpc/profile-id (:id profile) + :id (:id task)}))] + (t/testing "a reviewer cannot delete it" + (t/is (= :not-allowed (-> (delete reviewer) :error ex-data :code))) + (t/is (some? (th/db-get :file-task {:id (:id task)})))) + + (t/testing "its author can, and the deletion is an event" + (t/is (nil? (:error (delete author)))) + (t/is (some? (:deleted-at (th/db-get :file-task {:id (:id task)} + {::db/remove-deleted false})))) + (let [rows (th/db-exec! ["SELECT profile_id FROM file_task_event + WHERE task_id = ? AND type = 'deleted'" + (:id task)])] + (t/is (= [(:id author)] (mapv :profile-id rows)))))))) + +;; --- Relinking a task + +(t/deftest relinking-a-task-moves-the-thread-it-was-created-with + (with-redefs [cf/flags (task-flags)] + (let [{:keys [author page-id rect-id branch-file-id]} (setup-review) + other-id (uuid/random) + relink (fn [task] + (th/command! {::th/type :relink-task + ::rpc/profile-id (:id author) + :id (:id task) + :page-id page-id + :frame-id uuid/zero + :shape-id other-id + :shape-name "Promo"}))] + (add-rect* author branch-file-id page-id other-id "Promo") + + (t/testing "a task created on a layer takes its thread along" + (let [task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id rect-id}))] + (t/is (nil? (:error (relink task)))) + (let [thread (th/db-get :comment-thread {:id (:thread-id task)})] + (t/is (= other-id (:shape-id thread))) + (t/is (= "layer" (:anchor-type thread)))))) + + (t/testing "a task made from a reply leaves the thread where it is" + (let [thread (:result (th/command! {::th/type :create-comment-thread + ::rpc/profile-id (:id author) + :file-id branch-file-id + :page-id page-id + :frame-id uuid/zero + :position (gpt/point 0) + :content "the radius is off" + :anchor {:type :layer :shape-id rect-id}})) + reply (:result (th/command! {::th/type :create-comment + ::rpc/profile-id (:id author) + :thread-id (:id thread) + :content "and the shadow"})) + task (:result (create-task* author {:file-id branch-file-id + :page-id page-id + :shape-id rect-id + :thread-id (:id thread) + :comment-id (:id reply)}))] + (t/is (nil? (:error (relink task)))) + (t/is (= rect-id (:shape-id (th/db-get :comment-thread {:id (:id thread)})))) + (t/is (= other-id (:shape-id (th/db-get :file-task {:id (:id task)}))))))))) diff --git a/frontend/src/app/main/data/workspace/review.cljs b/frontend/src/app/main/data/workspace/review.cljs index d83410d16f..e302be8b43 100644 --- a/frontend/src/app/main/data/workspace/review.cljs +++ b/frontend/src/app/main/data/workspace/review.cljs @@ -13,10 +13,9 @@ `:workspace-review-local` keeps the tool in use, the tab and filters of the review panel and the change shown on the canvas; - `:workspace-review-activity` the activity of the review, one row per - save of the branch since the review opened." + `:workspace-review-activity` the activity of the review, folded by the + backend from the saves of the branch since the review opened." (:require - [app.common.files.review-activity :as ra] [app.common.geom.point :as gpt] [app.common.uuid :as uuid] [app.main.data.comments :as dcmt] @@ -196,16 +195,20 @@ ;; --- Activity (defn- activity-fetched - [pr-id rows] + "Store the activity as the backend folds it: `:entries` what each layer + ends up as, `:sessions` the sittings of saves the dialog lists, + `:people` how many people saved and `:last-save` the newest save." + [pr-id result] (ptk/reify ::activity-fetched ptk/UpdateEvent (update [_ state] (assoc state :workspace-review-activity {:pr-id pr-id :status :loaded - :rows rows - :entries (ra/net-entries rows) - :sessions (ra/sessions rows)})))) + :entries (:entries result) + :sessions (:sessions result) + :people (:people result) + :last-save (:last-save result)})))) (defn fetch-activity "Load what the saves of the branch did since the review `pr-id` opened." diff --git a/frontend/src/app/main/data/workspace/tasks.cljs b/frontend/src/app/main/data/workspace/tasks.cljs index e35d96277c..b90b9e02cc 100644 --- a/frontend/src/app/main/data/workspace/tasks.cljs +++ b/frontend/src/app/main/data/workspace/tasks.cljs @@ -24,6 +24,7 @@ [app.common.files.helpers :as cfh] [app.common.geom.point :as gpt] [app.common.geom.shapes :as gsh] + [app.common.logging :as log] [app.common.types.shape-tree :as ctst] [app.common.uuid :as uuid] [app.config :as cf] @@ -71,6 +72,17 @@ [task] (some? (:lost-shape-name task))) +(defn restorable? + "The deleted layer of a task can be put back: the last deletion among + the `events` of the task kept the layer, which the server skips for a + very large one." + [events] + (-> (filter #(= "layer-deleted" (:type %)) events) + (last) + (get-in [:payload :objects]) + (seq) + (some?))) + (defn history? "The task came with a merged branch and is already closed: it is part of the history of that branch, not of the work on this file." @@ -180,15 +192,42 @@ (rx/of (fetch-task-events open-id)) (rx/empty))))))) +(defn- patch-tasks + "Put the rows `tasks` of a change into the tasks `data`; a task of + `task-ids` without a row was deleted." + [data task-ids tasks] + (let [rows (d/index-by :id tasks)] + (reduce (fn [data id] + (if-let [row (get rows id)] + (assoc data id row) + (dissoc data id))) + data + task-ids))) + (defn handle-tasks-change - "Another session changed the tasks of the open file." - [{:keys [file-id]}] - (ptk/reify ::handle-tasks-change - ptk/WatchEvent - (watch [_ state _] - (if (= file-id (:current-file-id state)) - (rx/of (refresh)) - (rx/empty))))) + "The tasks `task-ids` of a file changed. The message carries their rows + (`tasks`), which patch the list of the open file; the session that + made the change (`session-id`) holds them already and skips it. The + events of the open task are fetched again when it changed." + [{:keys [file-id session-id task-ids tasks]}] + (letfn [(applies? [state] + (and (= file-id (:current-file-id state)) + (not= session-id (:session-id state))))] + (ptk/reify ::handle-tasks-change + ptk/UpdateEvent + (update [_ state] + (if (applies? state) + (d/update-in-when state [:workspace-tasks :data] patch-tasks task-ids tasks) + state)) + + ptk/WatchEvent + (watch [_ state _] + (let [open-id (get-in state [:workspace-tasks-local :open])] + (if (and (applies? state) + (some? open-id) + (some #(= open-id %) task-ids)) + (rx/of (fetch-task-events open-id)) + (rx/empty))))))) ;; --- Opening a task @@ -532,7 +571,11 @@ (fn [moved] (rx/of (refresh) (layer-deleted-dialog moved message)))) - (rx/catch (fn [_] (rx/empty)))))))))) + (rx/catch (fn [cause] + (log/error :hint "unable to mark the tasks of deleted layers as lost" + :file-id (str file-id) + :cause cause) + (rx/of (ntf/error (tr "workspace.tasks.error.layer-deleted")))))))))))) (defn- layer-deleted-dialog "The dialog that follows the deletion of layers with open tasks: undo diff --git a/frontend/src/app/main/ui/workspace/review/details.cljs b/frontend/src/app/main/ui/workspace/review/details.cljs index 94637da102..f11c29d776 100644 --- a/frontend/src/app/main/ui/workspace/review/details.cljs +++ b/frontend/src/app/main/ui/workspace/review/details.cljs @@ -206,7 +206,7 @@ open (count (remove dwtk/closed? tasks)) closed (count (filter dwtk/closed? tasks)) counts (:counts pr) - last-row (first (:rows activity))] + last-save (:last-save activity)] [:div {:class (stl/css :tab-body)} [:div {:class (stl/css :facts)} @@ -225,10 +225,10 @@ [:> text* {:as "span" :typography t/body-small :class (stl/css :muted)} (tr "workspace.review.details.last-change")] [:> text* {:as "span" :typography t/body-small :class (stl/css :fact-value)} - (if (some? last-row) + (if (some? last-save) (tr "workspace.review.details.last-change-by" - (ct/timeago (:created-at last-row)) - (rvc/profile-name profiles (:profile-id last-row))) + (ct/timeago (:created-at last-save)) + (rvc/profile-name profiles (:profile-id last-save))) (ct/timeago (:review-updated-at pr)))]]] (when (and (pos? missing) (= "open" (:status pr))) @@ -460,7 +460,7 @@ local (mf/deref refs/review-local) kind (get local :change-filter :all) entries (:entries activity) - people (count (into #{} (map :profile-id) (:rows activity))) + people (:people activity 0) counts (frequencies (map :kind entries)) sessions (mf/with-memo [activity kind] (->> (:sessions activity) diff --git a/frontend/src/app/main/ui/workspace/review/tasks.cljs b/frontend/src/app/main/ui/workspace/review/tasks.cljs index b2af6fbafc..a2e50a90ad 100644 --- a/frontend/src/app/main/ui/workspace/review/tasks.cljs +++ b/frontend/src/app/main/ui/workspace/review/tasks.cljs @@ -131,6 +131,7 @@ open? (deref open*) status (:status task) options (use-assignee-options) + profile (mf/deref refs/profile) on-toggle (mf/use-fn @@ -194,8 +195,10 @@ (when-not (dwtk/closed? task) [:> menu-item* {:id "relink"} (tr "workspace.tasks.actions.relink")]) - [:> menu-item* {:id "delete"} - (tr "workspace.tasks.actions.delete")]]])) + ;; only its author may delete a task + (when (= (:id profile) (:created-by task)) + [:> menu-item* {:id "delete"} + (tr "workspace.tasks.actions.delete")])]])) ;; --- List of tasks @@ -282,10 +285,13 @@ "wont-do" (tr "workspace.tasks.event.wont-do" actor) (tr "workspace.tasks.event.status" actor)) "renamed" (tr "workspace.tasks.event.renamed" actor) - "relinked" (tr "workspace.tasks.event.relinked" actor (:shape-name payload)) + "relinked" (if (some? (:area payload)) + (tr "workspace.tasks.event.relinked-area" actor) + (tr "workspace.tasks.event.relinked" actor (:shape-name payload))) "layer-deleted" (tr "workspace.tasks.event.layer-deleted" actor (:shape-name payload)) "layer-restored" (tr "workspace.tasks.event.layer-restored" actor (:shape-name payload)) "moved-to-main" (tr "workspace.tasks.event.moved-to-main" (:branch-name payload)) + "deleted" (tr "workspace.tasks.event.deleted" actor) nil))) (defn- event-icon @@ -294,6 +300,7 @@ "layer-deleted" i/triangle-alert "status" (if (= "done" (:to payload)) i/tick i/view-as-list) "moved-to-main" i/git-merge + "deleted" i/delete i/view-as-list)) (mf/defc task-event* @@ -418,6 +425,7 @@ {::mf/private true} [{:keys [task]}] (let [profiles (mf/deref refs/profiles) + events (get (mf/deref refs/task-events) (:id task)) data (mf/deref refs/workspace-data) preview (mf/deref refs/pull-request-preview) objects (page-objects data (:page-id task)) @@ -457,7 +465,7 @@ (tr "workspace.tasks.lost.message" (rvc/board-name objects (:frame-id task)))] [:div {:class (stl/css :task-next-step-actions)} ;; restoring and relinking edit the branch: not inside a review - (when (nil? preview) + (when (and (nil? preview) (dwtk/restorable? events)) [:> button* {:variant "ghost" :icon i/history :on-click on-restore} (tr "workspace.tasks.actions.restore-layer")]) (when (nil? preview) diff --git a/frontend/test/frontend_tests/data/workspace_tasks_test.cljs b/frontend/test/frontend_tests/data/workspace_tasks_test.cljs index 801395f28c..012e799ec9 100644 --- a/frontend/test/frontend_tests/data/workspace_tasks_test.cljs +++ b/frontend/test/frontend_tests/data/workspace_tasks_test.cljs @@ -139,3 +139,61 @@ (t/is (not-any? #(= :get-comment-thread (:cmd %)) calls)) (t/is (not-any? #{::dcmt/created-thread-on-workspace} seen)) (t/is (some #{::dwtk/open-task} seen)))) + +;; --- Changes made to the tasks + +(def ^:private session-id (uuid/custom 3 1)) +(def ^:private task-id (uuid/custom 3 2)) + +(defn- tasks-state + "The open file with one task, open on the canvas, in the session + `session-id`." + [] + {:current-file-id file-id + :session-id session-id + :workspace-tasks {:status :loaded + :data {task-id {:id task-id :title "Old title" :status "open"}}} + :workspace-tasks-local {:open task-id}}) + +(defn- ^:async change-handled + "Handle the change `message` over the tasks of `tasks-state`: the state + it leaves, what it emits and what it asks the server." + [message] + (let [calls (atom []) + seen (atom []) + event (dwtk/handle-tasks-change message) + state (ptk/update event (tasks-state))] + (await (mock/with-mocks* + {rp/cmd! (fake-server calls)} + (await (hva/observe (ptk/watch event state (rx/empty)) + {:on-next #(swap! seen conj (ptk/type %))})))) + {:state state :calls @calls :seen @seen})) + +(defn- change-message + [from-session tasks] + {:type :file-tasks-change + :file-id file-id + :session-id from-session + :task-ids [task-id] + :tasks tasks}) + +(t/deftest ^:async a-change-from-this-session-does-not-reload-the-list + (let [{:keys [state calls seen]} + (await (change-handled (change-message session-id [{:id task-id :title "New title" :status "open"}])))] + (t/is (empty? seen)) + (t/is (not-any? #(= :get-file-tasks (:cmd %)) calls)) + (t/is (= "Old title" (get-in state [:workspace-tasks :data task-id :title]))))) + +(t/deftest ^:async a-change-from-another-session-patches-the-list + (t/testing "the row of the message replaces the task, and the events of the open task are fetched again" + (let [{:keys [state calls seen]} + (await (change-handled (change-message (uuid/next) [{:id task-id :title "New title" :status "done"}])))] + (t/is (= "New title" (get-in state [:workspace-tasks :data task-id :title]))) + (t/is (= "done" (get-in state [:workspace-tasks :data task-id :status]))) + (t/is (not-any? #{::dwtk/refresh ::dwtk/fetch-tasks} seen)) + (t/is (some #{::dwtk/fetch-task-events} seen)) + (t/is (not-any? #(= :get-file-tasks (:cmd %)) calls)))) + + (t/testing "a task named without a row was deleted" + (let [{:keys [state]} (await (change-handled (change-message (uuid/next) [])))] + (t/is (not (contains? (get-in state [:workspace-tasks :data]) task-id)))))) diff --git a/frontend/test/frontend_tests/ui/review_details_test.cljs b/frontend/test/frontend_tests/ui/review_details_test.cljs index 6bdd7d711d..79870bc2f5 100644 --- a/frontend/test/frontend_tests/ui/review_details_test.cljs +++ b/frontend/test/frontend_tests/ui/review_details_test.cljs @@ -6,6 +6,7 @@ (ns frontend-tests.ui.review-details-test (:require + [app.common.uuid :as uuid] [app.main.data.workspace.review :as dwrv] [app.main.ui.workspace.review.common :as rvc] [app.main.ui.workspace.review.details :as details] @@ -14,6 +15,8 @@ (def ^:private display-attr @#'details/display-attr) +(def ^:private activity-fetched @#'dwrv/activity-fetched) + (t/deftest a-fill-without-tokens-shows-its-value (let [fill-a [{:fill-color "#ff0000" :fill-opacity 1}] fill-b [{:fill-color "#00ff00" :fill-opacity 1}] @@ -41,3 +44,24 @@ (t/deftest every-task-state-has-its-colour (t/is (= ["info" "success" "warning" "purple" "error"] (mapv rvc/status-tone dwrv/task-statuses)))) + +(t/deftest the-activity-comes-folded-from-the-server + (let [entry {:id (uuid/random) :page-id (uuid/random) :kind :added} + session {:profile-id (uuid/random) + :start (js/Date.) + :end (js/Date.) + :entries [entry]} + last-save {:created-at (js/Date.) :profile-id (uuid/random)} + pr-id (uuid/random) + state (ptk/update (activity-fetched pr-id {:entries [entry] + :sessions [session] + :people 2 + :last-save last-save}) + {}) + activity (:workspace-review-activity state)] + (t/is (= :loaded (:status activity))) + (t/is (= pr-id (:pr-id activity))) + (t/is (= [entry] (:entries activity))) + (t/is (= [session] (:sessions activity))) + (t/is (= 2 (:people activity))) + (t/is (= last-save (:last-save activity))))) diff --git a/frontend/translations/en.po b/frontend/translations/en.po index ab5c6620f6..23818d99cd 100644 --- a/frontend/translations/en.po +++ b/frontend/translations/en.po @@ -12317,6 +12317,10 @@ msgstr "The task could not be changed. Try again." msgid "workspace.tasks.error.comment-has-task" msgstr "This comment is a task already." +#: src/app/main/data/workspace/tasks.cljs +msgid "workspace.tasks.error.layer-deleted" +msgstr "The tasks of the deleted layers could not be updated. Reload the file to see them." + #: src/app/main/ui/workspace/review/tasks.cljs msgid "workspace.tasks.event.assigned" msgstr "%s assigned it to %s" @@ -12325,6 +12329,10 @@ msgstr "%s assigned it to %s" msgid "workspace.tasks.event.assigned-to-you" msgstr "%s made this a task for you" +#: src/app/main/ui/workspace/review/tasks.cljs +msgid "workspace.tasks.event.deleted" +msgstr "%s deleted the task" + #: src/app/main/ui/workspace/review/tasks.cljs msgid "workspace.tasks.event.done" msgstr "%s marked it as done" @@ -12345,6 +12353,10 @@ msgstr "Moved to main with the merge of %s" msgid "workspace.tasks.event.relinked" msgstr "%s linked it to %s" +#: src/app/main/ui/workspace/review/tasks.cljs +msgid "workspace.tasks.event.relinked-area" +msgstr "%s placed it on the canvas, where its layer was" + #: src/app/main/ui/workspace/review/tasks.cljs msgid "workspace.tasks.event.renamed" msgstr "%s renamed it" diff --git a/frontend/translations/es.po b/frontend/translations/es.po index 702ae039d0..0746453e74 100644 --- a/frontend/translations/es.po +++ b/frontend/translations/es.po @@ -12471,6 +12471,10 @@ msgstr "No se pudo cambiar la tarea. Inténtalo de nuevo." msgid "workspace.tasks.error.comment-has-task" msgstr "Este comentario ya es una tarea." +#: src/app/main/data/workspace/tasks.cljs +msgid "workspace.tasks.error.layer-deleted" +msgstr "No se pudieron actualizar las tareas de las capas borradas. Recarga el archivo para verlas." + #: src/app/main/ui/workspace/review/tasks.cljs msgid "workspace.tasks.event.assigned" msgstr "%s se la asignó a %s" @@ -12479,6 +12483,10 @@ msgstr "%s se la asignó a %s" msgid "workspace.tasks.event.assigned-to-you" msgstr "%s hizo de esto una tarea para ti" +#: src/app/main/ui/workspace/review/tasks.cljs +msgid "workspace.tasks.event.deleted" +msgstr "%s borró la tarea" + #: src/app/main/ui/workspace/review/tasks.cljs msgid "workspace.tasks.event.done" msgstr "%s la marcó como hecha" @@ -12499,6 +12507,10 @@ msgstr "Pasó a main con la fusión de %s" msgid "workspace.tasks.event.relinked" msgstr "%s la enlazó a %s" +#: src/app/main/ui/workspace/review/tasks.cljs +msgid "workspace.tasks.event.relinked-area" +msgstr "%s la colocó en el lienzo, donde estaba su capa" + #: src/app/main/ui/workspace/review/tasks.cljs msgid "workspace.tasks.event.renamed" msgstr "%s le cambió el título"