diff --git a/.gitignore b/.gitignore index 24d14f2..d2bb8ac 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ izlek.key /config/izlek.toml CLAUDE.md /crates/izlek-web/assets +*.db.backup-* diff --git a/crates/izlek-core/migrations/0001_init.sql b/crates/izlek-core/migrations/0001_init.sql index 302abac..f68ea2a 100644 --- a/crates/izlek-core/migrations/0001_init.sql +++ b/crates/izlek-core/migrations/0001_init.sql @@ -1,18 +1,16 @@ -- Izlek's schema, whole, in one file. -- --- Plain versioned SQL applied at boot: Turso has no migration runner of its --- own, and keeping the schema as SQL is what makes the store trait swappable. +-- One plain SQL file, applied at boot to an empty database: Turso has no +-- migration runner of its own, and keeping the schema as SQL is what makes +-- the store trait swappable. -- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by -- creation, and Crockford-uppercase already, which is what lets a task key -- borrow its tail. -- --- This file is the whole schema, not the first link of a chain. Nothing has --- been released, so a change to a table is made here, in the table, and the --- database it describes is recreated — twenty migrations were collapsed into --- this file once for that reason, and a twenty-first would start the same rot --- over. The reasoning the old migrations carried is kept, on the tables it --- explains. The day Izlek runs somewhere with data worth keeping, the next --- change becomes 0002 and this note goes away. +-- This file is the whole schema, and it is edited in place: a change to a +-- table is made here, in the table, never appended as an ALTER. An existing +-- database is brought up to it by `izlek reconcile`, not by the store, so a +-- change to a table lands in two places — here, and in that tool's copy map. CREATE TABLE workspace ( id TEXT PRIMARY KEY, @@ -25,6 +23,12 @@ CREATE TABLE workspace ( photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, -- JSON array of allowed extensions. An empty array means every type. allowed_file_types TEXT NOT NULL DEFAULT '[]', + -- How long a notification waits for the rest of its workflow. One normal + -- sequence — open a card, fix the column, assign it, set a deadline — is + -- four writes and was four mails; held for a few quiet minutes it is one + -- mail saying where the card ended up. Zero sends each one the moment it + -- is owed, which is what this did before the column existed. + mail_batch_minutes INTEGER NOT NULL DEFAULT 5, -- The single sender every mail in the workspace goes through, written by -- the admin in Settings rather than by whoever has a shell on the box: a -- three-person team has those be different people, and the second one is @@ -51,6 +55,19 @@ CREATE TABLE workspace ( smtp_test_at TEXT, smtp_test_ms INTEGER, smtp_test_error TEXT, + -- Whether the mail server let us in, which is a different fact from + -- whether a mail was delivered. `smtp_test_*` above records a real + -- message going out to a real inbox; these record a handshake — + -- connect, negotiate TLS, say hello, authenticate, hang up. It proves + -- the host, the port, the encryption and the credentials, and proves + -- nothing about whether the from-address is one this account may send + -- as — a server that accepts the login can still refuse the envelope. + -- Kept apart so neither can be read as the other. Cleared whenever the + -- sender is edited, for the same reason the test result is: it was + -- about settings that no longer exist. + smtp_check_at TEXT, + smtp_check_ms INTEGER, + smtp_check_error TEXT, -- The address mail links point at, when the one the process was -- configured with is not the one people reach. A box behind a proxy -- answers on localhost and is known by a public name, and only an admin @@ -147,6 +164,29 @@ CREATE TABLE board_column ( is_done INTEGER NOT NULL DEFAULT 0 ); +-- A tag is the project a task belongs to. A task wears at most one, so the +-- link is a column on `task` rather than a join table: two projects on one +-- task is a mistake the schema can refuse outright. +-- +-- A tag belongs to a board, as a mail rule does. Its order is the admin's — +-- set by hand, up and down — so it is stored rather than derived from +-- anything the board already knows. +-- +-- `is_default` marks the board's one fallback: every task must wear a tag, +-- so the board has one tag that catches whatever loses its own. That there +-- is exactly one is the partial index's job, not the store's. +CREATE TABLE tag ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + name TEXT NOT NULL, + position INTEGER NOT NULL, + is_default INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL +); +CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1; +CREATE UNIQUE INDEX tag_name_unique ON tag(board_id, name); +CREATE INDEX tag_by_board ON tag(board_id, position); + -- A task, and a subtask, which is the same thing with a parent. -- -- `parent_id` is the whole of the subtask feature in this schema: a subtask @@ -172,6 +212,10 @@ CREATE TABLE task ( title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', column_id TEXT NOT NULL REFERENCES board_column(id), + -- The project the task belongs to — NOT NULL on purpose, which a + -- declared schema can say where an ALTER could not: every task wears a + -- tag, and the board's default one catches whatever loses its own. + tag_id TEXT NOT NULL REFERENCES tag(id), deadline TEXT, position REAL NOT NULL DEFAULT 0, created_by TEXT NOT NULL REFERENCES user(id), @@ -294,6 +338,14 @@ CREATE TABLE activity ( id TEXT PRIMARY KEY, task_id TEXT REFERENCES task(id), actor_id TEXT REFERENCES user(id), + -- Who an activity line is about, as opposed to the actor who did it: + -- an Assigned line is about the person just assigned, an Unassigned one + -- about the person just removed. A mail rule aimed at the assignees + -- re-derives its one recipient from this id, on a retry as well as on + -- the first run — the detail column carries only a display name, and + -- two people can share a name. NULL for lines that are about nobody: a + -- comment, a move, a delete. + subject_id TEXT REFERENCES user(id), kind TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL diff --git a/crates/izlek-core/src/board.rs b/crates/izlek-core/src/board.rs index 74e53ef..5fdb3e6 100644 --- a/crates/izlek-core/src/board.rs +++ b/crates/izlek-core/src/board.rs @@ -42,6 +42,9 @@ pub struct TaskRow { /// is still read with the rest, because a key it owns can appear on /// somebody else's card as a blocker. pub parent_id: Option, + /// The tag — the project — the task wears, if any. The name rides along + /// so a card can show a chip without a second sweep. + pub tag: Option, } /// One card crossing from one column into another, as it was written. @@ -111,6 +114,14 @@ impl Person { } } +/// A tag's id and name, as a card and the detail carry them: enough to show +/// a chip and to filter the board on, and nothing more. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct TagChip { + pub id: String, + pub name: String, +} + /// A card, assembled. Dependencies carry the *keys* of the tasks on the other /// end, because that is what the card shows and it saves the UI a second lookup. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -132,6 +143,8 @@ pub struct TaskCard { /// Both are zero for a card with none, which is what hides the chip. pub subtask_total: u32, pub subtask_done: u32, + /// The tag the card wears — its project — when it has one. + pub tag: Option, } impl TaskCard { @@ -143,8 +156,7 @@ impl TaskCard { /// also the only place the count appears when a move is refused, which is /// why the refusal itself does not carry one. pub fn subtask_label(&self) -> Option { - (self.subtask_total > 0) - .then(|| format!("{}/{}", self.subtask_done, self.subtask_total)) + (self.subtask_total > 0).then(|| format!("{}/{}", self.subtask_done, self.subtask_total)) } /// Whether finishing this card is currently refused. @@ -190,11 +202,18 @@ impl TaskCard { /// `None` when there's nothing to show (no deadline, not done). pub fn deadline_parts(&self, today: Date) -> Option { if let Some(done) = self.done_at { - return Some(DeadlineParts { date: day_label(done.date()), state: DeadlineState::Done }); + return Some(DeadlineParts { + date: day_label(done.date()), + state: DeadlineState::Done, + }); } self.deadline.map(|day| DeadlineParts { date: day_label(day), - state: if day < today { DeadlineState::Overdue } else { DeadlineState::OnTime }, + state: if day < today { + DeadlineState::Overdue + } else { + DeadlineState::OnTime + }, }) } } @@ -370,6 +389,7 @@ pub fn assemble( done_at: task.done_at, position: task.position, column_id: task.column_id, + tag: task.tag, }; cards.entry(card.column_id.clone()).or_default().push(card); } diff --git a/crates/izlek-core/src/detail.rs b/crates/izlek-core/src/detail.rs index d8c159e..de8c9d9 100644 --- a/crates/izlek-core/src/detail.rs +++ b/crates/izlek-core/src/detail.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; use time::{Date, OffsetDateTime, UtcOffset}; -use crate::board::{Column, DeadlineParts, DeadlineState, Person, day_label}; +use crate::board::{Column, DeadlineParts, DeadlineState, Person, TagChip, day_label}; /// The stored task, plus the two ids the reader needs to know it is allowed to /// see it. The description lives here rather than on @@ -420,14 +420,8 @@ mod zone_tests { fn a_stamp_shifts_with_the_stored_offset() { let at = time::macros::datetime!(2026-08-19 11:04 UTC); assert_eq!(moment_label(at), "Aug 19 11:04"); - assert_eq!( - moment_label_in(at, parse_zone("UTC+03:00")), - "Aug 19 14:04" - ); - assert_eq!( - moment_label_in(at, parse_zone("UTC-05:00")), - "Aug 19 06:04" - ); + assert_eq!(moment_label_in(at, parse_zone("UTC+03:00")), "Aug 19 14:04"); + assert_eq!(moment_label_in(at, parse_zone("UTC-05:00")), "Aug 19 06:04"); } #[test] @@ -449,6 +443,8 @@ pub struct TaskDetail { /// Every column on the board, so the status control has its options /// without a second call. pub columns: Vec, + /// The tag the task wears — its project — when it wears one. + pub tag: Option, pub deadline: Option, pub done_at: Option, pub assignees: Vec, @@ -505,7 +501,11 @@ impl TaskDetail { pub fn deadline_parts(&self, today: Date) -> Option { self.deadline.map(|day| DeadlineParts { date: day_label(day), - state: if !self.is_done() && day < today { DeadlineState::Overdue } else { DeadlineState::OnTime }, + state: if !self.is_done() && day < today { + DeadlineState::Overdue + } else { + DeadlineState::OnTime + }, }) } @@ -538,7 +538,9 @@ pub use reads::{DetailReads, load}; mod reads { use async_trait::async_trait; - use super::{ActivityEntry, Comment, DependencyEdge, FileLine, SubtaskLine, TaskDetail, TaskFacts}; + use super::{ + ActivityEntry, Comment, DependencyEdge, FileLine, SubtaskLine, TaskDetail, TaskFacts, + }; use crate::board::{Column, Person}; use crate::store::Result; @@ -642,6 +644,7 @@ mod reads { description: facts.description, column, columns, + tag: task.tag, deadline: task.deadline, done_at: task.done_at, assignees, diff --git a/crates/izlek-core/src/live.rs b/crates/izlek-core/src/live.rs index 0e2d05f..033f748 100644 --- a/crates/izlek-core/src/live.rs +++ b/crates/izlek-core/src/live.rs @@ -28,6 +28,9 @@ pub enum Topic { Queue, /// Mail rules and the decisions they made. Rules, + /// The board's tags — the projects tasks wear. Every member sees them on + /// the board, so every member may hear. + Tags, /// Workspace settings, sender, limits, public URL. Settings, /// The activity and event log. @@ -44,6 +47,7 @@ impl Topic { Topic::Members => "members", Topic::Queue => "queue", Topic::Rules => "rules", + Topic::Tags => "tags", Topic::Settings => "settings", Topic::Activity => "activity", } diff --git a/crates/izlek-core/src/mail.rs b/crates/izlek-core/src/mail.rs index 010d3b5..3599cf9 100644 --- a/crates/izlek-core/src/mail.rs +++ b/crates/izlek-core/src/mail.rs @@ -123,6 +123,11 @@ pub const HOLD: Duration = Duration::minutes(1); /// that is thinking about it, short enough that a crash is not a lost day. pub const LEASE: Duration = Duration::minutes(5); +/// How far past its first trigger a batch can be pushed. A card somebody is +/// working on all afternoon would otherwise never settle, and its mail would +/// never go — so the debounce yields after four windows and sends what it has. +pub const MAX_HOLD_WINDOWS: i32 = 4; + /// The wait before the next attempt, doubling and capped: five minutes, ten, /// twenty, forty, an hour. pub fn backoff(attempts: u32) -> Duration { @@ -144,6 +149,9 @@ pub struct Report { /// Mails held back because there is no sender to send them through. Owed, /// not failed: no attempt was spent and none will be until one exists. pub held: u32, + /// Mails written down and left to wait out the workspace's quiet window, + /// so the rest of the workflow can join them in one envelope. + pub batched: u32, } pub struct Engine { @@ -495,6 +503,12 @@ impl Engine { /// anything is claimed: an empty audience leaves no ledger row at all, so /// a rule that only ever resolves to the actor is silent rather than being /// a row the admin has to read as a failure. + /// + /// A line that is about one person narrows the audience to that person: + /// an Assigned rule is for the one just assigned, not for everybody + /// already on the card. The subject is read from the stored row rather + /// than from the name in the detail, so the audience a restart resolves + /// is the audience the first pass resolved — two people can share a name. async fn owe( &self, rule: &MailRule, @@ -502,10 +516,22 @@ impl Engine { task_id: &str, report: &mut Report, ) -> crate::store::Result<()> { - let recipients = match rule.audience { - Audience::Assignees => self.store.recipients_for_task(task_id).await?, - Audience::Board => self.store.recipients_for_board(&rule.board_id).await?, - Audience::Creator => self.store.recipients_for_task_creator(task_id).await?, + let recipients = match (rule.audience, event) { + ( + Audience::Assignees, + Event::Happened(ActivityEvent { + subject_id: Some(about), + .. + }), + ) => self + .store + .recipient(about) + .await? + .map(|one| vec![one]) + .unwrap_or_default(), + (Audience::Assignees, _) => self.store.recipients_for_task(task_id).await?, + (Audience::Board, _) => self.store.recipients_for_board(&rule.board_id).await?, + (Audience::Creator, _) => self.store.recipients_for_task_creator(task_id).await?, }; let resolved_nobody = recipients.is_empty(); let now = OffsetDateTime::now_utc(); @@ -531,18 +557,39 @@ impl Engine { .await?; return Ok(()); } + // The workspace's quiet window. Zero is what İzlek did before it had + // one: every trigger its own mail, sent as soon as it is owed. + let window = self + .store + .workspace() + .await? + .map(|workspace| i64::from(workspace.mail_batch_minutes)) + .unwrap_or(0); + let hold = Duration::minutes(window); for recipient in audience { + // A held row comes due when the window closes rather than when the + // lease does; with no window it keeps the lease it always had, + // which is what stops the pass that queued it from grabbing it + // back before it has been composed. + let due = if window > 0 { now + hold } else { now + LEASE }; let claimed = self .store - .claim_send( - &rule.id, - event.id(), - task_id, - &recipient.email, - now, - now + LEASE, - ) + .claim_send(&rule.id, event.id(), task_id, &recipient.email, now, due) .await?; + if window > 0 { + // Everything this person is already owed about this card waits + // for the new arrival: that is the debounce. The ceiling is + // measured from the oldest mail in the batch, so a card under + // constant edit still goes out. + self.store + .hold_batch( + task_id, + &recipient.email, + now + hold, + hold * MAX_HOLD_WINDOWS, + ) + .await?; + } match claimed { Some(send) => { self.store @@ -555,8 +602,15 @@ impl Engine { now, ) .await?; - let mail = self.compose(&send, rule, event).await?; - self.attempt(&send, mail, report).await?; + // With a window the row is left where it lies: the + // delivery pass picks it up when it comes due, together + // with everything else this person is owed about the card. + if window > 0 { + report.batched += 1; + } else { + let mail = self.compose(&send, rule, event).await?; + self.attempt(&send, mail, report).await?; + } } None => { self.store @@ -588,11 +642,15 @@ impl Engine { // pass and the same write wakes the sweep, so two passes reach the // same row together. Each is handed only what it took, and only a // `ClaimedSend` can be mailed. See `Store::claim_sends_owed`. + // Rule rows are answered one mail per task per person: several + // triggers about one card, held through the same quiet window, are + // one thing that happened as far as the reader is concerned. Invites + // and notices are never folded in — each carries its own subject and + // body, composed once at mint time, and belongs to nobody's card. + let mut batches: Vec<(String, String, Vec)> = Vec::new(); for send in self.store.claim_sends_owed(now, now + LEASE, limit).await? { - // An invite and an admin's notice both owe no rule and no event: - // each carries its own subject and body, composed once at mint - // time. Without this arm a notice falls through to the rule path, - // finds no rule_id, and is skipped every run — queued forever. + // Without this arm a notice falls through to the rule path, finds + // no rule_id, and is skipped every run — queued forever. if matches!(send.kind, SendKind::Invite | SendKind::Notice) { let mail = Outgoing { to: send.recipient.clone(), @@ -602,47 +660,110 @@ impl Engine { self.attempt(&send, Some(mail), &mut report).await?; continue; } - let Some(rule_id) = send.rule_id.as_deref() else { + let Some(task_id) = send.task_id.clone() else { continue; }; - let Some(event_id) = send.event_id.as_deref() else { + let recipient = send.recipient.clone(); + match batches + .iter_mut() + .find(|(task, to, _)| task == &task_id && to == &recipient) + { + Some((_, _, group)) => group.push(send), + None => batches.push((task_id, recipient, vec![send])), + } + } + + for (_, _, group) in batches { + // The newest event is the one that decides the mail: its rule + // supplies the subject, and its moment is the moment the mail + // speaks about. + let mut newest: Option<(Event, MailRule)> = None; + let mut details = false; + for send in &group { + let (Some(rule_id), Some(event_id)) = + (send.rule_id.as_deref(), send.event_id.as_deref()) + else { + continue; + }; + let (Some(rule), Some(event)) = ( + self.store.mail_rule(rule_id).await?, + self.store.event(event_id).await?, + ) else { + continue; + }; + details |= rule.include_task_details; + let newer = newest + .as_ref() + .map(|(known, _)| event.at() > known.at()) + .unwrap_or(true); + if newer { + newest = Some((event, rule)); + } + } + let Some((event, rule)) = newest else { continue; }; - let Some(rule) = self.store.mail_rule(rule_id).await? else { + let Some(first) = group.first() else { continue; }; - let Some(event) = self.store.event(event_id).await? else { - continue; + let mail = if group.len() == 1 { + self.compose(first, &rule, &event).await? + } else { + self.compose_batch(first, &rule, &event, details).await? }; - let mail = self.compose(&send, &rule, &event).await?; - self.attempt(&send, mail, &mut report).await?; + self.attempt_group(&group, mail, &mut report).await?; } Ok(report) } - /// One attempt, and the ledger line it leaves behind. + /// One attempt for one claimed row. async fn attempt( &self, send: &ClaimedSend, mail: Option, report: &mut Report, + ) -> crate::store::Result<()> { + self.attempt_group(std::slice::from_ref(send), mail, report) + .await + } + + /// One attempt, and the ledger lines it leaves behind — one per row in + /// the group. + /// + /// A batch is several owed rows answered by a single mail, so the send + /// happens once and every row in it is marked with the same outcome: they + /// were all in that envelope. The claim invariant is unchanged — this + /// takes `ClaimedSend`s, so a row that was merely read still cannot be + /// mailed. + async fn attempt_group( + &self, + sends: &[ClaimedSend], + mail: Option, + report: &mut Report, ) -> crate::store::Result<()> { let Some(mail) = mail else { return Ok(()); }; + let Some(send) = sends.first() else { + return Ok(()); + }; let now = OffsetDateTime::now_utc(); match self.mailer.send(&mail).await { Ok(()) => { - self.store.record_send_accepted(&send.id, now).await?; + for one in sends { + self.store.record_send_accepted(&one.id, now).await?; + } report.sent += 1; } Err(problem) if !problem.attempted => { // No sender. The mail keeps its place in the ledger and its // attempts, and is looked at again on the next sweep — by then // an admin may have filled the panel in. - self.store - .defer_send(&send.id, &problem.message, now + HOLD, now) - .await?; + for one in sends { + self.store + .defer_send(&one.id, &problem.message, now + HOLD, now) + .await?; + } report.held += 1; } Err(problem) => { @@ -651,9 +772,11 @@ impl Engine { // left looking like it is still coming. let retry_at = (problem.retryable && attempts < MAX_ATTEMPTS).then(|| now + backoff(attempts)); - self.store - .record_send_refused(&send.id, &problem.message, retry_at, now) - .await?; + for one in sends { + self.store + .record_send_refused(&one.id, &problem.message, retry_at, now) + .await?; + } if retry_at.is_some() { report.failed += 1; } else { @@ -810,6 +933,76 @@ impl Engine { body, })) } + + /// The mail a whole batch answers with: where the task stands NOW. + /// + /// A batch is several triggers about one task for one person, held + /// together through a quiet window. Naming each of them would be a diary, + /// and half its entries are already wrong — a column set by mistake and + /// corrected inside the window happened, but is not the case. So the mail + /// reads the task as it is at send time and says that; the subject comes + /// from the rule behind the newest event, which is the reason the mail is + /// going out at all. + async fn compose_batch( + &self, + send: &MailSend, + newest_rule: &MailRule, + newest_event: &Event, + details: bool, + ) -> crate::store::Result> { + let Some(task_id) = send.task_id.as_deref() else { + return Ok(None); + }; + let Some(facts) = self.store.task(task_id).await? else { + return Ok(None); + }; + let columns = self.store.columns_for_board(&facts.board_id).await?; + let column = columns + .iter() + .find(|column| column.id == facts.row.column_id) + .map(|column| column.name.clone()) + .unwrap_or_else(|| "somewhere".to_string()); + let assignees = self.store.assignees_for_task(task_id).await?; + let assignees = if assignees.is_empty() { + "none".to_string() + } else { + assignees + .iter() + .map(|person| person.display_name.as_str()) + .collect::>() + .join(", ") + }; + let deadline = facts + .row + .deadline + .map(|date| date.to_string()) + .unwrap_or_else(|| "none".to_string()); + let base = self + .store + .workspace() + .await? + .and_then(|workspace| workspace.public_url) + .unwrap_or_else(|| self.fallback_url.clone()); + let mut body = format!( + "{key} — {title}\n\nColumn: {column}\nDeadline: {deadline}\nAssignees: {assignees}\n\n{when}\n\n{base}/?task={id}\n", + key = facts.row.task_key, + title = facts.row.title, + when = day_and_time(newest_event.at()), + id = facts.row.id, + ); + if details { + body.push_str(&format!( + "\nKey: {key}\nTitle: {title}\n", + key = facts.row.task_key, + title = facts.row.title, + )); + } + Ok(Some(Outgoing { + to: send.recipient.clone(), + subject: newest_rule.subject.clone(), + body, + })) + } } /// The `ActivityKind` a trigger fires on. `StatusBecomes`/`Unblocked` fire on diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 85cfd60..1bd32c3 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -6,7 +6,7 @@ use async_trait::async_trait; use serde::{Deserialize, Serialize}; -use time::OffsetDateTime; +use time::{Duration, OffsetDateTime}; use crate::Role; use crate::board::{BoardReads, Moved, TaskRow, Transition}; @@ -14,9 +14,15 @@ use crate::detail::{ActivityKind, DeletionCost, DetailReads}; #[cfg(feature = "server")] pub mod secret; +#[cfg(feature = "server")] +pub mod reconcile; +#[cfg(feature = "server")] +pub mod schema; pub mod turso_store; pub use turso_store::TursoStore; +#[cfg(feature = "server")] +pub use reconcile::{reconcile, ReconcileOptions}; #[derive(Debug, thiserror::Error)] pub enum StoreError { @@ -75,6 +81,9 @@ pub struct Workspace { pub attachment_limit_bytes: u64, pub photo_limit_bytes: u64, pub allowed_file_types: Vec, + /// The quiet window a notification waits out before it is sent, in + /// minutes. `0` sends every trigger the moment it is owed. + pub mail_batch_minutes: u32, /// The origin mail links point at, when an admin has set one. `None` /// means the address the process listens on — a box behind a proxy /// answers on localhost and is reached on a public name, and only an @@ -206,6 +215,20 @@ pub struct NewUser { pub invited_by: Option, } +/// The profile page's totals for one person: what is on their plate, what +/// finished under them, what they opened, what they said. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserStats { + /// Tasks the person is on now, sitting in a column that is not done. + pub assigned_open: u32, + /// Tasks they are on that reached a done column. + pub assigned_done: u32, + /// Tasks they opened, whoever carries them now. + pub created: u32, + /// Comments they wrote. + pub comments: u32, +} + /// A first-sign-in link. Only the hash of the token is ever stored; the /// plaintext is shown once, when the link is created or resent. #[derive(Debug, Clone, PartialEq)] @@ -323,6 +346,21 @@ pub struct MailRule { pub include_task_details: bool, } +/// A tag is the project a task belongs to. A task wears at most one, so the +/// link is a column on the task, not a join table. Tags belong to a board, +/// like the mail rules do, and their order is the admin's — set by hand, so +/// it is stored rather than derived. One tag per board is the default its +/// tasks fall back to, and it cannot be deleted — only renamed and +/// reordered. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Tag { + pub id: String, + pub board_id: String, + pub name: String, + pub position: i64, + pub is_default: bool, +} + /// Where one mail got to. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum SendState { @@ -585,6 +623,9 @@ pub struct ActivityEvent { pub board_id: String, pub kind: ActivityKind, pub actor_id: String, + /// The person the line is about — the one just assigned, say — when it + /// is about anyone in particular. + pub subject_id: Option, pub detail: String, pub at: OffsetDateTime, } @@ -646,7 +687,6 @@ pub struct Recipient { /// trait a test can wrap and count. #[async_trait] pub trait Store: BoardReads + DetailReads + 'static { - // -- live updates ------------------------------------------------------ /// A receiver of committed-write announcements. One [`Change`] per @@ -705,6 +745,7 @@ pub trait Store: BoardReads + DetailReads + 'static { attachment_limit_bytes: u64, photo_limit_bytes: u64, allowed_file_types: &[String], + mail_batch_minutes: u32, ) -> Result<()>; // -- users ------------------------------------------------------------- @@ -722,6 +763,12 @@ pub trait Store: BoardReads + DetailReads + 'static { async fn count_users(&self, workspace_id: &str) -> Result; + /// One person's totals, for their profile. A soft-deleted task counts + /// nowhere: it has left the board, so it has left the person. + /// + /// This is a read, for looking: nothing announces. + async fn user_stats(&self, user_id: &str) -> Result; + async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>; async fn set_profile(&self, user_id: &str, display_name: &str) -> Result<()>; @@ -964,10 +1011,13 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Appends one line to a task's activity trail and returns its row id. /// `actor_id` is `None` when the system did it rather than a person. + /// `subject_id` is the person the line is ABOUT — the one just assigned, + /// say — and `None` for a line that is about nobody. async fn record_activity( &self, task_id: &str, actor_id: Option<&str>, + subject_id: Option<&str>, kind: &ActivityKind, detail: &str, at: OffsetDateTime, @@ -1033,6 +1083,29 @@ pub trait Store: BoardReads + DetailReads + 'static { /// When each rule last got a mail accepted, for the "last sent" line. async fn mail_rule_last_sent(&self, board_id: &str) -> Result>; + // -- tags -------------------------------------------------------------- + + /// Every tag on the board, in the admin's hand-set order. + async fn tags(&self, board_id: &str) -> Result>; + + /// Appends a tag at the end of the board's order. The name is unique per + /// board: two tags with one name are one project spelled twice. + async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result; + + async fn rename_tag(&self, tag_id: &str, name: &str) -> Result<()>; + + /// Deletes a tag. Its tasks move to the board's default tag; the default + /// itself is refused — it is where they would go. + async fn delete_tag(&self, tag_id: &str) -> Result<()>; + + /// Swaps a tag with its neighbour in the order. A tag already at that end + /// stays put: nothing to swap is not an error. + async fn move_tag(&self, tag_id: &str, up: bool) -> Result<()>; + + /// Sets the tag a task wears. A tag from another board is + /// [`StoreError::NotFound`] — it is not one of this board's projects at + /// all. + async fn set_task_tag(&self, task_id: &str, tag_id: &str) -> Result<()>; // -- the send ledger --------------------------------------------------- /// Takes ownership of one mail by writing its row, and answers `None` if @@ -1240,6 +1313,27 @@ pub trait Store: BoardReads + DetailReads + 'static { /// store, so no caller can mail one by forgetting to filter. async fn recipients_for_board(&self, board_id: &str) -> Result>; + /// Pushes every mail still merely owed about this task, for this person, + /// out to `until` — but never past `cap`, the moment the oldest of them + /// stops waiting no matter what. + /// + /// This is the debounce: each new trigger about a card postpones the mail + /// the card already owes, so a person is told once, after the work has + /// settled. Only rows that are still pending and have never been + /// attempted move — a mail already refused is on its own retry clock, and + /// a batch must not drag it back. + async fn hold_batch( + &self, + task_id: &str, + recipient: &str, + until: OffsetDateTime, + cap: Duration, + ) -> Result<()>; + /// Whoever opened the task, unless they are a Viewer. async fn recipients_for_task_creator(&self, task_id: &str) -> Result>; + + /// One person by id, unless they are a Viewer — the subject of an + /// activity line, for a rule that mails the person the line is about. + async fn recipient(&self, user_id: &str) -> Result>; } diff --git a/crates/izlek-core/src/store/reconcile.rs b/crates/izlek-core/src/store/reconcile.rs new file mode 100644 index 0000000..4d3bae7 --- /dev/null +++ b/crates/izlek-core/src/store/reconcile.rs @@ -0,0 +1,738 @@ +//! Reconcile a live Turso database with the declared whole schema. +//! +//! The live file is never altered in place. Instead a new file is built from +//! `migrations/0001_init.sql`, the data is copied with an explicit per-table +//! column map, the copy is verified, and only then the files are swapped. The +//! original file is kept as a timestamped backup and is never deleted. + +use super::{Result, StoreError}; +use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint}; +use turso::{Builder, Connection, params}; +use ulid::Ulid; + +/// How the caller wants to confirm the rebuild. +pub struct ReconcileOptions { + /// Print the diff and plan, then stop without touching anything. + pub dry_run: bool, + /// Skip the interactive confirmation. + pub yes: bool, + /// Boot path: do not prompt, log what happened and proceed. + pub auto: bool, +} + +/// Rebuilds the database at `path` to match the declared schema. +/// +/// - Empty or already-current databases are a no-op. +/// - A differing database is backed up, rebuilt, verified and swapped into +/// place. +/// - A rebuild that fails verification deletes the `.rebuilt` file and leaves +/// the original untouched. +pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> { + if path == ":memory:" { + return Err(StoreError::Backend( + "reconcile is not meaningful on an in-memory database".into(), + )); + } + let db_path = std::path::Path::new(path); + if !db_path.exists() { + return Err(StoreError::Backend(format!("database not found: {}", path))); + } + + // Open the live database read-only to inspect its fingerprint. + let old_db = Builder::new_local(path) + .build() + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let old_conn = old_db.connect().map_err(|e| StoreError::Backend(e.to_string()))?; + + let old_fp = fingerprint(&old_conn).await?; + let new_fp = declared_fingerprint().await?; + + if old_fp == new_fp { + if !opts.auto { + println!("database already matches the declared schema"); + } + return Ok(()); + } + + let diff = diff_report(&old_fp, &new_fp); + + if opts.dry_run { + println!("schema difference:\n{}", diff); + println!("dry run: would rebuild {}", path); + return Ok(()); + } + + if opts.auto { + eprintln!("database schema differs from declared schema; rebuilding automatically"); + eprintln!("difference:\n{}", diff); + } else { + println!("schema difference:\n{}", diff); + if !opts.yes { + print!("rebuild {}? [y/N] ", path); + let _ = std::io::Write::flush(&mut std::io::stdout()); + let mut answer = String::new(); + match std::io::stdin().read_line(&mut answer) { + Ok(_) if answer.trim().eq_ignore_ascii_case("y") => {} + _ => { + println!("rebuild cancelled"); + return Ok(()); + } + } + } + } + + let rebuilt_path = format!("{}.rebuilt", path); + cleanup_rebuilt(&rebuilt_path); + + let result = rebuild(path, &rebuilt_path, &old_conn).await; + + // Close the read-only connection before any file moves; this also + // releases the WAL locks on the original file. + drop(old_conn); + drop(old_db); + + if let Err(e) = result { + cleanup_rebuilt(&rebuilt_path); + return Err(e); + } + + let backup_path = backup_name(path)?; + std::fs::rename(path, &backup_path).map_err(|e| { + StoreError::Backend(format!( + "failed to move original database to backup {}: {}", + backup_path, e + )) + })?; + // SQLite WAL/SHM siblings belong to the main file; the backup must be a + // complete database on its own, and the rebuilt file starts with none. + rename_sibling(path, &backup_path, "-wal"); + rename_sibling(path, &backup_path, "-shm"); + if let Err(e) = std::fs::rename(&rebuilt_path, path) { + // Best-effort undo so the live file is not gone. If this also fails, + // the caller has both the backup and the rebuilt file to recover from. + let _ = std::fs::rename(&backup_path, path); + let _ = rename_sibling(&backup_path, path, "-wal"); + let _ = rename_sibling(&backup_path, path, "-shm"); + return Err(StoreError::Backend(format!( + "failed to move rebuilt database into place {}: {}", + rebuilt_path, e + ))); + } + // The rebuilt file was checkpointed before the swap, so its own sidecars + // hold nothing — but a `.rebuilt-wal` left lying about would be adopted by + // the NEXT rebuild's fresh `.rebuilt` file, which is how a stale WAL + // corrupts a database that was otherwise fine. + let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path)); + let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path)); + + if opts.auto { + eprintln!("database rebuilt and verified; original backed up to {}", backup_path); + eprintln!("rebuilt database now at {}", path); + } else { + println!("database rebuilt and verified"); + println!("original backed up to {}", backup_path); + println!("rebuilt database now at {}", path); + } + + Ok(()) +} + +/// Does the actual rebuild: creates `.rebuilt`, copies the data (seeding the +/// tags partway, where the foreign keys allow it), and verifies the result. On success the rebuilt file is complete and +/// checkpointed; on failure the caller deletes it. +async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Result<()> { + // The copy runs as `INSERT ... SELECT FROM old.`, which needs + // ATTACH — still gated in this engine, and switched on only here, for the + // one connection that does the rebuild. The verification afterwards is + // what protects the data, not the copy's mechanism. + let new_db = Builder::new_local(rebuilt_path) + .experimental_attach(true) + .build() + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let new_conn = new_db.connect().map_err(|e| StoreError::Backend(e.to_string()))?; + + new_conn + .execute("PRAGMA foreign_keys = ON", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + new_conn + .execute_batch(SCHEMA) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + copy_data(old_conn, &new_conn, path).await?; + verify(old_conn, &new_conn).await?; + + // A checkpoint PRAGMA answers with a row, so it is a query: `execute` + // treats a row as a failure ("unexpected row during execution"). + let mut checkpoint = new_conn + .query("PRAGMA wal_checkpoint(TRUNCATE)", ()) + .await + .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?; + while checkpoint + .next() + .await + .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))? + .is_some() + {} + + Ok(()) +} + +/// Seeds one `General` tag per board into the new database, before `task` +/// is copied. The tag is the default for that board, so every task copied +/// afterwards can map its `tag_id` to it. +async fn seed_general_tags(old_conn: &Connection, new_conn: &Connection) -> Result<()> { + let mut rows = old_conn + .query("SELECT id, created_at FROM board", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? { + let board_id: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + let created_at: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + let id = Ulid::new().to_string(); + new_conn + .execute( + "INSERT INTO main.tag (id, board_id, name, position, is_default, created_at) \ + VALUES (?1, ?2, 'General', 0, 1, ?3)", + params![id, board_id, created_at], + ) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + } + Ok(()) +} + +/// A per-table column map. Every destination column must appear exactly once; +/// `copy_data` validates this against the declared schema before inserting. +struct TableMap { + name: &'static str, + columns: Vec<(&'static str, String)>, +} + +/// Builds the explicit column map. Unchanged tables map every column to +/// `old.`; the changed tables carry the migration-specific expressions. +fn build_maps(old_has_smtp_check: bool, old_has_batch_window: bool) -> Vec { + let mut maps = Vec::new(); + + maps.push(TableMap { + name: "workspace", + columns: vec![ + ("id", "old.id".into()), + ("name", "old.name".into()), + ("created_at", "old.created_at".into()), + ("attachment_limit_bytes", "old.attachment_limit_bytes".into()), + ("photo_limit_bytes", "old.photo_limit_bytes".into()), + ("allowed_file_types", "old.allowed_file_types".into()), + ( + // A database written before notifications were batched has no + // window of its own; it starts on the schema's own default + // rather than on zero, which would keep the old behaviour by + // accident and make the feature look broken. + "mail_batch_minutes", + if old_has_batch_window { + "old.mail_batch_minutes".into() + } else { + "5".to_string() + }, + ), + ("smtp_host", "old.smtp_host".into()), + ("smtp_port", "old.smtp_port".into()), + ("smtp_username", "old.smtp_username".into()), + ("smtp_password", "old.smtp_password".into()), + ("smtp_from_name", "old.smtp_from_name".into()), + ("smtp_from_address", "old.smtp_from_address".into()), + ("smtp_test_at", "old.smtp_test_at".into()), + ("smtp_test_ms", "old.smtp_test_ms".into()), + ("smtp_test_error", "old.smtp_test_error".into()), + ( + "smtp_check_at", + if old_has_smtp_check { + "old.smtp_check_at".into() + } else { + "NULL".into() + }, + ), + ( + "smtp_check_ms", + if old_has_smtp_check { + "old.smtp_check_ms".into() + } else { + "NULL".into() + }, + ), + ( + "smtp_check_error", + if old_has_smtp_check { + "old.smtp_check_error".into() + } else { + "NULL".into() + }, + ), + ("public_url", "old.public_url".into()), + ], + }); + + maps.push(TableMap { + name: "user", + columns: old_cols(&[ + "id", + "workspace_id", + "email", + "display_name", + "role", + "password_hash", + "invited_by", + "timezone", + "theme", + "language", + "ui", + "photo", + "photo_mime", + "created_at", + "last_signed_in_at", + ]), + }); + maps.push(TableMap { + name: "workspace_owner", + columns: old_cols(&["singleton", "user_id", "claimed_at"]), + }); + maps.push(TableMap { + name: "signin_link", + columns: old_cols(&["id", "user_id", "token_hash", "created_at", "expires_at", "used_at"]), + }); + maps.push(TableMap { + name: "session", + columns: old_cols(&["id", "user_id", "token_hash", "created_at", "expires_at", "revoked_at"]), + }); + maps.push(TableMap { + name: "auth_attempt", + columns: old_cols(&["id", "bucket", "attempted_at"]), + }); + maps.push(TableMap { + name: "board", + columns: old_cols(&["id", "workspace_id", "name", "task_prefix", "created_at"]), + }); + maps.push(TableMap { + name: "board_column", + columns: old_cols(&["id", "board_id", "name", "position", "is_done"]), + }); + // `tag` is seeded, not copied. + maps.push(TableMap { + name: "task", + columns: vec![ + ("id", "old.id".into()), + ("board_id", "old.board_id".into()), + ("parent_id", "old.parent_id".into()), + ("task_key", "old.task_key".into()), + ("title", "old.title".into()), + ("description", "old.description".into()), + ("column_id", "old.column_id".into()), + ( + "tag_id", + "(SELECT id FROM main.tag WHERE board_id = old.board_id AND is_default = 1)".into(), + ), + ("deadline", "old.deadline".into()), + ("position", "old.position".into()), + ("created_by", "old.created_by".into()), + ("created_at", "old.created_at".into()), + ("updated_at", "old.updated_at".into()), + ("done_at", "old.done_at".into()), + ("deleted_at", "old.deleted_at".into()), + ], + }); + maps.push(TableMap { + name: "task_assignee", + columns: old_cols(&["task_id", "user_id"]), + }); + maps.push(TableMap { + name: "task_watcher", + columns: old_cols(&["task_id", "user_id"]), + }); + maps.push(TableMap { + name: "task_dependency", + columns: old_cols(&[ + "blocked_task_id", + "blocking_task_id", + "created_at", + "cleared_at", + ]), + }); + maps.push(TableMap { + name: "comment", + columns: old_cols(&["id", "task_id", "author_id", "body", "created_at"]), + }); + maps.push(TableMap { + name: "attachment", + columns: old_cols(&[ + "id", + "task_id", + "comment_id", + "file_name", + "mime_type", + "size_bytes", + "bytes", + "uploaded_by", + "created_at", + ]), + }); + maps.push(TableMap { + name: "transition", + columns: old_cols(&[ + "id", + "task_id", + "from_column", + "to_column", + "actor_id", + "created_at", + ]), + }); + maps.push(TableMap { + name: "freeing", + columns: old_cols(&[ + "id", + "board_id", + "cause_key", + "cause_title", + "actor_id", + "created_at", + ]), + }); + maps.push(TableMap { + name: "activity", + columns: vec![ + ("id", "old.id".into()), + ("task_id", "old.task_id".into()), + ("actor_id", "old.actor_id".into()), + ("subject_id", "NULL".into()), + ("kind", "old.kind".into()), + ("detail", "old.detail".into()), + ("created_at", "old.created_at".into()), + ], + }); + maps.push(TableMap { + name: "mail_rule", + columns: old_cols(&[ + "id", + "board_id", + "trigger_kind", + "trigger_column", + "subject", + "audience", + "enabled", + "created_at", + "include_task_details", + ]), + }); + maps.push(TableMap { + name: "mail_send", + columns: old_cols(&[ + "id", + "rule_id", + "event_id", + "task_id", + "recipient", + "state", + "attempts", + "last_error", + "claimed_at", + "next_attempt_at", + "sent_at", + "kind", + "subject", + "body", + ]), + }); + maps.push(TableMap { + name: "mail_decision", + columns: old_cols(&[ + "id", + "rule_id", + "event_id", + "task_id", + "outcome", + "detail", + "created_at", + ]), + }); + + maps +} + +fn old_cols(cols: &[&'static str]) -> Vec<(&'static str, String)> { + cols.iter().map(|c| (*c, format!("old.{}", c))).collect() +} + +/// Returns true if the attached old `workspace` table already carries the +/// sender-check columns added by the old 0002 migration. +async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result { + let mut rows = conn + .query(&format!("PRAGMA table_info({table})"), ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? { + let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + if name == column { + return Ok(true); + } + } + Ok(false) +} + +/// Validates that every destination column is covered and that no map +/// references a column that does not exist. A missing column is a startup +/// error, never a silent NULL. +async fn validate_maps(conn: &Connection, maps: &[TableMap]) -> Result<()> { + use std::collections::HashSet; + + for map in maps { + let sql = format!("PRAGMA table_info({})", map.name); + let mut rows = conn + .query(&sql, ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let mut actual = HashSet::new(); + while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? { + let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + actual.insert(name); + } + + for (col, _) in &map.columns { + if !actual.contains(*col) { + return Err(StoreError::Backend(format!( + "reconcile map for {} references missing column {}", + map.name, col + ))); + } + } + for col in actual { + if !map.columns.iter().any(|(c, _)| c == &col) { + return Err(StoreError::Backend(format!( + "reconcile map for {} is missing column {} (would become NULL)", + map.name, col + ))); + } + } + } + Ok(()) +} + +/// Copies every mapped table from the attached old database into the new +/// main schema, in foreign-key-safe order. +async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> Result<()> { + let escaped = path.replace('\'', "''"); + new_conn + .execute(&format!("ATTACH DATABASE '{}' AS old", escaped), ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + let has_smtp_check = old_has_column(old_conn, "workspace", "smtp_check_at").await?; + let has_batch_window = + old_has_column(old_conn, "workspace", "mail_batch_minutes").await?; + let maps = build_maps(has_smtp_check, has_batch_window); + validate_maps(new_conn, &maps).await?; + + for map in maps { + // The `General` tags are seeded between `board` and `task`: they point + // at boards, so the boards must already be here, and the tasks that + // will point back at them must not be here yet. + if map.name == "task" { + seed_general_tags(old_conn, new_conn).await?; + } + let cols = map.columns.iter().map(|(c, _)| *c).collect::>().join(", "); + // `old` is the attached SCHEMA, not a table, so `old.id` in a select + // list reads as "table old, column id". The source table is aliased + // and the maps' `old.` prefix rewritten onto that alias. + let exprs = map + .columns + .iter() + .map(|(_, e)| e.replace("old.", "src.")) + .collect::>() + .join(", "); + let sql = format!( + "INSERT INTO main.{} ({}) SELECT {} FROM old.{} AS src", + map.name, cols, exprs, map.name + ); + new_conn + .execute(&sql, ()) + .await + .map_err(|e| StoreError::Backend(format!("{} while copying {}: {}", e, map.name, sql)))?; + } + + new_conn + .execute("DETACH DATABASE old", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + Ok(()) +} + +/// Verifies the rebuilt database before the swap. +async fn verify(old_conn: &Connection, new_conn: &Connection) -> Result<()> { + let mut rows = new_conn + .query("PRAGMA foreign_key_check", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let mut fk_errors = Vec::new(); + while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? { + let table: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + let rowid: i64 = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + let parent: String = row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?; + let fkid: i64 = row.get(3).map_err(|e| StoreError::Backend(e.to_string()))?; + fk_errors.push(format!( + "{} rowid {} references {} (foreign key {})", + table, rowid, parent, fkid + )); + } + if !fk_errors.is_empty() { + return Err(StoreError::Backend(format!( + "foreign key check failed:\n{}", + fk_errors.join("\n") + ))); + } + + let mut rows = new_conn + .query("PRAGMA integrity_check", ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let mut integrity = Vec::new(); + while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? { + let msg: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + integrity.push(msg); + } + if integrity.len() != 1 || integrity[0] != "ok" { + return Err(StoreError::Backend(format!( + "integrity check failed: {:?}", + integrity + ))); + } + + let tables = [ + "workspace", + "user", + "workspace_owner", + "signin_link", + "session", + "auth_attempt", + "board", + "board_column", + "task", + "task_assignee", + "task_watcher", + "task_dependency", + "comment", + "attachment", + "transition", + "freeing", + "activity", + "mail_rule", + "mail_send", + "mail_decision", + ]; + for table in tables { + let old_count = count_rows(old_conn, table).await?; + let new_count = count_rows(new_conn, table).await?; + if old_count != new_count { + return Err(StoreError::Backend(format!( + "row count mismatch for {}: old {} new {}", + table, old_count, new_count + ))); + } + } + + // `tag` is new: one default tag per board. + let board_count = count_rows(old_conn, "board").await?; + let tag_count = count_rows(new_conn, "tag").await?; + if tag_count != board_count { + return Err(StoreError::Backend(format!( + "tag row count {} does not match board count {}", + tag_count, board_count + ))); + } + + Ok(()) +} + +async fn count_rows(conn: &Connection, table: &str) -> Result { + let sql = format!("SELECT COUNT(*) FROM {}", table); + let mut rows = conn + .query(&sql, ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? else { + return Err(StoreError::Backend(format!( + "could not count rows in {}", + table + ))); + }; + row.get::(0).map_err(|e| StoreError::Backend(e.to_string())) +} + +fn cleanup_rebuilt(rebuilt_path: &str) { + let _ = std::fs::remove_file(rebuilt_path); + let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path)); + let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path)); +} + +/// Move a SQLite sidecar file (`-wal` or `-shm`) if it exists. A missing +/// sibling is fine: WAL mode may not have created one, and the backup is +/// still consistent without it. +fn rename_sibling(from: &str, to: &str, suffix: &str) { + let from_path = format!("{}{}", from, suffix); + let to_path = format!("{}{}", to, suffix); + if std::path::Path::new(&from_path).exists() { + let _ = std::fs::rename(&from_path, &to_path); + } +} + +fn backup_name(path: &str) -> Result { + let format = time::format_description::parse_borrowed::<2>( + "[year]-[month]-[day]T[hour][minute][second]Z", + ) + .map_err(|e| StoreError::Backend(format!("invalid time format: {}", e)))?; + let stamp = time::OffsetDateTime::now_utc() + .format(&format) + .map_err(|e| StoreError::Backend(format!("time format failed: {}", e)))?; + + let candidate = format!("{}.backup-{}", path, stamp); + if !std::path::Path::new(&candidate).exists() { + return Ok(candidate); + } + let mut n = 1; + loop { + let candidate = format!("{}.backup-{}-{}", path, stamp, n); + if !std::path::Path::new(&candidate).exists() { + return Ok(candidate); + } + n += 1; + if n > 1000 { + return Err(StoreError::Backend( + "could not find an unused backup name".into(), + )); + } + } +} + +#[cfg(test)] +mod tests { + use super::backup_name; + + #[test] + fn backup_name_has_no_colons_or_spaces() { + let name = backup_name("/tmp/izlek.db").unwrap(); + assert!(name.starts_with("/tmp/izlek.db.backup-")); + assert!(!name.contains(':')); + assert!(!name.contains(' ')); + } + + #[test] + fn backup_name_avoids_collision() { + let first = backup_name("/tmp/izlek.db").unwrap(); + std::fs::File::create(&first).unwrap(); + let second = backup_name("/tmp/izlek.db").unwrap(); + assert_ne!(first, second); + std::fs::remove_file(&first).unwrap(); + } +} diff --git a/crates/izlek-core/src/store/schema.rs b/crates/izlek-core/src/store/schema.rs new file mode 100644 index 0000000..bbed767 --- /dev/null +++ b/crates/izlek-core/src/store/schema.rs @@ -0,0 +1,360 @@ +//! Schema fingerprinting: compare the database SQLite actually has with the +//! declared whole schema in `migrations/0001_init.sql`. +//! +//! SQLite stores `CREATE` statements as written, comments and all, so two +//! databases built from the same logical schema but different comments or +//! whitespace would otherwise look different. The normaliser here strips the +//! cosmetic differences that do not change what the schema means. + +use super::{Result, StoreError}; +use turso::Connection; + +/// The declared whole schema, applied to an empty database. +pub(crate) const SCHEMA: &str = include_str!("../../migrations/0001_init.sql"); + +/// Reads and normalises the schema of the connected database. +/// +/// The fingerprint is a deterministic text built from `sqlite_master`: +/// `type|name|normalised_sql` for every non-sqlite object, ordered by type +/// and name. Two schemas that mean the same thing produce the same string; +/// two schemas that differ in tables, indexes, columns or constraints do not. +pub async fn fingerprint(conn: &Connection) -> Result { + let mut rows = conn + .query( + "SELECT type, name, sql FROM sqlite_master \ + WHERE name NOT LIKE 'sqlite_%' \ + ORDER BY type, name", + (), + ) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + + let mut out = String::new(); + while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? { + let t: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + let sql: Option = + row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?; + out.push_str(&t); + out.push('|'); + out.push_str(&name); + out.push('|'); + if let Some(sql) = sql { + out.push_str(&normalize_schema(&sql)); + } + out.push('\n'); + } + Ok(out) +} + +/// Builds an in-memory database from the declared schema and fingerprints it. +pub async fn declared_fingerprint() -> Result { + let db = turso::Builder::new_local(":memory:") + .build() + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?; + conn.execute_batch(SCHEMA) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + fingerprint(&conn).await +} + +/// A single schema object for diff reporting. +#[derive(Debug, Clone)] +pub(crate) struct SchemaObject { + pub(crate) kind: String, + pub(crate) name: String, + pub(crate) sql: String, +} + +/// Parses the normalised schema into objects keyed by (kind, name). +pub(crate) fn parse_objects(fingerprint: &str) -> Vec { + fingerprint + .lines() + .filter(|line| !line.is_empty()) + .filter_map(|line| { + let mut parts = line.splitn(3, '|'); + let kind = parts.next()?.to_string(); + let name = parts.next()?.to_string(); + let sql = parts.next().unwrap_or("").to_string(); + Some(SchemaObject { kind, name, sql }) + }) + .collect() +} + +/// Human-readable description of how two fingerprints differ. +pub(crate) fn diff_report(old: &str, new: &str) -> String { + let old_objs = parse_objects(old); + let new_objs = parse_objects(new); + + let mut missing = Vec::new(); + let mut extra = Vec::new(); + let mut changed = Vec::new(); + + for old_obj in &old_objs { + match new_objs.iter().find(|n| n.kind == old_obj.kind && n.name == old_obj.name) { + Some(new_obj) if new_obj.sql != old_obj.sql => changed.push((old_obj, new_obj)), + Some(_) => {} + None => missing.push(old_obj), + } + } + for new_obj in &new_objs { + if !old_objs.iter().any(|o| o.kind == new_obj.kind && o.name == new_obj.name) { + extra.push(new_obj); + } + } + + let mut lines = Vec::new(); + for obj in missing { + lines.push(format!("- {} {} (removed)", obj.kind, obj.name)); + } + for obj in extra { + lines.push(format!("+ {} {} (added)", obj.kind, obj.name)); + } + for (old_obj, new_obj) in changed { + lines.push(format!("~ {} {} (changed)", old_obj.kind, old_obj.name)); + if old_obj.kind == "table" { + let old_cols = extract_column_names(&old_obj.sql); + let new_cols = extract_column_names(&new_obj.sql); + let added: Vec<&str> = new_cols + .iter() + .filter(|c| !old_cols.contains(c)) + .map(String::as_str) + .collect(); + let removed: Vec<&str> = old_cols + .iter() + .filter(|c| !new_cols.contains(c)) + .map(String::as_str) + .collect(); + if !added.is_empty() { + lines.push(format!(" added columns: {}", added.join(", "))); + } + if !removed.is_empty() { + lines.push(format!(" removed columns: {}", removed.join(", "))); + } + } + } + + if lines.is_empty() { + "schemas differ (cosmetic normalisation only)".to_string() + } else { + lines.join("\n") + } +} + +/// Extracts the column names from a normalised CREATE TABLE statement. +/// Constraints at the table level are ignored; only top-level definitions +/// that start with an identifier are collected. +fn extract_column_names(sql: &str) -> Vec { + let body = match sql.strip_prefix("CREATE TABLE ") { + Some(rest) => rest, + None => return Vec::new(), + }; + let body = remove_if_not_exists(body); + let Some(start) = body.find('(') else { + return Vec::new(); + }; + let Some(end) = body.rfind(')') else { + return Vec::new(); + }; + let body = &body[start + 1..end]; + + let mut cols = Vec::new(); + let mut depth = 0i32; + let mut current = String::new(); + for ch in body.chars() { + match ch { + '(' => { + depth += 1; + current.push(ch); + } + ')' => { + depth -= 1; + current.push(ch); + } + ',' if depth == 0 => { + if let Some(col) = first_identifier(¤t) { + cols.push(col); + } + current.clear(); + } + _ => current.push(ch), + } + } + if !current.is_empty() { + if let Some(col) = first_identifier(¤t) { + cols.push(col); + } + } + cols +} + +fn first_identifier(item: &str) -> Option { + let item = item.trim(); + if item.is_empty() { + return None; + } + let first = item.split_whitespace().next()?; + let first = first.to_lowercase(); + if first == "constraint" + || first == "primary" + || first == "unique" + || first == "check" + || first == "foreign" + { + return None; + } + Some(first) +} + +/// Normalises SQL text so that cosmetic differences disappear. +/// +/// Differences deliberately ignored: +/// - whitespace runs collapse to a single space; +/// - SQL comments (`--` to end of line, `/* ... */`) are removed; +/// - `IF NOT EXISTS` is removed (case-insensitive, whole tokens only). +/// +/// Differences deliberately preserved: +/// - identifier case and spelling; +/// - string literal contents, including any whitespace or comment-like text +/// inside them; +/// - numeric literals, keyword order and constraint text. +fn normalize_schema(sql: &str) -> String { + let mut out = String::with_capacity(sql.len()); + let mut chars = sql.chars().peekable(); + let mut in_string = false; + let mut prev_ws = false; + + while let Some(ch) = chars.next() { + if in_string { + out.push(ch); + if ch == '\'' { + if chars.peek() == Some(&'\'') { + out.push(chars.next().unwrap()); + } else { + in_string = false; + } + } + continue; + } + + if ch == '-' && chars.peek() == Some(&'-') { + chars.next(); + while let Some(c) = chars.next() { + if c == '\n' { + break; + } + } + prev_ws = true; + continue; + } + + if ch == '/' && chars.peek() == Some(&'*') { + chars.next(); + while let Some(c) = chars.next() { + if c == '*' && chars.peek() == Some(&'/') { + chars.next(); + break; + } + } + prev_ws = true; + continue; + } + + if ch == '\'' { + in_string = true; + out.push(ch); + prev_ws = false; + continue; + } + + if ch.is_whitespace() { + prev_ws = true; + continue; + } + + if prev_ws && !out.is_empty() { + out.push(' '); + } + out.push(ch); + prev_ws = false; + } + + remove_if_not_exists(&out) +} + +/// Strips a normalised `IF NOT EXISTS` token sequence, preserving whitespace +/// around it. Because `normalize_schema` has already collapsed whitespace, the +/// sequence appears as separate tokens separated by single spaces. +fn remove_if_not_exists(sql: &str) -> String { + let tokens: Vec<&str> = sql.split(' ').collect(); + let mut out = Vec::with_capacity(tokens.len()); + let mut i = 0; + while i < tokens.len() { + if i + 2 < tokens.len() + && tokens[i].eq_ignore_ascii_case("IF") + && tokens[i + 1].eq_ignore_ascii_case("NOT") + && tokens[i + 2].eq_ignore_ascii_case("EXISTS") + { + i += 3; + } else { + out.push(tokens[i]); + i += 1; + } + } + out.join(" ") +} + +#[cfg(test)] +mod tests { + use super::{normalize_schema, parse_objects}; + + #[test] + fn comments_and_whitespace_do_not_change_meaning() { + let a = "CREATE TABLE foo (\n id INTEGER, -- the key\n name TEXT /* a comment */\n);"; + let b = "CREATE TABLE foo ( id INTEGER, name TEXT );"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn if_not_exists_is_ignored() { + let a = "CREATE TABLE IF NOT EXISTS foo (id INTEGER);"; + let b = "CREATE TABLE foo (id INTEGER);"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn string_literals_are_preserved() { + let a = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');"; + let b = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn real_differences_still_differ() { + let a = "CREATE TABLE foo (id INTEGER);"; + let b = "CREATE TABLE foo (id TEXT);"; + assert_ne!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn if_not_exists_does_not_corrupt_identifiers() { + // The stripper looks for whole tokens; words that merely appear + // inside identifiers or string literals must stay put. + let a = "CREATE TABLE IF NOT EXISTS notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');"; + let b = "CREATE TABLE notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');"; + assert_eq!(normalize_schema(a), normalize_schema(b)); + } + + #[test] + fn partial_index_where_clause_is_parsed_safely() { + // Partial-index SQL contains a WHERE clause; diff_report must not + // try to extract column names from it, and parsing must not panic. + let fp = "index|tag_one_default|CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1\n"; + let objs = parse_objects(fp); + assert_eq!(objs.len(), 1); + assert_eq!(objs[0].kind, "index"); + assert_eq!(objs[0].name, "tag_one_default"); + } +} diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 2a37888..460c275 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -7,7 +7,7 @@ use async_trait::async_trait; use rand::Rng; -use time::OffsetDateTime; +use time::{Duration, OffsetDateTime}; use time::format_description::well_known::Rfc3339; use turso::transaction::TransactionBehavior; use turso::{Builder, Connection, Row, Value, params}; @@ -15,32 +15,24 @@ use ulid::Ulid; use super::secret; use super::{ - ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion, - ClaimedSend, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, - MailSend, - NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState, - SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User, - Workspace, + ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten, + Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, + MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState, + SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger, + User, UserStats, Workspace, }; +use super::{reconcile, ReconcileOptions, schema}; use crate::Role; -use crate::live::{Change, Topic}; -use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition}; +use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition}; use crate::detail::{ ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine, SubtaskLine, TaskFacts, }; +use crate::live::{Change, Topic}; use time::Date; use time::format_description::BorrowedFormatItem; use time::macros::format_description; -/// Every migration, in order. There is one: nothing has been released, so a -/// schema change is made in `0001_init.sql` and the database recreated. A -/// second file is for the day there is data worth keeping. -const MIGRATIONS: &[(i64, &str)] = &[ - (1, include_str!("../../migrations/0001_init.sql")), - (2, include_str!("../../migrations/0002_sender_check.sql")), -]; - /// The board a fresh workspace gets, and its columns. `Done` is the column /// that stamps a card finished. const DEFAULT_BOARD_NAME: &str = "Board"; @@ -79,7 +71,10 @@ impl TursoStore { /// would fill the log with the sound of an idle app. fn announce(&self, topics: impl IntoIterator) { for topic in topics { - let _ = self.live.send(Change { topic, seq: crate::live::next_seq() }); + let _ = self.live.send(Change { + topic, + seq: crate::live::next_seq(), + }); } } @@ -87,6 +82,10 @@ impl TursoStore { /// up to date. `:memory:` gives a throwaway database for tests. pub async fn open(path: &str) -> Result { let existed = path != ":memory:" && std::path::Path::new(path).exists(); + // Before anything holds this file open: a database of an older shape is + // rebuilt now, while no handle of ours points at the file that the + // rebuild is about to replace. + Self::repair_if_stale(path).await?; let db = Builder::new_local(path).build().await.map_err(backend)?; let conn = db.connect().map_err(backend)?; // Turso is a single-writer engine. Two connections on one Database @@ -117,9 +116,21 @@ impl TursoStore { // the reader is told it lagged and resyncs, which is cheaper than the // memory a larger buffer would cost to avoid saying so. let (live, _) = tokio::sync::broadcast::channel(256); - let store = Self { conn: tokio::sync::Mutex::new(conn), db, key, live }; - store.migrate().await?; + let store = Self { + conn: tokio::sync::Mutex::new(conn), + db, + key, + live, + }; + store.migrate(path).await?; store.encrypt_plaintext_passwords().await?; + // The file may have been rebuilt from a backup; its permissions and + // any transient WAL/SHM siblings should still be private. + if path != ":memory:" { + restrict_if_present(std::path::Path::new(path))?; + restrict_if_present(&sibling(path, "-wal"))?; + restrict_if_present(&sibling(path, "-shm"))?; + } Ok(store) } @@ -151,107 +162,145 @@ impl TursoStore { } for (id, plaintext) in pending { let sealed = secret::seal(&self.key, &plaintext); - conn - .execute( - "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2", - params![sealed, id], - ) - .await - .map_err(backend)?; + conn.execute( + "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2", + params![sealed, id], + ) + .await + .map_err(backend)?; } Ok(()) } - async fn migrate(&self) -> Result<()> { - self.conn - .lock() - .await - .execute( - "CREATE TABLE IF NOT EXISTS schema_version ( - version INTEGER PRIMARY KEY, - applied_at TEXT NOT NULL - )", + /// Brings the database to the declared schema. + /// + /// - An empty database is created from `migrations/0001_init.sql`. + /// - A database that already matches the declared schema is left alone. + /// - A stale database is backed up, rebuilt, and re-verified once. + /// If the rebuilt database still does not match, the process stops + /// with the original backed up and untouched. + /// + /// SQLite's DDL is transactional, so a schema that dies halfway leaves + /// nothing behind: a half-created database is a boot that starts over, + /// not a database with a hole in it. + async fn migrate(&self, path: &str) -> Result<()> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT COUNT(*) FROM sqlite_master \ + WHERE type = 'table' AND name NOT LIKE 'sqlite_%'", (), ) .await .map_err(backend)?; + let empty = match rows.next().await.map_err(backend)? { + Some(row) => row.get::(0).map_err(backend)? == 0, + None => true, + }; + drop(rows); - let applied = self.applied_versions().await?; - for (version, sql) in MIGRATIONS { - if applied.contains(version) { - continue; + if empty { + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; + if let Err(e) = conn.execute_batch(super::schema::SCHEMA).await { + let _ = conn.execute("ROLLBACK", ()).await; + return Err(backend(e)); } - self.apply(*version, sql).await?; + return conn.execute("COMMIT", ()).await.map_err(backend).map(|_| ()); + } + + if path == ":memory:" { + // Tests own an in-memory database; its schema is whatever the + // test created, and the open should not try to reconcile it. + return Ok(()); + } + + // `repair_if_stale` ran before this handle was ever opened, so by now + // the file on disk matches. Saying so here is cheap and turns a + // reordering mistake into a refusal to start rather than a store + // running against a schema the code does not expect. + let have = schema::fingerprint(&conn).await.map_err(backend)?; + let want = schema::declared_fingerprint().await.map_err(backend)?; + if have != want { + return Err(StoreError::Backend(format!( + "database does not match the declared schema and was not repaired; \ + do not restart. diff:\n{}", + schema::diff_report(&have, &want) + ))); } Ok(()) } - /// One migration and the row that says it ran, in one transaction. + /// Brings a database of an older shape onto the declared schema, BEFORE + /// any long-lived handle is opened on it. /// - /// A migration is not only a thing that can fail: one that rebuilds a - /// table — which is how SQLite drops a CHECK or a foreign key — would - /// leave the table gone rather than merely unmigrated if it died between - /// the DROP and the RENAME. So the file and its `schema_version` row - /// commit together or not at all, and a half-applied migration is a boot - /// that starts over rather than a database with a hole in it. - /// - /// SQLite's DDL is transactional, which is what makes this possible at all. - async fn apply(&self, version: i64, sql: &str) -> Result<()> { - let conn = self.conn.lock().await; - conn - .execute("BEGIN IMMEDIATE", ()) - .await - .map_err(backend)?; - let written = async { - conn.execute_batch(sql).await?; - conn - .execute( - "INSERT INTO schema_version (version, applied_at) VALUES (?1, ?2)", - params![ - version, - now_text().map_err(|_| turso::Error::Misuse( - "the clock could not be read".to_string() - ))? - ], - ) - .await?; - Ok::<_, turso::Error>(()) + /// The order matters and is the whole reason this is not part of + /// `migrate`: `reconcile` swaps a rebuilt file into place, so a + /// `turso::Database` opened beforehand still refers to the file that is + /// now the backup. Reconnecting such a handle reads the old database and + /// makes a successful rebuild look like a failed one. + async fn repair_if_stale(path: &str) -> Result<()> { + if path == ":memory:" || !std::path::Path::new(path).exists() { + return Ok(()); } - .await; - match written { - Ok(()) => conn - .execute("COMMIT", ()) + let (have, empty) = { + let db = Builder::new_local(path).build().await.map_err(backend)?; + let conn = db.connect().map_err(backend)?; + let mut rows = conn + .query( + "SELECT COUNT(*) FROM sqlite_master \ + WHERE type = 'table' AND name NOT LIKE 'sqlite_%'", + (), + ) .await - .map_err(backend) - .map(|_| ()), - Err(e) => { - let _ = conn.execute("ROLLBACK", ()).await; - Err(backend(e)) - } + .map_err(backend)?; + let empty = match rows.next().await.map_err(backend)? { + Some(row) => row.get::(0).map_err(backend)? == 0, + None => true, + }; + drop(rows); + let have = if empty { + String::new() + } else { + schema::fingerprint(&conn).await.map_err(backend)? + }; + (have, empty) + }; + if empty { + return Ok(()); } - } - - async fn applied_versions(&self) -> Result> { - let conn = self.conn.lock().await; - let mut rows = conn - .query("SELECT version FROM schema_version", ()) - .await - .map_err(backend)?; - let mut out = Vec::new(); - while let Some(row) = rows.next().await.map_err(backend)? { - out.push(row.get::(0).map_err(backend)?); + let want = schema::declared_fingerprint().await.map_err(backend)?; + if have == want { + return Ok(()); } - Ok(out) - } - /// The schema version the database is actually at. - pub async fn schema_version(&self) -> Result { - Ok(self - .applied_versions() - .await? - .into_iter() - .max() - .unwrap_or(0)) + eprintln!( + "database schema differs from the declared schema; rebuilding automatically\n{}", + schema::diff_report(&have, &want) + ); + reconcile( + path, + ReconcileOptions { + dry_run: false, + yes: false, + auto: true, + }, + ) + .await?; + + // Check the result once, on a handle opened after the swap. A + // normalisation bug that rebuilt forever would otherwise write a + // full-size backup on every restart until the disk filled. + let db = Builder::new_local(path).build().await.map_err(backend)?; + let conn = db.connect().map_err(backend)?; + let after = schema::fingerprint(&conn).await.map_err(backend)?; + if after != want { + return Err(StoreError::Backend(format!( + "rebuild did not match the declared schema; the original is backed up beside it \ + and this is not retried. diff:\n{}", + schema::diff_report(&after, &want) + ))); + } + Ok(()) } /// A connection of its own, for work that opens a transaction. @@ -376,8 +425,8 @@ const DECISION_COLUMNS: &str = "id, rule_id, event_id, task_id, outcome, detail, fn decision_from(row: &Row) -> Result { let raw = text(row, 4)?; - let outcome = - MailOutcome::parse(&raw).ok_or_else(|| StoreError::Corrupt(format!("mail outcome {raw:?}")))?; + let outcome = MailOutcome::parse(&raw) + .ok_or_else(|| StoreError::Corrupt(format!("mail outcome {raw:?}")))?; Ok(MailDecision { id: text(row, 0)?, rule_id: text(row, 1)?, @@ -575,6 +624,7 @@ fn workspace_from(row: &Row) -> Result { attachment_limit_bytes: row.get::(3).map_err(backend)?.max(0) as u64, allowed_file_types, photo_limit_bytes: row.get::(5).map_err(backend)?.max(0) as u64, + mail_batch_minutes: row.get::(19).map_err(backend)?.max(0) as u32, smtp_host: opt_text(row, 6)?, smtp_port: row.get::>(7).map_err(backend)?, smtp_username: opt_text(row, 8)?, @@ -609,7 +659,7 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \ smtp_from_name, smtp_from_address, \ (smtp_password IS NOT NULL AND smtp_password <> ''), \ smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \ - smtp_check_at, smtp_check_ms, smtp_check_error"; + smtp_check_at, smtp_check_ms, smtp_check_error, mail_batch_minutes"; fn user_from(row: &Row) -> Result { Ok(User { @@ -723,7 +773,7 @@ impl Store for TursoStore { board_id.clone(), workspace_id.clone(), DEFAULT_BOARD_NAME, - now + now.clone(), ], ) .await?; @@ -741,6 +791,15 @@ impl Store for TursoStore { ) .await?; } + // Every task must wear a tag, so the board comes with the one + // that catches whatever loses its own — English, like the + // columns beside it. + tx.execute( + "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \ + VALUES (?1, ?2, 'General', 0, 1, ?3)", + params![Ulid::new().to_string(), board_id.clone(), now.clone()], + ) + .await?; Ok::<_, turso::Error>(()) } .await; @@ -803,26 +862,28 @@ impl Store for TursoStore { // Sealed here, not by the caller — the `Store` trait keeps passing // plaintext so nothing outside this file needs to know a cipher // exists. See `crate::store::secret`. - let sealed_password = sender.password.as_deref().map(|p| secret::seal(&self.key, p)); - conn - .execute( - "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ + let sealed_password = sender + .password + .as_deref() + .map(|p| secret::seal(&self.key, p)); + conn.execute( + "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \ smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \ smtp_test_error = NULL, smtp_check_at = NULL, smtp_check_ms = NULL, \ smtp_check_error = NULL WHERE id = ?7", - params![ - sender.host, - sender.port as i64, - sender.username, - sealed_password, - sender.from_name, - sender.from_address, - workspace_id - ], - ) - .await - .map_err(backend)?; + params![ + sender.host, + sender.port as i64, + sender.username, + sealed_password, + sender.from_name, + sender.from_address, + workspace_id + ], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Settings]); Ok(()) @@ -830,19 +891,18 @@ impl Store for TursoStore { async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()> { let conn = self.conn.lock().await; - conn - .execute( - "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \ + conn.execute( + "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \ smtp_check_error = ?3 WHERE id = ?4", - params![ - stamp(check.at)?, - check.took_ms as i64, - check.error, - workspace_id - ], - ) - .await - .map_err(backend)?; + params![ + stamp(check.at)?, + check.took_ms as i64, + check.error, + workspace_id + ], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Settings]); Ok(()) @@ -850,19 +910,18 @@ impl Store for TursoStore { async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()> { let conn = self.conn.lock().await; - conn - .execute( - "UPDATE workspace SET smtp_test_at = ?1, smtp_test_ms = ?2, \ + conn.execute( + "UPDATE workspace SET smtp_test_at = ?1, smtp_test_ms = ?2, \ smtp_test_error = ?3 WHERE id = ?4", - params![ - stamp(test.at)?, - test.took_ms as i64, - test.error, - workspace_id - ], - ) - .await - .map_err(backend)?; + params![ + stamp(test.at)?, + test.took_ms as i64, + test.error, + workspace_id + ], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Settings]); Ok(()) @@ -891,13 +950,12 @@ impl Store for TursoStore { async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()> { let conn = self.conn.lock().await; - conn - .execute( - "UPDATE workspace SET public_url = ?1 WHERE id = ?2", - params![public_url, workspace_id], - ) - .await - .map_err(backend)?; + conn.execute( + "UPDATE workspace SET public_url = ?1 WHERE id = ?2", + params![public_url, workspace_id], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Settings]); Ok(()) @@ -909,23 +967,24 @@ impl Store for TursoStore { attachment_limit_bytes: u64, photo_limit_bytes: u64, allowed_file_types: &[String], + mail_batch_minutes: u32, ) -> Result<()> { let conn = self.conn.lock().await; let types = serde_json::to_string(allowed_file_types) .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))?; - conn - .execute( - "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \ - allowed_file_types = ?3 WHERE id = ?4", - params![ - attachment_limit_bytes as i64, - photo_limit_bytes as i64, - types, - workspace_id - ], - ) - .await - .map_err(backend)?; + conn.execute( + "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \ + allowed_file_types = ?3, mail_batch_minutes = ?5 WHERE id = ?4", + params![ + attachment_limit_bytes as i64, + photo_limit_bytes as i64, + types, + workspace_id, + i64::from(mail_batch_minutes) + ], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Settings]); Ok(()) @@ -1018,6 +1077,46 @@ impl Store for TursoStore { } } + async fn user_stats(&self, user_id: &str) -> Result { + // One row of four scalars: a profile reads its whole summary in a + // single trip. `deleted_at` is excluded everywhere — a task off the + // board is off the person's page as well. + let row = self + .one_row( + "SELECT \ + (SELECT COUNT(*) FROM task_assignee a \ + JOIN task t ON t.id = a.task_id \ + JOIN board_column c ON c.id = t.column_id \ + WHERE a.user_id = ?1 AND t.deleted_at IS NULL AND c.is_done = 0), \ + (SELECT COUNT(*) FROM task_assignee a \ + JOIN task t ON t.id = a.task_id \ + JOIN board_column c ON c.id = t.column_id \ + WHERE a.user_id = ?1 AND t.deleted_at IS NULL AND c.is_done = 1), \ + (SELECT COUNT(*) FROM task WHERE created_by = ?1 AND deleted_at IS NULL), \ + (SELECT COUNT(*) FROM comment m JOIN task t ON t.id = m.task_id \ + WHERE m.author_id = ?1 AND t.deleted_at IS NULL)", + params![user_id], + ) + .await?; + let Some(row) = row else { + return Ok(UserStats { + assigned_open: 0, + assigned_done: 0, + created: 0, + comments: 0, + }); + }; + let at = |i: usize| -> Result { + row.get::(i).map_err(backend).map(|n| n.max(0) as u32) + }; + Ok(UserStats { + assigned_open: at(0)?, + assigned_done: at(1)?, + created: at(2)?, + comments: at(3)?, + }) + } + async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()> { let conn = self.conn.lock().await; let n = conn @@ -1125,7 +1224,13 @@ impl Store for TursoStore { params![email, user_id], ) .await - .map_err(|e| if is_constraint_violation(&e) { StoreError::Conflict("account") } else { backend(e) })?; + .map_err(|e| { + if is_constraint_violation(&e) { + StoreError::Conflict("account") + } else { + backend(e) + } + })?; if n == 0 { Err(StoreError::NotFound) } else { @@ -1355,13 +1460,12 @@ impl Store for TursoStore { // sign-in — traffic in exchange for a screen that would look identical. async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> { let conn = self.conn.lock().await; - conn - .execute( - "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)", - params![Ulid::new().to_string(), bucket, stamp(at)?], - ) - .await - .map_err(backend)?; + conn.execute( + "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)", + params![Ulid::new().to_string(), bucket, stamp(at)?], + ) + .await + .map_err(backend)?; Ok(()) } @@ -1382,25 +1486,23 @@ impl Store for TursoStore { async fn clear_auth_attempts(&self, bucket: &str) -> Result<()> { let conn = self.conn.lock().await; - conn - .execute( - "DELETE FROM auth_attempt WHERE bucket = ?1", - params![bucket], - ) - .await - .map_err(backend)?; + conn.execute( + "DELETE FROM auth_attempt WHERE bucket = ?1", + params![bucket], + ) + .await + .map_err(backend)?; Ok(()) } async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result { let conn = self.conn.lock().await; - conn - .execute( - "DELETE FROM auth_attempt WHERE attempted_at < ?1", - params![stamp(before)?], - ) - .await - .map_err(backend) + conn.execute( + "DELETE FROM auth_attempt WHERE attempted_at < ?1", + params![stamp(before)?], + ) + .await + .map_err(backend) } // -- board ------------------------------------------------------------- @@ -1414,14 +1516,13 @@ impl Store for TursoStore { ) -> Result { let conn = self.conn.lock().await; let id = Ulid::new().to_string(); - conn - .execute( - "INSERT INTO board_column (id, board_id, name, position, is_done) \ + conn.execute( + "INSERT INTO board_column (id, board_id, name, position, is_done) \ VALUES (?1, ?2, ?3, ?4, ?5)", - params![id.clone(), board_id, name, position, i64::from(is_done)], - ) - .await - .map_err(backend)?; + params![id.clone(), board_id, name, position, i64::from(is_done)], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Board]); Ok(Column { @@ -1500,6 +1601,20 @@ impl Store for TursoStore { drop(rows); let position = last + 1.0; + // A task always wears a tag, so one is chosen here when nobody + // named one: the board's default. The NOT NULL on `task.tag_id` + // makes choosing it the write's job, not an afterthought. + let mut rows = tx + .query( + "SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1", + params![new.board_id], + ) + .await?; + let default_tag = match rows.next().await? { + Some(row) => row.get::(0)?, + None => return Ok(Err(StoreError::NotFound)), + }; + drop(rows); // The key's tail is the end of this task's own id (a ULID — // Crockford-uppercase already, and the last chars are its random // bits) rather than a per-board counter: a counter leaves visible @@ -1512,8 +1627,8 @@ impl Store for TursoStore { match tx .execute( "INSERT INTO task (id, board_id, parent_id, task_key, title, description, \ - column_id, deadline, position, created_by, created_at, updated_at) \ - VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)", + column_id, tag_id, deadline, position, created_by, created_at, updated_at) \ + VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?12, ?7, ?8, ?9, ?10, ?10)", params![ id.clone(), new.board_id, @@ -1525,7 +1640,8 @@ impl Store for TursoStore { position, new.created_by, now.clone(), - new.parent_id + new.parent_id, + default_tag.clone() ], ) .await @@ -1539,8 +1655,8 @@ impl Store for TursoStore { } }; tx.execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, ?2, ?3, ?4, '', ?5)", + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)", params![ activity_id.clone(), id.clone(), @@ -1593,6 +1709,7 @@ impl Store for TursoStore { position, done_at: None, parent_id: new.parent_id.map(str::to_string), + tag: None, }, activity_id, transition: Transition { @@ -1717,6 +1834,7 @@ impl Store for TursoStore { position: row.get::(5).unwrap_or(0.0), done_at: opt_stamp(&row, 6)?, parent_id: Some(parent_id.to_string()), + tag: None, }); } Ok(out) @@ -1924,8 +2042,8 @@ impl Store for TursoStore { ) .await?; tx.execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, ?2, ?3, ?4, '', ?5)", + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)", params![ activity_id.clone(), task_id, @@ -1956,25 +2074,24 @@ impl Store for TursoStore { let conn = self.conn.lock().await; let id = Ulid::new().to_string(); let size = new.bytes.len() as i64; - conn - .execute( - "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \ + conn.execute( + "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \ size_bytes, bytes, uploaded_by, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", - params![ - id.clone(), - new.task_id, - new.comment_id, - new.file_name, - new.mime_type, - size, - new.bytes, - new.uploaded_by, - stamp(new.at)? - ], - ) - .await - .map_err(backend)?; + params![ + id.clone(), + new.task_id, + new.comment_id, + new.file_name, + new.mime_type, + size, + new.bytes, + new.uploaded_by, + stamp(new.at)? + ], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Task(new.task_id.to_string())]); Ok(id) @@ -2109,8 +2226,8 @@ impl Store for TursoStore { for (kind, detail) in lines { let id = Ulid::new().to_string(); tx.execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6)", params![id.clone(), task_id, actor_id, kind, detail, stamp.clone()], ) .await?; @@ -2289,8 +2406,8 @@ impl Store for TursoStore { .await?; tx.execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6)", params![ Ulid::new().to_string(), task_id, @@ -2413,8 +2530,8 @@ impl Store for TursoStore { .await?; let deleted_activity_id = Ulid::new().to_string(); tx.execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, ?2, ?3, ?4, '', ?5)", + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)", params![ deleted_activity_id.clone(), task_id, @@ -2446,8 +2563,8 @@ impl Store for TursoStore { continue; } tx.execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, ?2, NULL, ?3, ?4, ?5)", + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, ?2, NULL, NULL, ?3, ?4, ?5)", params![ Ulid::new().to_string(), blocked.clone(), @@ -2599,27 +2716,28 @@ impl Store for TursoStore { &self, task_id: &str, actor_id: Option<&str>, + subject_id: Option<&str>, kind: &ActivityKind, detail: &str, at: OffsetDateTime, ) -> Result { let conn = self.conn.lock().await; let id = Ulid::new().to_string(); - conn - .execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6)", - params![ - id.clone(), - task_id, - actor_id, - kind.as_str(), - detail, - stamp(at)? - ], - ) - .await - .map_err(backend)?; + conn.execute( + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + id.clone(), + task_id, + actor_id, + subject_id, + kind.as_str(), + detail, + stamp(at)? + ], + ) + .await + .map_err(backend)?; drop(conn); // Task-scoped: the task's own trail and the workspace feed both grew. self.announce([Topic::Activity, Topic::Task(task_id.to_string())]); @@ -2635,14 +2753,13 @@ impl Store for TursoStore { ) -> Result { let conn = self.conn.lock().await; let id = Ulid::new().to_string(); - conn - .execute( - "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ - VALUES (?1, NULL, ?2, ?3, ?4, ?5)", - params![id.clone(), actor_id, kind.as_str(), detail, stamp(at)?], - ) - .await - .map_err(backend)?; + conn.execute( + "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \ + VALUES (?1, NULL, ?2, NULL, ?3, ?4, ?5)", + params![id.clone(), actor_id, kind.as_str(), detail, stamp(at)?], + ) + .await + .map_err(backend)?; drop(conn); // Workspace-wide, belonging to no task — the feed only. self.announce([Topic::Activity]); @@ -2696,10 +2813,7 @@ impl Store for TursoStore { let sql = format!( "SELECT {RULE_COLUMNS} FROM mail_rule WHERE board_id = ?1 ORDER BY created_at, rowid" ); - let mut rows = conn - .query(&sql, params![board_id]) - .await - .map_err(backend)?; + let mut rows = conn.query(&sql, params![board_id]).await.map_err(backend)?; let mut out = Vec::new(); while let Some(row) = rows.next().await.map_err(backend)? { out.push(rule_from(&row)?); @@ -2799,7 +2913,7 @@ impl Store for TursoStore { match self .one_row( "SELECT activity.id, activity.task_id, task.board_id, activity.kind, \ - activity.actor_id, activity.detail, activity.created_at \ + activity.actor_id, activity.subject_id, activity.detail, activity.created_at \ FROM activity JOIN task ON task.id = activity.task_id \ WHERE activity.id = ?1", params![event_id], @@ -2812,8 +2926,9 @@ impl Store for TursoStore { board_id: text(&row, 2)?, kind: ActivityKind::parse(&text(&row, 3)?), actor_id: opt_text(&row, 4)?.unwrap_or_default(), - detail: text(&row, 5)?, - at: parse_stamp(&text(&row, 6)?)?, + subject_id: opt_text(&row, 5)?, + detail: text(&row, 6)?, + at: parse_stamp(&text(&row, 7)?)?, }))), None => Ok(None), } @@ -3187,14 +3302,13 @@ impl Store for TursoStore { async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()> { let conn = self.conn.lock().await; - conn - .execute( - "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \ + conn.execute( + "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \ WHERE id = ?2 AND state IN ('failed', 'abandoned')", - params![stamp(at)?, send_id], - ) - .await - .map_err(backend)?; + params![stamp(at)?, send_id], + ) + .await + .map_err(backend)?; drop(conn); self.announce([Topic::Queue]); Ok(()) @@ -3213,16 +3327,23 @@ impl Store for TursoStore { ) -> Result<()> { let conn = self.conn.lock().await; let id = Ulid::new().to_string(); - conn - .execute( - "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \ + conn.execute( + "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \ created_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \ ON CONFLICT (rule_id, event_id, task_id) DO NOTHING", - params![id, rule_id, event_id, task_id, outcome.as_str(), detail, stamp(at)?], - ) - .await - .map_err(backend)?; + params![ + id, + rule_id, + event_id, + task_id, + outcome.as_str(), + detail, + stamp(at)? + ], + ) + .await + .map_err(backend)?; drop(conn); // A decision is what the rules page's decisions tab renders. self.announce([Topic::Rules]); @@ -3449,7 +3570,9 @@ impl Store for TursoStore { FeedPage::Newest => { vals.extend(filter_vals); vals.push(i64::from(limit).into()); - format!("{SELECT} WHERE 1=1{filter_sql} ORDER BY a.created_at {base}, a.id {base} LIMIT ?") + format!( + "{SELECT} WHERE 1=1{filter_sql} ORDER BY a.created_at {base}, a.id {base} LIMIT ?" + ) } FeedPage::Before(cursor) => { // Further along in `dir`'s reading order: older when @@ -3596,6 +3719,51 @@ impl Store for TursoStore { recipients_from(&mut rows).await } + async fn hold_batch( + &self, + task_id: &str, + recipient: &str, + until: OffsetDateTime, + cap: Duration, + ) -> Result<()> { + let conn = self.conn.lock().await; + // Read the rows and their birth moments first: the ceiling is per + // row — the oldest mail in the batch is the one whose patience runs + // out — and expressing that in SQL over RFC 3339 text would be a + // date-format trick rather than a calculation. + let mut rows = conn + .query( + "SELECT id, claimed_at FROM mail_send \ + WHERE task_id = ?1 AND recipient = ?2 AND kind = 'rule' \ + AND state = 'pending' AND attempts = 0 \ + AND next_attempt_at IS NOT NULL", + params![task_id, recipient], + ) + .await + .map_err(backend)?; + let mut held = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + let id = text(&row, 0)?; + let born = parse_stamp(&text(&row, 1)?)?; + held.push((id, born)); + } + drop(rows); + for (id, born) in held { + let ceiling = born + cap; + let when = if until > ceiling { ceiling } else { until }; + conn.execute( + "UPDATE mail_send SET next_attempt_at = ?1 \ + WHERE id = ?2 AND state = 'pending' AND attempts = 0", + params![stamp(when)?, id], + ) + .await + .map_err(backend)?; + } + drop(conn); + self.announce([Topic::Queue]); + Ok(()) + } + async fn recipients_for_task_creator(&self, task_id: &str) -> Result> { let conn = self.conn.lock().await; let mut rows = conn @@ -3609,6 +3777,268 @@ impl Store for TursoStore { .map_err(backend)?; recipients_from(&mut rows).await } + + async fn recipient(&self, user_id: &str) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT u.id, u.email, u.display_name FROM user u \ + WHERE u.id = ?1 AND u.role <> ?2", + params![user_id, Role::Viewer.as_str()], + ) + .await + .map_err(backend)?; + Ok(recipients_from(&mut rows).await?.into_iter().next()) + } + + // -- tags -------------------------------------------------------------- + + async fn tags(&self, board_id: &str) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, board_id, name, position, is_default FROM tag WHERE board_id = ?1 \ + ORDER BY position", + params![board_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(Tag { + id: text(&row, 0)?, + board_id: text(&row, 1)?, + name: text(&row, 2)?, + position: row.get::(3).map_err(backend)?, + is_default: row.get::(4).map_err(backend)? != 0, + }); + } + Ok(out) + } + + async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result { + let id = Ulid::new().to_string(); + let now = stamp(at)?; + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + // A new tag lands at the end of the board's order. The name is the + // unique index's to police — a pre-read would only widen the race. + let written = async { + let mut rows = tx + .query( + "SELECT COALESCE(MAX(position), 0) FROM tag WHERE board_id = ?1", + params![board_id], + ) + .await?; + let position = match rows.next().await? { + Some(row) => row.get::(0).unwrap_or(0) + 1, + None => 1, + }; + drop(rows); + tx.execute( + "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \ + VALUES (?1, ?2, ?3, ?4, 0, ?5)", + params![id.clone(), board_id, name, position, now], + ) + .await?; + Ok::<_, turso::Error>(position) + } + .await; + + let position = match written { + Ok(position) => position, + Err(e) => { + let _ = tx.rollback().await; + return Err(if is_constraint_violation(&e) { + StoreError::Conflict("tag") + } else { + backend(e) + }); + } + }; + tx.commit().await.map_err(backend)?; + + self.announce([Topic::Board, Topic::Tags]); + Ok(Tag { + id, + board_id: board_id.to_string(), + name: name.to_string(), + position, + is_default: false, + }) + } + + async fn rename_tag(&self, tag_id: &str, name: &str) -> Result<()> { + let conn = self.conn.lock().await; + let n = conn + .execute( + "UPDATE tag SET name = ?1 WHERE id = ?2", + params![name, tag_id], + ) + .await + .map_err(|e| { + if is_constraint_violation(&e) { + StoreError::Conflict("tag") + } else { + backend(e) + } + })?; + if n == 0 { + return Err(StoreError::NotFound); + } + drop(conn); + self.announce([Topic::Board, Topic::Tags]); + Ok(()) + } + + async fn delete_tag(&self, tag_id: &str) -> Result<()> { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + // The default is the board's fallback, not a project anyone can + // retire: deleting it would leave its board's tasks nowhere to go. + // Any other tag's tasks move to that default, in the one write set: + // no task is ever seen pointing at a project that is not there. + let deleted = async { + let mut rows = tx + .query( + "SELECT board_id, is_default FROM tag WHERE id = ?1", + params![tag_id], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok::<_, turso::Error>(Err(StoreError::NotFound)); + }; + let board_id: String = row.get(0)?; + let is_default: i64 = row.get(1)?; + drop(rows); + if is_default != 0 { + return Ok(Err(StoreError::Conflict("default_tag"))); + } + tx.execute( + "UPDATE task SET tag_id = \ + (SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1) \ + WHERE tag_id = ?2", + params![board_id, tag_id], + ) + .await?; + tx.execute("DELETE FROM tag WHERE id = ?1", params![tag_id]) + .await?; + Ok(Ok(())) + } + .await; + match deleted { + Ok(Ok(())) => {} + Ok(Err(refused)) => { + let _ = tx.rollback().await; + return Err(refused); + } + Err(e) => { + let _ = tx.rollback().await; + return Err(backend(e)); + } + } + tx.commit().await.map_err(backend)?; + self.announce([Topic::Board, Topic::Tags]); + Ok(()) + } + + async fn move_tag(&self, tag_id: &str, up: bool) -> Result<()> { + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + let written = async { + let mut rows = tx + .query( + "SELECT board_id, position FROM tag WHERE id = ?1", + params![tag_id], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok::<_, turso::Error>(Err(StoreError::NotFound)); + }; + let board_id: String = row.get(0)?; + let position: i64 = row.get(1)?; + drop(rows); + let other = if up { position - 1 } else { position + 1 }; + let mut rows = tx + .query( + "SELECT id FROM tag WHERE board_id = ?1 AND position = ?2", + params![board_id, other], + ) + .await?; + let Some(neighbour) = rows.next().await? else { + // Already at that end of the order: nothing to swap, and that + // is not an error. + return Ok(Ok(())); + }; + let neighbour_id: String = neighbour.get(0)?; + drop(rows); + tx.execute( + "UPDATE tag SET position = ?1 WHERE id = ?2", + params![position, neighbour_id], + ) + .await?; + tx.execute( + "UPDATE tag SET position = ?1 WHERE id = ?2", + params![other, tag_id], + ) + .await?; + Ok(Ok(())) + } + .await; + match written { + Ok(Ok(())) => {} + Ok(Err(refused)) => { + let _ = tx.rollback().await; + return Err(refused); + } + Err(e) => { + let _ = tx.rollback().await; + return Err(backend(e)); + } + } + tx.commit().await.map_err(backend)?; + self.announce([Topic::Board, Topic::Tags]); + Ok(()) + } + + async fn set_task_tag(&self, task_id: &str, tag_id: &str) -> Result<()> { + // A tag not of this task's board is NotFound, not refused: the + // asker named a thing that is not one of this board's projects. + let known = self + .one_row( + "SELECT g.id FROM tag g JOIN task t ON t.board_id = g.board_id \ + WHERE g.id = ?1 AND t.id = ?2 AND t.deleted_at IS NULL", + params![tag_id, task_id], + ) + .await?; + if known.is_none() { + return Err(StoreError::NotFound); + } + let conn = self.conn.lock().await; + let n = conn + .execute( + "UPDATE task SET tag_id = ?1 WHERE id = ?2 AND deleted_at IS NULL", + params![tag_id, task_id], + ) + .await + .map_err(backend)?; + if n == 0 { + return Err(StoreError::NotFound); + } + drop(conn); + self.announce([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]); + Ok(()) + } } #[async_trait] @@ -3617,8 +4047,10 @@ impl DetailReads for TursoStore { let row = self .one_row( "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \ - t.done_at, t.description, t.board_id, b.workspace_id, t.parent_id \ - FROM task t JOIN board b ON b.id = t.board_id \ + t.done_at, t.description, t.board_id, b.workspace_id, t.parent_id, \ + t.tag_id, g.name \ + FROM task t LEFT JOIN tag g ON g.id = t.tag_id \ + JOIN board b ON b.id = t.board_id \ WHERE t.id = ?1 AND t.deleted_at IS NULL", params![task_id], ) @@ -3634,6 +4066,13 @@ impl DetailReads for TursoStore { position: row.get::(5).map_err(backend)?, done_at: opt_stamp(&row, 6)?, parent_id: opt_text(&row, 10)?, + tag: match opt_text(&row, 11)? { + Some(id) => Some(TagChip { + id, + name: text(&row, 12)?, + }), + None => None, + }, }, description: text(&row, 7)?, board_id: text(&row, 8)?, @@ -3922,8 +4361,10 @@ impl BoardReads for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT id, task_key, title, column_id, deadline, position, done_at, parent_id \ - FROM task WHERE board_id = ?1 AND deleted_at IS NULL", + "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \ + t.done_at, t.parent_id, t.tag_id, g.name \ + FROM task t LEFT JOIN tag g ON g.id = t.tag_id \ + WHERE t.board_id = ?1 AND t.deleted_at IS NULL", params![board_id], ) .await @@ -3939,6 +4380,13 @@ impl BoardReads for TursoStore { position: row.get::(5).map_err(backend)?, done_at: opt_stamp(&row, 6)?, parent_id: opt_text(&row, 7)?, + tag: match opt_text(&row, 8)? { + Some(id) => Some(TagChip { + id, + name: text(&row, 9)?, + }), + None => None, + }, }); } Ok(out) @@ -4209,47 +4657,3 @@ mod probe { let _ = std::fs::remove_dir_all(&dir); } } - -#[cfg(test)] -mod migration { - use super::*; - - /// A migration that dies halfway leaves nothing behind — not a table it - /// created, and not a version row saying it ran. 0005 drops `mail_send` - /// before it renames the rebuilt table into place, so a migration that can - /// only half-apply is a migration that can lose the mail ledger. - #[tokio::test] - async fn a_migration_that_fails_partway_leaves_nothing_behind() { - let dir = std::env::temp_dir().join(format!("izlek-migration-{}", Ulid::new())); - std::fs::create_dir_all(&dir).unwrap(); - let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap()) - .await - .unwrap(); - let before = store.schema_version().await.unwrap(); - - let broken = "CREATE TABLE half_applied (id TEXT);\n\ - INSERT INTO no_such_table (id) VALUES ('x');"; - assert!( - store.apply(before + 1, broken).await.is_err(), - "the second statement cannot succeed" - ); - - assert_eq!( - store.schema_version().await.unwrap(), - before, - "a failed migration is not recorded as applied" - ); - assert!( - store - .one_row( - "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'half_applied'", - (), - ) - .await - .unwrap() - .is_none(), - "and the table its first statement created is rolled back with it" - ); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/crates/izlek-core/tests/fixtures/pre-collapse/0001_init.sql b/crates/izlek-core/tests/fixtures/pre-collapse/0001_init.sql new file mode 100644 index 0000000..302abac --- /dev/null +++ b/crates/izlek-core/tests/fixtures/pre-collapse/0001_init.sql @@ -0,0 +1,391 @@ +-- Izlek's schema, whole, in one file. +-- +-- Plain versioned SQL applied at boot: Turso has no migration runner of its +-- own, and keeping the schema as SQL is what makes the store trait swappable. +-- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by +-- creation, and Crockford-uppercase already, which is what lets a task key +-- borrow its tail. +-- +-- This file is the whole schema, not the first link of a chain. Nothing has +-- been released, so a change to a table is made here, in the table, and the +-- database it describes is recreated — twenty migrations were collapsed into +-- this file once for that reason, and a twenty-first would start the same rot +-- over. The reasoning the old migrations carried is kept, on the tables it +-- explains. The day Izlek runs somewhere with data worth keeping, the next +-- change becomes 0002 and this note goes away. + +CREATE TABLE workspace ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + created_at TEXT NOT NULL, + -- Limits. Each states its consequence in the UI, not here. They are + -- workspace content — an admin edits them, and no restart should be + -- needed to raise an attachment ceiling. + attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400, + photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, + -- JSON array of allowed extensions. An empty array means every type. + allowed_file_types TEXT NOT NULL DEFAULT '[]', + -- The single sender every mail in the workspace goes through, written by + -- the admin in Settings rather than by whoever has a shell on the box: a + -- three-person team has those be different people, and the second one is + -- not always awake. + -- + -- `smtp_password` holds ciphertext, never the typed string. The server + -- has to present the password to the mail host on every send, so a + -- one-way hash is impossible; instead `store::secret` seals it under a + -- key kept in `izlek.key` beside this file, so a database copied for a + -- backup does not carry a working credential with it. No field on + -- `Workspace` exposes it — it is written by `Store::set_sender` and read + -- by `Store::smtp_password`, which only the mailer calls. + smtp_host TEXT, + smtp_port INTEGER, + smtp_username TEXT, + smtp_password TEXT, + smtp_from_name TEXT, + smtp_from_address TEXT, + -- The result of the last "send a test mail to myself", kept rather than + -- shown once: an admin fills the sender in, presses the button, and comes + -- back tomorrow wondering whether it ever worked. `smtp_test_error` is the + -- mail server's own words, so the admin can act on them; the mailer builds + -- its errors from what the server said, never from the credentials it sent. + smtp_test_at TEXT, + smtp_test_ms INTEGER, + smtp_test_error TEXT, + -- The address mail links point at, when the one the process was + -- configured with is not the one people reach. A box behind a proxy + -- answers on localhost and is known by a public name, and only an admin + -- knows which — so it is workspace content, and `config/izlek.toml`'s + -- `base_url` is what an empty one falls back to. + public_url TEXT +); + +CREATE TABLE user ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspace(id), + email TEXT NOT NULL, + display_name TEXT NOT NULL, + -- 'admin' | 'member' | 'viewer' + role TEXT NOT NULL, + -- NULL until the person picks a password on first sign-in. The admin + -- creates the account with a name and an address and nothing else. + password_hash TEXT, + -- Whoever made this account, so the first-sign-in screen can greet the + -- invited person by the inviter's name instead of reading their own name + -- back to them. NULL for the first account, which nobody invited. A + -- reference rather than a copied name, so a later rename is reflected. + invited_by TEXT REFERENCES user(id), + -- Display preferences. Stored data everywhere else stays UTC and + -- language-neutral; these only change how a browser renders it for the + -- one person signed in as this user, and nothing stored depends on them. + timezone TEXT NOT NULL DEFAULT 'UTC', + theme TEXT NOT NULL DEFAULT 'light', + language TEXT NOT NULL DEFAULT 'en', + ui TEXT NOT NULL DEFAULT 'instrument', + -- The profile picture lives here as bytes, the way an attachment does: + -- no filesystem path survives a backup or a move. + photo BLOB, + photo_mime TEXT, + created_at TEXT NOT NULL, + last_signed_in_at TEXT +); +CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email); + +-- One workspace, one owner. The singleton column is the whole point: the row +-- can exist at most once, so a second claim cannot race a first one. +CREATE TABLE workspace_owner ( + singleton INTEGER PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + claimed_at TEXT NOT NULL +); + +-- First sign-in / resend links. Only the hash is stored: the plaintext is +-- shown once when the admin creates or resends it. +CREATE TABLE signin_link ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + token_hash TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + used_at TEXT +); +CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash); + +CREATE TABLE session ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + token_hash TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + revoked_at TEXT +); +CREATE UNIQUE INDEX session_token ON session(token_hash); +CREATE INDEX session_by_user ON session(user_id); + +-- The rate-limit ledger: one row per attempt, pruned by age. +CREATE TABLE auth_attempt ( + id TEXT PRIMARY KEY, + bucket TEXT NOT NULL, + attempted_at TEXT NOT NULL +); +CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at); + +CREATE TABLE board ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL REFERENCES workspace(id), + name TEXT NOT NULL, + -- The key prefix this board's tasks carry (`DZ-14`). + task_prefix TEXT NOT NULL DEFAULT 'DZ', + created_at TEXT NOT NULL +); + +CREATE TABLE board_column ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + name TEXT NOT NULL, + position INTEGER NOT NULL, + -- The column a finished task lands in; drives the "done Aug 14" card state. + is_done INTEGER NOT NULL DEFAULT 0 +); + +-- A task, and a subtask, which is the same thing with a parent. +-- +-- `parent_id` is the whole of the subtask feature in this schema: a subtask +-- has every column a task has, so it carries assignees, a deadline, comments, +-- files, activity and mail exactly like anything else, and promoting one to +-- a task of its own is a single UPDATE rather than a move between tables. +-- +-- Two rules the column cannot state itself, enforced in the store instead: +-- a parent must have `parent_id IS NULL` (one level, never a tree), and a +-- child sits on its parent's board. SQLite cannot ask, in a CHECK, whether +-- the row a foreign key points at has a NULL parent. +-- +-- The board shows only rows with no parent; a subtask reaches its own detail +-- page through its parent's. +CREATE TABLE task ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + parent_id TEXT REFERENCES task(id), + -- Human key from the mockups, e.g. DZ-14. The tail is the end of the + -- task's own ULID rather than a per-board counter: a counter leaves + -- visible gaps once tasks are deleted. + task_key TEXT NOT NULL, + title TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + column_id TEXT NOT NULL REFERENCES board_column(id), + deadline TEXT, + position REAL NOT NULL DEFAULT 0, + created_by TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + done_at TEXT, + deleted_at TEXT +); +CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key); +CREATE INDEX task_by_column ON task(column_id); +CREATE INDEX task_by_parent ON task(parent_id); + +CREATE TABLE task_assignee ( + task_id TEXT NOT NULL REFERENCES task(id), + user_id TEXT NOT NULL REFERENCES user(id), + PRIMARY KEY (task_id, user_id) +); + +CREATE TABLE task_watcher ( + task_id TEXT NOT NULL REFERENCES task(id), + user_id TEXT NOT NULL REFERENCES user(id), + PRIMARY KEY (task_id, user_id) +); + +-- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the +-- blocking task finishes, which is what the "you can start now" rule reads. +-- +-- The CHECK is new: a task blocking itself was only ever stopped in +-- application code, and a row like that would make a card permanently and +-- unfixably blocked by its own existence. +CREATE TABLE task_dependency ( + blocked_task_id TEXT NOT NULL REFERENCES task(id), + blocking_task_id TEXT NOT NULL REFERENCES task(id), + created_at TEXT NOT NULL, + cleared_at TEXT, + PRIMARY KEY (blocked_task_id, blocking_task_id), + CHECK (blocked_task_id <> blocking_task_id) +); +-- The primary key answers "what is this task waiting on"; the other +-- direction — "who is waiting on this one", which every finish and every +-- delete asks — has no prefix of it to use. +CREATE INDEX task_dependency_by_blocking ON task_dependency(blocking_task_id); + +CREATE TABLE comment ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + author_id TEXT NOT NULL REFERENCES user(id), + body TEXT NOT NULL, + created_at TEXT NOT NULL +); +CREATE INDEX comment_by_task ON comment(task_id); + +-- Attachments live in the database file, not on disk beside it. +-- +-- Izlek is one process over one file, and a second place to keep state is a +-- second thing to back up, to lock, and to get out of step with the rows that +-- name it. And a path is exactly where an uploaded file name must never end +-- up: `../../etc` is a valid file name and a terrible path. Keeping the bytes +-- here means `file_name` is only ever a label printed on a chip, never +-- anything the server resolves. +CREATE TABLE attachment ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + comment_id TEXT REFERENCES comment(id), + file_name TEXT NOT NULL, + mime_type TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + bytes BLOB NOT NULL, + uploaded_by TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); +CREATE INDEX attachment_by_task ON attachment(task_id); + +-- 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. +-- +-- `from_column` deliberately carries no REFERENCES: a task created straight +-- into a column writes a transition with `from_column = ''`, meaning "created +-- into", so a rule watching that column fires for a new card and not only for +-- one dragged in later. No column's id is ever ''. +CREATE TABLE transition ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + from_column TEXT NOT NULL, + 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); + +-- A deletion that let other tasks go, recorded as a fact. +-- +-- The unblocked rule has two causes and only one of them is a crossing: a +-- blocker can finish, or a blocker can be deleted. The crossing already has a +-- row in `transition`; the deletion had nowhere to be written, so a mail owed +-- because of one had no event to hang from and no way to be rebuilt on a +-- retry. This is that row. +-- +-- `cause_key` and `cause_title` are copied rather than joined: the task they +-- name is deleted, and a mail sent an hour later still has to be able to say +-- which task it was. +CREATE TABLE freeing ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + cause_key TEXT NOT NULL, + cause_title TEXT NOT NULL, + actor_id TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); +CREATE INDEX freeing_by_board ON freeing(board_id, created_at); + +-- The activity strip in the task detail: who did what. `task_id` is nullable +-- because account and admin events — sign-ins, invites, role changes — have +-- no task to sit under, and still have to be loggable. +CREATE TABLE activity ( + id TEXT PRIMARY KEY, + task_id TEXT REFERENCES task(id), + actor_id TEXT REFERENCES user(id), + kind TEXT NOT NULL, + detail TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL +); +CREATE INDEX activity_by_task ON activity(task_id); +CREATE INDEX activity_recent ON activity(created_at); + +-- Mail rules are written only by the admin. +-- +-- `trigger_kind` carries no CHECK on purpose: the set of triggers grows +-- without a schema change. `audience` does carry one, because those three +-- values are the only audiences the engine knows how to resolve. +CREATE TABLE mail_rule ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + trigger_kind TEXT NOT NULL, + trigger_column TEXT REFERENCES board_column(id), + subject TEXT NOT NULL, + -- 'assignees' — the people the card points at; 'board' — everyone who can + -- write on the board; 'creator' — whoever opened the card. + audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board', 'creator')), + enabled INTEGER NOT NULL DEFAULT 1, + -- Fold the task's own facts into the body instead of the subject line + -- being all the recipient reads. Off by default. + include_task_details INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + -- Only a status rule names a column, and a status rule that names none + -- watches every column. The check is here so a rule that names a column + -- it could not act on cannot be stored at all. + CHECK (trigger_column IS NULL OR trigger_kind = 'status') +); +CREATE INDEX mail_rule_by_board ON mail_rule(board_id); + +-- One row per mail owed, from the moment it is claimed until it is sent or +-- abandoned. +-- +-- Three shapes share the table. A 'rule' send is owed to somebody because a +-- rule matched an event on a task, and carries all three. An 'invite' or a +-- 'notice' has none of them — a person is invited before they have a task, a +-- transition, or a rule to owe them anything — and carries its own subject +-- and body instead of getting them from `mail_rule`. The two CHECKs make the +-- shapes exclusive, so a half-built row cannot be stored. +-- +-- `event_id` names a transition or a freeing without a foreign key: two +-- tables can cause a send, so the column cannot point at either and hold both. +CREATE TABLE mail_send ( + id TEXT PRIMARY KEY, + rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE, + event_id TEXT, + task_id TEXT REFERENCES task(id), + recipient TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + claimed_at TEXT NOT NULL, + next_attempt_at TEXT, + sent_at TEXT, + kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')), + subject TEXT, + body TEXT, + CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)), + CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL)) +); +CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient); +CREATE INDEX mail_send_owed ON mail_send(next_attempt_at); +CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at); +-- The task's own mail strip reads by task, which neither index above starts +-- with: both lead on `rule_id`, and an invite has none. +CREATE INDEX mail_send_by_task ON mail_send(task_id); + +-- What the mail engine decided, for every rule and every event, not just the +-- mails it sent. +-- +-- `mail_send` only exists once a mail is owed and claimed; a card that moved +-- but matched no rule, a rule that was disabled, a task deleted before its +-- mail could go out — none of that left a trace. This is that trace, so "why +-- did nobody get mailed" has an answer that is not "look at the logs from +-- that day". +-- +-- `task_id` carries no foreign key on purpose: a `task_gone` row exists +-- precisely because the task it names no longer does, and it has to keep +-- saying so afterwards. +CREATE TABLE mail_decision ( + id TEXT PRIMARY KEY, + rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE, + event_id TEXT NOT NULL, + task_id TEXT NOT NULL, + outcome TEXT NOT NULL CHECK (outcome IN + ('owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone')), + detail TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL +); +CREATE UNIQUE INDEX mail_decision_once ON mail_decision(rule_id, event_id, task_id); +CREATE INDEX mail_decision_recent ON mail_decision(created_at); +CREATE INDEX mail_decision_by_task ON mail_decision(task_id); diff --git a/crates/izlek-core/migrations/0002_sender_check.sql b/crates/izlek-core/tests/fixtures/pre-collapse/0002_sender_check.sql similarity index 100% rename from crates/izlek-core/migrations/0002_sender_check.sql rename to crates/izlek-core/tests/fixtures/pre-collapse/0002_sender_check.sql diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 6dec664..2902f4c 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -9,8 +9,8 @@ use std::path::PathBuf; use izlek_core::Role; use izlek_core::auth::{Token, hash_password}; use izlek_core::store::{ - Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, - SendState, Store, StoreError, Trigger, TursoStore, User, + Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState, + Store, StoreError, Trigger, TursoStore, User, }; use time::{Duration, OffsetDateTime}; use ulid::Ulid; @@ -95,24 +95,19 @@ async fn member(store: &TursoStore, workspace_id: &str, email: &str, name: &str) } #[tokio::test] -async fn migrations_apply_once_and_survive_reopen() { +async fn the_schema_is_created_once_and_survives_reopen() { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - // Whatever the newest migration is — pinning the number here only means - // editing this line every time one is added, which tests the constant - // rather than the behaviour. - let applied = first.schema_version().await.unwrap(); - assert!(applied >= 1, "no migration applied at all"); claim(&first).await; drop(first); - // Re-opening must not re-run a migration (0001's CREATE TABLE would fail) - // and must not lose what the first open wrote. + // Re-opening a database that already has tables must not re-run the + // schema (its CREATE TABLE would fail on the first one) and must not + // lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), applied); assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek"); drop(second); let _ = std::fs::remove_dir_all(&dir); @@ -169,7 +164,15 @@ async fn subtasks_go_one_level_deep() { let board = scratch.store.board(&workspace).await.unwrap().unwrap(); let column_id = column_named(&scratch.store, &workspace, "Backlog").await; - let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await; + let parent = add_task( + &scratch.store, + &workspace, + "Backlog", + "Parent", + None, + &admin, + ) + .await; let child = scratch .store .create_task(NewTask { @@ -238,10 +241,22 @@ async fn a_task_cannot_be_its_own_parent() { async fn parenting_and_promoting_are_each_one_write() { let scratch = Scratch::open().await; let (workspace, admin) = claim(&scratch.store).await; - let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await; + let parent = add_task( + &scratch.store, + &workspace, + "Backlog", + "Parent", + None, + &admin, + ) + .await; let loose = add_task(&scratch.store, &workspace, "Review", "Loose", None, &admin).await; - scratch.store.set_parent(&loose, Some(&parent)).await.unwrap(); + scratch + .store + .set_parent(&loose, Some(&parent)) + .await + .unwrap(); let children = scratch.store.subtasks(&parent).await.unwrap(); assert_eq!(children.len(), 1); assert_eq!(children[0].id, loose); @@ -277,7 +292,15 @@ async fn a_parent_and_one_subtask( workspace: &str, admin: &str, ) -> (String, String) { - let parent = add_task(store, workspace, "Backlog", "Ship the exporter", None, admin).await; + let parent = add_task( + store, + workspace, + "Backlog", + "Ship the exporter", + None, + admin, + ) + .await; let board = store.board(workspace).await.unwrap().unwrap(); let column_id = column_named(store, workspace, "Backlog").await; let child = store @@ -328,7 +351,15 @@ async fn a_parent_does_not_finish_before_its_subtasks_do() { ); // The subtask finishing is what lets the parent through. - moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await; + moved_to( + &scratch.store, + &workspace, + &child, + "Backlog", + "Done", + &admin, + ) + .await; let recorded = scratch .store .move_task(&parent, &backlog, &done, &admin, OffsetDateTime::now_utc()) @@ -379,7 +410,15 @@ async fn a_subtask_finishes_on_its_own_account() { let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await; // The rule is about a parent's parts, not about being somebody's part. - moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await; + moved_to( + &scratch.store, + &workspace, + &child, + "Backlog", + "Done", + &admin, + ) + .await; } #[tokio::test] @@ -395,7 +434,15 @@ async fn a_deleted_subtask_stops_holding_its_parent() { .delete_task(&child, &admin, OffsetDateTime::now_utc()) .await .unwrap(); - moved_to(&scratch.store, &workspace, &parent, "Backlog", "Done", &admin).await; + moved_to( + &scratch.store, + &workspace, + &parent, + "Backlog", + "Done", + &admin, + ) + .await; } #[tokio::test] @@ -405,7 +452,15 @@ async fn a_promoted_subtask_stops_holding_its_parent() { let (parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await; scratch.store.set_parent(&child, None).await.unwrap(); - moved_to(&scratch.store, &workspace, &parent, "Backlog", "Done", &admin).await; + moved_to( + &scratch.store, + &workspace, + &parent, + "Backlog", + "Done", + &admin, + ) + .await; } #[tokio::test] @@ -424,7 +479,15 @@ async fn the_board_counts_subtasks_instead_of_carding_them() { assert_eq!(cards[0].subtask_label().as_deref(), Some("0/1")); assert!(cards[0].holds_on_subtasks()); - moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await; + moved_to( + &scratch.store, + &workspace, + &child, + "Backlog", + "Done", + &admin, + ) + .await; let board = load(&scratch.store, &workspace).await.unwrap().unwrap(); let card = board .columns @@ -453,7 +516,15 @@ async fn a_subtask_blocking_a_card_still_names_itself_on_it() { let scratch = Scratch::open().await; let (workspace, admin) = claim(&scratch.store).await; let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await; - let other = add_task(&scratch.store, &workspace, "Backlog", "Waiting", None, &admin).await; + let other = add_task( + &scratch.store, + &workspace, + "Backlog", + "Waiting", + None, + &admin, + ) + .await; scratch .store .add_dependency(&other, &child, OffsetDateTime::now_utc()) @@ -699,9 +770,9 @@ async fn many_concurrent_callers_never_see_concurrent_use_forbidden() { } for task in tasks { - task.await - .unwrap() - .expect("concurrent store access must never surface Misuse(\"concurrent use forbidden\")"); + task.await.unwrap().expect( + "concurrent store access must never surface Misuse(\"concurrent use forbidden\")", + ); } drop(store); @@ -784,7 +855,11 @@ async fn a_save_with_no_password_typed_keeps_the_stored_one() { from_name: "İzlek".into(), from_address: "izlek@izlek.sh".into(), }; - scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap(); + scratch + .store + .set_sender(&ws_id, sender.clone()) + .await + .unwrap(); sender.port = 465; sender.password = None; @@ -794,7 +869,12 @@ async fn a_save_with_no_password_typed_keeps_the_stored_one() { assert_eq!(ws.smtp_port, Some(465), "the edit did not land"); assert!(ws.smtp_password_set, "the password was blanked by an edit"); assert_eq!( - scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + scratch + .store + .smtp_password(&ws_id) + .await + .unwrap() + .as_deref(), Some("keep-me") ); } @@ -812,12 +892,21 @@ async fn a_typed_password_replaces_the_stored_one() { from_name: "İzlek".into(), from_address: "izlek@izlek.sh".into(), }; - scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap(); + scratch + .store + .set_sender(&ws_id, sender.clone()) + .await + .unwrap(); sender.password = Some("the-new-one".into()); scratch.store.set_sender(&ws_id, sender).await.unwrap(); assert_eq!( - scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + scratch + .store + .smtp_password(&ws_id) + .await + .unwrap() + .as_deref(), Some("the-new-one") ); } @@ -846,7 +935,10 @@ async fn the_stored_password_is_not_the_plaintext_on_disk() { let conn = raw_conn(&scratch).await; let mut rows = conn - .query("SELECT smtp_password FROM workspace WHERE id = ?1", turso::params![ws_id.clone()]) + .query( + "SELECT smtp_password FROM workspace WHERE id = ?1", + turso::params![ws_id.clone()], + ) .await .unwrap(); let row = rows.next().await.unwrap().unwrap(); @@ -855,11 +947,19 @@ async fn the_stored_password_is_not_the_plaintext_on_disk() { !column.contains("a-very-secret-string"), "the plaintext is sitting in the column: {column}" ); - assert!(column.starts_with("v1:"), "expected the sealed envelope, got: {column}"); + assert!( + column.starts_with("v1:"), + "expected the sealed envelope, got: {column}" + ); // And the read path still gets the real password back. assert_eq!( - scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + scratch + .store + .smtp_password(&ws_id) + .await + .unwrap() + .as_deref(), Some("a-very-secret-string") ); } @@ -921,7 +1021,12 @@ async fn a_password_that_will_not_decrypt_reads_back_as_none() { .await .unwrap(); assert_eq!( - scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), + scratch + .store + .smtp_password(&ws_id) + .await + .unwrap() + .as_deref(), Some("a-fresh-password"), "retyping the password heals a store that could not decrypt it" ); @@ -942,7 +1047,12 @@ async fn the_database_and_key_file_are_owner_only() { .permissions() .mode() & 0o777; - assert_eq!(mode, 0o600, "{} is not owner-only: {mode:o}", path.display()); + assert_eq!( + mode, + 0o600, + "{} is not owner-only: {mode:o}", + path.display() + ); } } @@ -952,7 +1062,7 @@ async fn limits_round_trip_including_the_file_type_list() { let types = vec!["png".to_string(), "pdf".to_string()]; scratch .store - .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types) + .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types, 5) .await .unwrap(); let ws = scratch.store.workspace().await.unwrap().unwrap(); @@ -1119,11 +1229,26 @@ async fn email_change_persists_and_refuses_a_taken_address() { .await .unwrap(); // Case-folded the same way sign-in matches an address. - assert!(store.user_by_email(&ws_id, "grace.new@izlek.sh").await.unwrap().is_some()); - assert!(store.user_by_email(&ws_id, "grace@izlek.sh").await.unwrap().is_none()); + assert!( + store + .user_by_email(&ws_id, "grace.new@izlek.sh") + .await + .unwrap() + .is_some() + ); + assert!( + store + .user_by_email(&ws_id, "grace@izlek.sh") + .await + .unwrap() + .is_none() + ); // Taken by the admin already claimed above. - let err = store.set_email(&user_id, &ws_id, "ada@izlek.sh").await.unwrap_err(); + let err = store + .set_email(&user_id, &ws_id, "ada@izlek.sh") + .await + .unwrap_err(); assert!(matches!(err, StoreError::Conflict("account"))); user_id }; @@ -1650,7 +1775,11 @@ async fn adding_a_member_queues_the_mail_that_carries_the_link() { .await .unwrap(); - let queue = accounts.store().mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let queue = accounts + .store() + .mail_queue(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let queued = queue .iter() .find(|s| s.recipient == "grace@izlek.sh") @@ -2356,7 +2485,10 @@ async fn count_and_filtered_keyset_walk_cover_exactly_the_filtered_set() { .unwrap(); } - let filter = ActivityFilter { actor: Some(admin.clone()), ..Default::default() }; + let filter = ActivityFilter { + actor: Some(admin.clone()), + ..Default::default() + }; let total = store.count_activity(&filter).await.unwrap(); assert_eq!(total, 10); @@ -2371,17 +2503,27 @@ async fn count_and_filtered_keyset_walk_cover_exactly_the_filtered_set() { break; } let last = rows.last().unwrap(); - page = FeedPage::Before(FeedCursor { at: last.at, id: last.id.clone() }); + page = FeedPage::Before(FeedCursor { + at: last.at, + id: last.id.clone(), + }); walked.extend(rows); } assert_eq!(walked.len(), 10); - assert!(walked.iter().all(|r| r.actor_name.as_deref() == Some("Ada"))); + assert!( + walked + .iter() + .all(|r| r.actor_name.as_deref() == Some("Ada")) + ); let preceding = store .count_activity_preceding( &filter, Dir::Newest, - Some(&FeedCursor { at: walked[3].at, id: walked[3].id.clone() }), + Some(&FeedCursor { + at: walked[3].at, + id: walked[3].id.clone(), + }), ) .await .unwrap(); @@ -2413,11 +2555,16 @@ async fn a_claimed_workspace_starts_with_four_named_columns() { /// comes off the task's own id now, not a per-board counter, so exact keys /// are no longer predictable — only the shape and per-board uniqueness are. fn is_task_key_shaped(key: &str, prefix: &str) -> bool { - let Some(tail) = key.strip_prefix(prefix).and_then(|rest| rest.strip_prefix('-')) else { + let Some(tail) = key + .strip_prefix(prefix) + .and_then(|rest| rest.strip_prefix('-')) + else { return false; }; (5..=7).contains(&tail.len()) - && tail.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()) + && tail + .chars() + .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()) } #[tokio::test] @@ -2432,7 +2579,10 @@ async fn tasks_get_key_tails_off_their_own_id_not_a_board_counter() { let keys: Vec<&str> = board.cards().map(|card| card.task_key.as_str()).collect(); assert_eq!(keys.len(), 2); for key in &keys { - assert!(is_task_key_shaped(key, "DZ"), "key {key} is not shaped like DZ-<5..7 chars>"); + assert!( + is_task_key_shaped(key, "DZ"), + "key {key} is not shaped like DZ-<5..7 chars>" + ); } assert_ne!(keys[0], keys[1], "two tasks never share a key"); } @@ -2487,7 +2637,12 @@ async fn a_card_carries_its_assignees_comments_and_dependency_keys() { } let board = board_of(store, &workspace).await; - let blocked_key = board.cards().find(|card| card.id == blocked).unwrap().task_key.clone(); + let blocked_key = board + .cards() + .find(|card| card.id == blocked) + .unwrap() + .task_key + .clone(); let card = board.cards().find(|card| card.id == blocking).unwrap(); assert_eq!(card.assignees.len(), 2); assert_eq!(card.comment_count, 3); @@ -2617,10 +2772,28 @@ async fn a_board_costs_six_queries_whatever_its_size() { .unwrap(); } } + // A tag rides the task query as a join: the sweep stays at six. + let board_meta = store.board(&workspace).await.unwrap().unwrap(); + let tag = store + .create_tag(&board_meta.id, "shipping", OffsetDateTime::now_utc()) + .await + .unwrap(); + let tagged = previous.expect("the loop created tasks"); + store.set_task_tag(&tagged, &tag.id).await.unwrap(); let big = CountingReads::new(store); let board = load(&big, &workspace).await.unwrap().unwrap(); assert_eq!(board.task_count(), 40); + let tagged_card = board + .columns + .iter() + .flat_map(|column| column.cards.iter()) + .find(|card| card.id == tagged) + .unwrap(); + assert_eq!( + tagged_card.tag.as_ref().map(|t| t.name.as_str()), + Some("shipping") + ); assert_eq!( big.count(), 6, @@ -2628,99 +2801,339 @@ async fn a_board_costs_six_queries_whatever_its_size() { ); } -#[test] -fn initials_fall_back_to_two_letters() { - let person = |name: &str| Person { - id: "u".into(), - display_name: name.into(), - has_photo: false, - }; - assert_eq!(person("Mel Duarte").initials(), "MD"); - assert_eq!(person("Ada").initials(), "A"); - assert_eq!(person(" ").initials(), "?"); -} - -// -- task detail ------------------------------------------------------------ +// -- tags ------------------------------------------------------------------- -use izlek_core::detail::{ - ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts, - load as load_detail, -}; +#[tokio::test] +async fn tags_are_created_in_order_renamed_moved_and_deleted() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + let at = OffsetDateTime::now_utc(); -/// The same trick as [`CountingReads`], for the detail screen: the round trips -/// one task costs must not follow how much it carries. -struct CountingDetail<'a> { - inner: &'a TursoStore, - calls: AtomicUsize, -} + let alpha = store.create_tag(&board.id, "alpha", at).await.unwrap(); + let beta = store.create_tag(&board.id, "beta", at).await.unwrap(); + let gamma = store.create_tag(&board.id, "gamma", at).await.unwrap(); + assert_eq!((alpha.position, beta.position, gamma.position), (1, 2, 3)); -impl<'a> CountingDetail<'a> { - fn new(inner: &'a TursoStore) -> Self { - Self { - inner, - calls: AtomicUsize::new(0), - } - } + store.rename_tag(&beta.id, "beta2").await.unwrap(); + assert_eq!( + tag_order(&store.tags(&board.id).await.unwrap()), + ["General", "alpha", "beta2", "gamma"] + ); - fn count(&self) -> usize { - self.calls.load(Ordering::Relaxed) - } + // Swapping moves one place, never to the far end. + store.move_tag(&beta.id, true).await.unwrap(); + assert_eq!( + tag_order(&store.tags(&board.id).await.unwrap()), + ["General", "beta2", "alpha", "gamma"] + ); + // A tag already at that end stays put: nothing to swap is not an error. + store.move_tag(&gamma.id, false).await.unwrap(); + assert_eq!( + tag_order(&store.tags(&board.id).await.unwrap()), + ["General", "beta2", "alpha", "gamma"] + ); + store.move_tag(&beta.id, true).await.unwrap(); + assert_eq!( + tag_order(&store.tags(&board.id).await.unwrap()), + ["beta2", "General", "alpha", "gamma"] + ); + store.move_tag(&alpha.id, true).await.unwrap(); + assert_eq!( + tag_order(&store.tags(&board.id).await.unwrap()), + ["beta2", "alpha", "General", "gamma"] + ); - fn tick(&self) { - self.calls.fetch_add(1, Ordering::Relaxed); - } + store.delete_tag(&beta.id).await.unwrap(); + assert_eq!( + tag_order(&store.tags(&board.id).await.unwrap()), + ["alpha", "General", "gamma"] + ); + assert!(matches!( + store.delete_tag(&beta.id).await, + Err(StoreError::NotFound) + )); } -#[async_trait::async_trait] -impl DetailReads for CountingDetail<'_> { - async fn task(&self, task_id: &str) -> Result, StoreError> { - self.tick(); - self.inner.task(task_id).await - } - - async fn columns_for_board( - &self, - board_id: &str, - ) -> Result, StoreError> { - self.tick(); - self.inner.columns_for_board(board_id).await - } +#[tokio::test] +async fn a_boards_tags_have_unique_names() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + let at = OffsetDateTime::now_utc(); - async fn assignees_for_task(&self, task_id: &str) -> Result, StoreError> { - self.tick(); - self.inner.assignees_for_task(task_id).await - } + store.create_tag(&board.id, "ops", at).await.unwrap(); + assert!( + matches!( + store.create_tag(&board.id, "ops", at).await, + Err(StoreError::Conflict("tag")) + ), + "two tags with one name are one project spelled twice" + ); - async fn assignable_people(&self, workspace_id: &str) -> Result, StoreError> { - self.tick(); - self.inner.assignable_people(workspace_id).await - } + // The same name on another board is a different project. + let other = Scratch::open().await; + let (other_ws, _other_admin) = claim(&other.store).await; + let other_board = other.store.board(&other_ws).await.unwrap().unwrap(); + other + .store + .create_tag(&other_board.id, "ops", at) + .await + .unwrap(); - async fn dependencies_for_task( - &self, - task_id: &str, - ) -> Result, StoreError> { - self.tick(); - self.inner.dependencies_for_task(task_id).await - } + // A rename into a clash refuses the same way. + let ship = store.create_tag(&board.id, "ship", at).await.unwrap(); + assert!(matches!( + store.rename_tag(&ship.id, "ops").await, + Err(StoreError::Conflict("tag")) + )); +} - async fn comments_for_task(&self, task_id: &str) -> Result, StoreError> { - self.tick(); - self.inner.comments_for_task(task_id).await - } +fn tag_order(tags: &[izlek_core::store::Tag]) -> Vec<&str> { + tags.iter().map(|t| t.name.as_str()).collect() +} - async fn files_for_task( - &self, - task_id: &str, - ) -> Result, StoreError> { - self.tick(); - self.inner.files_for_task(task_id).await - } +fn card_of<'a>( + view: &'a izlek_core::board::BoardView, + task: &str, +) -> &'a izlek_core::board::TaskCard { + view.columns + .iter() + .flat_map(|column| column.cards.iter()) + .find(|card| card.id == task) + .unwrap() +} - async fn activity_for_task(&self, task_id: &str) -> Result, StoreError> { - self.tick(); - self.inner.activity_for_task(task_id).await - } +#[tokio::test] +async fn deleting_a_tag_moves_its_tasks_to_the_default_and_a_foreign_tag_is_not_found() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + let tag = store + .create_tag(&board.id, "ops", OffsetDateTime::now_utc()) + .await + .unwrap(); + let task = add_task(store, &workspace, "Backlog", "tagged", None, &admin).await; + + // The task came wearing the default; moving it to `ops` shows in the + // card and the detail alike. + let view = board_of(store, &workspace).await; + assert_eq!( + card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()), + Some("General") + ); + store.set_task_tag(&task, &tag.id).await.unwrap(); + let view = board_of(store, &workspace).await; + assert_eq!( + card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()), + Some("ops") + ); + let detail = load_detail(store, &workspace, &task) + .await + .unwrap() + .unwrap(); + assert_eq!( + detail.tag.as_ref().map(|t| t.id.as_str()), + Some(tag.id.as_str()) + ); + + // A tag from another board — or one that never existed — is not found, + // not refused: it is not one of this board's projects at all. + let other = Scratch::open().await; + let (other_ws, _other_admin) = claim(&other.store).await; + let other_board = other.store.board(&other_ws).await.unwrap().unwrap(); + let foreign = other + .store + .create_tag(&other_board.id, "foreign", OffsetDateTime::now_utc()) + .await + .unwrap(); + assert!(matches!( + store.set_task_tag(&task, &foreign.id).await, + Err(StoreError::NotFound) + )); + assert!(matches!( + store.set_task_tag(&task, "no-such-tag").await, + Err(StoreError::NotFound) + )); + + // Deleting a worn tag leaves the task on the board's default, and the + // task survives. + store.delete_tag(&tag.id).await.unwrap(); + let view = board_of(store, &workspace).await; + assert_eq!( + card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()), + Some("General") + ); +} + +#[tokio::test] +async fn a_fresh_board_comes_with_a_default_tag_and_new_tasks_wear_it() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + + let tags = store.tags(&board.id).await.unwrap(); + assert_eq!(tags.len(), 1, "a claimed board seeds exactly one tag"); + assert!(tags[0].is_default, "the seeded tag is the default"); + assert_eq!((tags[0].name.as_str(), tags[0].position), ("General", 0)); + + // Nobody chose a tag; the task wears the board's default all the same. + let task = add_task(store, &workspace, "Backlog", "first", None, &admin).await; + let view = board_of(store, &workspace).await; + assert_eq!( + card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()), + Some("General") + ); +} + +#[tokio::test] +async fn the_default_tag_cannot_be_deleted_but_renames_and_moves_like_any_other() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + let default = &store.tags(&board.id).await.unwrap()[0]; + + assert!(matches!( + store.delete_tag(&default.id).await, + Err(StoreError::Conflict("default_tag")) + )); + + store.rename_tag(&default.id, "Projects").await.unwrap(); + store + .create_tag(&board.id, "alpha", OffsetDateTime::now_utc()) + .await + .unwrap(); + store.move_tag(&default.id, false).await.unwrap(); + assert_eq!( + tag_order(&store.tags(&board.id).await.unwrap()), + ["alpha", "Projects"] + ); +} + +#[tokio::test] +async fn a_board_cannot_hold_two_defaults_and_a_task_cannot_go_tagless() { + let (scratch, workspace, _admin) = workspace_with_admin().await; + let board = scratch.store.board(&workspace).await.unwrap().unwrap(); + + // Two defaults is a schema rule, so it is the schema that refuses — + // exercised raw, because the store's own writes never try it. + let conn = raw_conn(&scratch).await; + let _ = conn + .execute( + "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \ + VALUES ('t2', ?1, 'second', 9, 1, '2026-01-01T00:00:00Z')", + turso::params![board.id.clone()], + ) + .await + .expect_err("a second default tag violates tag_one_default"); + + // And a task's tag_id is NOT NULL in the declared schema itself, not a + // habit of the write path. + let _ = conn + .execute( + "INSERT INTO task (id, board_id, task_key, title, column_id, tag_id, position, \ + created_by, created_at, updated_at) \ + VALUES ('tk', ?1, 'DZ-99', 'raw', (SELECT id FROM board_column LIMIT 1), NULL, 0, \ + (SELECT id FROM user LIMIT 1), '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')", + turso::params![board.id.clone()], + ) + .await + .expect_err("task.tag_id is NOT NULL"); +} + +#[test] +fn initials_fall_back_to_two_letters() { + let person = |name: &str| Person { + id: "u".into(), + display_name: name.into(), + has_photo: false, + }; + assert_eq!(person("Mel Duarte").initials(), "MD"); + assert_eq!(person("Ada").initials(), "A"); + assert_eq!(person(" ").initials(), "?"); +} + +// -- task detail ------------------------------------------------------------ + +use izlek_core::detail::{ + ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts, + load as load_detail, +}; + +/// The same trick as [`CountingReads`], for the detail screen: the round trips +/// one task costs must not follow how much it carries. +struct CountingDetail<'a> { + inner: &'a TursoStore, + calls: AtomicUsize, +} + +impl<'a> CountingDetail<'a> { + fn new(inner: &'a TursoStore) -> Self { + Self { + inner, + calls: AtomicUsize::new(0), + } + } + + fn count(&self) -> usize { + self.calls.load(Ordering::Relaxed) + } + + fn tick(&self) { + self.calls.fetch_add(1, Ordering::Relaxed); + } +} + +#[async_trait::async_trait] +impl DetailReads for CountingDetail<'_> { + async fn task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.task(task_id).await + } + + async fn columns_for_board( + &self, + board_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.columns_for_board(board_id).await + } + + async fn assignees_for_task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.assignees_for_task(task_id).await + } + + async fn assignable_people(&self, workspace_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.assignable_people(workspace_id).await + } + + async fn dependencies_for_task( + &self, + task_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.dependencies_for_task(task_id).await + } + + async fn comments_for_task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.comments_for_task(task_id).await + } + + async fn files_for_task( + &self, + task_id: &str, + ) -> Result, StoreError> { + self.tick(); + self.inner.files_for_task(task_id).await + } + + async fn activity_for_task(&self, task_id: &str) -> Result, StoreError> { + self.tick(); + self.inner.activity_for_task(task_id).await + } async fn family_for_task( &self, @@ -2830,7 +3243,6 @@ async fn a_dependency_that_would_close_a_circle_is_refused() { Err(StoreError::Cycle) )); - // The refusal wrote nothing. let detail = load_detail(store, &workspace, &c).await.unwrap().unwrap(); assert!(detail.blocked_by.is_empty()); } @@ -2987,7 +3399,11 @@ async fn saving_a_task_records_only_what_changed() { ) .await .unwrap(); - assert_eq!(ids, Vec::::new(), "a save that changed nothing writes nothing"); + assert_eq!( + ids, + Vec::::new(), + "a save that changed nothing writes nothing" + ); let detail = load_detail(store, &workspace, &task) .await .unwrap() @@ -3078,6 +3494,7 @@ async fn a_task_detail_costs_nine_queries_whatever_it_carries() { .record_activity( &heavy, Some(&person.id), + None, &ActivityKind::Moved, "to Review", now, @@ -3104,10 +3521,7 @@ async fn a_task_detail_costs_nine_queries_whatever_it_carries() { assert_eq!(detail.subtasks.len(), 20); assert!(detail.parent.is_none()); assert!( - detail - .subtasks - .iter() - .all(|part| part.assignees.len() == 1), + detail.subtasks.iter().all(|part| part.assignees.len() == 1), "a subtask row carries who holds it" ); // Twenty comments (each its own Commented line), twenty moves, plus the @@ -3561,7 +3975,7 @@ async fn a_rule_is_one_sentence_and_starts_live() { "You can start now", Audience::Assignees, OffsetDateTime::now_utc(), - false, + false, ) .await .expect("an unblocked rule is whole without a column"); @@ -3924,7 +4338,7 @@ async fn deleting_a_rule_takes_its_ledger_with_it() { // -- the engine ------------------------------------------------------------ -use izlek_core::mail::{Engine, MailError, Mailer, Outgoing, backoff}; +use izlek_core::mail::{Engine, MailError, Mailer, Outgoing, Report, backoff}; use std::sync::Mutex; /// A mail server that remembers instead of sending, and refuses when told to. @@ -3965,8 +4379,16 @@ impl Mailer for Remembering { } } -/// A store shared between the tests and an engine. +/// A store shared between the tests and an engine, with no quiet window: a +/// trigger is a mail, sent the moment it is owed. That is what every test +/// below the batching ones is about, and it is what `mail_batch_minutes = 0` +/// means. The batching tests open theirs with `waiting`. async fn shared() -> (PathBuf, Arc, String, String) { + waiting(0).await +} + +/// The same, with a quiet window of `minutes` on the workspace. +async fn waiting(minutes: u32) -> (PathBuf, Arc, String, String) { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let store = Arc::new( @@ -3975,6 +4397,17 @@ async fn shared() -> (PathBuf, Arc, String, String) { .unwrap(), ); let (workspace, admin) = claim(&store).await; + let limits = store.workspace().await.unwrap().unwrap(); + store + .set_limits( + &workspace, + limits.attachment_limit_bytes, + limits.photo_limit_bytes, + &limits.allowed_file_types, + minutes, + ) + .await + .unwrap(); (dir, store, workspace, admin) } @@ -4293,7 +4726,7 @@ async fn you_can_start_now_waits_for_the_last_blocker() { "You can start now", Audience::Assignees, now, - false, + false, ) .await .unwrap(); @@ -4365,7 +4798,7 @@ async fn a_deleted_blocker_also_says_you_can_start_now() { "You can start now", Audience::Assignees, now, - false, + false, ) .await .unwrap(); @@ -4431,7 +4864,7 @@ async fn a_delete_that_leaves_somebody_still_waiting_mails_nobody() { "You can start now", Audience::Assignees, now, - false, + false, ) .await .unwrap(); @@ -4478,7 +4911,7 @@ async fn a_mail_owed_by_a_delete_is_rebuilt_from_the_delete_on_a_retry() { "You can start now", Audience::Assignees, now, - false, + false, ) .await .unwrap(); @@ -4551,7 +4984,10 @@ async fn a_rule_that_owed_nobody_still_says_so() { let transition = moved_to(&store, &workspace, &task, "Backlog", "Done", &mate).await; engine.on_transition(&transition).await.unwrap(); - let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let decisions = store + .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let row = decisions .iter() .find(|d| d.rule_id == rule.id && d.task_id == task) @@ -4573,7 +5009,10 @@ async fn a_rule_that_did_not_match_leaves_a_reason() { let transition = moved_to(&store, &workspace, &task, "Backlog", "Review", &admin).await; engine.on_transition(&transition).await.unwrap(); - let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let decisions = store + .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let row = decisions .iter() .find(|d| d.rule_id == rule.id && d.task_id == task) @@ -4603,7 +5042,10 @@ async fn a_deleted_task_still_leaves_a_task_gone_row() { assert_eq!(report, Default::default()); assert!(mailer.sent().is_empty()); - let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let decisions = store + .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let row = decisions .iter() .find(|d| d.rule_id == rule.id && d.task_id == task) @@ -4670,7 +5112,7 @@ async fn a_rule_round_trips_every_word_the_board_speaks() { "A word the board speaks", Audience::Assignees, OffsetDateTime::now_utc(), - false, + false, ) .await .unwrap(); @@ -4703,20 +5145,19 @@ async fn updating_a_rule_leaves_its_identity_and_ledger_alone() { let now = OffsetDateTime::now_utc(); scratch .store - .record_mail_decision( - &rule.id, - &transition.id, - &task, - MailOutcome::Owed, - "", - now, - ) + .record_mail_decision(&rule.id, &transition.id, &task, MailOutcome::Owed, "", now) .await .unwrap(); scratch .store - .update_mail_rule(&rule.id, &Trigger::Unblocked, "New subject", Audience::Board, false) + .update_mail_rule( + &rule.id, + &Trigger::Unblocked, + "New subject", + Audience::Board, + false, + ) .await .unwrap(); @@ -4728,7 +5169,11 @@ async fn updating_a_rule_leaves_its_identity_and_ledger_alone() { assert_eq!(updated.enabled, rule.enabled); assert_eq!(updated.created_at, rule.created_at); - let decisions = scratch.store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let decisions = scratch + .store + .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); assert!( decisions.iter().any(|d| d.rule_id == rule.id), "the pre-existing decision no longer joins to the rule" @@ -4778,7 +5223,10 @@ async fn a_rules_creator_audience_names_who_opened_the_card() { .await .unwrap(); assert_eq!( - creators.iter().map(|p| p.user_id.as_str()).collect::>(), + creators + .iter() + .map(|p| p.user_id.as_str()) + .collect::>(), [admin.as_str()] ); @@ -4839,7 +5287,9 @@ async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() { // Bytes that are not text and are not valid UTF-8, because an attachment // is not a string and the column it lives in must not treat it as one. - let bytes: Vec = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe]; + let bytes: Vec = vec![ + 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe, + ]; let id = store .add_attachment(NewAttachment { task_id: &task, @@ -5006,7 +5456,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() { let now = OffsetDateTime::now_utc(); let pending = store - .claim_send(&rule.id, &transition.id, &task, "pending@izlek.sh", now, now) + .claim_send( + &rule.id, + &transition.id, + &task, + "pending@izlek.sh", + now, + now, + ) .await .unwrap() .unwrap(); @@ -5029,7 +5486,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() { store.record_send_accepted(&sent.id, now).await.unwrap(); let abandoned = store - .claim_send(&rule.id, &transition.id, &task, "abandoned@izlek.sh", now, now) + .claim_send( + &rule.id, + &transition.id, + &task, + "abandoned@izlek.sh", + now, + now, + ) .await .unwrap() .unwrap(); @@ -5038,7 +5502,10 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() { .await .unwrap(); - let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let queue = store + .mail_queue(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let ids: Vec<&str> = queue.iter().map(|s| s.id.as_str()).collect(); assert!(ids.contains(&pending.id.as_str())); assert!(ids.contains(&failed.id.as_str())); @@ -5063,7 +5530,10 @@ async fn an_invite_mail_is_owed_without_a_rule() { let found = owed.iter().find(|s| s.id == invite.id).unwrap(); assert_eq!(found.rule_id, None); - let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let queue = store + .mail_queue(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let found = queue.iter().find(|s| s.id == invite.id).unwrap(); assert_eq!(found.rule_id, None); } @@ -5083,7 +5553,10 @@ async fn an_invite_mail_with_no_sender_is_held_not_failed() { assert_eq!(report.held, 1); assert_eq!(report.sent, 0); - let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let queue = store + .mail_queue(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let held = queue .iter() .find(|s| s.recipient == "newcomer@izlek.sh") @@ -5128,10 +5601,7 @@ async fn two_passes_over_one_owed_mail_send_it_once() { // request's pass and the sweep's. let request = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); - let (a, b) = tokio::join!( - request.deliver_owed(now, 10), - sweep.deliver_owed(now, 10), - ); + let (a, b) = tokio::join!(request.deliver_owed(now, 10), sweep.deliver_owed(now, 10),); let (a, b) = (a.unwrap(), b.unwrap()); let sent = mailer.sent.lock().unwrap().len(); @@ -5249,13 +5719,14 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() { let t0 = OffsetDateTime::now_utc(); store - .record_activity(&task_a, Some(&admin), &ActivityKind::Created, "", t0) + .record_activity(&task_a, Some(&admin), None, &ActivityKind::Created, "", t0) .await .unwrap(); store .record_activity( &task_b, Some(&other), + None, &ActivityKind::Retitled, "new title", t0 + Duration::seconds(1), @@ -5263,7 +5734,15 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() { .await .unwrap(); - let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); + let feed = store + .recent_activity( + 10, + izlek_core::store::FeedPage::Newest, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter::default(), + ) + .await + .unwrap(); // Two "created" lines came free with the two tasks; the two just recorded // sit newest first, ahead of both of those. assert_eq!(feed.len(), 4); @@ -5299,13 +5778,29 @@ async fn keyset_paging_covers_every_activity_row_once() { } let _ = workspace; - let whole = store.recent_activity(100, FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); + let whole = store + .recent_activity( + 100, + FeedPage::Newest, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter::default(), + ) + .await + .unwrap(); assert_eq!(whole.len(), 23); let mut walked = Vec::new(); let mut page = FeedPage::Newest; loop { - let rows = store.recent_activity(7, page, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); + let rows = store + .recent_activity( + 7, + page, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter::default(), + ) + .await + .unwrap(); if rows.is_empty() { break; } @@ -5329,7 +5824,7 @@ async fn an_account_event_rides_the_feed_without_a_task() { let t0 = OffsetDateTime::now_utc(); store - .record_activity(&task, Some(&admin), &ActivityKind::Created, "", t0) + .record_activity(&task, Some(&admin), None, &ActivityKind::Created, "", t0) .await .unwrap(); store @@ -5342,7 +5837,15 @@ async fn an_account_event_rides_the_feed_without_a_task() { .await .unwrap(); - let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap(); + let feed = store + .recent_activity( + 10, + izlek_core::store::FeedPage::Newest, + izlek_core::store::Dir::Newest, + &izlek_core::store::ActivityFilter::default(), + ) + .await + .unwrap(); // The sign-in sits newest with no task on it; the task's own lines below // still name theirs. assert_eq!(feed[0].kind, ActivityKind::SignedIn); @@ -5440,7 +5943,7 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() { "You were assigned", Audience::Assignees, OffsetDateTime::now_utc(), - false, + false, ) .await .unwrap(); @@ -5453,6 +5956,7 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() { .record_activity( &task, Some(&admin), + None, &ActivityKind::Assigned, "Emre", OffsetDateTime::now_utc(), @@ -5477,31 +5981,175 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() { } #[tokio::test] -async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_commented() { +async fn assigning_one_person_mails_that_person_not_every_assignee() { let (dir, store, workspace, admin) = shared().await; - let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let first = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let second = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let third = member(&store, &workspace, "linus@izlek.sh", "Linus").await; let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &first).await.unwrap(); + store.assign_task(&task, &second).await.unwrap(); + store.assign_task(&task, &third).await.unwrap(); let board = store.board(&workspace).await.unwrap().unwrap(); store .create_mail_rule( &board.id, - &Trigger::Commented, - "A comment landed", - Audience::Creator, + &Trigger::Assigned, + "You were assigned", + Audience::Assignees, OffsetDateTime::now_utc(), - false, + false, ) .await .unwrap(); let mailer = Remembering::taking_everything(); let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); - + // Ada assigns Yusuf to a card that already carries three people: the line + // is about Yusuf, so Yusuf is the audience — not the three already there. + let fourth = member(&store, &workspace, "yusuf@izlek.sh", "Yusuf").await; + let activity_id = store + .record_activity( + &task, + Some(&admin), + Some(&fourth), + &ActivityKind::Assigned, + "Yusuf", + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let event = activity_event(&store, &activity_id).await; + + let report = engine.on_activity(&event).await.unwrap(); + assert_eq!(report.sent, 1, "one assignment, one mail"); + let sent = mailer.sent(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].to, "yusuf@izlek.sh"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn an_unassignment_mails_the_person_removed_not_the_rest() { + let (dir, store, workspace, admin) = shared().await; + let staying = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let leaving = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &staying).await.unwrap(); + store.assign_task(&task, &leaving).await.unwrap(); + let board = store.board(&workspace).await.unwrap().unwrap(); + store + .create_mail_rule( + &board.id, + &Trigger::Unassigned, + "You were unassigned", + Audience::Assignees, + OffsetDateTime::now_utc(), + false, + ) + .await + .unwrap(); + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + store.unassign_task(&task, &leaving).await.unwrap(); + let activity_id = store + .record_activity( + &task, + Some(&admin), + Some(&leaving), + &ActivityKind::Unassigned, + "Emre", + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let event = activity_event(&store, &activity_id).await; + + let report = engine.on_activity(&event).await.unwrap(); + assert_eq!(report.sent, 1, "one removal, one mail"); + let sent = mailer.sent(); + assert_eq!(sent.len(), 1); + assert_eq!( + sent[0].to, "emre@izlek.sh", + "the mail is for the one removed" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_rule_whose_line_has_no_subject_still_mails_every_assignee() { + let (dir, store, workspace, admin) = shared().await; + let first = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let second = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &first).await.unwrap(); + store.assign_task(&task, &second).await.unwrap(); + let board = store.board(&workspace).await.unwrap().unwrap(); + store + .create_mail_rule( + &board.id, + &Trigger::Commented, + "There was movement", + Audience::Assignees, + OffsetDateTime::now_utc(), + false, + ) + .await + .unwrap(); + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + // A comment has no subject: the audience stays the whole assignee list, + // minus the actor, exactly as before the subject column existed. + let activity_id = store + .record_activity( + &task, + Some(&admin), + None, + &ActivityKind::Commented, + "", + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let event = activity_event(&store, &activity_id).await; + + let report = engine.on_activity(&event).await.unwrap(); + assert_eq!(report.sent, 2, "both assignees, the old breadth"); + let mut to: Vec<_> = mailer.sent().iter().map(|m| m.to.clone()).collect(); + to.sort(); + assert_eq!(to, vec!["emre@izlek.sh", "grace@izlek.sh"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_commented() { + let (dir, store, workspace, admin) = shared().await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + let board = store.board(&workspace).await.unwrap().unwrap(); + store + .create_mail_rule( + &board.id, + &Trigger::Commented, + "A comment landed", + Audience::Creator, + OffsetDateTime::now_utc(), + false, + ) + .await + .unwrap(); + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + // Emre comments on Ada's task: Ada, the creator, gets mailed. let commented_by_mate = store .record_activity( &task, Some(&mate), + None, &ActivityKind::Commented, "", OffsetDateTime::now_utc(), @@ -5521,6 +6169,7 @@ async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_c .record_activity( &task, Some(&admin), + None, &ActivityKind::Commented, "", OffsetDateTime::now_utc(), @@ -5532,7 +6181,10 @@ async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_c assert_eq!(report, Default::default()); assert_eq!(mailer.sent().len(), 1, "no second mail went out"); - let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let decisions = store + .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let row = decisions .iter() .find(|d| d.event_id == commented_by_creator) @@ -5554,6 +6206,7 @@ async fn a_created_activity_does_not_fire_a_status_rule() { .record_activity( &task, Some(&admin), + None, &ActivityKind::Created, "", OffsetDateTime::now_utc(), @@ -5566,7 +6219,10 @@ async fn a_created_activity_does_not_fire_a_status_rule() { assert_eq!(report, Default::default()); assert!(mailer.sent().is_empty()); - let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap(); + let decisions = store + .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest) + .await + .unwrap(); let row = decisions .iter() .find(|d| d.rule_id == rule.id && d.task_id == task) @@ -5609,7 +6265,14 @@ async fn decisions_and_sends_for_task_read_only_that_tasks_own_rows() { .unwrap() .unwrap(); store - .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now, now) + .claim_send( + &rule.id, + &other_transition.id, + &other_task, + "emre@izlek.sh", + now, + now, + ) .await .unwrap(); @@ -5658,10 +6321,17 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() { assert!(reread_failed.next_attempt_at.is_some_and(|at| at <= now)); let reread_sent = sends.iter().find(|s| s.id == sent.id).unwrap(); - assert_eq!(reread_sent.state, SendState::Sent, "a sent send is untouched"); + assert_eq!( + reread_sent.state, + SendState::Sent, + "a sent send is untouched" + ); let owed = store.sends_owed(now, 10).await.unwrap(); - assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due"); + assert!( + owed.iter().any(|s| s.id == failed.id), + "the requeued send is now due" + ); } #[tokio::test] @@ -5723,7 +6393,10 @@ async fn the_engine_delivers_a_notice_that_owes_no_rule() { .sends_owed(now + Duration::hours(2), 10) .await .unwrap(); - assert!(owed.is_empty(), "a delivered notice is no longer owed: {owed:?}"); + assert!( + owed.is_empty(), + "a delivered notice is no longer owed: {owed:?}" + ); std::fs::remove_dir_all(dir).ok(); } @@ -5750,8 +6423,16 @@ async fn a_tasks_activity_reads_newest_first() { ); // Creation is the oldest thing that ever happens to a task, so it is last // now; a comment — the most recent act here — leads. - assert_eq!(activity.first().map(|line| line.kind.clone()), Some(ActivityKind::Commented), "{activity:?}"); - assert_eq!(activity.last().map(|line| line.kind.clone()), Some(ActivityKind::Created), "{activity:?}"); + assert_eq!( + activity.first().map(|line| line.kind.clone()), + Some(ActivityKind::Commented), + "{activity:?}" + ); + assert_eq!( + activity.last().map(|line| line.kind.clone()), + Some(ActivityKind::Created), + "{activity:?}" + ); } /// A status rule with no column watches the whole board: every crossing fires @@ -5786,7 +6467,9 @@ async fn a_status_rule_with_no_column_fires_on_every_crossing() { let sent = mailer.sent(); assert_eq!( - sent.iter().filter(|mail| mail.subject == "It moved").count(), + sent.iter() + .filter(|mail| mail.subject == "It moved") + .count(), 2, "both crossings fired the every-column rule: {sent:?}" ); @@ -5942,7 +6625,9 @@ async fn every_kind_of_write_announces_its_surface() { .unwrap(); let seen = announced(&mut rx); - for topic in ["board", "task", "members", "queue", "rules", "settings", "activity"] { + for topic in [ + "board", "task", "members", "queue", "rules", "settings", "activity", + ] { assert!( seen.iter().any(|k| k == topic), "no {topic} announcement; heard {seen:?}" @@ -6056,7 +6741,12 @@ async fn the_next_due_moment_is_the_earliest_one() { .await .unwrap(); store - .queue_notice("soon@izlek.sh", "Sooner", "body", now + Duration::minutes(5)) + .queue_notice( + "soon@izlek.sh", + "Sooner", + "body", + now + Duration::minutes(5), + ) .await .unwrap(); @@ -6085,21 +6775,32 @@ async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() { from_name: "İzlek".into(), from_address: "izlek@izlek.sh".into(), }; - store.set_sender(&workspace, sender("smtp.one.test")).await.unwrap(); + store + .set_sender(&workspace, sender("smtp.one.test")) + .await + .unwrap(); // A login that worked, and a mail that did not: both true at once, and // neither may be rendered as the other. store .record_sender_check( &workspace, - izlek_core::store::SenderCheck { at: now, took_ms: 120, error: None }, + izlek_core::store::SenderCheck { + at: now, + took_ms: 120, + error: None, + }, ) .await .unwrap(); store .record_sender_test( &workspace, - izlek_core::store::SenderTest { at: now, took_ms: 0, error: Some("550 not allowed".into()) }, + izlek_core::store::SenderTest { + at: now, + took_ms: 0, + error: Some("550 not allowed".into()), + }, ) .await .unwrap(); @@ -6115,8 +6816,850 @@ async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() { ); // Point it at a different server: what was known is now about nothing. - store.set_sender(&workspace, sender("smtp.two.test")).await.unwrap(); + store + .set_sender(&workspace, sender("smtp.two.test")) + .await + .unwrap(); let ws = store.workspace().await.unwrap().unwrap(); - assert!(ws.sender_check.is_none(), "a stale handshake survived an edit"); + assert!( + ws.sender_check.is_none(), + "a stale handshake survived an edit" + ); assert!(ws.sender_test.is_none(), "a stale test survived an edit"); } + +// --------------------------------------------------------------------------- +// izlek reconcile — bringing a database of the OLD shape onto the declared +// schema. These tests carry the user's rule (2026-08-31): a table alteration +// owes both a proof that the alteration holds and a proof that reconcile +// carries a live-shaped database across it. +// --------------------------------------------------------------------------- + +/// Builds a database at the PRE-COLLAPSE schema — the shape İzlek was actually +/// deployed with, kept verbatim in `tests/fixtures/` — and fills it with the +/// kinds of row a live workspace holds, blobs included. +async fn live_shaped_database() -> (PathBuf, String) { + let dir = std::env::temp_dir().join(format!("izlek-reconcile-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("izlek.db").to_str().unwrap().to_string(); + + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap(); + conn.execute_batch(include_str!("fixtures/pre-collapse/0001_init.sql")) + .await + .unwrap(); + conn.execute_batch(include_str!("fixtures/pre-collapse/0002_sender_check.sql")) + .await + .unwrap(); + + let now = "2026-08-30T12:00:00Z"; + let mut sql = String::new(); + sql.push_str(&format!( + "INSERT INTO workspace (id, name, created_at) VALUES ('W1', 'Dizey', '{now}');" + )); + for (id, email, name) in [ + ("U1", "one@example.com", "One"), + ("U2", "two@example.com", "Two"), + ] { + sql.push_str(&format!( + "INSERT INTO user (id, workspace_id, email, display_name, role, created_at) \ + VALUES ('{id}', 'W1', '{email}', '{name}', 'member', '{now}');" + )); + } + sql.push_str(&format!( + "INSERT INTO workspace_owner (singleton, user_id, claimed_at) VALUES (1, 'U1', '{now}');" + )); + // Two boards, so a task landing on the WRONG board's default tag is + // visible rather than accidentally correct. + for b in ["B1", "B2"] { + sql.push_str(&format!( + "INSERT INTO board (id, workspace_id, name, created_at) VALUES ('{b}', 'W1', '{b}', '{now}');" + )); + sql.push_str(&format!( + "INSERT INTO board_column (id, board_id, name, position, is_done) \ + VALUES ('C{b}', '{b}', 'Backlog', 0, 0);" + )); + } + for (t, b) in [("T1", "B1"), ("T2", "B1"), ("T3", "B2")] { + sql.push_str(&format!( + "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, updated_at) \ + VALUES ('{t}', '{b}', '{t}', 'a task', 'C{b}', 'U1', '{now}', '{now}');" + )); + sql.push_str(&format!( + "INSERT INTO task_assignee (task_id, user_id) VALUES ('{t}', 'U2');" + )); + sql.push_str(&format!( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES ('A{t}', '{t}', 'U1', 'created', '', '{now}');" + )); + } + // A soft-deleted task still belongs to a tag afterwards. + sql.push_str(&format!( + "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, updated_at, deleted_at) \ + VALUES ('T4', 'B2', 'T4', 'gone', 'CB2', 'U1', '{now}', '{now}', '{now}');" + )); + conn.execute_batch(&sql).await.unwrap(); + + // A blob, because an attachment that survives as NULL would pass a row + // count and lose the user's file. + let bytes: Vec = (0u8..=255).cycle().take(5000).collect(); + conn.execute( + "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, bytes, uploaded_by, created_at) \ + VALUES ('F1', 'T1', 'a.bin', 'application/octet-stream', ?1, ?2, 'U1', ?3)", + turso::params![bytes.len() as i64, bytes.clone(), now], + ) + .await + .unwrap(); + + (dir, path) +} + +async fn scalar(path: &str, sql: &str) -> i64 { + let db = turso::Builder::new_local(path).build().await.unwrap(); + let conn = db.connect().unwrap(); + let mut rows = conn.query(sql, ()).await.unwrap(); + rows.next().await.unwrap().unwrap().get::(0).unwrap() +} + +fn backups_beside(dir: &PathBuf) -> Vec { + let mut found: Vec = std::fs::read_dir(dir) + .unwrap() + .filter_map(|e| e.ok()) + .map(|e| e.file_name().to_string_lossy().to_string()) + .filter(|n| n.contains(".backup-") && !n.ends_with("-wal") && !n.ends_with("-shm")) + .collect(); + found.sort(); + found +} + +#[tokio::test] +async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() { + let (dir, path) = live_shaped_database().await; + + izlek_core::store::reconcile( + &path, + izlek_core::store::ReconcileOptions { + dry_run: false, + yes: true, + auto: true, + }, + ) + .await + .expect("reconcile refused a database of the shape we actually deployed"); + + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + + // The schema is now the declared one, exactly. + let after = izlek_core::store::schema::fingerprint(&conn).await.unwrap(); + let declared = izlek_core::store::schema::declared_fingerprint().await.unwrap(); + assert_eq!(after, declared, "the rebuilt schema is not the declared one"); + + // Nothing was dropped on the floor. + assert_eq!(scalar(&path, "SELECT COUNT(*) FROM user").await, 2); + assert_eq!(scalar(&path, "SELECT COUNT(*) FROM board").await, 2); + assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task").await, 4); + assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task_assignee").await, 3); + assert_eq!(scalar(&path, "SELECT COUNT(*) FROM activity").await, 3); + + // Every task wears its OWN board's default tag — the step no schema diff + // could have derived. + assert_eq!( + scalar(&path, "SELECT COUNT(*) FROM task WHERE tag_id IS NULL").await, + 0, + "a task came out of the rebuild with no tag" + ); + assert_eq!( + scalar( + &path, + "SELECT COUNT(*) FROM task t JOIN tag g ON g.id = t.tag_id \ + WHERE g.board_id = t.board_id AND g.is_default = 1", + ) + .await, + 4, + "a task was given another board's tag" + ); + assert_eq!( + scalar(&path, "SELECT COUNT(*) FROM tag").await, + 2, + "each board owes exactly one default tag" + ); + + // The blob survived byte for byte. + assert_eq!( + scalar(&path, "SELECT length(bytes) FROM attachment WHERE id = 'F1'").await, + 5000 + ); + assert_eq!( + scalar( + &path, + "SELECT COUNT(*) FROM attachment WHERE id = 'F1' AND hex(substr(bytes, 1, 4)) = '00010203'", + ) + .await, + 1, + "the attachment's bytes changed in the rebuild" + ); + + // The quiet window is a column the old shape never had: a workspace that + // crosses over gets the declared default rather than a NULL the app would + // have to read around. + assert_eq!( + scalar(&path, "SELECT mail_batch_minutes FROM workspace WHERE id = 'W1'").await, + 5, + "the workspace came across without a quiet window" + ); + + // And the references all still point at something. + let mut broken = conn.query("PRAGMA foreign_key_check", ()).await.unwrap(); + assert!( + broken.next().await.unwrap().is_none(), + "the rebuilt database has dangling references" + ); + + // The original is beside it, still holding the old shape. + let backups = backups_beside(&dir); + assert_eq!(backups.len(), 1, "the rebuild did not keep a backup"); + let backup = dir.join(&backups[0]).to_str().unwrap().to_string(); + assert_eq!( + scalar( + &backup, + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'tag'", + ) + .await, + 0, + "the backup is not the old-shaped database we started from" + ); + assert_eq!( + scalar(&backup, "SELECT COUNT(*) FROM task").await, + 4, + "the backup lost rows" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn reconciling_a_database_that_already_matches_changes_nothing() { + let scratch = Scratch::open().await; + let path = scratch.dir.join("izlek.db").to_str().unwrap().to_string(); + + izlek_core::store::reconcile( + &path, + izlek_core::store::ReconcileOptions { + dry_run: false, + yes: true, + auto: true, + }, + ) + .await + .expect("reconcile refused a current database"); + + assert!( + backups_beside(&scratch.dir).is_empty(), + "a database that needed nothing was backed up anyway" + ); +} + +#[tokio::test] +async fn opening_a_stale_database_repairs_it() { + let (dir, path) = live_shaped_database().await; + + // The boot path: no flag, no prompt — the store comes up on a database of + // the old shape, having repaired it on the way. + let store = TursoStore::open(&path) + .await + .expect("the store would not open a database it was supposed to repair"); + drop(store); + + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + assert_eq!( + izlek_core::store::schema::fingerprint(&conn).await.unwrap(), + izlek_core::store::schema::declared_fingerprint().await.unwrap(), + ); + assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task").await, 4); + assert_eq!(backups_beside(&dir).len(), 1); + + // Opening it again finds it current and leaves it alone. + let store = TursoStore::open(&path).await.unwrap(); + drop(store); + assert_eq!( + backups_beside(&dir).len(), + 1, + "a second open rebuilt a database that already matched" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test] +async fn two_repairs_leave_two_backups() { + let (dir, path) = live_shaped_database().await; + let opts = || izlek_core::store::ReconcileOptions { + dry_run: false, + yes: true, + auto: true, + }; + + izlek_core::store::reconcile(&path, opts()).await.unwrap(); + assert_eq!(backups_beside(&dir).len(), 1); + + // Put the database back to the old shape and repair it again: the first + // backup must still be there. He keeps every one of them. + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute("DROP TABLE tag_stub_check", ()).await.ok(); + conn.execute("CREATE TABLE stray (id TEXT PRIMARY KEY)", ()) + .await + .unwrap(); + drop(conn); + drop(db); + + izlek_core::store::reconcile(&path, opts()).await.unwrap(); + let backups = backups_beside(&dir); + assert_eq!( + backups.len(), + 2, + "the second repair overwrote the first backup: {backups:?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} +/// The other half of the alteration: a database that ALREADY carries the +/// quiet window keeps the number its admin set, rather than being handed the +/// default a fresh workspace gets. +#[tokio::test] +async fn a_rebuild_keeps_a_window_the_admin_already_set() { + let scratch = Scratch::open().await; + let path = scratch.dir.join("izlek.db").to_str().unwrap().to_string(); + let (workspace, _) = claim(&scratch.store).await; + let limits = scratch.store.workspace().await.unwrap().unwrap(); + scratch + .store + .set_limits( + &workspace, + limits.attachment_limit_bytes, + limits.photo_limit_bytes, + &limits.allowed_file_types, + 17, + ) + .await + .unwrap(); + + // Something the declared schema does not know about: enough to make the + // database stale, so the rebuild actually runs. + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute("CREATE TABLE stray (id TEXT PRIMARY KEY)", ()) + .await + .unwrap(); + drop(conn); + drop(db); + + izlek_core::store::reconcile( + &path, + izlek_core::store::ReconcileOptions { + dry_run: false, + yes: true, + auto: true, + }, + ) + .await + .unwrap(); + + assert_eq!( + scalar(&path, "SELECT mail_batch_minutes FROM workspace").await, + 17, + "the rebuild reset a window the admin had chosen" + ); + assert_eq!( + scalar( + &path, + "SELECT COUNT(*) FROM sqlite_master WHERE name = 'stray'", + ) + .await, + 0, + "the stray table survived a rebuild onto the declared schema" + ); +} + +// --- user stats (the profile page's counts) --------------------------------- + +#[tokio::test] +async fn user_stats_counts_what_a_person_holds_finished_opened_and_said() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let store = &scratch.store; + let mem = member(store, &workspace, "mem@izlek.sh", "Mem Ber").await; + let backlog = column_named(store, &workspace, "Backlog").await; + let done = column_named(store, &workspace, "Done").await; + let now = OffsetDateTime::now_utc(); + + let hold = add_task(store, &workspace, "Backlog", "Hold the door", None, &admin).await; + store.assign_task(&hold, &mem).await.unwrap(); + let finished = add_task(store, &workspace, "Backlog", "Paint the frame", None, &admin).await; + store.assign_task(&finished, &mem).await.unwrap(); + store.move_task(&finished, &backlog, &done, &admin, now).await.unwrap(); + // One of her own that she also holds: created and assigned must each + // count it in its own column, not argue about it. + let own = add_task(store, &workspace, "Backlog", "Sweep", None, &mem).await; + store.assign_task(&own, &mem).await.unwrap(); + add_task(store, &workspace, "Backlog", "Mop", None, &mem).await; + add_task(store, &workspace, "Backlog", "Dust", None, &mem).await; + for i in 0..4 { + store.add_comment(&hold, &mem, "a note", now + Duration::seconds(i)).await.unwrap(); + } + + assert_eq!( + store.user_stats(&mem).await.unwrap(), + izlek_core::store::UserStats { assigned_open: 2, assigned_done: 1, created: 3, comments: 4 }, + ); +} + +#[tokio::test] +async fn a_deleted_task_counts_nowhere_and_a_person_with_nothing_counts_nothing() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let store = &scratch.store; + let mem = member(store, &workspace, "mem@izlek.sh", "Mem Ber").await; + let shy = member(store, &workspace, "shy@izlek.sh", "Shy Guy").await; + let now = OffsetDateTime::now_utc(); + + assert_eq!( + store.user_stats(­).await.unwrap(), + izlek_core::store::UserStats { assigned_open: 0, assigned_done: 0, created: 0, comments: 0 }, + ); + + let doomed = add_task(store, &workspace, "Backlog", "Doomed", None, &mem).await; + store.assign_task(&doomed, &mem).await.unwrap(); + store.add_comment(&doomed, &mem, "a note", now).await.unwrap(); + assert_eq!(store.user_stats(&mem).await.unwrap().assigned_open, 1); + assert_eq!(store.user_stats(&mem).await.unwrap().comments, 1); + + store.delete_task(&doomed, &admin, now).await.unwrap(); + assert_eq!( + store.user_stats(&mem).await.unwrap(), + izlek_core::store::UserStats { assigned_open: 0, assigned_done: 0, created: 0, comments: 0 }, + "a soft-deleted task stays out of every number, its comments included", + ); +} +// -- the quiet window ------------------------------------------------------ + +/// Every rule on the board, so one workflow trips several of them. +async fn rules_for_a_workflow(store: &TursoStore, workspace: &str) { + let board = store.board(workspace).await.unwrap().unwrap(); + let now = OffsetDateTime::now_utc(); + for (trigger, subject, audience) in [ + (Trigger::Created, "New task", Audience::Board), + (Trigger::Assigned, "You were assigned", Audience::Assignees), + (Trigger::DeadlineSet, "Deadline set", Audience::Board), + ] { + store + .create_mail_rule(&board.id, &trigger, subject, audience, now, false) + .await + .unwrap(); + } +} + +/// Hands every activity row a save wrote to the engine, in order. +async fn tell_the_engine(store: &TursoStore, engine: &Engine, ids: &[String]) -> Report { + let mut total = Report::default(); + for id in ids { + let event = activity_event(store, id).await; + let one = engine.on_activity(&event).await.unwrap(); + total.sent += one.sent; + total.batched += one.batched; + total.already_owned += one.already_owned; + } + total +} + +/// His scenario: create a card, assign it, give it a deadline. Three rules, +/// three triggers, one uninterrupted minute of work — and the person who has +/// to read it gets one mail saying where the card ended up. +#[tokio::test] +async fn a_whole_workflow_inside_the_window_is_one_mail() { + use time::macros::date; + let (dir, store, workspace, admin) = waiting(5).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + rules_for_a_workflow(&store, &workspace).await; + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let board = store.board(&workspace).await.unwrap().unwrap(); + let column_id = column_named(&store, &workspace, "Backlog").await; + let created = store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + parent_id: None, + title: "Ship the exporter", + description: "", + deadline: None, + created_by: &admin, + }) + .await + .unwrap(); + let task = created.row.id.clone(); + let first = tell_the_engine(&store, &engine, &[created.activity_id]).await; + + store.assign_task(&task, &mate).await.unwrap(); + let assigned = store + .record_activity( + &task, + Some(&admin), + Some(&mate), + &ActivityKind::Assigned, + "Emre", + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let second = tell_the_engine(&store, &engine, &[assigned]).await; + + let ids = store + .save_task( + &task, + "Ship the exporter", + "", + Some(date!(2026 - 09 - 30)), + &admin, + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + let third = tell_the_engine(&store, &engine, &ids).await; + + assert_eq!( + (first.sent, second.sent, third.sent), + (0, 0, 0), + "nothing leaves the building while the window is open", + ); + assert_eq!( + first.batched + second.batched + third.batched, + 3, + "three triggers, three rows waiting on one another", + ); + assert!(mailer.sent().is_empty()); + + // The window closes. + let report = engine + .deliver_owed(OffsetDateTime::now_utc() + Duration::minutes(6), 10) + .await + .unwrap(); + assert_eq!(report.sent, 1, "one envelope for the whole workflow"); + let sent = mailer.sent(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].to, "emre@izlek.sh"); + assert_eq!( + sent[0].subject, "Deadline set", + "the newest thing that happened names the mail", + ); + assert!( + sent[0].body.contains("Column: Backlog"), + "the mail states where the card is now: {}", + sent[0].body, + ); + assert!( + sent[0].body.contains("Deadline: 2026-09-30"), + "and the deadline it ended up with: {}", + sent[0].body, + ); + assert!( + sent[0].body.contains("Assignees: Emre"), + "and who is on it: {}", + sent[0].body, + ); + + // Nothing is left owed, and a second pass has nothing to send. + let again = engine + .deliver_owed(OffsetDateTime::now_utc() + Duration::hours(2), 10) + .await + .unwrap(); + assert_eq!(again.sent, 0); + assert_eq!(mailer.sent().len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The mistake case: a card goes into the wrong column and is put right a +/// moment later. One mail, naming the column it is actually in. +#[tokio::test] +async fn a_column_put_right_inside_the_window_mails_only_where_the_card_ended_up() { + let (dir, store, workspace, admin) = waiting(5).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + a_rule(&store, &workspace, "Done", "Card is done").await; + a_rule(&store, &workspace, "In Progress", "Card is in progress").await; + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let wrong = moved_to(&store, &workspace, &task, "Backlog", "Done", &admin).await; + assert_eq!(engine.on_transition(&wrong).await.unwrap().sent, 0); + let right = moved_to(&store, &workspace, &task, "Done", "In Progress", &admin).await; + assert_eq!(engine.on_transition(&right).await.unwrap().sent, 0); + + let report = engine + .deliver_owed(OffsetDateTime::now_utc() + Duration::minutes(6), 10) + .await + .unwrap(); + assert_eq!(report.sent, 1); + let sent = mailer.sent(); + assert_eq!(sent.len(), 1); + assert_eq!(sent[0].subject, "Card is in progress"); + assert!( + sent[0].body.contains("Column: In Progress"), + "the mail says where the card is, not where it was: {}", + sent[0].body, + ); + assert!( + !sent[0].body.contains("Column: Done"), + "the mistake is not mailed to anybody: {}", + sent[0].body, + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A second event about the same card pushes the first one's mail out again: +/// the window is quiet time, not a fixed timer from the first trigger. +#[tokio::test] +async fn a_second_event_pushes_the_batch_out_again() { + let (dir, store, workspace, admin) = waiting(5).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + a_rule(&store, &workspace, "Done", "Card is done").await; + a_rule(&store, &workspace, "In Progress", "Card is in progress").await; + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let first = moved_to(&store, &workspace, &task, "Backlog", "Done", &admin).await; + engine.on_transition(&first).await.unwrap(); + let due_then = the_one_row(&store).await.next_attempt_at.unwrap(); + + let second = moved_to(&store, &workspace, &task, "Done", "In Progress", &admin).await; + engine.on_transition(&second).await.unwrap(); + let rows = store + .sends_owed(OffsetDateTime::now_utc() + Duration::hours(2), 10) + .await + .unwrap(); + assert_eq!(rows.len(), 2, "two triggers, two rows"); + for row in &rows { + assert!( + row.next_attempt_at.unwrap() > due_then, + "the first row waits for the second one's window too", + ); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Reads the single pending row back. +async fn the_one_row(store: &TursoStore) -> izlek_core::store::MailSend { + let mut rows = store + .sends_owed(OffsetDateTime::now_utc() + Duration::hours(2), 10) + .await + .unwrap(); + assert_eq!(rows.len(), 1, "expected exactly one owed row"); + rows.remove(0) +} + +/// A card somebody edits all afternoon would never settle, so the push has a +/// ceiling measured from the oldest mail in the batch: after four windows it +/// goes out with whatever it has. +#[tokio::test] +async fn the_hold_has_a_ceiling_measured_from_the_oldest_mail() { + let (dir, store, workspace, admin) = waiting(1).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + let rule = a_rule(&store, &workspace, "Done", "Card is done").await; + + // A row born ten minutes ago: the afternoon-long edit, without the + // afternoon. + let born = OffsetDateTime::now_utc() - Duration::minutes(10); + store + .claim_send(&rule.id, "event-1", &task, "emre@izlek.sh", born, born) + .await + .unwrap() + .expect("a fresh row is claimed"); + + let far = OffsetDateTime::now_utc() + Duration::minutes(5); + store + .hold_batch(&task, "emre@izlek.sh", far, Duration::minutes(4)) + .await + .unwrap(); + + let row = the_one_row(&store).await; + let due = row.next_attempt_at.unwrap(); + assert!( + due < far, + "the push is clipped rather than granted: {due} vs {far}", + ); + assert_eq!( + due, born + Duration::minutes(4), + "the ceiling is the oldest mail's own patience running out", + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A workspace with no window is İzlek as it was: a trigger is a mail, sent +/// the moment it is owed. +#[tokio::test] +async fn no_window_sends_each_trigger_as_it_happens() { + let (dir, store, workspace, admin) = waiting(0).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + a_rule(&store, &workspace, "Done", "Card is done").await; + a_rule(&store, &workspace, "In Progress", "Card is in progress").await; + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let first = moved_to(&store, &workspace, &task, "Backlog", "Done", &admin).await; + assert_eq!(engine.on_transition(&first).await.unwrap().sent, 1); + let second = moved_to(&store, &workspace, &task, "Done", "In Progress", &admin).await; + assert_eq!(engine.on_transition(&second).await.unwrap().sent, 1); + assert_eq!(mailer.sent().len(), 2, "two crossings, two mails"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The batch is one card and one reader. Two cards are two mails, and two +/// people are two mails — nobody is told about somebody else's card because +/// the clock happened to line up. +#[tokio::test] +async fn a_batch_is_one_card_and_one_reader() { + let (dir, store, workspace, admin) = waiting(5).await; + let emre = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let grace = member(&store, &workspace, "grace@izlek.sh", "Grace").await; + let first = add_task(&store, &workspace, "Backlog", "First", None, &admin).await; + let second = add_task(&store, &workspace, "Backlog", "Second", None, &admin).await; + for task in [&first, &second] { + store.assign_task(task, &emre).await.unwrap(); + store.assign_task(task, &grace).await.unwrap(); + } + a_rule(&store, &workspace, "Done", "Card is done").await; + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + for task in [&first, &second] { + let crossing = moved_to(&store, &workspace, task, "Backlog", "Done", &admin).await; + engine.on_transition(&crossing).await.unwrap(); + } + + let report = engine + .deliver_owed(OffsetDateTime::now_utc() + Duration::minutes(6), 10) + .await + .unwrap(); + assert_eq!(report.sent, 4, "two cards times two readers"); + let mut addressed: Vec = mailer + .sent() + .into_iter() + .map(|mail| format!("{} {}", mail.to, mail.body.lines().next().unwrap_or_default())) + .collect(); + addressed.sort(); + assert_eq!(addressed.len(), 4); + assert_eq!( + addressed.iter().filter(|line| line.contains("First")).count(), + 2, + ); + assert_eq!( + addressed.iter().filter(|line| line.contains("emre@izlek.sh")).count(), + 2, + ); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An invitation belongs to nobody's card: it carries its own subject and body +/// and is never folded into a batch, however long the window is. +#[tokio::test] +async fn an_invitation_is_never_folded_into_a_batch() { + let (dir, store, workspace, admin) = waiting(5).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + a_rule(&store, &workspace, "Done", "Card is done").await; + store + .queue_invite( + "emre@izlek.sh", + "Join the workspace", + "Your link: https://izlek.sh/join", + OffsetDateTime::now_utc(), + ) + .await + .unwrap(); + + let mailer = Remembering::taking_everything(); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + let crossing = moved_to(&store, &workspace, &task, "Backlog", "Done", &admin).await; + engine.on_transition(&crossing).await.unwrap(); + + let report = engine + .deliver_owed(OffsetDateTime::now_utc() + Duration::minutes(6), 10) + .await + .unwrap(); + assert_eq!(report.sent, 2, "the invitation and the card's mail"); + let subjects: Vec = mailer + .sent() + .into_iter() + .map(|mail| mail.subject) + .collect(); + assert!(subjects.contains(&"Join the workspace".to_string()), "{subjects:?}"); + assert!(subjects.contains(&"Card is done".to_string()), "{subjects:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A batch that the server refuses is one refusal for every row in it, and +/// the retry is the same batch again — not one mail per row once the ledger +/// has been touched. +#[tokio::test] +async fn a_refused_batch_is_retried_as_a_batch() { + let (dir, store, workspace, admin) = waiting(5).await; + let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await; + let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await; + store.assign_task(&task, &mate).await.unwrap(); + a_rule(&store, &workspace, "Done", "Card is done").await; + a_rule(&store, &workspace, "In Progress", "Card is in progress").await; + + let mailer = Remembering::refusing(vec![MailError::retryable("host is down")]); + let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh"); + for (from, to) in [("Backlog", "Done"), ("Done", "In Progress")] { + let crossing = moved_to(&store, &workspace, &task, from, to, &admin).await; + engine.on_transition(&crossing).await.unwrap(); + } + + let refused = engine + .deliver_owed(OffsetDateTime::now_utc() + Duration::minutes(6), 10) + .await + .unwrap(); + assert_eq!(refused.failed, 1, "one envelope, one refusal"); + assert!(mailer.sent().is_empty()); + let owed = store + .sends_owed(OffsetDateTime::now_utc() + Duration::hours(2), 10) + .await + .unwrap(); + assert_eq!(owed.len(), 2, "both rows are still owed"); + for row in &owed { + assert_eq!(row.state, SendState::Failed); + assert_eq!(row.attempts, 1, "the batch spent one attempt, not two"); + } + + let sent = engine + .deliver_owed( + OffsetDateTime::now_utc() + Duration::minutes(6) + backoff(1), + 10, + ) + .await + .unwrap(); + assert_eq!(sent.sent, 1, "the retry is one envelope as well"); + assert_eq!(mailer.sent().len(), 1); + assert!( + store + .sends_owed(OffsetDateTime::now_utc() + Duration::hours(2), 10) + .await + .unwrap() + .is_empty(), + "nothing is left owed", + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/izlek-web/src/board.rs b/crates/izlek-web/src/board.rs index 7869b20..cafa4dc 100644 --- a/crates/izlek-web/src/board.rs +++ b/crates/izlek-web/src/board.rs @@ -214,6 +214,11 @@ fn valid_sort(sort: Option<&str>) -> &'static str { _ => "deadline", } } +/// The `?tag=` filter: an id only counts while it names a tag on this +/// board — a stale or hand-edited query string falls back to all. +fn valid_tag(tag: Option<&str>, tags: &[izlek_core::store::Tag]) -> Option { + tag.and_then(|id| tags.iter().find(|t| t.id == id).map(|t| t.id.clone())) +} /// `deadline` is the order [`izlek_core::board::load`] already hands back /// (soonest first); the other two re-order in place here so core stays free @@ -228,7 +233,12 @@ fn sort_column_cards(cards: &mut [TaskCard], sort: &str) { } /// The whole column list. -async fn board_columns(cx: &Cx, sort: String) -> Result { +async fn board_columns( + cx: &Cx, + sort: String, + tag_filter: Option, + default_tag_id: Option<&str>, +) -> Result { let user = match require_user(cx).await { Ok(user) => user, Err(refusal) => { @@ -251,6 +261,11 @@ async fn board_columns(cx: &Cx, sort: String) -> Result { }; for column in &mut view_data.columns { sort_column_cards(&mut column.cards, &sort); + if let Some(tag_id) = &tag_filter { + column + .cards + .retain(|card| card.tag.as_ref().is_some_and(|tag| tag.id == *tag_id)); + } } let today = OffsetDateTime::now_utc().date(); let may_write = user.role.can_write_tasks(); @@ -262,7 +277,7 @@ async fn board_columns(cx: &Cx, sort: String) -> Result { .collect(); let mut columns = Vec::new(); for column in view_data.columns { - columns.push(render_column(cx, column, today, may_write, &all_columns, lang).await?); + columns.push(render_column(cx, column, today, may_write, &all_columns, default_tag_id, lang).await?); } view! { @@ -277,6 +292,7 @@ async fn render_column( today: Date, may_write: bool, all_columns: &[(String, String)], + default_tag_id: Option<&str>, lang: Lang, ) -> Result { let column_id = column.column.id; @@ -295,6 +311,7 @@ async fn render_column( &column_id, may_write, all_columns, + default_tag_id, lang, ) .await?, @@ -327,6 +344,7 @@ async fn render_card( column_id: &str, may_write: bool, all_columns: &[(String, String)], + default_tag_id: Option<&str>, lang: Lang, ) -> Result { let blocks = card.blocks.len(); @@ -381,6 +399,11 @@ async fn render_card( (deadline) + if let Some(tag) = &card.tag { + if Some(tag.id.as_str()) != default_tag_id { + (tag.name.clone()) + } + } if let Some(parts) = subtasks.clone() { (format!("{parts} \u{2630}")) } @@ -509,6 +532,7 @@ struct BoardQuery { sort: Option, confirm: Option, new: Option, + tag: Option, } /// The noun a sort key shows in the ` + + for tag in &tags { + + } + + +
if overdue > 0 { (format!("{overdue} {}", t(lang, Key::Overdue))) } if blocked > 0 { (format!("{blocked} {}", t(lang, Key::Blocked))) } @@ -607,7 +651,7 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result { }
- (board_columns(cx, sort.clone()).await?) + (board_columns(cx, sort.clone(), tag_filter.clone(), default_tag_id).await?)
if let Some(task_id) = &open_task { @@ -644,6 +688,7 @@ mod sort_tests { blocks: Vec::new(), subtask_total: 0, subtask_done: 0, + tag: None, } } diff --git a/crates/izlek-web/src/detail.rs b/crates/izlek-web/src/detail.rs index f987af4..676bfb1 100644 --- a/crates/izlek-web/src/detail.rs +++ b/crates/izlek-web/src/detail.rs @@ -88,6 +88,9 @@ pub struct DetailSnapshot { pub attachment_limit_mb: u64, pub notifications: Vec, pub may_administer: bool, + /// Every tag on this workspace's board, in the admin's hand-set order — + /// the tag field reads both its options and its current value from here. + pub tags: Vec, } /// One send's fate, joined to the sends of its decision's event. @@ -360,6 +363,13 @@ async fn load_snapshot( linkable.sort_by(|a, b| a.id.cmp(&b.id)); } + // The tag field's options: every tag on the board, in the admin's + // hand-set order. A workspace with no board yet has no tags either. + let tags = match store.board(&user.workspace_id).await? { + Some(board) => store.tags(&board.id).await?, + None => Vec::new(), + }; + let may_write = user.role.can_write_tasks(); let may_administer = user.role.can_administer(); let lang = Lang::from_code(&user.language); @@ -446,6 +456,7 @@ async fn load_snapshot( allowed_file_types, attachment_limit_mb, notifications, + tags, may_administer, me: Me::from(&user), today: OffsetDateTime::now_utc().date(), @@ -515,6 +526,34 @@ async fn save_task(cx: &Cx, Form(input): Form) -> Redirect { redirect(cx, None) } +#[derive(Deserialize)] +struct SetTaskTagForm { + task_id: String, + tag_id: String, +} + +/// Files a task under a tag. A Viewer can read tags but not set them; the +/// tag has to be this workspace board's own. No activity is recorded and no +/// mail follows — re-labeling a card is not a thing anybody needs told +/// about. +#[route(POST "/api/set_task_tag")] +async fn set_task_tag(cx: &Cx, Form(input): Form) -> Redirect { + let (actor, _) = match writer_and_task(cx, &input.task_id).await { + Ok(pair) => pair, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let store = accounts(cx).store().clone(); + let Some(board) = store.board(&actor.workspace_id).await? else { + return redirect(cx, Some(Refusal::Unavailable)); + }; + let tags = store.tags(&board.id).await?; + if !tags.iter().any(|tag| tag.id == input.tag_id) { + return redirect(cx, Some(Refusal::NotFound)); + } + store.set_task_tag(&input.task_id, &input.tag_id).await?; + redirect(cx, None) +} + /// Puts someone on a task. A Viewer can neither do this nor be the target. #[route(POST "/api/assign")] async fn assign(cx: &Cx, Form(input): Form) -> Redirect { @@ -542,6 +581,7 @@ async fn assign(cx: &Cx, Form(input): Form) -> Redirect { .record_activity( &input.task_id, Some(&actor.id), + Some(&person.id), &ActivityKind::Assigned, &person.display_name, OffsetDateTime::now_utc(), @@ -573,6 +613,7 @@ async fn unassign(cx: &Cx, Form(input): Form) -> Redirect { .record_activity( &input.task_id, Some(&actor.id), + Some(&person.id), &ActivityKind::Unassigned, &person.display_name, OffsetDateTime::now_utc(), @@ -611,6 +652,7 @@ async fn link_tasks(cx: &Cx, Form(input): Form) -> Redirect { .record_activity( &input.task_id, Some(&actor.id), + None, &ActivityKind::Linked, &other.row.task_key, now, @@ -644,6 +686,7 @@ async fn unlink_tasks(cx: &Cx, Form(input): Form) -> Redirect { .record_activity( &input.task_id, Some(&actor.id), + None, &ActivityKind::Unlinked, &other.row.task_key, now, @@ -742,6 +785,7 @@ async fn set_parent(cx: &Cx, Form(input): Form) -> Redirect { .record_activity( &input.task_id, Some(&actor.id), + None, &kind, &other_key, OffsetDateTime::now_utc(), @@ -852,6 +896,7 @@ async fn delete_file(cx: &Cx, Form(input): Form) -> Redirect { .record_activity( &attachment.task_id, Some(&user.id), + None, &izlek_core::detail::ActivityKind::FileRemoved, &attachment.file_name, time::OffsetDateTime::now_utc(), @@ -1694,6 +1739,7 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool, tab: Tab) allowed_file_types, attachment_limit_mb: _, notifications, + tags, may_administer: _, } = snapshot; let lang = Lang::from_code(&me.language); @@ -1828,6 +1874,25 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool, tab: Tab) } +
+ (t(lang, Key::Project)) + if may_write { +
+ + + + } else { + + ( + detail.tag.as_ref().map(|tag| tag.name.clone()).unwrap_or_default() + ) + + } +
(t(lang, Key::Deadline)) (deadline_control(cx, &detail, today, may_write, lang).await?) diff --git a/crates/izlek-web/src/files.rs b/crates/izlek-web/src/files.rs index 2a0b94c..e999258 100644 --- a/crates/izlek-web/src/files.rs +++ b/crates/izlek-web/src/files.rs @@ -424,6 +424,7 @@ async fn upload( .record_activity( &task_id, Some(&user.id), + None, &izlek_core::detail::ActivityKind::FileAdded, &label, OffsetDateTime::now_utc(), diff --git a/crates/izlek-web/src/i18n.rs b/crates/izlek-web/src/i18n.rs index 3649499..db32717 100644 --- a/crates/izlek-web/src/i18n.rs +++ b/crates/izlek-web/src/i18n.rs @@ -102,10 +102,23 @@ pub enum Key { // Topbar nav / chrome shared by board.rs, rules.rs, logs.rs, settings.rs. NavBoard, NavMailRules, + NavTags, NavLogs, NavSettings, AdminOnly, + // tags.rs — Project/AllTags also serve board.rs's filter and detail.rs. + NewTag, + NameLabel, + AddTag, + SaveTag, + EditThisTag, + DeleteThisTag, + MoveTagUp, + MoveTagDown, + Project, + AllTags, + // settings.rs YourProfile, Remove, @@ -329,6 +342,13 @@ pub enum Key { Oldest, From, To, + // people.rs + TasksOpenLabel, + TasksDoneLabel, + TasksCreatedLabel, + CommentsLabel, + RecentActivity, + MailBatchLabel, } /// The lone templated phrase — a name in the middle reads worse as two @@ -497,6 +517,29 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (AdminOnly, En) => "Admin only", (AdminOnly, Tr) => "Sadece yönetici", + (NavTags, En) => "Tags", + (NavTags, Tr) => "Etiketler", + (NewTag, En) => "New tag", + (NewTag, Tr) => "Yeni etiket", + (NameLabel, En) => "NAME", + (NameLabel, Tr) => "İSİM", + (AddTag, En) => "Add tag", + (AddTag, Tr) => "Etiket ekle", + (SaveTag, En) => "Save tag", + (SaveTag, Tr) => "Etiketi kaydet", + (EditThisTag, En) => "Edit this tag", + (EditThisTag, Tr) => "Bu etiketi düzenle", + (DeleteThisTag, En) => "Delete this tag", + (DeleteThisTag, Tr) => "Bu etiketi sil", + (MoveTagUp, En) => "Move up", + (MoveTagUp, Tr) => "Yukarı taşı", + (MoveTagDown, En) => "Move down", + (MoveTagDown, Tr) => "Aşağı taşı", + (Project, En) => "Project", + (Project, Tr) => "Proje", + (AllTags, En) => "All", + (AllTags, Tr) => "Tümü", + (YourProfile, En) => "Your profile", (YourProfile, Tr) => "Profilin", (Remove, En) => "Remove", @@ -936,6 +979,18 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (From, Tr) => "Başlangıç", (To, En) => "To", (To, Tr) => "Bitiş", + (TasksOpenLabel, En) => "Open tasks", + (TasksOpenLabel, Tr) => "Açık görevler", + (TasksDoneLabel, En) => "Done tasks", + (TasksDoneLabel, Tr) => "Biten görevler", + (TasksCreatedLabel, En) => "Tasks created", + (TasksCreatedLabel, Tr) => "Oluşturulan görevler", + (CommentsLabel, En) => "Comments", + (CommentsLabel, Tr) => "Yorumlar", + (RecentActivity, En) => "Recent activity", + (RecentActivity, Tr) => "Son etkinlik", + (MailBatchLabel, En) => "Mail delay (minutes)", + (MailBatchLabel, Tr) => "Posta gecikmesi (dakika)", } } diff --git a/crates/izlek-web/src/layout.rs b/crates/izlek-web/src/layout.rs index 449a8e8..08e271f 100644 --- a/crates/izlek-web/src/layout.rs +++ b/crates/izlek-web/src/layout.rs @@ -124,6 +124,7 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result {
(me.display_name.clone())
(me.email.clone())
(t(lang, role_key))
+ (t(lang, Key::YourProfile))
@@ -132,23 +133,25 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result { } } -/// The four signed-in pages, as the topbar nav links between them. +/// The five signed-in pages, as the topbar nav links between them. #[derive(Clone, Copy, PartialEq)] pub enum NavPage { Board, Rules, Logs, + Tags, Settings, } impl NavPage { - const ALL: [Self; 4] = [Self::Board, Self::Rules, Self::Logs, Self::Settings]; + const ALL: [Self; 5] = [Self::Board, Self::Rules, Self::Logs, Self::Tags, Self::Settings]; fn href(self) -> &'static str { match self { Self::Board => "/", Self::Rules => "/rules", Self::Logs => "/logs", + Self::Tags => "/tags", Self::Settings => "/settings", } } @@ -158,13 +161,14 @@ impl NavPage { Self::Board => Key::NavBoard, Self::Rules => Key::NavMailRules, Self::Logs => Key::NavLogs, + Self::Tags => Key::NavTags, Self::Settings => Key::NavSettings, } } } -/// The topbar's page nav, shared by every signed-in page: the four pages -/// with the current one marked, the admin-only ones (rules, logs) shown +/// The topbar's page nav, shared by every signed-in page: the five pages +/// with the current one marked, the admin-only ones (rules, logs, tags) shown /// only to roles that can administer. Plain ``s — the soft-nav forwarder /// swaps them like any same-origin link, so `data-hard` stays off. pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang: Lang) -> Result { @@ -172,7 +176,7 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang: cx =>
(crate::layout::avatar(cx, &member_person, "avatar-sm").await?) - (member.display_name.clone()) + (member.display_name.clone()) if member.is_you { (t(lang, Key::You)) } diff --git a/crates/izlek-web/src/tags.rs b/crates/izlek-web/src/tags.rs new file mode 100644 index 0000000..dbb1944 --- /dev/null +++ b/crates/izlek-web/src/tags.rs @@ -0,0 +1,364 @@ +//! Task tags, ported from `izlek-web/src/rules.rs` onto topcoat's +//! server-rendered pages. +//! +//! The screen is the admin's, and so is every call behind it: a tag renames +//! what every member sees on the board and in the task modal, so writing one +//! is not something a Member may do even if they reach the endpoint directly. +//! The chip in the artboard says "Admin only"; the guard is in the handlers. +//! +//! There is no client-side signal here to hold which row is being edited — +//! every topcoat page is rendered fresh, server-side, on every request. Which +//! tag (if any) is open for editing rides `?edit=` on `/tags` +//! itself: the row renders as the rename form server-side instead of the +//! display row, no script required. +//! +//! The board's default tag ships no delete control: the store refuses the +//! delete anyway (every task falls back to it), and a control that cannot +//! act is not drawn. + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use topcoat::Result; +use topcoat::context::Cx; +use topcoat::router::content::{Form, Json}; +use topcoat::router::request::headers; +use topcoat::router::{HeaderName, StatusCode, header, page, query_params, route}; +use topcoat::view::view; + +use izlek_core::store::{Store, Tag, User}; + +use crate::i18n::{Key, Lang, t}; +use crate::server::{Refusal, accounts, refusal_of, require_admin}; + +/// One tag as the screen reads it: a name, an order and whether it is the +/// default every task wears when nothing else is chosen. +#[derive(Clone, Debug, Serialize)] +struct TagLine { + id: String, + name: String, + position: i64, + is_default: bool, +} + +/// Every tag on the workspace's own board, in the admin's hand-set order. +async fn tags_of( + store: &Arc, + user: &User, +) -> std::result::Result, Refusal> { + let Some(board) = store + .board(&user.workspace_id) + .await + .map_err(|_| Refusal::Unavailable)? + else { + return Err(Refusal::Unavailable); + }; + Ok(store + .tags(&board.id) + .await + .map_err(|_| Refusal::Unavailable)? + .into_iter() + .map(|tag| TagLine { + id: tag.id, + name: tag.name, + position: tag.position, + is_default: tag.is_default, + }) + .collect()) +} + +/// The admin's store, once the tag id has been shown to name a tag on this +/// workspace's own board. +/// +/// A tag id is opaque and arrives from the browser, so "not yours" and "not a +/// tag" are the same answer: neither tells the caller whether the id exists +/// somewhere else. +async fn tag_of_this_workspace( + cx: &Cx, + tag_id: &str, +) -> std::result::Result<(Arc, User, Tag), Refusal> { + let user = require_admin(cx).await?; + let store = accounts(cx).store().clone(); + let board = store + .board(&user.workspace_id) + .await + .map_err(|_| Refusal::Unavailable)? + .ok_or(Refusal::Unavailable)?; + let tag = store + .tags(&board.id) + .await + .map_err(|_| Refusal::Unavailable)? + .into_iter() + .find(|tag| tag.id == tag_id) + .ok_or(Refusal::NotFound)?; + Ok((store, user, tag)) +} + +/// The page a browser without script is sent back to on a 303: the page the +/// form was posted from, or home when there is no `Referer` to read. +fn back_to(cx: &Cx) -> String { + headers(cx) + .get(header::REFERER) + .and_then(|value| value.to_str().ok()) + .unwrap_or("/") + .to_string() +} + +/// A 303 to [`back_to`], carrying `refusal` as the body for +/// `crate::server::carry_refusal_on_redirect` to read and copy onto the query. +type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json>)>; + +fn redirect(cx: &Cx, refusal: Option) -> Redirect { + Ok(( + StatusCode::SEE_OTHER, + [(header::LOCATION, back_to(cx))], + Json(refusal), + )) +} + +#[derive(Deserialize)] +struct CreateTagForm { + name: String, +} + +/// Writes one tag. A duplicate name is the store's `Conflict`, which lands +/// here like every other store error: the admin sees "something went wrong" +/// and the list still shows the tag they collide with. +#[route(POST "/api/create_tag")] +async fn create_tag(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_admin(cx).await { + Ok(user) => user, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let name = input.name.trim().to_string(); + if name.is_empty() { + return redirect(cx, Some(Refusal::EmptyTag)); + } + let store = accounts(cx).store().clone(); + let board = match store.board(&user.workspace_id).await { + Ok(Some(board)) => board, + _ => return redirect(cx, Some(Refusal::Unavailable)), + }; + if store + .create_tag(&board.id, &name, time::OffsetDateTime::now_utc()) + .await + .is_err() + { + return redirect(cx, Some(Refusal::Unavailable)); + } + redirect(cx, None) +} + +#[derive(Deserialize)] +struct RenameTagForm { + tag_id: String, + name: String, +} + +/// Rewrites a tag's name in place, guarded exactly like the rest — the tag +/// itself has to be this workspace's, or an id from elsewhere could be +/// renamed by an admin who never owned it. +#[route(POST "/api/rename_tag")] +async fn rename_tag(cx: &Cx, Form(input): Form) -> Redirect { + let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await { + Ok(triple) => triple, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let name = input.name.trim().to_string(); + if name.is_empty() { + return redirect(cx, Some(Refusal::EmptyTag)); + } + if store.rename_tag(&input.tag_id, &name).await.is_err() { + return redirect(cx, Some(Refusal::Unavailable)); + } + redirect(cx, None) +} + +#[derive(Deserialize)] +struct DeleteTagForm { + tag_id: String, +} + +/// Removes a tag. The store refuses to delete the default — every task +/// without a tag wears it — and that refusal lands here as "unavailable"; +/// the row itself ships no delete control in the first place. +#[route(POST "/api/delete_tag")] +async fn delete_tag(cx: &Cx, Form(input): Form) -> Redirect { + let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await { + Ok(triple) => triple, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + if store.delete_tag(&input.tag_id).await.is_err() { + return redirect(cx, Some(Refusal::Unavailable)); + } + redirect(cx, None) +} + +#[derive(Deserialize)] +struct MoveTagForm { + tag_id: String, + direction: String, +} + +/// Steps a tag up or down the board's hand-set order. A move off either end +/// is the store's no-op, not an error; a direction that is neither word is a +/// form gone wrong, and does nothing. +#[route(POST "/api/move_tag")] +async fn move_tag(cx: &Cx, Form(input): Form) -> Redirect { + let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await { + Ok(triple) => triple, + Err(refusal) => return redirect(cx, Some(refusal)), + }; + let up = match input.direction.as_str() { + "up" => true, + "down" => false, + _ => return redirect(cx, None), + }; + if store.move_tag(&input.tag_id, up).await.is_err() { + return redirect(cx, Some(Refusal::Unavailable)); + } + redirect(cx, None) +} + +/// Which tag (if any) `/tags` renders open for editing. +#[query_params(error = redirect("/tags"))] +struct TagsQuery { + edit: Option, +} + +/// The "New tag" control and the form inside it. A `
` rather than +/// anything script-driven, so a browser with no script can still open it and +/// post the form. +async fn composer(cx: &Cx, refusal: Option<&Refusal>, lang: Lang) -> Result { + view! { + cx => +
+ (t(lang, Key::NewTag)) +
+ +
+ if let Some(refusal) = refusal { + (refusal.message_in(lang)) + } + +
+
+
+ } +} + +/// One tag's row: the rename form in place of it when `editing`, its display +/// otherwise. The default tag draws no delete form — the store would refuse +/// it, and a control that cannot act is not drawn. +async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal>, lang: Lang) -> Result { + if editing { + return view! { + cx => +
+
+ + +
+ if let Some(refusal) = refusal { + (refusal.message_in(lang)) + } + (t(lang, Key::Cancel)) + +
+
+
+ }; + } + + view! { + cx => +
+ (tag.name.clone()) + + (t(lang, Key::EditLabel)) + +
+ + + +
+
+ + + +
+ + if !tag.is_default { +
+ + +
+ } +
+ } +} + +#[page("/tags")] +async fn tags_page(cx: &Cx) -> Result { + let user = match require_admin(cx).await { + Ok(user) => user, + Err(refusal) => { + return view! { +
+

(refusal.message())

+

(t(Lang::En, Key::BackToBoard))

+
+ }; + } + }; + let lang = Lang::from_code(&user.language); + let store = accounts(cx).store().clone(); + let tags = match tags_of(&store, &user).await { + Ok(tags) => tags, + Err(refusal) => { + return view! { +
+

(refusal.message_in(lang))

+

(t(lang, Key::BackToBoard))

+
+ }; + } + }; + let edit_id = query_params::(cx)?.edit.clone(); + let create_refusal = refusal_of(cx, "create_tag"); + let rename_refusal = refusal_of(cx, "rename_tag"); + + view! { +
+ (crate::layout::mark(cx).await?) + (crate::layout::topbar_nav(cx, crate::layout::NavPage::Tags, user.role, lang).await?) +
+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?) +
+ +
+
+
+

(t(lang, Key::NavTags))

+ (t(lang, Key::AdminOnly)) +
+ + (composer(cx, create_refusal.as_ref(), lang).await?) + +
+ for tag in &tags { + (tag_row(cx, tag, edit_id.as_deref() == Some(tag.id.as_str()), rename_refusal.as_ref(), lang).await?) + } +
+
+ (crate::dropdown::dropdown_script(cx).await?) + (crate::layout::escape_script(cx).await?) +
+ } +} diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index d82038e..8742e27 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -2477,6 +2477,7 @@ async fn a_member_who_posts_new_limits_anyway_is_refused() { ("attachment_limit_mb", "400"), ("photo_limit_mb", "19"), ("allowed_file_types", "png"), + ("mail_batch_minutes", "5"), ], ) .await; @@ -2508,6 +2509,7 @@ async fn an_admin_changes_the_limits_and_they_stay_changed() { ("attachment_limit_mb", "10"), ("photo_limit_mb", "1"), ("allowed_file_types", ".PNG, png, pdf"), + ("mail_batch_minutes", "5"), ], ) .await; @@ -2544,6 +2546,7 @@ async fn a_limit_outside_what_the_disk_should_promise_is_refused() { ("attachment_limit_mb", attachment), ("photo_limit_mb", photo), ("allowed_file_types", ""), + ("mail_batch_minutes", "5"), ], ) .await; @@ -2575,6 +2578,7 @@ async fn a_file_type_that_is_not_an_extension_is_refused() { ("attachment_limit_mb", "25"), ("photo_limit_mb", "2"), ("allowed_file_types", "../etc/passwd"), + ("mail_batch_minutes", "5"), ], ) .await; @@ -4112,6 +4116,7 @@ async fn a_file_past_the_workspace_limit_is_refused_before_it_is_kept() { ("attachment_limit_mb", "1"), ("photo_limit_mb", "2"), ("allowed_file_types", ""), + ("mail_batch_minutes", "5"), ], ) .await; @@ -4165,6 +4170,7 @@ async fn a_file_type_off_the_list_is_refused() { ("attachment_limit_mb", "25"), ("photo_limit_mb", "2"), ("allowed_file_types", "png"), + ("mail_batch_minutes", "5"), ], ) .await; @@ -5347,6 +5353,7 @@ async fn a_photo_over_the_workspace_limit_is_refused_and_stores_nothing() { ("attachment_limit_mb", "25"), ("photo_limit_mb", "1"), ("allowed_file_types", ""), + ("mail_batch_minutes", "5"), ], ) .await; @@ -7304,6 +7311,220 @@ async fn a_member_may_not_check_the_sender() { assert_ne!(answer.body, "null", "a member was allowed to dial the server"); } +// --- tags ------------------------------------------------------------------- + +/// Makes a tag over HTTP and hands the store row back — the tests need the +/// id, and the mutation itself is still a real post. +async fn a_tag(app: &App, cookie: &str, name: &str) -> izlek_core::store::Tag { + let answer = app.post("/api/create_tag", Some(cookie), &[("name", name)]).await; + assert_eq!(answer.body, "null", "the tag was refused: {}", answer.body); + let workspace_id = app.workspace_id().await; + let board = app + .store + .board(&workspace_id) + .await + .unwrap() + .expect("no board"); + app.store + .tags(&board.id) + .await + .unwrap() + .into_iter() + .find(|tag| tag.name == name) + .expect("the new tag is not on the board") +} + +#[tokio::test] +async fn a_non_admin_cannot_create_rename_delete_or_move_a_tag() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let member = invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await; + + let create = app.post("/api/create_tag", Some(&member), &[("name", "Sneak")]).await; + assert!(create.body.contains("Forbidden"), "{}", create.body); + let rename = app + .post( + "/api/rename_tag", + Some(&member), + &[("tag_id", "t1"), ("name", "Sneak")], + ) + .await; + assert!(rename.body.contains("Forbidden"), "{}", rename.body); + let delete = app.post("/api/delete_tag", Some(&member), &[("tag_id", "t1")]).await; + assert!(delete.body.contains("Forbidden"), "{}", delete.body); + let move_it = app + .post( + "/api/move_tag", + Some(&member), + &[("tag_id", "t1"), ("direction", "up")], + ) + .await; + assert!(move_it.body.contains("Forbidden"), "{}", move_it.body); +} + +#[tokio::test] +async fn a_viewer_cannot_set_a_task_tag() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let viewer = invited(&app, &admin_cookie, "hush@izlek.sh", "Hush Rao", Role::Viewer).await; + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Label me not").await; + let aurora = a_tag(&app, &admin_cookie, "Aurora").await; + + let answer = app + .post( + "/api/set_task_tag", + Some(&viewer), + &[("task_id", &task), ("tag_id", &aurora.id)], + ) + .await; + assert!(answer.body.contains("Forbidden"), "{}", answer.body); +} + +#[tokio::test] +async fn the_task_modal_lists_every_tag_and_names_the_current_one() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Sort into color").await; + let aurora = a_tag(&app, &admin_cookie, "Aurora").await; + + let workspace_id = app.workspace_id().await; + let board = app + .store + .board(&workspace_id) + .await + .unwrap() + .expect("no board"); + let default_id = app + .store + .tags(&board.id) + .await + .unwrap() + .into_iter() + .find(|tag| tag.is_default) + .expect("no default tag") + .id; + let selected = |html: &str, id: &str| html.contains(&format!(r#"value="{id}" selected"#)); + + let page = String::from_utf8( + app.get(&format!("/?task={task}"), Some(&admin_cookie)).await.bytes, + ) + .unwrap(); + assert!(page.contains(r#"name="tag_id""#), "no tag field in the modal: {page}"); + assert!(page.contains("General"), "the default tag is not offered: {page}"); + assert!(page.contains("Aurora"), "the new tag is not offered: {page}"); + assert!(selected(&page, &default_id), "the current tag is not named: {page}"); + assert!(!selected(&page, &aurora.id), "an unchosen tag reads as current: {page}"); + + let switched = app + .post( + "/api/set_task_tag", + Some(&admin_cookie), + &[("task_id", &task), ("tag_id", &aurora.id)], + ) + .await; + assert_eq!(switched.body, "null", "the switch was refused: {}", switched.body); + + let page = String::from_utf8( + app.get(&format!("/?task={task}"), Some(&admin_cookie)).await.bytes, + ) + .unwrap(); + assert!(selected(&page, &aurora.id), "the switch did not name Aurora: {page}"); + assert!(!selected(&page, &default_id), "the old tag still reads current: {page}"); +} + +#[tokio::test] +async fn the_board_tag_filter_narrows_cards_and_an_unknown_tag_falls_back_to_all() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let first = a_task(&app, &admin_cookie, &column, "Aurora work").await; + let second = a_task(&app, &admin_cookie, &column, "Boreal work").await; + let aurora = a_tag(&app, &admin_cookie, "Aurora").await; + let boreal = a_tag(&app, &admin_cookie, "Boreal").await; + + let switched = app + .post( + "/api/set_task_tag", + Some(&admin_cookie), + &[("task_id", &second), ("tag_id", &boreal.id)], + ) + .await; + assert_eq!(switched.body, "null", "the switch was refused: {}", switched.body); + + let tagged = app + .post( + "/api/set_task_tag", + Some(&admin_cookie), + &[("task_id", &first), ("tag_id", &aurora.id)], + ) + .await; + assert_eq!(tagged.body, "null", "the first switch was refused: {}", tagged.body); + + let filtered = String::from_utf8( + app.get(&format!("/?tag={}", aurora.id), Some(&admin_cookie)) + .await + .bytes, + ) + .unwrap(); + assert!(filtered.contains("Aurora work"), "the tagged card is gone: {filtered}"); + assert!( + !filtered.contains("Boreal work"), + "the other card did not filter out: {filtered}" + ); + + let everything = String::from_utf8( + app.get("/?tag=bogus", Some(&admin_cookie)).await.bytes, + ) + .unwrap(); + assert!( + everything.contains("Aurora work") && everything.contains("Boreal work"), + "an unknown tag did not fall back to all: {everything}" + ); + assert!( + everything.contains("General"), + "the default tag is not an option in the filter: {everything}" + ); +} + +#[tokio::test] +async fn the_default_tag_cannot_be_deleted_and_ships_no_delete_button() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + let _aurora = a_tag(&app, &admin_cookie, "Aurora").await; + + let workspace_id = app.workspace_id().await; + let board = app + .store + .board(&workspace_id) + .await + .unwrap() + .expect("no board"); + let default_id = app + .store + .tags(&board.id) + .await + .unwrap() + .into_iter() + .find(|tag| tag.is_default) + .expect("no default tag") + .id; + + let refused = app + .post("/api/delete_tag", Some(&admin_cookie), &[("tag_id", &default_id)]) + .await; + assert!(refused.body.contains("Unavailable"), "{}", refused.body); + + let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap(); + assert_eq!( + page.matches(r#"action="/api/delete_tag""#).count(), + 1, + "the default tag's row ships a delete control: {page}" + ); + assert!(page.contains("Aurora"), "the created tag is not listed: {page}"); +} + /// An open live stream must not be something the shutdown has to wait out. /// /// The server stops accepting connections and then gives in-flight requests @@ -7338,3 +7559,139 @@ async fn a_live_stream_ends_when_the_server_is_told_to_stop() { .await; assert!(ended.is_ok(), "the stream outlived the stop"); } +// --- profile page ----------------------------------------------------------- + +/// One task row id, for the profile fixture. Fixture setup goes through the +/// store directly, the way `record_sender_check`'s test does. +async fn a_task_by(app: &App, board_id: &str, column_id: &str, title: &str, creator: &str) -> String { + app.store + .create_task(izlek_core::store::NewTask { + board_id, + column_id, + parent_id: None, + title, + description: "", + deadline: None, + created_by: creator, + }) + .await + .unwrap() + .row + .id +} + +/// Two tasks on Mem's plate, one finished under her, three she opened, four +/// comments — the numbers the profile page has to show: 2 / 1 / 3 / 4. +async fn profile_counts_fixture(app: &App, member: &str, admin: &str) { + let workspace = app.workspace_id().await; + let board = app.store.board(&workspace).await.unwrap().expect("no board"); + let columns = app.store.columns(&board.id).await.unwrap(); + let open = columns + .iter() + .find(|column| !column.is_done) + .expect("no open column") + .id + .clone(); + let done = columns + .iter() + .find(|column| column.is_done) + .expect("no done column") + .id + .clone(); + let now = time::OffsetDateTime::now_utc(); + + let hold = a_task_by(app, &board.id, &open, "Hold the door", admin).await; + app.store.assign_task(&hold, member).await.unwrap(); + let other = a_task_by(app, &board.id, &open, "Oil the hinges", admin).await; + app.store.assign_task(&other, member).await.unwrap(); + let finished = a_task_by(app, &board.id, &open, "Paint the frame", admin).await; + app.store.assign_task(&finished, member).await.unwrap(); + app.store.move_task(&finished, &open, &done, admin, now).await.unwrap(); + for title in ["Sweep", "Mop", "Dust"] { + a_task_by(app, &board.id, &open, title, member).await; + } + for _ in 0..4 { + app.store.add_comment(&hold, member, "a note", now).await.unwrap(); + } +} + +#[tokio::test] +async fn a_member_may_read_another_members_profile_name_address_and_counts() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await; + let reader = invited(&app, &admin_cookie, "ivy@izlek.sh", "Ivy Lear", Role::Member).await; + let mem_id = user_id(&app, "mem@izlek.sh").await; + let admin_id = app + .store + .users(&app.workspace_id().await) + .await + .unwrap() + .into_iter() + .find(|user| user.role == Role::Admin) + .unwrap() + .id; + profile_counts_fixture(&app, &mem_id, &admin_id).await; + + let page = app.get(&format!("/people/{mem_id}"), Some(&reader)).await; + assert_eq!(page.status.as_u16(), 200); + let html = String::from_utf8(page.bytes).unwrap(); + assert!(html.contains("Mem Ber"), "{html}"); + assert!(html.contains("mem@izlek.sh"), "{html}"); + for count in [2, 1, 3, 4] { + assert_eq!( + html.matches(&format!(">{count}")).count(), + 1, + "the {count} stat is not on the page once: {html}" + ); + } +} + +#[tokio::test] +async fn a_profile_is_not_found_signed_out_or_outside_the_workspace() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await; + let mem_id = user_id(&app, "mem@izlek.sh").await; + + let signed_out = app.get(&format!("/people/{mem_id}"), None).await; + assert_eq!(signed_out.status.as_u16(), 404, "never a 403, never a page"); + + // A person who exists, but in another workspace, reads exactly like a + // missing one — the id is not looked at twice. + let other = App::open().await; + // A workspace has to be claimed before it holds anybody to be a stranger. + let _ = admin(&other).await; + let stranger = other.store.users(&other.workspace_id().await).await.unwrap()[0] + .id + .clone(); + let foreign = app.get(&format!("/people/{stranger}"), Some(&admin_cookie)).await; + assert_eq!(foreign.status.as_u16(), 404); + + let missing = app.get("/people/nobody", Some(&admin_cookie)).await; + assert_eq!(missing.status.as_u16(), 404); +} + +#[tokio::test] +async fn only_your_own_profile_offers_the_edit_link() { + let app = App::open().await; + let admin_cookie = admin(&app).await; + invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await; + let mem_id = user_id(&app, "mem@izlek.sh").await; + let ivy = invited(&app, &admin_cookie, "ivy@izlek.sh", "Ivy Lear", Role::Member).await; + let ivy_id = user_id(&app, "ivy@izlek.sh").await; + + let own = app.get(&format!("/people/{ivy_id}"), Some(&ivy)).await; + let own_html = String::from_utf8(own.bytes).unwrap(); + assert!( + own_html.contains(r#"href="/settings?section=profile""#), + "no edit link on your own profile: {own_html}" + ); + + let theirs = app.get(&format!("/people/{mem_id}"), Some(&ivy)).await; + let theirs_html = String::from_utf8(theirs.bytes).unwrap(); + assert!( + !theirs_html.contains("settings?section=profile"), + "someone else's profile grew an editor: {theirs_html}" + ); +} \ No newline at end of file diff --git a/style/_ledger.scss b/style/_ledger.scss index 84a217c..92f15ed 100644 --- a/style/_ledger.scss +++ b/style/_ledger.scss @@ -103,6 +103,14 @@ &-off { background: transparent; } } + .tag-row { + background: transparent; + border: none; + border-bottom: 1px solid var(--border); + border-radius: 0; + padding: 14px 2px; + } + // Activity log reads as a ruled ledger column too: no boxes, the actor // named in the display face like .member-name. .log-row { diff --git a/style/main.scss b/style/main.scss index b29784b..40e61a8 100644 --- a/style/main.scss +++ b/style/main.scss @@ -348,6 +348,18 @@ body:has(.settings-shell) { > .settings-shell { flex: 1; min-height: 0; } } +// A profile is one column of its own; it pans inside itself like every other +// page here, and the document never grows a scrollbar. +body:has(.people-shell) { + height: 100vh; + overflow: hidden; + display: flex; + flex-direction: column; + + > * { flex: none; } + > .people-shell { flex: 1; min-height: 0; } +} + a { color: var(--accent); transition: color var(--dur-fast) var(--ease); @@ -882,6 +894,15 @@ a { color: var(--muted); } +.card-tag { + font-family: var(--font-mono); + font-size: 11px; + color: var(--muted); + background: var(--surface-sunken); + border-radius: var(--radius-sm); + padding: 2px 6px; +} + /// Parts still open is the same warning the blocker chips carry: this card /// cannot reach the done column yet. .card-subtasks-open { color: var(--warn-ink); } @@ -3461,3 +3482,125 @@ input[type="radio"] { flex-direction: column; gap: 6px; } + +.tag-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.tag-row { + display: flex; + align-items: center; + gap: 14px; + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-md); +} + +.tag-name { + flex-grow: 1; + min-width: 0; + font-size: 13px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.tag-new { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); +} + +.tag-new-open { + display: flex; + align-items: center; + height: var(--control-h); + padding: 0 16px; + font-size: 13px; + font-weight: 600; + color: var(--accent-ink); + cursor: pointer; + list-style: none; + + &::marker, &::-webkit-details-marker { display: none; } + &::before { content: '+'; margin-right: 8px; font-size: 13px; } +} + +.tag-form { + display: flex; + flex-direction: column; + gap: 20px; + padding: 0 16px 16px; + border-top: 1px solid var(--border); + padding-top: 16px; +} + +.tag-field { + display: flex; + flex-direction: column; + gap: 6px; +} + +// --- Profile (a member's page) ---------------------------------------------- + +.people-shell { + width: 100%; + max-width: 860px; + margin: 0 auto; + padding: 24px 32px 40px; + display: flex; + flex-direction: column; + gap: 20px; + overflow-y: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { display: none; } + > * { flex: none; } +} + +.people-stats { + display: flex; + flex-wrap: wrap; + gap: 28px; + margin: 0; + + dt { + font-size: 11px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); + } + + dd { + margin: 0; + font-size: 20px; + font-weight: 600; + font-variant-numeric: tabular-nums; + } +} + +.people-feed { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; + gap: 8px; + + li { + display: flex; + align-items: baseline; + gap: 10px; + } +} + +.people-feed-day { + margin-left: auto; + flex: none; + white-space: nowrap; + color: var(--muted); + font-size: 12px; +}