forge
Explore
Log in

Don't you dare go Hollow

A move is a crossing, and the crossing is a fact

Browse files at this commit

6aab1b322f62f065f35cd0224bffaea3fb1a80e0Ahmet Kaan GümüşParent: 7fd5ec2
  • feat
    • a move is a crossing, and the crossing is a fact
Show full message
✨ feat(store): a move is a crossing, and the crossing is a fact

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.
crates/dizey-core/migrations/0003_transition.sqladded+17 -0
@@ -0,0 +1,17 @@
1+-- Every move of a card from one column to another, written as a fact in the
2+-- same transaction as the move itself.
3+--
4+-- The mail rules trigger on the transition, not on the task's current column:
5+-- a card that goes Review -> Done -> Review has crossed into Done once, and
6+-- nothing recomputed from `task.column_id` afterwards can tell you that. So
7+-- this table is the record, and the rules read it.
8+CREATE TABLE transition (
9+ id TEXT PRIMARY KEY,
10+ task_id TEXT NOT NULL REFERENCES task(id),
11+ from_column TEXT NOT NULL REFERENCES board_column(id),
12+ to_column TEXT NOT NULL REFERENCES board_column(id),
13+ actor_id TEXT NOT NULL REFERENCES user(id),
14+ created_at TEXT NOT NULL
15+);
16+
17+CREATE INDEX transition_by_task ON transition(task_id, created_at);
crates/dizey-core/src/board.rsmodified+31 -0
@@ -39,6 +39,37 @@ pub struct TaskRow {
3939 pub done_at: Option<OffsetDateTime>,
4040 }
4141
42+/// One card crossing from one column into another, as it was written.
43+///
44+/// `at` is the moment the move committed, taken inside the same transaction
45+/// as the move. The mail engine reads it rather than stamping its own clock:
46+/// a send retried on Thursday still has to say the card moved on Tuesday.
47+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48+pub struct Transition {
49+ pub id: String,
50+ pub task_id: String,
51+ pub from_column: String,
52+ pub to_column: String,
53+ pub actor_id: String,
54+ pub at: OffsetDateTime,
55+}
56+
57+/// What a move attempt did.
58+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59+pub enum Moved {
60+ /// The card changed column. This is the fact that was written, and the
61+ /// only outcome the mail rules act on.
62+ Recorded(Transition),
63+ /// The card was dropped back in the column it came from. Nothing was
64+ /// written: that is not a transition, and a rule must not fire for it.
65+ Unchanged,
66+ /// Somebody else moved the card between the drag starting and the drop
67+ /// landing, so the column this move was told to move it out of is no
68+ /// longer the column it is in. Nothing was written and the caller should
69+ /// re-read the board rather than overwrite a decision it never saw.
70+ Stale,
71+}
72+
4273 /// Whoever a card can point at. The address is not here: a board card never
4374 /// shows one, so it never leaves the server for this screen.
4475 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
crates/dizey-core/src/store/mod.rsmodified+28 -1
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
99 use time::OffsetDateTime;
1010
1111 use crate::Role;
12-use crate::board::{BoardReads, TaskRow};
12+use crate::board::{BoardReads, Moved, TaskRow};
1313 use crate::detail::{ActivityKind, DeletionCost, DetailReads};
1414
1515 pub mod turso_store;
@@ -329,6 +329,33 @@ pub trait Store: BoardReads + DetailReads + 'static {
329329 at: OffsetDateTime,
330330 ) -> Result<()>;
331331
332+ /// Moves a task into a column and records the crossing, both in one
333+ /// transaction, so a transition never exists without the move that caused
334+ /// it and a move never happens without leaving the fact behind.
335+ ///
336+ /// `from_column_id` is the column the caller believed the card was in when
337+ /// the drag started, and the update is conditional on it still being true.
338+ /// Two people dragging the same card at once therefore produce exactly one
339+ /// transition: the loser is told [`Moved::Stale`] and re-reads, rather than
340+ /// writing a second crossing out of a column the card had already left.
341+ ///
342+ /// A card dropped back where it came from answers [`Moved::Unchanged`] and
343+ /// writes nothing at all — not the transition, not the activity line, not
344+ /// an `updated_at` bump. It did not move.
345+ ///
346+ /// Moving into a column with `is_done` set stamps `done_at`; moving out of
347+ /// one clears it, in the same transaction, because the card's finished
348+ /// state is a consequence of where it sits and must not be able to drift
349+ /// from it.
350+ async fn move_task(
351+ &self,
352+ task_id: &str,
353+ from_column_id: &str,
354+ to_column_id: &str,
355+ actor_id: &str,
356+ at: OffsetDateTime,
357+ ) -> Result<Moved>;
358+
332359 /// Removes a task and every dependency edge it stood in. Tasks that were
333360 /// waiting only on this one become unblocked, and that is recorded in
334361 /// their activity — the rules engine will want to mail about it.
crates/dizey-core/src/store/turso_store.rsmodified+182 -1
@@ -14,7 +14,7 @@ use uuid::Uuid;
1414
1515 use super::{NewTask, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace};
1616 use crate::Role;
17-use crate::board::{BoardMeta, BoardReads, Column, Person, TaskRow};
17+use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition};
1818 use crate::detail::{
1919 ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, TaskFacts,
2020 };
@@ -26,6 +26,7 @@ use time::macros::format_description;
2626 const MIGRATIONS: &[(i64, &str)] = &[
2727 (1, include_str!("../../migrations/0001_init.sql")),
2828 (2, include_str!("../../migrations/0002_auth.sql")),
29+ (3, include_str!("../../migrations/0003_transition.sql")),
2930 ];
3031
3132 /// The board a fresh workspace gets, and its columns. `Done` is the column
@@ -149,6 +150,14 @@ fn now_text() -> Result<String> {
149150 stamp(OffsetDateTime::now_utc())
150151 }
151152
153+/// What the body of a move transaction decided, before the commit or rollback
154+/// that acts on it.
155+enum Outcome {
156+ Wrote,
157+ Stale,
158+ Missing,
159+}
160+
152161 fn stamp(at: OffsetDateTime) -> Result<String> {
153162 at.format(&Rfc3339)
154163 .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}")))
@@ -1159,6 +1168,178 @@ impl Store for TursoStore {
11591168 }
11601169 }
11611170
1171+ async fn move_task(
1172+ &self,
1173+ task_id: &str,
1174+ from_column_id: &str,
1175+ to_column_id: &str,
1176+ actor_id: &str,
1177+ at: OffsetDateTime,
1178+ ) -> Result<Moved> {
1179+ let stamp = stamp(at)?;
1180+ let transition_id = Uuid::new_v4().to_string();
1181+
1182+ // Dropping a card back where it came from is not a move. Answer before
1183+ // opening a transaction: there is nothing to serialise.
1184+ if from_column_id == to_column_id {
1185+ return Ok(Moved::Unchanged);
1186+ }
1187+
1188+ let mut conn = self.tx_conn().await?;
1189+ // IMMEDIATE: the whole point is that two drops on the same card cannot
1190+ // both read "it is in Backlog" and both write a crossing out of it.
1191+ let tx = conn
1192+ .transaction_with_behavior(TransactionBehavior::Immediate)
1193+ .await
1194+ .map_err(backend)?;
1195+
1196+ let written = async {
1197+ let mut rows = tx
1198+ .query(
1199+ "SELECT board_id, column_id FROM task \
1200+ WHERE id = ?1 AND deleted_at IS NULL",
1201+ params![task_id],
1202+ )
1203+ .await?;
1204+ let Some(row) = rows.next().await? else {
1205+ return Ok(Outcome::Missing);
1206+ };
1207+ let board_id = row.get::<String>(0)?;
1208+ let sitting_in = row.get::<String>(1)?;
1209+ drop(rows);
1210+
1211+ // Somebody moved it while the drag was in the air.
1212+ if sitting_in != from_column_id {
1213+ return Ok(Outcome::Stale);
1214+ }
1215+
1216+ // The destination has to be a column of this task's own board: a
1217+ // column id arrives in a form, and a form is not a promise.
1218+ let mut rows = tx
1219+ .query(
1220+ "SELECT name, is_done FROM board_column WHERE id = ?1 AND board_id = ?2",
1221+ params![to_column_id, board_id.clone()],
1222+ )
1223+ .await?;
1224+ let Some(row) = rows.next().await? else {
1225+ return Ok(Outcome::Missing);
1226+ };
1227+ let to_name = row.get::<String>(0)?;
1228+ let to_is_done = row.get::<i64>(1)? != 0;
1229+ drop(rows);
1230+
1231+ let mut rows = tx
1232+ .query(
1233+ "SELECT name FROM board_column WHERE id = ?1",
1234+ params![from_column_id],
1235+ )
1236+ .await?;
1237+ let from_name = match rows.next().await? {
1238+ Some(row) => row.get::<String>(0)?,
1239+ None => from_column_id.to_string(),
1240+ };
1241+ drop(rows);
1242+
1243+ // The card lands at the end of its new column. Where inside a
1244+ // column a card sits is the board's sort control's business, not
1245+ // the drop's.
1246+ let mut rows = tx
1247+ .query(
1248+ "SELECT COALESCE(MAX(position), 0) + 1 FROM task \
1249+ WHERE column_id = ?1 AND deleted_at IS NULL",
1250+ params![to_column_id],
1251+ )
1252+ .await?;
1253+ let landing = match rows.next().await? {
1254+ Some(row) => row.get::<f64>(0)?,
1255+ None => 1.0,
1256+ };
1257+ drop(rows);
1258+
1259+ // Conditional on the column read above, so this is still one
1260+ // writer even if the IMMEDIATE lock were ever relaxed.
1261+ let moved = tx
1262+ .execute(
1263+ "UPDATE task SET column_id = ?2, position = ?3, done_at = ?4, updated_at = ?5 \
1264+ WHERE id = ?1 AND column_id = ?6 AND deleted_at IS NULL",
1265+ params![
1266+ task_id,
1267+ to_column_id,
1268+ landing,
1269+ if to_is_done {
1270+ Some(stamp.clone())
1271+ } else {
1272+ None
1273+ },
1274+ stamp.clone(),
1275+ from_column_id
1276+ ],
1277+ )
1278+ .await?;
1279+ if moved == 0 {
1280+ return Ok(Outcome::Stale);
1281+ }
1282+
1283+ tx.execute(
1284+ "INSERT INTO transition \
1285+ (id, task_id, from_column, to_column, actor_id, created_at) \
1286+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1287+ params![
1288+ transition_id.clone(),
1289+ task_id,
1290+ from_column_id,
1291+ to_column_id,
1292+ actor_id,
1293+ stamp.clone()
1294+ ],
1295+ )
1296+ .await?;
1297+
1298+ tx.execute(
1299+ "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
1300+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
1301+ params![
1302+ Uuid::new_v4().to_string(),
1303+ task_id,
1304+ actor_id,
1305+ ActivityKind::Moved.as_str(),
1306+ format!("{from_name} to {to_name}"),
1307+ stamp.clone()
1308+ ],
1309+ )
1310+ .await?;
1311+
1312+ Ok::<_, turso::Error>(Outcome::Wrote)
1313+ }
1314+ .await;
1315+
1316+ match written {
1317+ Ok(Outcome::Wrote) => {
1318+ tx.commit().await.map_err(backend)?;
1319+ Ok(Moved::Recorded(Transition {
1320+ id: transition_id,
1321+ task_id: task_id.to_string(),
1322+ from_column: from_column_id.to_string(),
1323+ to_column: to_column_id.to_string(),
1324+ actor_id: actor_id.to_string(),
1325+ at,
1326+ }))
1327+ }
1328+ Ok(Outcome::Stale) => {
1329+ let _ = tx.rollback().await;
1330+ Ok(Moved::Stale)
1331+ }
1332+ Ok(Outcome::Missing) => {
1333+ let _ = tx.rollback().await;
1334+ Err(StoreError::NotFound)
1335+ }
1336+ Err(e) => {
1337+ let _ = tx.rollback().await;
1338+ Err(backend(e))
1339+ }
1340+ }
1341+ }
1342+
11621343 async fn delete_task(
11631344 &self,
11641345 task_id: &str,
crates/dizey-core/tests/store.rsmodified+199 -3
@@ -86,14 +86,14 @@ async fn migrations_apply_once_and_survive_reopen() {
8686 let path = dir.join("dizey.db").to_string_lossy().into_owned();
8787
8888 let first = TursoStore::open(&path).await.unwrap();
89- assert_eq!(first.schema_version().await.unwrap(), 2);
89+ assert_eq!(first.schema_version().await.unwrap(), 3);
9090 claim(&first).await;
9191 drop(first);
9292
9393 // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and
9494 // must not lose what the first open wrote.
9595 let second = TursoStore::open(&path).await.unwrap();
96- assert_eq!(second.schema_version().await.unwrap(), 2);
96+ assert_eq!(second.schema_version().await.unwrap(), 3);
9797 assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey");
9898 drop(second);
9999 let _ = std::fs::remove_dir_all(&dir);
@@ -1357,7 +1357,7 @@ async fn an_address_can_only_be_invited_once() {
13571357
13581358 // -- board ------------------------------------------------------------------
13591359
1360-use dizey_core::board::{BoardReads, BoardView, Person, load};
1360+use dizey_core::board::{BoardReads, BoardView, Moved, Person, load};
13611361 use dizey_core::store::NewTask;
13621362 use std::sync::atomic::{AtomicUsize, Ordering};
13631363 use time::Date;
@@ -2169,3 +2169,199 @@ async fn key_of(store: &TursoStore, workspace: &str, title: &str) -> String {
21692169 .task_key
21702170 .clone()
21712171 }
2172+
2173+// -- moving a card ---------------------------------------------------------
2174+
2175+#[tokio::test]
2176+async fn a_move_writes_the_crossing_in_the_same_breath() {
2177+ let (scratch, workspace, admin) = workspace_with_admin().await;
2178+ let store = &scratch.store;
2179+ let now = OffsetDateTime::now_utc();
2180+
2181+ let backlog = column_named(store, &workspace, "Backlog").await;
2182+ let progress = column_named(store, &workspace, "In Progress").await;
2183+ let task = add_task(
2184+ store,
2185+ &workspace,
2186+ "Backlog",
2187+ "wire the sender",
2188+ None,
2189+ &admin,
2190+ )
2191+ .await;
2192+
2193+ let moved = store
2194+ .move_task(&task, &backlog, &progress, &admin, now)
2195+ .await
2196+ .unwrap();
2197+
2198+ let Moved::Recorded(transition) = moved else {
2199+ panic!("a card that changed column has a transition, got {moved:?}");
2200+ };
2201+ assert_eq!(transition.task_id, task);
2202+ assert_eq!(transition.from_column, backlog);
2203+ assert_eq!(transition.to_column, progress);
2204+ assert_eq!(transition.actor_id, admin);
2205+ // The mail engine reads this timestamp rather than its own clock, so it is
2206+ // the move's moment and not the send's.
2207+ assert_eq!(transition.at, now);
2208+
2209+ let board = board_of(store, &workspace).await;
2210+ let card = board.cards().find(|card| card.id == task).unwrap();
2211+ assert_eq!(card.column_id, progress);
2212+
2213+ let detail = load_detail(store, &workspace, &task)
2214+ .await
2215+ .unwrap()
2216+ .unwrap();
2217+ let line = detail
2218+ .activity
2219+ .iter()
2220+ .find(|line| line.kind == ActivityKind::Moved)
2221+ .expect("the move is in the activity trail");
2222+ assert_eq!(
2223+ line.actor.as_ref().map(|who| who.id.as_str()),
2224+ Some(admin.as_str())
2225+ );
2226+ assert_eq!(line.detail, "Backlog to In Progress");
2227+}
2228+
2229+#[tokio::test]
2230+async fn a_card_dropped_back_where_it_came_from_did_not_move() {
2231+ let (scratch, workspace, admin) = workspace_with_admin().await;
2232+ let store = &scratch.store;
2233+ let now = OffsetDateTime::now_utc();
2234+
2235+ let backlog = column_named(store, &workspace, "Backlog").await;
2236+ let task = add_task(store, &workspace, "Backlog", "stays put", None, &admin).await;
2237+ let before = load_detail(store, &workspace, &task)
2238+ .await
2239+ .unwrap()
2240+ .unwrap();
2241+
2242+ let moved = store
2243+ .move_task(&task, &backlog, &backlog, &admin, now)
2244+ .await
2245+ .unwrap();
2246+
2247+ assert_eq!(moved, Moved::Unchanged);
2248+ let after = load_detail(store, &workspace, &task)
2249+ .await
2250+ .unwrap()
2251+ .unwrap();
2252+ assert_eq!(
2253+ after.activity.len(),
2254+ before.activity.len(),
2255+ "a drop that changed nothing wrote nothing"
2256+ );
2257+}
2258+
2259+#[tokio::test]
2260+async fn two_drags_of_one_card_leave_one_crossing() {
2261+ let (scratch, workspace, admin) = workspace_with_admin().await;
2262+ let store = &scratch.store;
2263+ let now = OffsetDateTime::now_utc();
2264+
2265+ let backlog = column_named(store, &workspace, "Backlog").await;
2266+ let progress = column_named(store, &workspace, "In Progress").await;
2267+ let review = column_named(store, &workspace, "Review").await;
2268+ let task = add_task(store, &workspace, "Backlog", "contested", None, &admin).await;
2269+
2270+ // Both people picked the card up out of Backlog. Only one drop can be
2271+ // acting on the board that was actually there.
2272+ let first = store
2273+ .move_task(&task, &backlog, &progress, &admin, now)
2274+ .await
2275+ .unwrap();
2276+ let second = store
2277+ .move_task(&task, &backlog, &review, &admin, now)
2278+ .await
2279+ .unwrap();
2280+
2281+ assert!(matches!(first, Moved::Recorded(_)));
2282+ assert_eq!(
2283+ second,
2284+ Moved::Stale,
2285+ "the second drop is not allowed to cross out of a column the card had left"
2286+ );
2287+
2288+ let detail = load_detail(store, &workspace, &task)
2289+ .await
2290+ .unwrap()
2291+ .unwrap();
2292+ let crossings = detail
2293+ .activity
2294+ .iter()
2295+ .filter(|line| line.kind == ActivityKind::Moved)
2296+ .count();
2297+ assert_eq!(crossings, 1);
2298+ let board = board_of(store, &workspace).await;
2299+ let card = board.cards().find(|card| card.id == task).unwrap();
2300+ assert_eq!(card.column_id, progress, "the winner's move stands");
2301+}
2302+
2303+#[tokio::test]
2304+async fn the_done_column_stamps_the_card_and_leaving_it_unstamps() {
2305+ let (scratch, workspace, admin) = workspace_with_admin().await;
2306+ let store = &scratch.store;
2307+ let now = OffsetDateTime::now_utc();
2308+
2309+ let backlog = column_named(store, &workspace, "Backlog").await;
2310+ let done = column_named(store, &workspace, "Done").await;
2311+ let task = add_task(store, &workspace, "Backlog", "finishes", None, &admin).await;
2312+
2313+ store
2314+ .move_task(&task, &backlog, &done, &admin, now)
2315+ .await
2316+ .unwrap();
2317+ let board = board_of(store, &workspace).await;
2318+ let card = board.cards().find(|card| card.id == task).unwrap();
2319+ assert!(card.is_done(), "a card in the done column is done");
2320+ assert!(card.done_at.is_some());
2321+
2322+ store
2323+ .move_task(&task, &done, &backlog, &admin, now)
2324+ .await
2325+ .unwrap();
2326+ let board = board_of(store, &workspace).await;
2327+ let card = board.cards().find(|card| card.id == task).unwrap();
2328+ assert!(!card.is_done(), "dragged back out, it is not finished");
2329+ assert!(card.done_at.is_none());
2330+}
2331+
2332+#[tokio::test]
2333+async fn a_column_from_another_board_is_not_a_destination() {
2334+ let (scratch, workspace, admin) = workspace_with_admin().await;
2335+ let store = &scratch.store;
2336+ let now = OffsetDateTime::now_utc();
2337+
2338+ let backlog = column_named(store, &workspace, "Backlog").await;
2339+ let task = add_task(store, &workspace, "Backlog", "stays here", None, &admin).await;
2340+
2341+ let refused = store
2342+ .move_task(&task, &backlog, "not-a-column", &admin, now)
2343+ .await;
2344+
2345+ assert!(matches!(refused, Err(StoreError::NotFound)));
2346+ let board = board_of(store, &workspace).await;
2347+ let card = board.cards().find(|card| card.id == task).unwrap();
2348+ assert_eq!(card.column_id, backlog, "nothing moved");
2349+}
2350+
2351+#[tokio::test]
2352+async fn a_deleted_card_does_not_move() {
2353+ let (scratch, workspace, admin) = workspace_with_admin().await;
2354+ let store = &scratch.store;
2355+ let now = OffsetDateTime::now_utc();
2356+
2357+ let backlog = column_named(store, &workspace, "Backlog").await;
2358+ let progress = column_named(store, &workspace, "In Progress").await;
2359+ let task = add_task(store, &workspace, "Backlog", "gone", None, &admin).await;
2360+ store.delete_task(&task, &admin, now).await.unwrap();
2361+
2362+ let refused = store
2363+ .move_task(&task, &backlog, &progress, &admin, now)
2364+ .await;
2365+
2366+ assert!(matches!(refused, Err(StoreError::NotFound)));
2367+}