From 6aab1b322f62f065f35cd0224bffaea3fb1a80e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 10:14:01 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(store):=20a=20move=20is=20a=20?= =?UTF-8?q?crossing,=20and=20the=20crossing=20is=20a=20fact?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The mail rules trigger on the transition, not on where a card currently sits: a task that goes Review → Done → Review has crossed into Done once, and nothing recomputed from `task.column_id` afterwards can say so. `move_task` therefore writes the crossing — from-column, to-column, actor, moment — in the same transaction as the move, and the moment is taken inside that transaction so slice 7 can say "moved to Done on Tuesday" even when the send is retried on Thursday. The update is conditional on the column the caller believed the card was in when the drag started. Two people dragging one card produce exactly one crossing: the loser is told `Moved::Stale` and re-reads, rather than writing a second crossing out of a column the card had already left. The transaction is IMMEDIATE, so the read that decides this cannot be overtaken by the write that invalidates it. A card dropped back where it came from is not a transition. It answers `Moved::Unchanged` and writes nothing at all — not the crossing, not the activity line, not an `updated_at` bump. Landing in a done column stamps `done_at` and leaving one clears it, in the same transaction, because a card's finished state is a consequence of where it sits and must not be able to drift from it. A destination column is checked to belong to the task's own board: a column id arrives in a form, and a form is not a promise. The card lands at the end of its new column. Where inside a column a card sits belongs to the board's sort control, not to the drop. 64 store tests, all passing. --- .../dizey-core/migrations/0003_transition.sql | 17 ++ crates/dizey-core/src/board.rs | 31 +++ crates/dizey-core/src/store/mod.rs | 29 ++- crates/dizey-core/src/store/turso_store.rs | 183 +++++++++++++++- crates/dizey-core/tests/store.rs | 202 +++++++++++++++++- 5 files changed, 457 insertions(+), 5 deletions(-) create mode 100644 crates/dizey-core/migrations/0003_transition.sql diff --git a/crates/dizey-core/migrations/0003_transition.sql b/crates/dizey-core/migrations/0003_transition.sql new file mode 100644 index 0000000..0c575bf --- /dev/null +++ b/crates/dizey-core/migrations/0003_transition.sql @@ -0,0 +1,17 @@ +-- Every move of a card from one column to another, written as a fact in the +-- same transaction as the move itself. +-- +-- The mail rules trigger on the transition, not on the task's current column: +-- a card that goes Review -> Done -> Review has crossed into Done once, and +-- nothing recomputed from `task.column_id` afterwards can tell you that. So +-- this table is the record, and the rules read it. +CREATE TABLE transition ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + from_column TEXT NOT NULL REFERENCES board_column(id), + to_column TEXT NOT NULL REFERENCES board_column(id), + actor_id TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); + +CREATE INDEX transition_by_task ON transition(task_id, created_at); diff --git a/crates/dizey-core/src/board.rs b/crates/dizey-core/src/board.rs index 80fcd7e..d8f9037 100644 --- a/crates/dizey-core/src/board.rs +++ b/crates/dizey-core/src/board.rs @@ -39,6 +39,37 @@ pub struct TaskRow { pub done_at: Option, } +/// One card crossing from one column into another, as it was written. +/// +/// `at` is the moment the move committed, taken inside the same transaction +/// as the move. The mail engine reads it rather than stamping its own clock: +/// a send retried on Thursday still has to say the card moved on Tuesday. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Transition { + pub id: String, + pub task_id: String, + pub from_column: String, + pub to_column: String, + pub actor_id: String, + pub at: OffsetDateTime, +} + +/// What a move attempt did. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum Moved { + /// The card changed column. This is the fact that was written, and the + /// only outcome the mail rules act on. + Recorded(Transition), + /// The card was dropped back in the column it came from. Nothing was + /// written: that is not a transition, and a rule must not fire for it. + Unchanged, + /// Somebody else moved the card between the drag starting and the drop + /// landing, so the column this move was told to move it out of is no + /// longer the column it is in. Nothing was written and the caller should + /// re-read the board rather than overwrite a decision it never saw. + Stale, +} + /// Whoever a card can point at. The address is not here: a board card never /// shows one, so it never leaves the server for this screen. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/dizey-core/src/store/mod.rs b/crates/dizey-core/src/store/mod.rs index 7f8cb67..0e6f94a 100644 --- a/crates/dizey-core/src/store/mod.rs +++ b/crates/dizey-core/src/store/mod.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use time::OffsetDateTime; use crate::Role; -use crate::board::{BoardReads, TaskRow}; +use crate::board::{BoardReads, Moved, TaskRow}; use crate::detail::{ActivityKind, DeletionCost, DetailReads}; pub mod turso_store; @@ -329,6 +329,33 @@ pub trait Store: BoardReads + DetailReads + 'static { at: OffsetDateTime, ) -> Result<()>; + /// Moves a task into a column and records the crossing, both in one + /// transaction, so a transition never exists without the move that caused + /// it and a move never happens without leaving the fact behind. + /// + /// `from_column_id` is the column the caller believed the card was in when + /// the drag started, and the update is conditional on it still being true. + /// Two people dragging the same card at once therefore produce exactly one + /// transition: the loser is told [`Moved::Stale`] and re-reads, rather than + /// writing a second crossing out of a column the card had already left. + /// + /// A card dropped back where it came from answers [`Moved::Unchanged`] and + /// writes nothing at all — not the transition, not the activity line, not + /// an `updated_at` bump. It did not move. + /// + /// Moving into a column with `is_done` set stamps `done_at`; moving out of + /// one clears it, in the same transaction, because the card's finished + /// state is a consequence of where it sits and must not be able to drift + /// from it. + async fn move_task( + &self, + task_id: &str, + from_column_id: &str, + to_column_id: &str, + actor_id: &str, + at: OffsetDateTime, + ) -> Result; + /// Removes a task and every dependency edge it stood in. Tasks that were /// waiting only on this one become unblocked, and that is recorded in /// their activity — the rules engine will want to mail about it. diff --git a/crates/dizey-core/src/store/turso_store.rs b/crates/dizey-core/src/store/turso_store.rs index 2a98c4c..9bed821 100644 --- a/crates/dizey-core/src/store/turso_store.rs +++ b/crates/dizey-core/src/store/turso_store.rs @@ -14,7 +14,7 @@ use uuid::Uuid; use super::{NewTask, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace}; use crate::Role; -use crate::board::{BoardMeta, BoardReads, Column, Person, TaskRow}; +use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition}; use crate::detail::{ ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, TaskFacts, }; @@ -26,6 +26,7 @@ use time::macros::format_description; const MIGRATIONS: &[(i64, &str)] = &[ (1, include_str!("../../migrations/0001_init.sql")), (2, include_str!("../../migrations/0002_auth.sql")), + (3, include_str!("../../migrations/0003_transition.sql")), ]; /// The board a fresh workspace gets, and its columns. `Done` is the column @@ -149,6 +150,14 @@ fn now_text() -> Result { stamp(OffsetDateTime::now_utc()) } +/// What the body of a move transaction decided, before the commit or rollback +/// that acts on it. +enum Outcome { + Wrote, + Stale, + Missing, +} + fn stamp(at: OffsetDateTime) -> Result { at.format(&Rfc3339) .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}"))) @@ -1159,6 +1168,178 @@ impl Store for TursoStore { } } + async fn move_task( + &self, + task_id: &str, + from_column_id: &str, + to_column_id: &str, + actor_id: &str, + at: OffsetDateTime, + ) -> Result { + let stamp = stamp(at)?; + let transition_id = Uuid::new_v4().to_string(); + + // Dropping a card back where it came from is not a move. Answer before + // opening a transaction: there is nothing to serialise. + if from_column_id == to_column_id { + return Ok(Moved::Unchanged); + } + + let mut conn = self.tx_conn().await?; + // IMMEDIATE: the whole point is that two drops on the same card cannot + // both read "it is in Backlog" and both write a crossing out of it. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + let written = async { + let mut rows = tx + .query( + "SELECT board_id, column_id FROM task \ + WHERE id = ?1 AND deleted_at IS NULL", + params![task_id], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(Outcome::Missing); + }; + let board_id = row.get::(0)?; + let sitting_in = row.get::(1)?; + drop(rows); + + // Somebody moved it while the drag was in the air. + if sitting_in != from_column_id { + return Ok(Outcome::Stale); + } + + // The destination has to be a column of this task's own board: a + // column id arrives in a form, and a form is not a promise. + let mut rows = tx + .query( + "SELECT name, is_done FROM board_column WHERE id = ?1 AND board_id = ?2", + params![to_column_id, board_id.clone()], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(Outcome::Missing); + }; + let to_name = row.get::(0)?; + let to_is_done = row.get::(1)? != 0; + drop(rows); + + let mut rows = tx + .query( + "SELECT name FROM board_column WHERE id = ?1", + params![from_column_id], + ) + .await?; + let from_name = match rows.next().await? { + Some(row) => row.get::(0)?, + None => from_column_id.to_string(), + }; + drop(rows); + + // The card lands at the end of its new column. Where inside a + // column a card sits is the board's sort control's business, not + // the drop's. + let mut rows = tx + .query( + "SELECT COALESCE(MAX(position), 0) + 1 FROM task \ + WHERE column_id = ?1 AND deleted_at IS NULL", + params![to_column_id], + ) + .await?; + let landing = match rows.next().await? { + Some(row) => row.get::(0)?, + None => 1.0, + }; + drop(rows); + + // Conditional on the column read above, so this is still one + // writer even if the IMMEDIATE lock were ever relaxed. + let moved = tx + .execute( + "UPDATE task SET column_id = ?2, position = ?3, done_at = ?4, updated_at = ?5 \ + WHERE id = ?1 AND column_id = ?6 AND deleted_at IS NULL", + params![ + task_id, + to_column_id, + landing, + if to_is_done { + Some(stamp.clone()) + } else { + None + }, + stamp.clone(), + from_column_id + ], + ) + .await?; + if moved == 0 { + return Ok(Outcome::Stale); + } + + tx.execute( + "INSERT INTO transition \ + (id, task_id, from_column, to_column, actor_id, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + transition_id.clone(), + task_id, + from_column_id, + to_column_id, + actor_id, + stamp.clone() + ], + ) + .await?; + + tx.execute( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + Uuid::new_v4().to_string(), + task_id, + actor_id, + ActivityKind::Moved.as_str(), + format!("{from_name} to {to_name}"), + stamp.clone() + ], + ) + .await?; + + Ok::<_, turso::Error>(Outcome::Wrote) + } + .await; + + match written { + Ok(Outcome::Wrote) => { + tx.commit().await.map_err(backend)?; + Ok(Moved::Recorded(Transition { + id: transition_id, + task_id: task_id.to_string(), + from_column: from_column_id.to_string(), + to_column: to_column_id.to_string(), + actor_id: actor_id.to_string(), + at, + })) + } + Ok(Outcome::Stale) => { + let _ = tx.rollback().await; + Ok(Moved::Stale) + } + Ok(Outcome::Missing) => { + let _ = tx.rollback().await; + Err(StoreError::NotFound) + } + Err(e) => { + let _ = tx.rollback().await; + Err(backend(e)) + } + } + } + async fn delete_task( &self, task_id: &str, diff --git a/crates/dizey-core/tests/store.rs b/crates/dizey-core/tests/store.rs index 995352b..bbda430 100644 --- a/crates/dizey-core/tests/store.rs +++ b/crates/dizey-core/tests/store.rs @@ -86,14 +86,14 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("dizey.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 2); + assert_eq!(first.schema_version().await.unwrap(), 3); claim(&first).await; drop(first); // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and // must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 2); + assert_eq!(second.schema_version().await.unwrap(), 3); assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); drop(second); let _ = std::fs::remove_dir_all(&dir); @@ -1357,7 +1357,7 @@ async fn an_address_can_only_be_invited_once() { // -- board ------------------------------------------------------------------ -use dizey_core::board::{BoardReads, BoardView, Person, load}; +use dizey_core::board::{BoardReads, BoardView, Moved, Person, load}; use dizey_core::store::NewTask; use std::sync::atomic::{AtomicUsize, Ordering}; use time::Date; @@ -2169,3 +2169,199 @@ async fn key_of(store: &TursoStore, workspace: &str, title: &str) -> String { .task_key .clone() } + +// -- moving a card --------------------------------------------------------- + +#[tokio::test] +async fn a_move_writes_the_crossing_in_the_same_breath() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let backlog = column_named(store, &workspace, "Backlog").await; + let progress = column_named(store, &workspace, "In Progress").await; + let task = add_task( + store, + &workspace, + "Backlog", + "wire the sender", + None, + &admin, + ) + .await; + + let moved = store + .move_task(&task, &backlog, &progress, &admin, now) + .await + .unwrap(); + + let Moved::Recorded(transition) = moved else { + panic!("a card that changed column has a transition, got {moved:?}"); + }; + assert_eq!(transition.task_id, task); + assert_eq!(transition.from_column, backlog); + assert_eq!(transition.to_column, progress); + assert_eq!(transition.actor_id, admin); + // The mail engine reads this timestamp rather than its own clock, so it is + // the move's moment and not the send's. + assert_eq!(transition.at, now); + + let board = board_of(store, &workspace).await; + let card = board.cards().find(|card| card.id == task).unwrap(); + assert_eq!(card.column_id, progress); + + let detail = load_detail(store, &workspace, &task) + .await + .unwrap() + .unwrap(); + let line = detail + .activity + .iter() + .find(|line| line.kind == ActivityKind::Moved) + .expect("the move is in the activity trail"); + assert_eq!( + line.actor.as_ref().map(|who| who.id.as_str()), + Some(admin.as_str()) + ); + assert_eq!(line.detail, "Backlog to In Progress"); +} + +#[tokio::test] +async fn a_card_dropped_back_where_it_came_from_did_not_move() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let backlog = column_named(store, &workspace, "Backlog").await; + let task = add_task(store, &workspace, "Backlog", "stays put", None, &admin).await; + let before = load_detail(store, &workspace, &task) + .await + .unwrap() + .unwrap(); + + let moved = store + .move_task(&task, &backlog, &backlog, &admin, now) + .await + .unwrap(); + + assert_eq!(moved, Moved::Unchanged); + let after = load_detail(store, &workspace, &task) + .await + .unwrap() + .unwrap(); + assert_eq!( + after.activity.len(), + before.activity.len(), + "a drop that changed nothing wrote nothing" + ); +} + +#[tokio::test] +async fn two_drags_of_one_card_leave_one_crossing() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let backlog = column_named(store, &workspace, "Backlog").await; + let progress = column_named(store, &workspace, "In Progress").await; + let review = column_named(store, &workspace, "Review").await; + let task = add_task(store, &workspace, "Backlog", "contested", None, &admin).await; + + // Both people picked the card up out of Backlog. Only one drop can be + // acting on the board that was actually there. + let first = store + .move_task(&task, &backlog, &progress, &admin, now) + .await + .unwrap(); + let second = store + .move_task(&task, &backlog, &review, &admin, now) + .await + .unwrap(); + + assert!(matches!(first, Moved::Recorded(_))); + assert_eq!( + second, + Moved::Stale, + "the second drop is not allowed to cross out of a column the card had left" + ); + + let detail = load_detail(store, &workspace, &task) + .await + .unwrap() + .unwrap(); + let crossings = detail + .activity + .iter() + .filter(|line| line.kind == ActivityKind::Moved) + .count(); + assert_eq!(crossings, 1); + let board = board_of(store, &workspace).await; + let card = board.cards().find(|card| card.id == task).unwrap(); + assert_eq!(card.column_id, progress, "the winner's move stands"); +} + +#[tokio::test] +async fn the_done_column_stamps_the_card_and_leaving_it_unstamps() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let backlog = column_named(store, &workspace, "Backlog").await; + let done = column_named(store, &workspace, "Done").await; + let task = add_task(store, &workspace, "Backlog", "finishes", None, &admin).await; + + store + .move_task(&task, &backlog, &done, &admin, now) + .await + .unwrap(); + let board = board_of(store, &workspace).await; + let card = board.cards().find(|card| card.id == task).unwrap(); + assert!(card.is_done(), "a card in the done column is done"); + assert!(card.done_at.is_some()); + + store + .move_task(&task, &done, &backlog, &admin, now) + .await + .unwrap(); + let board = board_of(store, &workspace).await; + let card = board.cards().find(|card| card.id == task).unwrap(); + assert!(!card.is_done(), "dragged back out, it is not finished"); + assert!(card.done_at.is_none()); +} + +#[tokio::test] +async fn a_column_from_another_board_is_not_a_destination() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let backlog = column_named(store, &workspace, "Backlog").await; + let task = add_task(store, &workspace, "Backlog", "stays here", None, &admin).await; + + let refused = store + .move_task(&task, &backlog, "not-a-column", &admin, now) + .await; + + assert!(matches!(refused, Err(StoreError::NotFound))); + let board = board_of(store, &workspace).await; + let card = board.cards().find(|card| card.id == task).unwrap(); + assert_eq!(card.column_id, backlog, "nothing moved"); +} + +#[tokio::test] +async fn a_deleted_card_does_not_move() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let now = OffsetDateTime::now_utc(); + + let backlog = column_named(store, &workspace, "Backlog").await; + let progress = column_named(store, &workspace, "In Progress").await; + let task = add_task(store, &workspace, "Backlog", "gone", None, &admin).await; + store.delete_task(&task, &admin, now).await.unwrap(); + + let refused = store + .move_task(&task, &backlog, &progress, &admin, now) + .await; + + assert!(matches!(refused, Err(StoreError::NotFound))); +}