The board — six queries, joined in Rust
Browse files at this commit65b6f6564ebb9000a62241c12b7afd2ca080d951Parent: 6067dfe- feat
- the board — six queries, joined in Rust
6 changed files +1145 -3
- crates/dizey-core/Cargo.toml +1 -0
- crates/dizey-core/src/board.rs +343 -0
- crates/dizey-core/src/lib.rs +4 -0
- crates/dizey-core/src/store/mod.rs +59 -1
- crates/dizey-core/src/store/turso_store.rs +396 -2
- crates/dizey-core/tests/store.rs +342 -0
crates/dizey-core/Cargo.tomlmodified+1 -0
| @@ -35,5 +35,6 @@ turso = { workspace = true, optional = true } | |||
| 35 | uuid = { workspace = true, optional = true } | 35 | uuid = { workspace = true, optional = true } |
| 36 | 36 | ||
| 37 | [dev-dependencies] | 37 | [dev-dependencies] |
| 38 | +async-trait = "0.1.92" | ||
| 38 | serde_json.workspace = true | 39 | serde_json.workspace = true |
| 39 | tokio = { workspace = true } | 40 | tokio = { workspace = true } |
crates/dizey-core/src/board.rsadded+343 -0
| @@ -0,0 +1,343 @@ | |||
| 1 | +//! The board vocabulary: columns, cards and the numbers the Main artboard puts | ||
| 2 | +//! in its chrome. | ||
| 3 | +//! | ||
| 4 | +//! This module is deliberately free of the `server` feature: the browser bundle | ||
| 5 | +//! renders these exact types, so a card means the same thing on both sides and | ||
| 6 | +//! nothing has to be re-derived from a wire format. | ||
| 7 | + | ||
| 8 | +use serde::{Deserialize, Serialize}; | ||
| 9 | +use time::{Date, Month, OffsetDateTime}; | ||
| 10 | + | ||
| 11 | +/// A board and the key prefix its tasks carry (`DZ-14`). | ||
| 12 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 13 | +pub struct BoardMeta { | ||
| 14 | + pub id: String, | ||
| 15 | + pub name: String, | ||
| 16 | + pub task_prefix: String, | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +/// A column. `is_done` is what turns a card into the finished, greyed state | ||
| 20 | +/// with a "done Aug 14" stamp rather than a deadline chip. | ||
| 21 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 22 | +pub struct Column { | ||
| 23 | + pub id: String, | ||
| 24 | + pub name: String, | ||
| 25 | + pub position: i64, | ||
| 26 | + pub is_done: bool, | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// One task as the store holds it, before assignees, comments and dependencies | ||
| 30 | +/// are hung off it. | ||
| 31 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | ||
| 32 | +pub struct TaskRow { | ||
| 33 | + pub id: String, | ||
| 34 | + pub task_key: String, | ||
| 35 | + pub title: String, | ||
| 36 | + pub column_id: String, | ||
| 37 | + pub deadline: Option<Date>, | ||
| 38 | + pub position: f64, | ||
| 39 | + pub done_at: Option<OffsetDateTime>, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// Whoever a card can point at. The address is not here: a board card never | ||
| 43 | +/// shows one, so it never leaves the server for this screen. | ||
| 44 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
| 45 | +pub struct Person { | ||
| 46 | + pub id: String, | ||
| 47 | + pub display_name: String, | ||
| 48 | + pub photo_path: Option<String>, | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +impl Person { | ||
| 52 | + /// The two-letter fallback the artboard uses when there is no photo (`MD`). | ||
| 53 | + pub fn initials(&self) -> String { | ||
| 54 | + let mut letters = self | ||
| 55 | + .display_name | ||
| 56 | + .split_whitespace() | ||
| 57 | + .filter_map(|word| word.chars().next()) | ||
| 58 | + .filter(|c| c.is_alphanumeric()); | ||
| 59 | + let first = letters.next(); | ||
| 60 | + let second = letters.next(); | ||
| 61 | + match (first, second) { | ||
| 62 | + (Some(a), Some(b)) => format!("{a}{b}").to_uppercase(), | ||
| 63 | + (Some(a), None) => a.to_uppercase().to_string(), | ||
| 64 | + _ => "?".to_string(), | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// A card, assembled. Dependencies carry the *keys* of the tasks on the other | ||
| 70 | +/// end, because that is what the card shows and it saves the UI a second lookup. | ||
| 71 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | ||
| 72 | +pub struct TaskCard { | ||
| 73 | + pub id: String, | ||
| 74 | + pub task_key: String, | ||
| 75 | + pub title: String, | ||
| 76 | + pub column_id: String, | ||
| 77 | + pub deadline: Option<Date>, | ||
| 78 | + pub done_at: Option<OffsetDateTime>, | ||
| 79 | + pub position: f64, | ||
| 80 | + pub assignees: Vec<Person>, | ||
| 81 | + pub comment_count: u32, | ||
| 82 | + /// Keys of the tasks that must finish before this one can start. | ||
| 83 | + pub blocked_by: Vec<String>, | ||
| 84 | + /// Keys of the tasks waiting on this one. | ||
| 85 | + pub blocks: Vec<String>, | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +impl TaskCard { | ||
| 89 | + pub fn is_done(&self) -> bool { | ||
| 90 | + self.done_at.is_some() | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + /// Blocked means something unfinished is in front of it. A finished task is | ||
| 94 | + /// never counted as blocked, whatever it still points at. | ||
| 95 | + pub fn is_blocked(&self) -> bool { | ||
| 96 | + !self.is_done() && !self.blocked_by.is_empty() | ||
| 97 | + } | ||
| 98 | + | ||
| 99 | + /// Past its deadline and not finished. A deadline of today is not overdue. | ||
| 100 | + pub fn is_overdue(&self, today: Date) -> bool { | ||
| 101 | + match self.deadline { | ||
| 102 | + Some(day) => !self.is_done() && day < today, | ||
| 103 | + None => false, | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + pub fn is_assigned_to(&self, user_id: &str) -> bool { | ||
| 108 | + self.assignees.iter().any(|person| person.id == user_id) | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + /// The chip the card shows where a deadline would go: `Sep 12`, | ||
| 112 | + /// `Aug 21 · overdue`, `done Aug 14` or `no deadline`. | ||
| 113 | + pub fn deadline_label(&self, today: Date) -> String { | ||
| 114 | + if let Some(done) = self.done_at { | ||
| 115 | + return format!("done {}", day_label(done.date())); | ||
| 116 | + } | ||
| 117 | + match self.deadline { | ||
| 118 | + Some(day) if day < today => format!("{} · overdue", day_label(day)), | ||
| 119 | + Some(day) => day_label(day), | ||
| 120 | + None => "no deadline".to_string(), | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// A column with its cards already in it. | ||
| 126 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | ||
| 127 | +pub struct ColumnView { | ||
| 128 | + pub column: Column, | ||
| 129 | + pub cards: Vec<TaskCard>, | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +/// Everything one board screen needs, in one value. | ||
| 133 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | ||
| 134 | +pub struct BoardView { | ||
| 135 | + pub board: BoardMeta, | ||
| 136 | + pub columns: Vec<ColumnView>, | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +impl BoardView { | ||
| 140 | + pub fn cards(&self) -> impl Iterator<Item = &TaskCard> { | ||
| 141 | + self.columns.iter().flat_map(|column| column.cards.iter()) | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + pub fn task_count(&self) -> usize { | ||
| 145 | + self.cards().count() | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + pub fn is_empty(&self) -> bool { | ||
| 149 | + self.task_count() == 0 | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + /// The `1 overdue` chip in the filter bar. | ||
| 153 | + pub fn overdue_count(&self, today: Date) -> usize { | ||
| 154 | + self.cards().filter(|card| card.is_overdue(today)).count() | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + /// The `2 blocked` chip beside it. | ||
| 158 | + pub fn blocked_count(&self) -> usize { | ||
| 159 | + self.cards().filter(|card| card.is_blocked()).count() | ||
| 160 | + } | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +/// `Sep 12` — the card chips are day-and-month, never a year. | ||
| 164 | +pub fn day_label(day: Date) -> String { | ||
| 165 | + let month = match day.month() { | ||
| 166 | + Month::January => "Jan", | ||
| 167 | + Month::February => "Feb", | ||
| 168 | + Month::March => "Mar", | ||
| 169 | + Month::April => "Apr", | ||
| 170 | + Month::May => "May", | ||
| 171 | + Month::June => "Jun", | ||
| 172 | + Month::July => "Jul", | ||
| 173 | + Month::August => "Aug", | ||
| 174 | + Month::September => "Sep", | ||
| 175 | + Month::October => "Oct", | ||
| 176 | + Month::November => "Nov", | ||
| 177 | + Month::December => "Dec", | ||
| 178 | + }; | ||
| 179 | + format!("{month} {:02}", day.day()) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// Builds the board from six flat sweeps. | ||
| 183 | +/// | ||
| 184 | +/// Every input is the whole board's worth of one thing, so the caller makes a | ||
| 185 | +/// fixed number of queries no matter how many tasks there are — see | ||
| 186 | +/// [`load`](crate::board::load). The joining happens here, in Rust. | ||
| 187 | +pub fn assemble( | ||
| 188 | + board: BoardMeta, | ||
| 189 | + mut columns: Vec<Column>, | ||
| 190 | + tasks: Vec<TaskRow>, | ||
| 191 | + assignees: Vec<(String, Person)>, | ||
| 192 | + comment_counts: Vec<(String, u32)>, | ||
| 193 | + dependencies: Vec<(String, String)>, | ||
| 194 | +) -> BoardView { | ||
| 195 | + use std::collections::HashMap; | ||
| 196 | + | ||
| 197 | + let key_of: HashMap<&str, &str> = tasks | ||
| 198 | + .iter() | ||
| 199 | + .map(|task| (task.id.as_str(), task.task_key.as_str())) | ||
| 200 | + .collect(); | ||
| 201 | + | ||
| 202 | + let mut people: HashMap<String, Vec<Person>> = HashMap::new(); | ||
| 203 | + for (task_id, person) in assignees { | ||
| 204 | + people.entry(task_id).or_default().push(person); | ||
| 205 | + } | ||
| 206 | + let counts: HashMap<String, u32> = comment_counts.into_iter().collect(); | ||
| 207 | + | ||
| 208 | + let finished: HashMap<&str, bool> = tasks | ||
| 209 | + .iter() | ||
| 210 | + .map(|task| (task.id.as_str(), task.done_at.is_some())) | ||
| 211 | + .collect(); | ||
| 212 | + | ||
| 213 | + let mut blocked_by: HashMap<String, Vec<String>> = HashMap::new(); | ||
| 214 | + let mut blocks: HashMap<String, Vec<String>> = HashMap::new(); | ||
| 215 | + for (blocked, blocking) in &dependencies { | ||
| 216 | + // A dependency on a task from another board would have no key here; it | ||
| 217 | + // is dropped rather than shown as a dangling chip. A dependency whose | ||
| 218 | + // other end is finished is dropped too: nothing is waiting on a task | ||
| 219 | + // that is done, whatever the row still says. | ||
| 220 | + let done = |id: &str| finished.get(id).copied().unwrap_or(false); | ||
| 221 | + if let Some(key) = key_of.get(blocking.as_str()) | ||
| 222 | + && !done(blocking) | ||
| 223 | + { | ||
| 224 | + blocked_by | ||
| 225 | + .entry(blocked.clone()) | ||
| 226 | + .or_default() | ||
| 227 | + .push((*key).to_string()); | ||
| 228 | + } | ||
| 229 | + if let Some(key) = key_of.get(blocked.as_str()) | ||
| 230 | + && !done(blocked) | ||
| 231 | + { | ||
| 232 | + blocks | ||
| 233 | + .entry(blocking.clone()) | ||
| 234 | + .or_default() | ||
| 235 | + .push((*key).to_string()); | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + let mut cards: HashMap<String, Vec<TaskCard>> = HashMap::new(); | ||
| 240 | + for task in tasks { | ||
| 241 | + let card = TaskCard { | ||
| 242 | + comment_count: counts.get(&task.id).copied().unwrap_or(0), | ||
| 243 | + assignees: people.remove(&task.id).unwrap_or_default(), | ||
| 244 | + blocked_by: blocked_by.remove(&task.id).unwrap_or_default(), | ||
| 245 | + blocks: blocks.remove(&task.id).unwrap_or_default(), | ||
| 246 | + id: task.id, | ||
| 247 | + task_key: task.task_key, | ||
| 248 | + title: task.title, | ||
| 249 | + deadline: task.deadline, | ||
| 250 | + done_at: task.done_at, | ||
| 251 | + position: task.position, | ||
| 252 | + column_id: task.column_id, | ||
| 253 | + }; | ||
| 254 | + cards.entry(card.column_id.clone()).or_default().push(card); | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + columns.sort_by_key(|column| column.position); | ||
| 258 | + let columns = columns | ||
| 259 | + .into_iter() | ||
| 260 | + .map(|column| { | ||
| 261 | + let mut cards = cards.remove(&column.id).unwrap_or_default(); | ||
| 262 | + sort_cards(&mut cards); | ||
| 263 | + ColumnView { column, cards } | ||
| 264 | + }) | ||
| 265 | + .collect(); | ||
| 266 | + | ||
| 267 | + BoardView { board, columns } | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +/// The board's default order, which the artboard names "Sort: deadline": | ||
| 271 | +/// soonest deadline first, cards without one after them, ties broken by the | ||
| 272 | +/// hand-set position so a column never reshuffles on its own. | ||
| 273 | +fn sort_cards(cards: &mut [TaskCard]) { | ||
| 274 | + cards.sort_by(|a, b| { | ||
| 275 | + (a.deadline.is_none(), a.deadline) | ||
| 276 | + .cmp(&(b.deadline.is_none(), b.deadline)) | ||
| 277 | + .then(a.position.total_cmp(&b.position)) | ||
| 278 | + .then_with(|| a.task_key.cmp(&b.task_key)) | ||
| 279 | + }); | ||
| 280 | +} | ||
| 281 | + | ||
| 282 | +#[cfg(feature = "server")] | ||
| 283 | +pub use reads::{BoardReads, load}; | ||
| 284 | + | ||
| 285 | +#[cfg(feature = "server")] | ||
| 286 | +mod reads { | ||
| 287 | + use async_trait::async_trait; | ||
| 288 | + | ||
| 289 | + use super::{BoardMeta, BoardView, Column, Person, TaskRow, assemble}; | ||
| 290 | + use crate::store::Result; | ||
| 291 | + | ||
| 292 | + /// The board's read half, split out from [`Store`](crate::Store) so a test | ||
| 293 | + /// can wrap it and count the round trips a board costs. | ||
| 294 | + /// | ||
| 295 | + /// Every method sweeps the whole board. There is deliberately no | ||
| 296 | + /// "assignees for this task" here: one query per card is how a board with | ||
| 297 | + /// fourteen tasks becomes sixty round trips against a single-writer file. | ||
| 298 | + #[async_trait] | ||
| 299 | + pub trait BoardReads: Send + Sync { | ||
| 300 | + /// The workspace's board. There is one today; the type is ready for | ||
| 301 | + /// more. | ||
| 302 | + async fn board(&self, workspace_id: &str) -> Result<Option<BoardMeta>>; | ||
| 303 | + | ||
| 304 | + async fn columns(&self, board_id: &str) -> Result<Vec<Column>>; | ||
| 305 | + | ||
| 306 | + /// Live tasks, deleted ones left out. | ||
| 307 | + async fn tasks_for_board(&self, board_id: &str) -> Result<Vec<TaskRow>>; | ||
| 308 | + | ||
| 309 | + /// `(task id, person)` for every assignment on the board. | ||
| 310 | + async fn assignees_for_board(&self, board_id: &str) -> Result<Vec<(String, Person)>>; | ||
| 311 | + | ||
| 312 | + /// `(task id, comments)`, tasks with none left out. | ||
| 313 | + async fn comment_counts_for_board(&self, board_id: &str) -> Result<Vec<(String, u32)>>; | ||
| 314 | + | ||
| 315 | + /// `(blocked task id, blocking task id)` for every dependency still in | ||
| 316 | + /// force. | ||
| 317 | + async fn dependencies_for_board(&self, board_id: &str) -> Result<Vec<(String, String)>>; | ||
| 318 | + } | ||
| 319 | + | ||
| 320 | + /// Loads a whole board in six queries — one for the board and one sweep per | ||
| 321 | + /// thing a card carries — and joins them in Rust. | ||
| 322 | + /// | ||
| 323 | + /// The count does not move with the number of tasks; `board_costs_the_same_ | ||
| 324 | + /// six_queries_at_any_size` in `tests/store.rs` holds that line. | ||
| 325 | + pub async fn load(reads: &dyn BoardReads, workspace_id: &str) -> Result<Option<BoardView>> { | ||
| 326 | + let Some(board) = reads.board(workspace_id).await? else { | ||
| 327 | + return Ok(None); | ||
| 328 | + }; | ||
| 329 | + let columns = reads.columns(&board.id).await?; | ||
| 330 | + let tasks = reads.tasks_for_board(&board.id).await?; | ||
| 331 | + let assignees = reads.assignees_for_board(&board.id).await?; | ||
| 332 | + let comment_counts = reads.comment_counts_for_board(&board.id).await?; | ||
| 333 | + let dependencies = reads.dependencies_for_board(&board.id).await?; | ||
| 334 | + Ok(Some(assemble( | ||
| 335 | + board, | ||
| 336 | + columns, | ||
| 337 | + tasks, | ||
| 338 | + assignees, | ||
| 339 | + comment_counts, | ||
| 340 | + dependencies, | ||
| 341 | + ))) | ||
| 342 | + } | ||
| 343 | +} | ||
crates/dizey-core/src/lib.rsmodified+4 -0
| @@ -5,7 +5,9 @@ | |||
| 5 | //! that must never reach the browser: the store, the password hashing and the | 5 | //! that must never reach the browser: the store, the password hashing and the |
| 6 | //! token minting. | 6 | //! token minting. |
| 7 | 7 | ||
| 8 | +pub mod board; | ||
| 8 | pub mod role; | 9 | pub mod role; |
| 10 | +pub use board::{BoardView, Column, TaskCard}; | ||
| 9 | pub use role::Role; | 11 | pub use role::Role; |
| 10 | 12 | ||
| 11 | #[cfg(feature = "server")] | 13 | #[cfg(feature = "server")] |
| @@ -18,4 +20,6 @@ pub mod store; | |||
| 18 | #[cfg(feature = "server")] | 20 | #[cfg(feature = "server")] |
| 19 | pub use accounts::{AccountError, Accounts}; | 21 | pub use accounts::{AccountError, Accounts}; |
| 20 | #[cfg(feature = "server")] | 22 | #[cfg(feature = "server")] |
| 23 | +pub use board::{BoardReads, load as load_board}; | ||
| 24 | +#[cfg(feature = "server")] | ||
| 21 | pub use store::{Store, StoreError, TursoStore}; | 25 | pub use store::{Store, StoreError, TursoStore}; |
crates/dizey-core/src/store/mod.rsmodified+59 -1
| @@ -8,6 +8,7 @@ use async_trait::async_trait; | |||
| 8 | use serde::{Deserialize, Serialize}; | 8 | use serde::{Deserialize, Serialize}; |
| 9 | use time::OffsetDateTime; | 9 | use time::OffsetDateTime; |
| 10 | 10 | ||
| 11 | +use crate::board::{BoardReads, TaskRow}; | ||
| 11 | use crate::Role; | 12 | use crate::Role; |
| 12 | 13 | ||
| 13 | pub mod turso_store; | 14 | pub mod turso_store; |
| @@ -139,9 +140,23 @@ impl Session { | |||
| 139 | } | 140 | } |
| 140 | } | 141 | } |
| 141 | 142 | ||
| 143 | +/// A task as it is written. The key (`DZ-14`) is not here: the store hands it | ||
| 144 | +/// out from the board's counter, so two tasks created at once cannot collide. | ||
| 145 | +pub struct NewTask<'a> { | ||
| 146 | + pub board_id: &'a str, | ||
| 147 | + pub column_id: &'a str, | ||
| 148 | + pub title: &'a str, | ||
| 149 | + pub description: &'a str, | ||
| 150 | + pub deadline: Option<time::Date>, | ||
| 151 | + pub created_by: &'a str, | ||
| 152 | +} | ||
| 153 | + | ||
| 142 | /// The storage boundary. Dyn-safe on purpose: handlers hold `Arc<dyn Store>`. | 154 | /// The storage boundary. Dyn-safe on purpose: handlers hold `Arc<dyn Store>`. |
| 155 | +/// | ||
| 156 | +/// The board's reads live in [`BoardReads`], so the sweep-per-board shape is a | ||
| 157 | +/// trait a test can wrap and count. | ||
| 143 | #[async_trait] | 158 | #[async_trait] |
| 144 | -pub trait Store: Send + Sync + 'static { | 159 | +pub trait Store: BoardReads + 'static { |
| 145 | // -- workspace --------------------------------------------------------- | 160 | // -- workspace --------------------------------------------------------- |
| 146 | 161 | ||
| 147 | /// Claims an empty database: writes the workspace, its first account and | 162 | /// Claims an empty database: writes the workspace, its first account and |
| @@ -275,4 +290,47 @@ pub trait Store: Send + Sync + 'static { | |||
| 275 | /// Drops attempt rows older than `before`, so the ledger does not grow | 290 | /// Drops attempt rows older than `before`, so the ledger does not grow |
| 276 | /// without bound. | 291 | /// without bound. |
| 277 | async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result<u64>; | 292 | async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result<u64>; |
| 293 | + | ||
| 294 | + // -- board ------------------------------------------------------------- | ||
| 295 | + | ||
| 296 | + /// Adds a column to the end of a board. | ||
| 297 | + async fn create_column( | ||
| 298 | + &self, | ||
| 299 | + board_id: &str, | ||
| 300 | + name: &str, | ||
| 301 | + position: i64, | ||
| 302 | + is_done: bool, | ||
| 303 | + ) -> Result<crate::board::Column>; | ||
| 304 | + | ||
| 305 | + /// Writes a task and hands it the next key on its board, in one | ||
| 306 | + /// transaction, so two writers cannot both take `DZ-14`. | ||
| 307 | + async fn create_task(&self, new: NewTask<'_>) -> Result<TaskRow>; | ||
| 308 | + | ||
| 309 | + /// Idempotent: assigning someone twice is not an error. | ||
| 310 | + async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()>; | ||
| 311 | + | ||
| 312 | + async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()>; | ||
| 313 | + | ||
| 314 | + /// `blocked` cannot start until `blocking` is finished. | ||
| 315 | + async fn add_dependency( | ||
| 316 | + &self, | ||
| 317 | + blocked_task_id: &str, | ||
| 318 | + blocking_task_id: &str, | ||
| 319 | + at: OffsetDateTime, | ||
| 320 | + ) -> Result<()>; | ||
| 321 | + | ||
| 322 | + async fn clear_dependency( | ||
| 323 | + &self, | ||
| 324 | + blocked_task_id: &str, | ||
| 325 | + blocking_task_id: &str, | ||
| 326 | + at: OffsetDateTime, | ||
| 327 | + ) -> Result<()>; | ||
| 328 | + | ||
| 329 | + async fn add_comment( | ||
| 330 | + &self, | ||
| 331 | + task_id: &str, | ||
| 332 | + author_id: &str, | ||
| 333 | + body: &str, | ||
| 334 | + at: OffsetDateTime, | ||
| 335 | + ) -> Result<String>; | ||
| 278 | } | 336 | } |
crates/dizey-core/src/store/turso_store.rsmodified+396 -2
| @@ -13,9 +13,13 @@ use turso::{Builder, Connection, Row, Value, params}; | |||
| 13 | use uuid::Uuid; | 13 | use uuid::Uuid; |
| 14 | 14 | ||
| 15 | use super::{ | 15 | use super::{ |
| 16 | - DeletePolicy, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace, | 16 | + DeletePolicy, NewTask, NewUser, Result, Session, SigninLink, Store, StoreError, User, Workspace, |
| 17 | }; | 17 | }; |
| 18 | use crate::Role; | 18 | use crate::Role; |
| 19 | +use crate::board::{BoardMeta, BoardReads, Column, Person, TaskRow}; | ||
| 20 | +use time::Date; | ||
| 21 | +use time::format_description::BorrowedFormatItem; | ||
| 22 | +use time::macros::format_description; | ||
| 19 | 23 | ||
| 20 | /// Every migration, in order. Adding one means appending a file and a line. | 24 | /// Every migration, in order. Adding one means appending a file and a line. |
| 21 | const MIGRATIONS: &[(i64, &str)] = &[ | 25 | const MIGRATIONS: &[(i64, &str)] = &[ |
| @@ -23,6 +27,16 @@ const MIGRATIONS: &[(i64, &str)] = &[ | |||
| 23 | (2, include_str!("../../migrations/0002_auth.sql")), | 27 | (2, include_str!("../../migrations/0002_auth.sql")), |
| 24 | ]; | 28 | ]; |
| 25 | 29 | ||
| 30 | +/// The board a fresh workspace gets, and its columns. `Done` is the column | ||
| 31 | +/// that stamps a card finished. | ||
| 32 | +const DEFAULT_BOARD_NAME: &str = "Board"; | ||
| 33 | +const DEFAULT_COLUMNS: &[(&str, bool)] = &[ | ||
| 34 | + ("Backlog", false), | ||
| 35 | + ("In Progress", false), | ||
| 36 | + ("Review", false), | ||
| 37 | + ("Done", true), | ||
| 38 | +]; | ||
| 39 | + | ||
| 26 | pub struct TursoStore { | 40 | pub struct TursoStore { |
| 27 | /// Shared by every single-statement call. Turso serialises statements on a | 41 | /// Shared by every single-statement call. Turso serialises statements on a |
| 28 | /// connection, so this is safe; transactions are the exception and take a | 42 | /// connection, so this is safe; transactions are the exception and take a |
| @@ -142,6 +156,24 @@ fn parse_stamp(raw: &str) -> Result<OffsetDateTime> { | |||
| 142 | .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}"))) | 156 | .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}"))) |
| 143 | } | 157 | } |
| 144 | 158 | ||
| 159 | +/// Deadlines are days, not instants: a deadline is the same day wherever the | ||
| 160 | +/// person reading the card is. | ||
| 161 | +const DAY: &[BorrowedFormatItem] = format_description!("[year]-[month]-[day]"); | ||
| 162 | + | ||
| 163 | +fn day_text(day: Date) -> Result<String> { | ||
| 164 | + day.format(&DAY) | ||
| 165 | + .map_err(|e| StoreError::Corrupt(format!("deadline: {e}"))) | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +fn opt_day(row: &Row, idx: usize) -> Result<Option<Date>> { | ||
| 169 | + match row.get::<Option<String>>(idx).map_err(backend)? { | ||
| 170 | + Some(raw) => Date::parse(&raw, &DAY) | ||
| 171 | + .map(Some) | ||
| 172 | + .map_err(|e| StoreError::Corrupt(format!("deadline {raw:?}: {e}"))), | ||
| 173 | + None => Ok(None), | ||
| 174 | + } | ||
| 175 | +} | ||
| 176 | + | ||
| 145 | fn opt_stamp(row: &Row, idx: usize) -> Result<Option<OffsetDateTime>> { | 177 | fn opt_stamp(row: &Row, idx: usize) -> Result<Option<OffsetDateTime>> { |
| 146 | match row.get::<Option<String>>(idx).map_err(backend)? { | 178 | match row.get::<Option<String>>(idx).map_err(backend)? { |
| 147 | Some(raw) => Ok(Some(parse_stamp(&raw)?)), | 179 | Some(raw) => Ok(Some(parse_stamp(&raw)?)), |
| @@ -247,6 +279,7 @@ impl Store for TursoStore { | |||
| 247 | ) -> Result<(Workspace, User)> { | 279 | ) -> Result<(Workspace, User)> { |
| 248 | let workspace_id = Uuid::new_v4().to_string(); | 280 | let workspace_id = Uuid::new_v4().to_string(); |
| 249 | let admin_id = Uuid::new_v4().to_string(); | 281 | let admin_id = Uuid::new_v4().to_string(); |
| 282 | + let board_id = Uuid::new_v4().to_string(); | ||
| 250 | let now = now_text()?; | 283 | let now = now_text()?; |
| 251 | let email = fold_email(email); | 284 | let email = fold_email(email); |
| 252 | 285 | ||
| @@ -282,9 +315,36 @@ impl Store for TursoStore { | |||
| 282 | tx.execute( | 315 | tx.execute( |
| 283 | "INSERT INTO workspace_owner (singleton, user_id, claimed_at) \ | 316 | "INSERT INTO workspace_owner (singleton, user_id, claimed_at) \ |
| 284 | VALUES (1, ?1, ?2)", | 317 | VALUES (1, ?1, ?2)", |
| 285 | - params![admin_id.clone(), now], | 318 | + params![admin_id.clone(), now.clone()], |
| 319 | + ) | ||
| 320 | + .await?; | ||
| 321 | + // A claimed workspace is never boardless: the EmptyBoard screen is | ||
| 322 | + // four named columns waiting for a first card, not a setup step. | ||
| 323 | + tx.execute( | ||
| 324 | + "INSERT INTO board (id, workspace_id, name, task_prefix, created_at) \ | ||
| 325 | + VALUES (?1, ?2, ?3, 'DZ', ?4)", | ||
| 326 | + params![ | ||
| 327 | + board_id.clone(), | ||
| 328 | + workspace_id.clone(), | ||
| 329 | + DEFAULT_BOARD_NAME, | ||
| 330 | + now | ||
| 331 | + ], | ||
| 286 | ) | 332 | ) |
| 287 | .await?; | 333 | .await?; |
| 334 | + for (position, (name, is_done)) in DEFAULT_COLUMNS.iter().enumerate() { | ||
| 335 | + tx.execute( | ||
| 336 | + "INSERT INTO board_column (id, board_id, name, position, is_done) \ | ||
| 337 | + VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 338 | + params![ | ||
| 339 | + Uuid::new_v4().to_string(), | ||
| 340 | + board_id.clone(), | ||
| 341 | + *name, | ||
| 342 | + position as i64, | ||
| 343 | + i64::from(*is_done) | ||
| 344 | + ], | ||
| 345 | + ) | ||
| 346 | + .await?; | ||
| 347 | + } | ||
| 288 | Ok::<_, turso::Error>(()) | 348 | Ok::<_, turso::Error>(()) |
| 289 | } | 349 | } |
| 290 | .await; | 350 | .await; |
| @@ -703,6 +763,340 @@ impl Store for TursoStore { | |||
| 703 | .await | 763 | .await |
| 704 | .map_err(backend) | 764 | .map_err(backend) |
| 705 | } | 765 | } |
| 766 | + | ||
| 767 | + // -- board ------------------------------------------------------------- | ||
| 768 | + | ||
| 769 | + async fn create_column( | ||
| 770 | + &self, | ||
| 771 | + board_id: &str, | ||
| 772 | + name: &str, | ||
| 773 | + position: i64, | ||
| 774 | + is_done: bool, | ||
| 775 | + ) -> Result<Column> { | ||
| 776 | + let id = Uuid::new_v4().to_string(); | ||
| 777 | + self.conn | ||
| 778 | + .execute( | ||
| 779 | + "INSERT INTO board_column (id, board_id, name, position, is_done) \ | ||
| 780 | + VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 781 | + params![id.clone(), board_id, name, position, i64::from(is_done)], | ||
| 782 | + ) | ||
| 783 | + .await | ||
| 784 | + .map_err(backend)?; | ||
| 785 | + Ok(Column { | ||
| 786 | + id, | ||
| 787 | + name: name.to_string(), | ||
| 788 | + position, | ||
| 789 | + is_done, | ||
| 790 | + }) | ||
| 791 | + } | ||
| 792 | + | ||
| 793 | + async fn create_task(&self, new: NewTask<'_>) -> Result<TaskRow> { | ||
| 794 | + let id = Uuid::new_v4().to_string(); | ||
| 795 | + let now = now_text()?; | ||
| 796 | + let deadline = new.deadline.map(day_text).transpose()?; | ||
| 797 | + | ||
| 798 | + let mut conn = self.tx_conn().await?; | ||
| 799 | + // IMMEDIATE: the key comes off a counter, so the read of next_task_no | ||
| 800 | + // and the write that bumps it must not be interleaved with another | ||
| 801 | + // writer's pair. | ||
| 802 | + let tx = conn | ||
| 803 | + .transaction_with_behavior(TransactionBehavior::Immediate) | ||
| 804 | + .await | ||
| 805 | + .map_err(backend)?; | ||
| 806 | + | ||
| 807 | + let written = async { | ||
| 808 | + let mut rows = tx | ||
| 809 | + .query( | ||
| 810 | + "SELECT task_prefix, next_task_no FROM board WHERE id = ?1", | ||
| 811 | + params![new.board_id], | ||
| 812 | + ) | ||
| 813 | + .await?; | ||
| 814 | + let Some(row) = rows.next().await? else { | ||
| 815 | + return Ok(None); | ||
| 816 | + }; | ||
| 817 | + let prefix = row.get::<String>(0)?; | ||
| 818 | + let number = row.get::<i64>(1)?; | ||
| 819 | + drop(rows); | ||
| 820 | + tx.execute( | ||
| 821 | + "UPDATE board SET next_task_no = ?1 WHERE id = ?2", | ||
| 822 | + params![number + 1, new.board_id], | ||
| 823 | + ) | ||
| 824 | + .await?; | ||
| 825 | + | ||
| 826 | + // New cards land at the end of their column. | ||
| 827 | + let mut rows = tx | ||
| 828 | + .query( | ||
| 829 | + "SELECT COALESCE(MAX(position), 0) FROM task WHERE column_id = ?1", | ||
| 830 | + params![new.column_id], | ||
| 831 | + ) | ||
| 832 | + .await?; | ||
| 833 | + let last = match rows.next().await? { | ||
| 834 | + Some(row) => row.get::<f64>(0).unwrap_or(0.0), | ||
| 835 | + None => 0.0, | ||
| 836 | + }; | ||
| 837 | + drop(rows); | ||
| 838 | + let position = last + 1.0; | ||
| 839 | + | ||
| 840 | + let task_key = format!("{prefix}-{number:02}"); | ||
| 841 | + tx.execute( | ||
| 842 | + "INSERT INTO task (id, board_id, task_key, title, description, column_id, \ | ||
| 843 | + deadline, position, created_by, created_at, updated_at) \ | ||
| 844 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)", | ||
| 845 | + params![ | ||
| 846 | + id.clone(), | ||
| 847 | + new.board_id, | ||
| 848 | + task_key.clone(), | ||
| 849 | + new.title, | ||
| 850 | + new.description, | ||
| 851 | + new.column_id, | ||
| 852 | + deadline.clone(), | ||
| 853 | + position, | ||
| 854 | + new.created_by, | ||
| 855 | + now.clone() | ||
| 856 | + ], | ||
| 857 | + ) | ||
| 858 | + .await?; | ||
| 859 | + Ok::<_, turso::Error>(Some((task_key, position))) | ||
| 860 | + } | ||
| 861 | + .await; | ||
| 862 | + | ||
| 863 | + let written = match written { | ||
| 864 | + Ok(Some(written)) => written, | ||
| 865 | + Ok(None) => { | ||
| 866 | + let _ = tx.rollback().await; | ||
| 867 | + return Err(StoreError::NotFound); | ||
| 868 | + } | ||
| 869 | + Err(e) => { | ||
| 870 | + let _ = tx.rollback().await; | ||
| 871 | + return Err(backend(e)); | ||
| 872 | + } | ||
| 873 | + }; | ||
| 874 | + tx.commit().await.map_err(backend)?; | ||
| 875 | + | ||
| 876 | + let (task_key, position) = written; | ||
| 877 | + Ok(TaskRow { | ||
| 878 | + id, | ||
| 879 | + task_key, | ||
| 880 | + title: new.title.to_string(), | ||
| 881 | + column_id: new.column_id.to_string(), | ||
| 882 | + deadline: new.deadline, | ||
| 883 | + position, | ||
| 884 | + done_at: None, | ||
| 885 | + }) | ||
| 886 | + } | ||
| 887 | + | ||
| 888 | + async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> { | ||
| 889 | + self.conn | ||
| 890 | + .execute( | ||
| 891 | + "INSERT OR IGNORE INTO task_assignee (task_id, user_id) VALUES (?1, ?2)", | ||
| 892 | + params![task_id, user_id], | ||
| 893 | + ) | ||
| 894 | + .await | ||
| 895 | + .map_err(backend)?; | ||
| 896 | + Ok(()) | ||
| 897 | + } | ||
| 898 | + | ||
| 899 | + async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()> { | ||
| 900 | + self.conn | ||
| 901 | + .execute( | ||
| 902 | + "DELETE FROM task_assignee WHERE task_id = ?1 AND user_id = ?2", | ||
| 903 | + params![task_id, user_id], | ||
| 904 | + ) | ||
| 905 | + .await | ||
| 906 | + .map_err(backend)?; | ||
| 907 | + Ok(()) | ||
| 908 | + } | ||
| 909 | + | ||
| 910 | + async fn add_dependency( | ||
| 911 | + &self, | ||
| 912 | + blocked_task_id: &str, | ||
| 913 | + blocking_task_id: &str, | ||
| 914 | + at: OffsetDateTime, | ||
| 915 | + ) -> Result<()> { | ||
| 916 | + // Re-adding a dependency that was cleared puts it back in force rather | ||
| 917 | + // than leaving the cleared row to hide it. | ||
| 918 | + self.conn | ||
| 919 | + .execute( | ||
| 920 | + "INSERT INTO task_dependency (blocked_task_id, blocking_task_id, created_at) \ | ||
| 921 | + VALUES (?1, ?2, ?3) \ | ||
| 922 | + ON CONFLICT (blocked_task_id, blocking_task_id) \ | ||
| 923 | + DO UPDATE SET created_at = ?3, cleared_at = NULL", | ||
| 924 | + params![blocked_task_id, blocking_task_id, stamp(at)?], | ||
| 925 | + ) | ||
| 926 | + .await | ||
| 927 | + .map_err(backend)?; | ||
| 928 | + Ok(()) | ||
| 929 | + } | ||
| 930 | + | ||
| 931 | + async fn clear_dependency( | ||
| 932 | + &self, | ||
| 933 | + blocked_task_id: &str, | ||
| 934 | + blocking_task_id: &str, | ||
| 935 | + at: OffsetDateTime, | ||
| 936 | + ) -> Result<()> { | ||
| 937 | + self.conn | ||
| 938 | + .execute( | ||
| 939 | + "UPDATE task_dependency SET cleared_at = ?3 \ | ||
| 940 | + WHERE blocked_task_id = ?1 AND blocking_task_id = ?2 AND cleared_at IS NULL", | ||
| 941 | + params![blocked_task_id, blocking_task_id, stamp(at)?], | ||
| 942 | + ) | ||
| 943 | + .await | ||
| 944 | + .map_err(backend)?; | ||
| 945 | + Ok(()) | ||
| 946 | + } | ||
| 947 | + | ||
| 948 | + async fn add_comment( | ||
| 949 | + &self, | ||
| 950 | + task_id: &str, | ||
| 951 | + author_id: &str, | ||
| 952 | + body: &str, | ||
| 953 | + at: OffsetDateTime, | ||
| 954 | + ) -> Result<String> { | ||
| 955 | + let id = Uuid::new_v4().to_string(); | ||
| 956 | + self.conn | ||
| 957 | + .execute( | ||
| 958 | + "INSERT INTO comment (id, task_id, author_id, body, created_at) \ | ||
| 959 | + VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 960 | + params![id.clone(), task_id, author_id, body, stamp(at)?], | ||
| 961 | + ) | ||
| 962 | + .await | ||
| 963 | + .map_err(backend)?; | ||
| 964 | + Ok(id) | ||
| 965 | + } | ||
| 966 | +} | ||
| 967 | + | ||
| 968 | +#[async_trait] | ||
| 969 | +impl BoardReads for TursoStore { | ||
| 970 | + async fn board(&self, workspace_id: &str) -> Result<Option<BoardMeta>> { | ||
| 971 | + let row = self | ||
| 972 | + .one_row( | ||
| 973 | + "SELECT id, name, task_prefix FROM board WHERE workspace_id = ?1 \ | ||
| 974 | + ORDER BY created_at LIMIT 1", | ||
| 975 | + params![workspace_id], | ||
| 976 | + ) | ||
| 977 | + .await?; | ||
| 978 | + match row { | ||
| 979 | + Some(row) => Ok(Some(BoardMeta { | ||
| 980 | + id: text(&row, 0)?, | ||
| 981 | + name: text(&row, 1)?, | ||
| 982 | + task_prefix: text(&row, 2)?, | ||
| 983 | + })), | ||
| 984 | + None => Ok(None), | ||
| 985 | + } | ||
| 986 | + } | ||
| 987 | + | ||
| 988 | + async fn columns(&self, board_id: &str) -> Result<Vec<Column>> { | ||
| 989 | + let mut rows = self | ||
| 990 | + .conn | ||
| 991 | + .query( | ||
| 992 | + "SELECT id, name, position, is_done FROM board_column WHERE board_id = ?1 \ | ||
| 993 | + ORDER BY position", | ||
| 994 | + params![board_id], | ||
| 995 | + ) | ||
| 996 | + .await | ||
| 997 | + .map_err(backend)?; | ||
| 998 | + let mut out = Vec::new(); | ||
| 999 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 1000 | + out.push(Column { | ||
| 1001 | + id: text(&row, 0)?, | ||
| 1002 | + name: text(&row, 1)?, | ||
| 1003 | + position: row.get::<i64>(2).map_err(backend)?, | ||
| 1004 | + is_done: row.get::<i64>(3).map_err(backend)? != 0, | ||
| 1005 | + }); | ||
| 1006 | + } | ||
| 1007 | + Ok(out) | ||
| 1008 | + } | ||
| 1009 | + | ||
| 1010 | + async fn tasks_for_board(&self, board_id: &str) -> Result<Vec<TaskRow>> { | ||
| 1011 | + let mut rows = self | ||
| 1012 | + .conn | ||
| 1013 | + .query( | ||
| 1014 | + "SELECT id, task_key, title, column_id, deadline, position, done_at \ | ||
| 1015 | + FROM task WHERE board_id = ?1 AND deleted_at IS NULL", | ||
| 1016 | + params![board_id], | ||
| 1017 | + ) | ||
| 1018 | + .await | ||
| 1019 | + .map_err(backend)?; | ||
| 1020 | + let mut out = Vec::new(); | ||
| 1021 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 1022 | + out.push(TaskRow { | ||
| 1023 | + id: text(&row, 0)?, | ||
| 1024 | + task_key: text(&row, 1)?, | ||
| 1025 | + title: text(&row, 2)?, | ||
| 1026 | + column_id: text(&row, 3)?, | ||
| 1027 | + deadline: opt_day(&row, 4)?, | ||
| 1028 | + position: row.get::<f64>(5).map_err(backend)?, | ||
| 1029 | + done_at: opt_stamp(&row, 6)?, | ||
| 1030 | + }); | ||
| 1031 | + } | ||
| 1032 | + Ok(out) | ||
| 1033 | + } | ||
| 1034 | + | ||
| 1035 | + async fn assignees_for_board(&self, board_id: &str) -> Result<Vec<(String, Person)>> { | ||
| 1036 | + let mut rows = self | ||
| 1037 | + .conn | ||
| 1038 | + .query( | ||
| 1039 | + "SELECT a.task_id, u.id, u.display_name, u.photo_path \ | ||
| 1040 | + FROM task_assignee a \ | ||
| 1041 | + JOIN task t ON t.id = a.task_id \ | ||
| 1042 | + JOIN user u ON u.id = a.user_id \ | ||
| 1043 | + WHERE t.board_id = ?1 AND t.deleted_at IS NULL \ | ||
| 1044 | + ORDER BY u.display_name", | ||
| 1045 | + params![board_id], | ||
| 1046 | + ) | ||
| 1047 | + .await | ||
| 1048 | + .map_err(backend)?; | ||
| 1049 | + let mut out = Vec::new(); | ||
| 1050 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 1051 | + out.push(( | ||
| 1052 | + text(&row, 0)?, | ||
| 1053 | + Person { | ||
| 1054 | + id: text(&row, 1)?, | ||
| 1055 | + display_name: text(&row, 2)?, | ||
| 1056 | + photo_path: opt_text(&row, 3)?, | ||
| 1057 | + }, | ||
| 1058 | + )); | ||
| 1059 | + } | ||
| 1060 | + Ok(out) | ||
| 1061 | + } | ||
| 1062 | + | ||
| 1063 | + async fn comment_counts_for_board(&self, board_id: &str) -> Result<Vec<(String, u32)>> { | ||
| 1064 | + let mut rows = self | ||
| 1065 | + .conn | ||
| 1066 | + .query( | ||
| 1067 | + "SELECT c.task_id, COUNT(*) FROM comment c \ | ||
| 1068 | + JOIN task t ON t.id = c.task_id \ | ||
| 1069 | + WHERE t.board_id = ?1 AND t.deleted_at IS NULL \ | ||
| 1070 | + GROUP BY c.task_id", | ||
| 1071 | + params![board_id], | ||
| 1072 | + ) | ||
| 1073 | + .await | ||
| 1074 | + .map_err(backend)?; | ||
| 1075 | + let mut out = Vec::new(); | ||
| 1076 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 1077 | + let count = row.get::<i64>(1).map_err(backend)?.max(0) as u32; | ||
| 1078 | + out.push((text(&row, 0)?, count)); | ||
| 1079 | + } | ||
| 1080 | + Ok(out) | ||
| 1081 | + } | ||
| 1082 | + | ||
| 1083 | + async fn dependencies_for_board(&self, board_id: &str) -> Result<Vec<(String, String)>> { | ||
| 1084 | + let mut rows = self | ||
| 1085 | + .conn | ||
| 1086 | + .query( | ||
| 1087 | + "SELECT d.blocked_task_id, d.blocking_task_id FROM task_dependency d \ | ||
| 1088 | + JOIN task t ON t.id = d.blocked_task_id \ | ||
| 1089 | + WHERE t.board_id = ?1 AND d.cleared_at IS NULL AND t.deleted_at IS NULL", | ||
| 1090 | + params![board_id], | ||
| 1091 | + ) | ||
| 1092 | + .await | ||
| 1093 | + .map_err(backend)?; | ||
| 1094 | + let mut out = Vec::new(); | ||
| 1095 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 1096 | + out.push((text(&row, 0)?, text(&row, 1)?)); | ||
| 1097 | + } | ||
| 1098 | + Ok(out) | ||
| 1099 | + } | ||
| 706 | } | 1100 | } |
| 707 | 1101 | ||
| 708 | #[cfg(test)] | 1102 | #[cfg(test)] |
crates/dizey-core/tests/store.rsmodified+342 -0
| @@ -1200,3 +1200,345 @@ async fn an_address_can_only_be_invited_once() { | |||
| 1200 | Err(AccountError::AddressTaken) | 1200 | Err(AccountError::AddressTaken) |
| 1201 | )); | 1201 | )); |
| 1202 | } | 1202 | } |
| 1203 | + | ||
| 1204 | +// -- board ------------------------------------------------------------------ | ||
| 1205 | + | ||
| 1206 | +use dizey_core::board::{BoardReads, BoardView, Person, load}; | ||
| 1207 | +use dizey_core::store::NewTask; | ||
| 1208 | +use std::sync::atomic::{AtomicUsize, Ordering}; | ||
| 1209 | +use time::Date; | ||
| 1210 | +use time::macros::date; | ||
| 1211 | + | ||
| 1212 | +/// Wraps the real store and counts the round trips a board costs. | ||
| 1213 | +/// | ||
| 1214 | +/// This is the whole point of [`BoardReads`] being its own trait: the guard | ||
| 1215 | +/// against N+1 is tested by its effect — the count does not move when the board | ||
| 1216 | +/// gets bigger — rather than by reading the queries and taking their word. | ||
| 1217 | +struct CountingReads<'a> { | ||
| 1218 | + inner: &'a TursoStore, | ||
| 1219 | + calls: AtomicUsize, | ||
| 1220 | +} | ||
| 1221 | + | ||
| 1222 | +impl<'a> CountingReads<'a> { | ||
| 1223 | + fn new(inner: &'a TursoStore) -> Self { | ||
| 1224 | + Self { | ||
| 1225 | + inner, | ||
| 1226 | + calls: AtomicUsize::new(0), | ||
| 1227 | + } | ||
| 1228 | + } | ||
| 1229 | + | ||
| 1230 | + fn count(&self) -> usize { | ||
| 1231 | + self.calls.load(Ordering::Relaxed) | ||
| 1232 | + } | ||
| 1233 | + | ||
| 1234 | + fn tick(&self) { | ||
| 1235 | + self.calls.fetch_add(1, Ordering::Relaxed); | ||
| 1236 | + } | ||
| 1237 | +} | ||
| 1238 | + | ||
| 1239 | +#[async_trait::async_trait] | ||
| 1240 | +impl BoardReads for CountingReads<'_> { | ||
| 1241 | + async fn board( | ||
| 1242 | + &self, | ||
| 1243 | + workspace_id: &str, | ||
| 1244 | + ) -> Result<Option<dizey_core::board::BoardMeta>, StoreError> { | ||
| 1245 | + self.tick(); | ||
| 1246 | + self.inner.board(workspace_id).await | ||
| 1247 | + } | ||
| 1248 | + | ||
| 1249 | + async fn columns(&self, board_id: &str) -> Result<Vec<dizey_core::board::Column>, StoreError> { | ||
| 1250 | + self.tick(); | ||
| 1251 | + self.inner.columns(board_id).await | ||
| 1252 | + } | ||
| 1253 | + | ||
| 1254 | + async fn tasks_for_board( | ||
| 1255 | + &self, | ||
| 1256 | + board_id: &str, | ||
| 1257 | + ) -> Result<Vec<dizey_core::board::TaskRow>, StoreError> { | ||
| 1258 | + self.tick(); | ||
| 1259 | + self.inner.tasks_for_board(board_id).await | ||
| 1260 | + } | ||
| 1261 | + | ||
| 1262 | + async fn assignees_for_board( | ||
| 1263 | + &self, | ||
| 1264 | + board_id: &str, | ||
| 1265 | + ) -> Result<Vec<(String, Person)>, StoreError> { | ||
| 1266 | + self.tick(); | ||
| 1267 | + self.inner.assignees_for_board(board_id).await | ||
| 1268 | + } | ||
| 1269 | + | ||
| 1270 | + async fn comment_counts_for_board( | ||
| 1271 | + &self, | ||
| 1272 | + board_id: &str, | ||
| 1273 | + ) -> Result<Vec<(String, u32)>, StoreError> { | ||
| 1274 | + self.tick(); | ||
| 1275 | + self.inner.comment_counts_for_board(board_id).await | ||
| 1276 | + } | ||
| 1277 | + | ||
| 1278 | + async fn dependencies_for_board( | ||
| 1279 | + &self, | ||
| 1280 | + board_id: &str, | ||
| 1281 | + ) -> Result<Vec<(String, String)>, StoreError> { | ||
| 1282 | + self.tick(); | ||
| 1283 | + self.inner.dependencies_for_board(board_id).await | ||
| 1284 | + } | ||
| 1285 | +} | ||
| 1286 | + | ||
| 1287 | +async fn board_of(store: &TursoStore, workspace_id: &str) -> BoardView { | ||
| 1288 | + load(store, workspace_id) | ||
| 1289 | + .await | ||
| 1290 | + .unwrap() | ||
| 1291 | + .expect("a claimed workspace has a board") | ||
| 1292 | +} | ||
| 1293 | + | ||
| 1294 | +async fn column_named(store: &TursoStore, workspace_id: &str, name: &str) -> String { | ||
| 1295 | + let board = board_of(store, workspace_id).await; | ||
| 1296 | + board | ||
| 1297 | + .columns | ||
| 1298 | + .iter() | ||
| 1299 | + .find(|column| column.column.name == name) | ||
| 1300 | + .unwrap_or_else(|| panic!("no column named {name}")) | ||
| 1301 | + .column | ||
| 1302 | + .id | ||
| 1303 | + .clone() | ||
| 1304 | +} | ||
| 1305 | + | ||
| 1306 | +async fn add_task( | ||
| 1307 | + store: &TursoStore, | ||
| 1308 | + workspace_id: &str, | ||
| 1309 | + column: &str, | ||
| 1310 | + title: &str, | ||
| 1311 | + deadline: Option<Date>, | ||
| 1312 | + author: &str, | ||
| 1313 | +) -> String { | ||
| 1314 | + let board = store.board(workspace_id).await.unwrap().unwrap(); | ||
| 1315 | + let column_id = column_named(store, workspace_id, column).await; | ||
| 1316 | + store | ||
| 1317 | + .create_task(NewTask { | ||
| 1318 | + board_id: &board.id, | ||
| 1319 | + column_id: &column_id, | ||
| 1320 | + title, | ||
| 1321 | + description: "", | ||
| 1322 | + deadline, | ||
| 1323 | + created_by: author, | ||
| 1324 | + }) | ||
| 1325 | + .await | ||
| 1326 | + .unwrap() | ||
| 1327 | + .id | ||
| 1328 | +} | ||
| 1329 | + | ||
| 1330 | +#[tokio::test] | ||
| 1331 | +async fn a_claimed_workspace_starts_with_four_named_columns() { | ||
| 1332 | + let (scratch, workspace, _admin) = workspace_with_admin().await; | ||
| 1333 | + let board = board_of(&scratch.store, &workspace).await; | ||
| 1334 | + | ||
| 1335 | + let names: Vec<&str> = board | ||
| 1336 | + .columns | ||
| 1337 | + .iter() | ||
| 1338 | + .map(|column| column.column.name.as_str()) | ||
| 1339 | + .collect(); | ||
| 1340 | + assert_eq!(names, ["Backlog", "In Progress", "Review", "Done"]); | ||
| 1341 | + assert!(board.is_empty(), "a fresh board has no cards"); | ||
| 1342 | + // Only the last column finishes a task. | ||
| 1343 | + let done: Vec<bool> = board | ||
| 1344 | + .columns | ||
| 1345 | + .iter() | ||
| 1346 | + .map(|column| column.column.is_done) | ||
| 1347 | + .collect(); | ||
| 1348 | + assert_eq!(done, [false, false, false, true]); | ||
| 1349 | +} | ||
| 1350 | + | ||
| 1351 | +#[tokio::test] | ||
| 1352 | +async fn tasks_get_consecutive_keys_off_the_board_counter() { | ||
| 1353 | + let (scratch, workspace, admin) = workspace_with_admin().await; | ||
| 1354 | + let store = &scratch.store; | ||
| 1355 | + for title in ["Pricing page draft", "Choose analytics stack"] { | ||
| 1356 | + add_task(store, &workspace, "Backlog", title, None, &admin).await; | ||
| 1357 | + } | ||
| 1358 | + | ||
| 1359 | + let board = board_of(store, &workspace).await; | ||
| 1360 | + let keys: Vec<&str> = board.cards().map(|card| card.task_key.as_str()).collect(); | ||
| 1361 | + assert_eq!(keys, ["DZ-01", "DZ-02"]); | ||
| 1362 | +} | ||
| 1363 | + | ||
| 1364 | +#[tokio::test] | ||
| 1365 | +async fn a_card_carries_its_assignees_comments_and_dependency_keys() { | ||
| 1366 | + let (scratch, workspace, admin) = workspace_with_admin().await; | ||
| 1367 | + let store = &scratch.store; | ||
| 1368 | + let mel = store | ||
| 1369 | + .create_user(NewUser { | ||
| 1370 | + workspace_id: workspace.clone(), | ||
| 1371 | + email: "mel@dizey.sh".into(), | ||
| 1372 | + display_name: "Mel Duarte".into(), | ||
| 1373 | + role: Role::Member, | ||
| 1374 | + }) | ||
| 1375 | + .await | ||
| 1376 | + .unwrap(); | ||
| 1377 | + | ||
| 1378 | + let blocking = add_task( | ||
| 1379 | + store, | ||
| 1380 | + &workspace, | ||
| 1381 | + "In Progress", | ||
| 1382 | + "CLI install script (curl | sh)", | ||
| 1383 | + Some(date!(2026 - 08 - 21)), | ||
| 1384 | + &admin, | ||
| 1385 | + ) | ||
| 1386 | + .await; | ||
| 1387 | + let blocked = add_task( | ||
| 1388 | + store, | ||
| 1389 | + &workspace, | ||
| 1390 | + "Backlog", | ||
| 1391 | + "Onboarding email sequence", | ||
| 1392 | + Some(date!(2026 - 10 - 06)), | ||
| 1393 | + &admin, | ||
| 1394 | + ) | ||
| 1395 | + .await; | ||
| 1396 | + | ||
| 1397 | + store.assign_task(&blocking, &admin).await.unwrap(); | ||
| 1398 | + store.assign_task(&blocking, &mel.id).await.unwrap(); | ||
| 1399 | + // Assigning twice is the same as assigning once. | ||
| 1400 | + store.assign_task(&blocking, &mel.id).await.unwrap(); | ||
| 1401 | + store | ||
| 1402 | + .add_dependency(&blocked, &blocking, OffsetDateTime::now_utc()) | ||
| 1403 | + .await | ||
| 1404 | + .unwrap(); | ||
| 1405 | + for body in ["needs a checksum", "and a version pin", "ready for review"] { | ||
| 1406 | + store | ||
| 1407 | + .add_comment(&blocking, &admin, body, OffsetDateTime::now_utc()) | ||
| 1408 | + .await | ||
| 1409 | + .unwrap(); | ||
| 1410 | + } | ||
| 1411 | + | ||
| 1412 | + let board = board_of(store, &workspace).await; | ||
| 1413 | + let card = board.cards().find(|card| card.id == blocking).unwrap(); | ||
| 1414 | + assert_eq!(card.assignees.len(), 2); | ||
| 1415 | + assert_eq!(card.comment_count, 3); | ||
| 1416 | + assert_eq!(card.blocks, ["DZ-02"]); | ||
| 1417 | + assert!(card.blocked_by.is_empty()); | ||
| 1418 | + assert!(!card.is_blocked()); | ||
| 1419 | + | ||
| 1420 | + let waiting = board.cards().find(|card| card.id == blocked).unwrap(); | ||
| 1421 | + assert_eq!(waiting.blocked_by, ["DZ-01"]); | ||
| 1422 | + assert!(waiting.is_blocked()); | ||
| 1423 | + assert_eq!(waiting.comment_count, 0); | ||
| 1424 | + assert!(waiting.assignees.is_empty()); | ||
| 1425 | + | ||
| 1426 | + let today = date!(2026 - 08 - 26); | ||
| 1427 | + assert_eq!(card.deadline_label(today), "Aug 21 · overdue"); | ||
| 1428 | + assert_eq!(waiting.deadline_label(today), "Oct 06"); | ||
| 1429 | + assert_eq!(board.overdue_count(today), 1); | ||
| 1430 | + assert_eq!(board.blocked_count(), 1); | ||
| 1431 | +} | ||
| 1432 | + | ||
| 1433 | +#[tokio::test] | ||
| 1434 | +async fn a_cleared_dependency_stops_showing_on_the_card() { | ||
| 1435 | + let (scratch, workspace, admin) = workspace_with_admin().await; | ||
| 1436 | + let store = &scratch.store; | ||
| 1437 | + let blocking = add_task(store, &workspace, "In Progress", "Invite flow", None, &admin).await; | ||
| 1438 | + let blocked = add_task(store, &workspace, "Backlog", "Terms of service", None, &admin).await; | ||
| 1439 | + let now = OffsetDateTime::now_utc(); | ||
| 1440 | + store.add_dependency(&blocked, &blocking, now).await.unwrap(); | ||
| 1441 | + | ||
| 1442 | + let board = board_of(store, &workspace).await; | ||
| 1443 | + assert!( | ||
| 1444 | + board | ||
| 1445 | + .cards() | ||
| 1446 | + .find(|card| card.id == blocked) | ||
| 1447 | + .unwrap() | ||
| 1448 | + .is_blocked() | ||
| 1449 | + ); | ||
| 1450 | + | ||
| 1451 | + store | ||
| 1452 | + .clear_dependency(&blocked, &blocking, now) | ||
| 1453 | + .await | ||
| 1454 | + .unwrap(); | ||
| 1455 | + let board = board_of(store, &workspace).await; | ||
| 1456 | + let card = board.cards().find(|card| card.id == blocked).unwrap(); | ||
| 1457 | + assert!(card.blocked_by.is_empty()); | ||
| 1458 | + assert!(!card.is_blocked()); | ||
| 1459 | +} | ||
| 1460 | + | ||
| 1461 | +#[tokio::test] | ||
| 1462 | +async fn cards_sort_by_deadline_with_the_undated_last() { | ||
| 1463 | + let (scratch, workspace, admin) = workspace_with_admin().await; | ||
| 1464 | + let store = &scratch.store; | ||
| 1465 | + for (title, deadline) in [ | ||
| 1466 | + ("Choose analytics stack", None), | ||
| 1467 | + ("Terms of service review", Some(date!(2026 - 09 - 30))), | ||
| 1468 | + ("Pricing page draft", Some(date!(2026 - 09 - 12))), | ||
| 1469 | + ] { | ||
| 1470 | + add_task(store, &workspace, "Backlog", title, deadline, &admin).await; | ||
| 1471 | + } | ||
| 1472 | + | ||
| 1473 | + let board = board_of(store, &workspace).await; | ||
| 1474 | + let titles: Vec<&str> = board.columns[0] | ||
| 1475 | + .cards | ||
| 1476 | + .iter() | ||
| 1477 | + .map(|card| card.title.as_str()) | ||
| 1478 | + .collect(); | ||
| 1479 | + assert_eq!( | ||
| 1480 | + titles, | ||
| 1481 | + [ | ||
| 1482 | + "Pricing page draft", | ||
| 1483 | + "Terms of service review", | ||
| 1484 | + "Choose analytics stack" | ||
| 1485 | + ] | ||
| 1486 | + ); | ||
| 1487 | +} | ||
| 1488 | + | ||
| 1489 | +#[tokio::test] | ||
| 1490 | +async fn a_board_costs_six_queries_whatever_its_size() { | ||
| 1491 | + let (scratch, workspace, admin) = workspace_with_admin().await; | ||
| 1492 | + let store = &scratch.store; | ||
| 1493 | + | ||
| 1494 | + let small = CountingReads::new(store); | ||
| 1495 | + load(&small, &workspace).await.unwrap(); | ||
| 1496 | + assert_eq!(small.count(), 6, "an empty board"); | ||
| 1497 | + | ||
| 1498 | + // Forty tasks, each with an assignee, a comment and a dependency — the | ||
| 1499 | + // three things a naive card query fans out on. | ||
| 1500 | + let mut previous: Option<String> = None; | ||
| 1501 | + for n in 0..40 { | ||
| 1502 | + let id = add_task( | ||
| 1503 | + store, | ||
| 1504 | + &workspace, | ||
| 1505 | + "Backlog", | ||
| 1506 | + &format!("task {n}"), | ||
| 1507 | + Some(date!(2026 - 09 - 12)), | ||
| 1508 | + &admin, | ||
| 1509 | + ) | ||
| 1510 | + .await; | ||
| 1511 | + store.assign_task(&id, &admin).await.unwrap(); | ||
| 1512 | + store | ||
| 1513 | + .add_comment(&id, &admin, "a note", OffsetDateTime::now_utc()) | ||
| 1514 | + .await | ||
| 1515 | + .unwrap(); | ||
| 1516 | + if let Some(previous) = previous.replace(id.clone()) { | ||
| 1517 | + store | ||
| 1518 | + .add_dependency(&id, &previous, OffsetDateTime::now_utc()) | ||
| 1519 | + .await | ||
| 1520 | + .unwrap(); | ||
| 1521 | + } | ||
| 1522 | + } | ||
| 1523 | + | ||
| 1524 | + let big = CountingReads::new(store); | ||
| 1525 | + let board = load(&big, &workspace).await.unwrap().unwrap(); | ||
| 1526 | + assert_eq!(board.task_count(), 40); | ||
| 1527 | + assert_eq!( | ||
| 1528 | + big.count(), | ||
| 1529 | + 6, | ||
| 1530 | + "the round trips a board costs must not follow the number of tasks" | ||
| 1531 | + ); | ||
| 1532 | +} | ||
| 1533 | + | ||
| 1534 | +#[test] | ||
| 1535 | +fn initials_fall_back_to_two_letters() { | ||
| 1536 | + let person = |name: &str| Person { | ||
| 1537 | + id: "u".into(), | ||
| 1538 | + display_name: name.into(), | ||
| 1539 | + photo_path: None, | ||
| 1540 | + }; | ||
| 1541 | + assert_eq!(person("Mel Duarte").initials(), "MD"); | ||
| 1542 | + assert_eq!(person("Ada").initials(), "A"); | ||
| 1543 | + assert_eq!(person(" ").initials(), "?"); | ||
| 1544 | +} | ||