forge
Explore
Log in

Don't you dare go Hollow

One tag per card, a page per person, one schema, one mail

Browse files at this commit

de54fefad0b720acbf1b8cdf24431ae16c102d69Ahmet Kaan GümüşParent: e49a1d2
  • feat
    • one tag per card, a page per person, one schema, one mail
Show full message
✨ feat(izlek): one tag per card, a page per person, one schema, one mail

Four things that turned out to be one commit, because the schema underneath
them stopped being a chain.

The assignment rule mailed the wrong people. "Notify the assignees" was read
as "notify everyone on the card whenever anyone is assigned", so three
assignments were nine mails. An activity line that is *about* somebody now
carries that person's id, and the audience for such a line is that person
alone — read from the stored subject rather than from the display name in
the detail, so a restart resolves the audience the first pass resolved and
two people may share a name.

Tags: a card belongs to exactly one. Every board is born with a `General`
tag that cannot be deleted and cannot be a second default, deleting a tag
moves its cards there, and `task.tag_id` is `NOT NULL` — there is no
tagless state to write a view around. Admins order them on /tags.

Every member has a page at /people/{id}: their photo, their address, what
they hold open, what they finished, what they opened and what they said.
A stranger's id is a 404 rather than a 403, because a workspace does not
confirm who is in it to somebody who is not.

The migration chain is gone. `0001_init.sql` is now the whole declared
schema, and a database is compared against it by fingerprint at boot: if it
does not match, the store keeps a backup and rebuilds it onto the declared
shape before it will serve — `izlek reconcile` is the same code with a flag.
The rebuild carries data across by a hand-written column map rather than by
guessing from a diff, which is how every task ends up on its *own* board's
default tag. It was run against the live database before this landed: 1
workspace, 4 users, 6 tasks, 59 activity rows, a 1 MB attachment and three
photos, all byte-identical afterwards with `foreign_key_check` clean.

And mail waits. A workspace has a quiet window (`mail_batch_minutes`,
default 5, 0 for the old behaviour): an owed mail is born due when the
window closes, and each further event about the same card pushes that
person's pending rows out again. What goes out is one envelope per card per
reader, stating where the card ended up — column, deadline, assignees —
rather than one mail per trigger. Create a card, fix its column, assign it,
set a deadline: four rules, four triggers, one mail. The push is clipped at
four windows from the oldest mail in the batch, so a card somebody edits all
afternoon still goes out. Invites and notices are never folded into a batch;
they carry their own subject and body. A batch the server refuses spends one
attempt for the whole envelope and is retried as one envelope, because the
claim is still the only way to mail a row.

Tests: his workflow is one mail and a wrong column put right is one mail
naming only the right column; the debounce, the ceiling and the zero window
each have their own case; the alteration is carried across by reconcile in
both directions — a database that never had the column gets the default, one
whose admin already chose a number keeps it.

28 changed files +5672 -586

.gitignoremodified+1 -0
@@ -8,3 +8,4 @@ izlek.key
8 /config/izlek.toml8 /config/izlek.toml
9 CLAUDE.md9 CLAUDE.md
10 /crates/izlek-web/assets10 /crates/izlek-web/assets
11+*.db.backup-*
crates/izlek-core/migrations/0001_init.sqlmodified+61 -9
@@ -1,18 +1,16 @@
1 -- Izlek's schema, whole, in one file.1 -- Izlek's schema, whole, in one file.
2 --2 --
3--- Plain versioned SQL applied at boot: Turso has no migration runner of its3+-- One plain SQL file, applied at boot to an empty database: Turso has no
4--- own, and keeping the schema as SQL is what makes the store trait swappable.4+-- migration runner of its own, and keeping the schema as SQL is what makes
5+-- the store trait swappable.
5 -- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by6 -- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by
6 -- creation, and Crockford-uppercase already, which is what lets a task key7 -- creation, and Crockford-uppercase already, which is what lets a task key
7 -- borrow its tail.8 -- borrow its tail.
8 --9 --
9--- This file is the whole schema, not the first link of a chain. Nothing has10+-- This file is the whole schema, and it is edited in place: a change to a
10--- been released, so a change to a table is made here, in the table, and the11+-- table is made here, in the table, never appended as an ALTER. An existing
11--- database it describes is recreated — twenty migrations were collapsed into12+-- database is brought up to it by `izlek reconcile`, not by the store, so a
12--- this file once for that reason, and a twenty-first would start the same rot13+-- change to a table lands in two places — here, and in that tool's copy map.
13--- over. The reasoning the old migrations carried is kept, on the tables it
14--- explains. The day Izlek runs somewhere with data worth keeping, the next
15--- change becomes 0002 and this note goes away.
16 14
17 CREATE TABLE workspace (15 CREATE TABLE workspace (
18 id TEXT PRIMARY KEY,16 id TEXT PRIMARY KEY,
@@ -25,6 +23,12 @@ CREATE TABLE workspace (
25 photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,23 photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,
26 -- JSON array of allowed extensions. An empty array means every type.24 -- JSON array of allowed extensions. An empty array means every type.
27 allowed_file_types TEXT NOT NULL DEFAULT '[]',25 allowed_file_types TEXT NOT NULL DEFAULT '[]',
26+ -- How long a notification waits for the rest of its workflow. One normal
27+ -- sequence — open a card, fix the column, assign it, set a deadline — is
28+ -- four writes and was four mails; held for a few quiet minutes it is one
29+ -- mail saying where the card ended up. Zero sends each one the moment it
30+ -- is owed, which is what this did before the column existed.
31+ mail_batch_minutes INTEGER NOT NULL DEFAULT 5,
28 -- The single sender every mail in the workspace goes through, written by32 -- The single sender every mail in the workspace goes through, written by
29 -- the admin in Settings rather than by whoever has a shell on the box: a33 -- the admin in Settings rather than by whoever has a shell on the box: a
30 -- three-person team has those be different people, and the second one is34 -- three-person team has those be different people, and the second one is
@@ -51,6 +55,19 @@ CREATE TABLE workspace (
51 smtp_test_at TEXT,55 smtp_test_at TEXT,
52 smtp_test_ms INTEGER,56 smtp_test_ms INTEGER,
53 smtp_test_error TEXT,57 smtp_test_error TEXT,
58+ -- Whether the mail server let us in, which is a different fact from
59+ -- whether a mail was delivered. `smtp_test_*` above records a real
60+ -- message going out to a real inbox; these record a handshake —
61+ -- connect, negotiate TLS, say hello, authenticate, hang up. It proves
62+ -- the host, the port, the encryption and the credentials, and proves
63+ -- nothing about whether the from-address is one this account may send
64+ -- as — a server that accepts the login can still refuse the envelope.
65+ -- Kept apart so neither can be read as the other. Cleared whenever the
66+ -- sender is edited, for the same reason the test result is: it was
67+ -- about settings that no longer exist.
68+ smtp_check_at TEXT,
69+ smtp_check_ms INTEGER,
70+ smtp_check_error TEXT,
54 -- The address mail links point at, when the one the process was71 -- The address mail links point at, when the one the process was
55 -- configured with is not the one people reach. A box behind a proxy72 -- configured with is not the one people reach. A box behind a proxy
56 -- answers on localhost and is known by a public name, and only an admin73 -- answers on localhost and is known by a public name, and only an admin
@@ -147,6 +164,29 @@ CREATE TABLE board_column (
147 is_done INTEGER NOT NULL DEFAULT 0164 is_done INTEGER NOT NULL DEFAULT 0
148 );165 );
149 166
167+-- A tag is the project a task belongs to. A task wears at most one, so the
168+-- link is a column on `task` rather than a join table: two projects on one
169+-- task is a mistake the schema can refuse outright.
170+--
171+-- A tag belongs to a board, as a mail rule does. Its order is the admin's —
172+-- set by hand, up and down — so it is stored rather than derived from
173+-- anything the board already knows.
174+--
175+-- `is_default` marks the board's one fallback: every task must wear a tag,
176+-- so the board has one tag that catches whatever loses its own. That there
177+-- is exactly one is the partial index's job, not the store's.
178+CREATE TABLE tag (
179+ id TEXT PRIMARY KEY,
180+ board_id TEXT NOT NULL REFERENCES board(id),
181+ name TEXT NOT NULL,
182+ position INTEGER NOT NULL,
183+ is_default INTEGER NOT NULL DEFAULT 0,
184+ created_at TEXT NOT NULL
185+);
186+CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1;
187+CREATE UNIQUE INDEX tag_name_unique ON tag(board_id, name);
188+CREATE INDEX tag_by_board ON tag(board_id, position);
189+
150 -- A task, and a subtask, which is the same thing with a parent.190 -- A task, and a subtask, which is the same thing with a parent.
151 --191 --
152 -- `parent_id` is the whole of the subtask feature in this schema: a subtask192 -- `parent_id` is the whole of the subtask feature in this schema: a subtask
@@ -172,6 +212,10 @@ CREATE TABLE task (
172 title TEXT NOT NULL,212 title TEXT NOT NULL,
173 description TEXT NOT NULL DEFAULT '',213 description TEXT NOT NULL DEFAULT '',
174 column_id TEXT NOT NULL REFERENCES board_column(id),214 column_id TEXT NOT NULL REFERENCES board_column(id),
215+ -- The project the task belongs to — NOT NULL on purpose, which a
216+ -- declared schema can say where an ALTER could not: every task wears a
217+ -- tag, and the board's default one catches whatever loses its own.
218+ tag_id TEXT NOT NULL REFERENCES tag(id),
175 deadline TEXT,219 deadline TEXT,
176 position REAL NOT NULL DEFAULT 0,220 position REAL NOT NULL DEFAULT 0,
177 created_by TEXT NOT NULL REFERENCES user(id),221 created_by TEXT NOT NULL REFERENCES user(id),
@@ -294,6 +338,14 @@ CREATE TABLE activity (
294 id TEXT PRIMARY KEY,338 id TEXT PRIMARY KEY,
295 task_id TEXT REFERENCES task(id),339 task_id TEXT REFERENCES task(id),
296 actor_id TEXT REFERENCES user(id),340 actor_id TEXT REFERENCES user(id),
341+ -- Who an activity line is about, as opposed to the actor who did it:
342+ -- an Assigned line is about the person just assigned, an Unassigned one
343+ -- about the person just removed. A mail rule aimed at the assignees
344+ -- re-derives its one recipient from this id, on a retry as well as on
345+ -- the first run — the detail column carries only a display name, and
346+ -- two people can share a name. NULL for lines that are about nobody: a
347+ -- comment, a move, a delete.
348+ subject_id TEXT REFERENCES user(id),
297 kind TEXT NOT NULL,349 kind TEXT NOT NULL,
298 detail TEXT NOT NULL DEFAULT '',350 detail TEXT NOT NULL DEFAULT '',
299 created_at TEXT NOT NULL351 created_at TEXT NOT NULL
crates/izlek-core/src/board.rsmodified+24 -4
@@ -42,6 +42,9 @@ pub struct TaskRow {
42 /// is still read with the rest, because a key it owns can appear on42 /// is still read with the rest, because a key it owns can appear on
43 /// somebody else's card as a blocker.43 /// somebody else's card as a blocker.
44 pub parent_id: Option<String>,44 pub parent_id: Option<String>,
45+ /// The tag — the project — the task wears, if any. The name rides along
46+ /// so a card can show a chip without a second sweep.
47+ pub tag: Option<TagChip>,
45 }48 }
46 49
47 /// One card crossing from one column into another, as it was written.50 /// One card crossing from one column into another, as it was written.
@@ -111,6 +114,14 @@ impl Person {
111 }114 }
112 }115 }
113 116
117+/// A tag's id and name, as a card and the detail carry them: enough to show
118+/// a chip and to filter the board on, and nothing more.
119+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120+pub struct TagChip {
121+ pub id: String,
122+ pub name: String,
123+}
124+
114 /// A card, assembled. Dependencies carry the *keys* of the tasks on the other125 /// A card, assembled. Dependencies carry the *keys* of the tasks on the other
115 /// end, because that is what the card shows and it saves the UI a second lookup.126 /// end, because that is what the card shows and it saves the UI a second lookup.
116 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]127 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -132,6 +143,8 @@ pub struct TaskCard {
132 /// Both are zero for a card with none, which is what hides the chip.143 /// Both are zero for a card with none, which is what hides the chip.
133 pub subtask_total: u32,144 pub subtask_total: u32,
134 pub subtask_done: u32,145 pub subtask_done: u32,
146+ /// The tag the card wears — its project — when it has one.
147+ pub tag: Option<TagChip>,
135 }148 }
136 149
137 impl TaskCard {150 impl TaskCard {
@@ -143,8 +156,7 @@ impl TaskCard {
143 /// also the only place the count appears when a move is refused, which is156 /// also the only place the count appears when a move is refused, which is
144 /// why the refusal itself does not carry one.157 /// why the refusal itself does not carry one.
145 pub fn subtask_label(&self) -> Option<String> {158 pub fn subtask_label(&self) -> Option<String> {
146- (self.subtask_total > 0)159+ (self.subtask_total > 0).then(|| format!("{}/{}", self.subtask_done, self.subtask_total))
147- .then(|| format!("{}/{}", self.subtask_done, self.subtask_total))
148 }160 }
149 161
150 /// Whether finishing this card is currently refused.162 /// Whether finishing this card is currently refused.
@@ -190,11 +202,18 @@ impl TaskCard {
190 /// `None` when there's nothing to show (no deadline, not done).202 /// `None` when there's nothing to show (no deadline, not done).
191 pub fn deadline_parts(&self, today: Date) -> Option<DeadlineParts> {203 pub fn deadline_parts(&self, today: Date) -> Option<DeadlineParts> {
192 if let Some(done) = self.done_at {204 if let Some(done) = self.done_at {
193- return Some(DeadlineParts { date: day_label(done.date()), state: DeadlineState::Done });205+ return Some(DeadlineParts {
206+ date: day_label(done.date()),
207+ state: DeadlineState::Done,
208+ });
194 }209 }
195 self.deadline.map(|day| DeadlineParts {210 self.deadline.map(|day| DeadlineParts {
196 date: day_label(day),211 date: day_label(day),
197- state: if day < today { DeadlineState::Overdue } else { DeadlineState::OnTime },212+ state: if day < today {
213+ DeadlineState::Overdue
214+ } else {
215+ DeadlineState::OnTime
216+ },
198 })217 })
199 }218 }
200 }219 }
@@ -370,6 +389,7 @@ pub fn assemble(
370 done_at: task.done_at,389 done_at: task.done_at,
371 position: task.position,390 position: task.position,
372 column_id: task.column_id,391 column_id: task.column_id,
392+ tag: task.tag,
373 };393 };
374 cards.entry(card.column_id.clone()).or_default().push(card);394 cards.entry(card.column_id.clone()).or_default().push(card);
375 }395 }
crates/izlek-core/src/detail.rsmodified+14 -11
@@ -8,7 +8,7 @@
8 use serde::{Deserialize, Serialize};8 use serde::{Deserialize, Serialize};
9 use time::{Date, OffsetDateTime, UtcOffset};9 use time::{Date, OffsetDateTime, UtcOffset};
10 10
11-use crate::board::{Column, DeadlineParts, DeadlineState, Person, day_label};11+use crate::board::{Column, DeadlineParts, DeadlineState, Person, TagChip, day_label};
12 12
13 /// The stored task, plus the two ids the reader needs to know it is allowed to13 /// The stored task, plus the two ids the reader needs to know it is allowed to
14 /// see it. The description lives here rather than on14 /// see it. The description lives here rather than on
@@ -420,14 +420,8 @@ mod zone_tests {
420 fn a_stamp_shifts_with_the_stored_offset() {420 fn a_stamp_shifts_with_the_stored_offset() {
421 let at = time::macros::datetime!(2026-08-19 11:04 UTC);421 let at = time::macros::datetime!(2026-08-19 11:04 UTC);
422 assert_eq!(moment_label(at), "Aug 19 11:04");422 assert_eq!(moment_label(at), "Aug 19 11:04");
423- assert_eq!(423+ assert_eq!(moment_label_in(at, parse_zone("UTC+03:00")), "Aug 19 14:04");
424- moment_label_in(at, parse_zone("UTC+03:00")),424+ assert_eq!(moment_label_in(at, parse_zone("UTC-05:00")), "Aug 19 06:04");
425- "Aug 19 14:04"
426- );
427- assert_eq!(
428- moment_label_in(at, parse_zone("UTC-05:00")),
429- "Aug 19 06:04"
430- );
431 }425 }
432 426
433 #[test]427 #[test]
@@ -449,6 +443,8 @@ pub struct TaskDetail {
449 /// Every column on the board, so the status control has its options443 /// Every column on the board, so the status control has its options
450 /// without a second call.444 /// without a second call.
451 pub columns: Vec<Column>,445 pub columns: Vec<Column>,
446+ /// The tag the task wears — its project — when it wears one.
447+ pub tag: Option<TagChip>,
452 pub deadline: Option<Date>,448 pub deadline: Option<Date>,
453 pub done_at: Option<OffsetDateTime>,449 pub done_at: Option<OffsetDateTime>,
454 pub assignees: Vec<Person>,450 pub assignees: Vec<Person>,
@@ -505,7 +501,11 @@ impl TaskDetail {
505 pub fn deadline_parts(&self, today: Date) -> Option<DeadlineParts> {501 pub fn deadline_parts(&self, today: Date) -> Option<DeadlineParts> {
506 self.deadline.map(|day| DeadlineParts {502 self.deadline.map(|day| DeadlineParts {
507 date: day_label(day),503 date: day_label(day),
508- state: if !self.is_done() && day < today { DeadlineState::Overdue } else { DeadlineState::OnTime },504+ state: if !self.is_done() && day < today {
505+ DeadlineState::Overdue
506+ } else {
507+ DeadlineState::OnTime
508+ },
509 })509 })
510 }510 }
511 511
@@ -538,7 +538,9 @@ pub use reads::{DetailReads, load};
538 mod reads {538 mod reads {
539 use async_trait::async_trait;539 use async_trait::async_trait;
540 540
541- use super::{ActivityEntry, Comment, DependencyEdge, FileLine, SubtaskLine, TaskDetail, TaskFacts};541+ use super::{
542+ ActivityEntry, Comment, DependencyEdge, FileLine, SubtaskLine, TaskDetail, TaskFacts,
543+ };
542 use crate::board::{Column, Person};544 use crate::board::{Column, Person};
543 use crate::store::Result;545 use crate::store::Result;
544 546
@@ -642,6 +644,7 @@ mod reads {
642 description: facts.description,644 description: facts.description,
643 column,645 column,
644 columns,646 columns,
647+ tag: task.tag,
645 deadline: task.deadline,648 deadline: task.deadline,
646 done_at: task.done_at,649 done_at: task.done_at,
647 assignees,650 assignees,
crates/izlek-core/src/live.rsmodified+4 -0
@@ -28,6 +28,9 @@ pub enum Topic {
28 Queue,28 Queue,
29 /// Mail rules and the decisions they made.29 /// Mail rules and the decisions they made.
30 Rules,30 Rules,
31+ /// The board's tags — the projects tasks wear. Every member sees them on
32+ /// the board, so every member may hear.
33+ Tags,
31 /// Workspace settings, sender, limits, public URL.34 /// Workspace settings, sender, limits, public URL.
32 Settings,35 Settings,
33 /// The activity and event log.36 /// The activity and event log.
@@ -44,6 +47,7 @@ impl Topic {
44 Topic::Members => "members",47 Topic::Members => "members",
45 Topic::Queue => "queue",48 Topic::Queue => "queue",
46 Topic::Rules => "rules",49 Topic::Rules => "rules",
50+ Topic::Tags => "tags",
47 Topic::Settings => "settings",51 Topic::Settings => "settings",
48 Topic::Activity => "activity",52 Topic::Activity => "activity",
49 }53 }
crates/izlek-core/src/mail.rsmodified+226 -33
@@ -123,6 +123,11 @@ pub const HOLD: Duration = Duration::minutes(1);
123 /// that is thinking about it, short enough that a crash is not a lost day.123 /// that is thinking about it, short enough that a crash is not a lost day.
124 pub const LEASE: Duration = Duration::minutes(5);124 pub const LEASE: Duration = Duration::minutes(5);
125 125
126+/// How far past its first trigger a batch can be pushed. A card somebody is
127+/// working on all afternoon would otherwise never settle, and its mail would
128+/// never go — so the debounce yields after four windows and sends what it has.
129+pub const MAX_HOLD_WINDOWS: i32 = 4;
130+
126 /// The wait before the next attempt, doubling and capped: five minutes, ten,131 /// The wait before the next attempt, doubling and capped: five minutes, ten,
127 /// twenty, forty, an hour.132 /// twenty, forty, an hour.
128 pub fn backoff(attempts: u32) -> Duration {133 pub fn backoff(attempts: u32) -> Duration {
@@ -144,6 +149,9 @@ pub struct Report {
144 /// Mails held back because there is no sender to send them through. Owed,149 /// Mails held back because there is no sender to send them through. Owed,
145 /// not failed: no attempt was spent and none will be until one exists.150 /// not failed: no attempt was spent and none will be until one exists.
146 pub held: u32,151 pub held: u32,
152+ /// Mails written down and left to wait out the workspace's quiet window,
153+ /// so the rest of the workflow can join them in one envelope.
154+ pub batched: u32,
147 }155 }
148 156
149 pub struct Engine {157 pub struct Engine {
@@ -495,6 +503,12 @@ impl Engine {
495 /// anything is claimed: an empty audience leaves no ledger row at all, so503 /// anything is claimed: an empty audience leaves no ledger row at all, so
496 /// a rule that only ever resolves to the actor is silent rather than being504 /// a rule that only ever resolves to the actor is silent rather than being
497 /// a row the admin has to read as a failure.505 /// a row the admin has to read as a failure.
506+ ///
507+ /// A line that is about one person narrows the audience to that person:
508+ /// an Assigned rule is for the one just assigned, not for everybody
509+ /// already on the card. The subject is read from the stored row rather
510+ /// than from the name in the detail, so the audience a restart resolves
511+ /// is the audience the first pass resolved — two people can share a name.
498 async fn owe(512 async fn owe(
499 &self,513 &self,
500 rule: &MailRule,514 rule: &MailRule,
@@ -502,10 +516,22 @@ impl Engine {
502 task_id: &str,516 task_id: &str,
503 report: &mut Report,517 report: &mut Report,
504 ) -> crate::store::Result<()> {518 ) -> crate::store::Result<()> {
505- let recipients = match rule.audience {519+ let recipients = match (rule.audience, event) {
506- Audience::Assignees => self.store.recipients_for_task(task_id).await?,520+ (
507- Audience::Board => self.store.recipients_for_board(&rule.board_id).await?,521+ Audience::Assignees,
508- Audience::Creator => self.store.recipients_for_task_creator(task_id).await?,522+ Event::Happened(ActivityEvent {
523+ subject_id: Some(about),
524+ ..
525+ }),
526+ ) => self
527+ .store
528+ .recipient(about)
529+ .await?
530+ .map(|one| vec![one])
531+ .unwrap_or_default(),
532+ (Audience::Assignees, _) => self.store.recipients_for_task(task_id).await?,
533+ (Audience::Board, _) => self.store.recipients_for_board(&rule.board_id).await?,
534+ (Audience::Creator, _) => self.store.recipients_for_task_creator(task_id).await?,
509 };535 };
510 let resolved_nobody = recipients.is_empty();536 let resolved_nobody = recipients.is_empty();
511 let now = OffsetDateTime::now_utc();537 let now = OffsetDateTime::now_utc();
@@ -531,18 +557,39 @@ impl Engine {
531 .await?;557 .await?;
532 return Ok(());558 return Ok(());
533 }559 }
560+ // The workspace's quiet window. Zero is what İzlek did before it had
561+ // one: every trigger its own mail, sent as soon as it is owed.
562+ let window = self
563+ .store
564+ .workspace()
565+ .await?
566+ .map(|workspace| i64::from(workspace.mail_batch_minutes))
567+ .unwrap_or(0);
568+ let hold = Duration::minutes(window);
534 for recipient in audience {569 for recipient in audience {
570+ // A held row comes due when the window closes rather than when the
571+ // lease does; with no window it keeps the lease it always had,
572+ // which is what stops the pass that queued it from grabbing it
573+ // back before it has been composed.
574+ let due = if window > 0 { now + hold } else { now + LEASE };
535 let claimed = self575 let claimed = self
536 .store576 .store
537- .claim_send(577+ .claim_send(&rule.id, event.id(), task_id, &recipient.email, now, due)
538- &rule.id,
539- event.id(),
540- task_id,
541- &recipient.email,
542- now,
543- now + LEASE,
544- )
545 .await?;578 .await?;
579+ if window > 0 {
580+ // Everything this person is already owed about this card waits
581+ // for the new arrival: that is the debounce. The ceiling is
582+ // measured from the oldest mail in the batch, so a card under
583+ // constant edit still goes out.
584+ self.store
585+ .hold_batch(
586+ task_id,
587+ &recipient.email,
588+ now + hold,
589+ hold * MAX_HOLD_WINDOWS,
590+ )
591+ .await?;
592+ }
546 match claimed {593 match claimed {
547 Some(send) => {594 Some(send) => {
548 self.store595 self.store
@@ -555,8 +602,15 @@ impl Engine {
555 now,602 now,
556 )603 )
557 .await?;604 .await?;
558- let mail = self.compose(&send, rule, event).await?;605+ // With a window the row is left where it lies: the
559- self.attempt(&send, mail, report).await?;606+ // delivery pass picks it up when it comes due, together
607+ // with everything else this person is owed about the card.
608+ if window > 0 {
609+ report.batched += 1;
610+ } else {
611+ let mail = self.compose(&send, rule, event).await?;
612+ self.attempt(&send, mail, report).await?;
613+ }
560 }614 }
561 None => {615 None => {
562 self.store616 self.store
@@ -588,11 +642,15 @@ impl Engine {
588 // pass and the same write wakes the sweep, so two passes reach the642 // pass and the same write wakes the sweep, so two passes reach the
589 // same row together. Each is handed only what it took, and only a643 // same row together. Each is handed only what it took, and only a
590 // `ClaimedSend` can be mailed. See `Store::claim_sends_owed`.644 // `ClaimedSend` can be mailed. See `Store::claim_sends_owed`.
645+ // Rule rows are answered one mail per task per person: several
646+ // triggers about one card, held through the same quiet window, are
647+ // one thing that happened as far as the reader is concerned. Invites
648+ // and notices are never folded in — each carries its own subject and
649+ // body, composed once at mint time, and belongs to nobody's card.
650+ let mut batches: Vec<(String, String, Vec<ClaimedSend>)> = Vec::new();
591 for send in self.store.claim_sends_owed(now, now + LEASE, limit).await? {651 for send in self.store.claim_sends_owed(now, now + LEASE, limit).await? {
592- // An invite and an admin's notice both owe no rule and no event:652+ // Without this arm a notice falls through to the rule path, finds
593- // each carries its own subject and body, composed once at mint653+ // no rule_id, and is skipped every run — queued forever.
594- // time. Without this arm a notice falls through to the rule path,
595- // finds no rule_id, and is skipped every run — queued forever.
596 if matches!(send.kind, SendKind::Invite | SendKind::Notice) {654 if matches!(send.kind, SendKind::Invite | SendKind::Notice) {
597 let mail = Outgoing {655 let mail = Outgoing {
598 to: send.recipient.clone(),656 to: send.recipient.clone(),
@@ -602,47 +660,110 @@ impl Engine {
602 self.attempt(&send, Some(mail), &mut report).await?;660 self.attempt(&send, Some(mail), &mut report).await?;
603 continue;661 continue;
604 }662 }
605- let Some(rule_id) = send.rule_id.as_deref() else {663+ let Some(task_id) = send.task_id.clone() else {
606 continue;664 continue;
607 };665 };
608- let Some(event_id) = send.event_id.as_deref() else {666+ let recipient = send.recipient.clone();
667+ match batches
668+ .iter_mut()
669+ .find(|(task, to, _)| task == &task_id && to == &recipient)
670+ {
671+ Some((_, _, group)) => group.push(send),
672+ None => batches.push((task_id, recipient, vec![send])),
673+ }
674+ }
675+
676+ for (_, _, group) in batches {
677+ // The newest event is the one that decides the mail: its rule
678+ // supplies the subject, and its moment is the moment the mail
679+ // speaks about.
680+ let mut newest: Option<(Event, MailRule)> = None;
681+ let mut details = false;
682+ for send in &group {
683+ let (Some(rule_id), Some(event_id)) =
684+ (send.rule_id.as_deref(), send.event_id.as_deref())
685+ else {
686+ continue;
687+ };
688+ let (Some(rule), Some(event)) = (
689+ self.store.mail_rule(rule_id).await?,
690+ self.store.event(event_id).await?,
691+ ) else {
692+ continue;
693+ };
694+ details |= rule.include_task_details;
695+ let newer = newest
696+ .as_ref()
697+ .map(|(known, _)| event.at() > known.at())
698+ .unwrap_or(true);
699+ if newer {
700+ newest = Some((event, rule));
701+ }
702+ }
703+ let Some((event, rule)) = newest else {
609 continue;704 continue;
610 };705 };
611- let Some(rule) = self.store.mail_rule(rule_id).await? else {706+ let Some(first) = group.first() else {
612 continue;707 continue;
613 };708 };
614- let Some(event) = self.store.event(event_id).await? else {709+ let mail = if group.len() == 1 {
615- continue;710+ self.compose(first, &rule, &event).await?
711+ } else {
712+ self.compose_batch(first, &rule, &event, details).await?
616 };713 };
617- let mail = self.compose(&send, &rule, &event).await?;714+ self.attempt_group(&group, mail, &mut report).await?;
618- self.attempt(&send, mail, &mut report).await?;
619 }715 }
620 Ok(report)716 Ok(report)
621 }717 }
622 718
623- /// One attempt, and the ledger line it leaves behind.719+ /// One attempt for one claimed row.
624 async fn attempt(720 async fn attempt(
625 &self,721 &self,
626 send: &ClaimedSend,722 send: &ClaimedSend,
627 mail: Option<Outgoing>,723 mail: Option<Outgoing>,
628 report: &mut Report,724 report: &mut Report,
725+ ) -> crate::store::Result<()> {
726+ self.attempt_group(std::slice::from_ref(send), mail, report)
727+ .await
728+ }
729+
730+ /// One attempt, and the ledger lines it leaves behind — one per row in
731+ /// the group.
732+ ///
733+ /// A batch is several owed rows answered by a single mail, so the send
734+ /// happens once and every row in it is marked with the same outcome: they
735+ /// were all in that envelope. The claim invariant is unchanged — this
736+ /// takes `ClaimedSend`s, so a row that was merely read still cannot be
737+ /// mailed.
738+ async fn attempt_group(
739+ &self,
740+ sends: &[ClaimedSend],
741+ mail: Option<Outgoing>,
742+ report: &mut Report,
629 ) -> crate::store::Result<()> {743 ) -> crate::store::Result<()> {
630 let Some(mail) = mail else {744 let Some(mail) = mail else {
631 return Ok(());745 return Ok(());
632 };746 };
747+ let Some(send) = sends.first() else {
748+ return Ok(());
749+ };
633 let now = OffsetDateTime::now_utc();750 let now = OffsetDateTime::now_utc();
634 match self.mailer.send(&mail).await {751 match self.mailer.send(&mail).await {
635 Ok(()) => {752 Ok(()) => {
636- self.store.record_send_accepted(&send.id, now).await?;753+ for one in sends {
754+ self.store.record_send_accepted(&one.id, now).await?;
755+ }
637 report.sent += 1;756 report.sent += 1;
638 }757 }
639 Err(problem) if !problem.attempted => {758 Err(problem) if !problem.attempted => {
640 // No sender. The mail keeps its place in the ledger and its759 // No sender. The mail keeps its place in the ledger and its
641 // attempts, and is looked at again on the next sweep — by then760 // attempts, and is looked at again on the next sweep — by then
642 // an admin may have filled the panel in.761 // an admin may have filled the panel in.
643- self.store762+ for one in sends {
644- .defer_send(&send.id, &problem.message, now + HOLD, now)763+ self.store
645- .await?;764+ .defer_send(&one.id, &problem.message, now + HOLD, now)
765+ .await?;
766+ }
646 report.held += 1;767 report.held += 1;
647 }768 }
648 Err(problem) => {769 Err(problem) => {
@@ -651,9 +772,11 @@ impl Engine {
651 // left looking like it is still coming.772 // left looking like it is still coming.
652 let retry_at =773 let retry_at =
653 (problem.retryable && attempts < MAX_ATTEMPTS).then(|| now + backoff(attempts));774 (problem.retryable && attempts < MAX_ATTEMPTS).then(|| now + backoff(attempts));
654- self.store775+ for one in sends {
655- .record_send_refused(&send.id, &problem.message, retry_at, now)776+ self.store
656- .await?;777+ .record_send_refused(&one.id, &problem.message, retry_at, now)
778+ .await?;
779+ }
657 if retry_at.is_some() {780 if retry_at.is_some() {
658 report.failed += 1;781 report.failed += 1;
659 } else {782 } else {
@@ -810,6 +933,76 @@ impl Engine {
810 body,933 body,
811 }))934 }))
812 }935 }
936+
937+ /// The mail a whole batch answers with: where the task stands NOW.
938+ ///
939+ /// A batch is several triggers about one task for one person, held
940+ /// together through a quiet window. Naming each of them would be a diary,
941+ /// and half its entries are already wrong — a column set by mistake and
942+ /// corrected inside the window happened, but is not the case. So the mail
943+ /// reads the task as it is at send time and says that; the subject comes
944+ /// from the rule behind the newest event, which is the reason the mail is
945+ /// going out at all.
946+ async fn compose_batch(
947+ &self,
948+ send: &MailSend,
949+ newest_rule: &MailRule,
950+ newest_event: &Event,
951+ details: bool,
952+ ) -> crate::store::Result<Option<Outgoing>> {
953+ let Some(task_id) = send.task_id.as_deref() else {
954+ return Ok(None);
955+ };
956+ let Some(facts) = self.store.task(task_id).await? else {
957+ return Ok(None);
958+ };
959+ let columns = self.store.columns_for_board(&facts.board_id).await?;
960+ let column = columns
961+ .iter()
962+ .find(|column| column.id == facts.row.column_id)
963+ .map(|column| column.name.clone())
964+ .unwrap_or_else(|| "somewhere".to_string());
965+ let assignees = self.store.assignees_for_task(task_id).await?;
966+ let assignees = if assignees.is_empty() {
967+ "none".to_string()
968+ } else {
969+ assignees
970+ .iter()
971+ .map(|person| person.display_name.as_str())
972+ .collect::<Vec<_>>()
973+ .join(", ")
974+ };
975+ let deadline = facts
976+ .row
977+ .deadline
978+ .map(|date| date.to_string())
979+ .unwrap_or_else(|| "none".to_string());
980+ let base = self
981+ .store
982+ .workspace()
983+ .await?
984+ .and_then(|workspace| workspace.public_url)
985+ .unwrap_or_else(|| self.fallback_url.clone());
986+ let mut body = format!(
987+ "{key} — {title}\n\nColumn: {column}\nDeadline: {deadline}\nAssignees: {assignees}\n\n{when}\n\n{base}/?task={id}\n",
988+ key = facts.row.task_key,
989+ title = facts.row.title,
990+ when = day_and_time(newest_event.at()),
991+ id = facts.row.id,
992+ );
993+ if details {
994+ body.push_str(&format!(
995+ "\nKey: {key}\nTitle: {title}\n",
996+ key = facts.row.task_key,
997+ title = facts.row.title,
998+ ));
999+ }
1000+ Ok(Some(Outgoing {
1001+ to: send.recipient.clone(),
1002+ subject: newest_rule.subject.clone(),
1003+ body,
1004+ }))
1005+ }
813 }1006 }
814 1007
815 /// The `ActivityKind` a trigger fires on. `StatusBecomes`/`Unblocked` fire on1008 /// The `ActivityKind` a trigger fires on. `StatusBecomes`/`Unblocked` fire on
crates/izlek-core/src/store/mod.rsmodified+96 -2
@@ -6,7 +6,7 @@
6 6
7 use async_trait::async_trait;7 use async_trait::async_trait;
8 use serde::{Deserialize, Serialize};8 use serde::{Deserialize, Serialize};
9-use time::OffsetDateTime;9+use time::{Duration, OffsetDateTime};
10 10
11 use crate::Role;11 use crate::Role;
12 use crate::board::{BoardReads, Moved, TaskRow, Transition};12 use crate::board::{BoardReads, Moved, TaskRow, Transition};
@@ -14,9 +14,15 @@ use crate::detail::{ActivityKind, DeletionCost, DetailReads};
14 14
15 #[cfg(feature = "server")]15 #[cfg(feature = "server")]
16 pub mod secret;16 pub mod secret;
17+#[cfg(feature = "server")]
18+pub mod reconcile;
19+#[cfg(feature = "server")]
20+pub mod schema;
17 pub mod turso_store;21 pub mod turso_store;
18 22
19 pub use turso_store::TursoStore;23 pub use turso_store::TursoStore;
24+#[cfg(feature = "server")]
25+pub use reconcile::{reconcile, ReconcileOptions};
20 26
21 #[derive(Debug, thiserror::Error)]27 #[derive(Debug, thiserror::Error)]
22 pub enum StoreError {28 pub enum StoreError {
@@ -75,6 +81,9 @@ pub struct Workspace {
75 pub attachment_limit_bytes: u64,81 pub attachment_limit_bytes: u64,
76 pub photo_limit_bytes: u64,82 pub photo_limit_bytes: u64,
77 pub allowed_file_types: Vec<String>,83 pub allowed_file_types: Vec<String>,
84+ /// The quiet window a notification waits out before it is sent, in
85+ /// minutes. `0` sends every trigger the moment it is owed.
86+ pub mail_batch_minutes: u32,
78 /// The origin mail links point at, when an admin has set one. `None`87 /// The origin mail links point at, when an admin has set one. `None`
79 /// means the address the process listens on — a box behind a proxy88 /// means the address the process listens on — a box behind a proxy
80 /// answers on localhost and is reached on a public name, and only an89 /// answers on localhost and is reached on a public name, and only an
@@ -206,6 +215,20 @@ pub struct NewUser {
206 pub invited_by: Option<String>,215 pub invited_by: Option<String>,
207 }216 }
208 217
218+/// The profile page's totals for one person: what is on their plate, what
219+/// finished under them, what they opened, what they said.
220+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221+pub struct UserStats {
222+ /// Tasks the person is on now, sitting in a column that is not done.
223+ pub assigned_open: u32,
224+ /// Tasks they are on that reached a done column.
225+ pub assigned_done: u32,
226+ /// Tasks they opened, whoever carries them now.
227+ pub created: u32,
228+ /// Comments they wrote.
229+ pub comments: u32,
230+}
231+
209 /// A first-sign-in link. Only the hash of the token is ever stored; the232 /// A first-sign-in link. Only the hash of the token is ever stored; the
210 /// plaintext is shown once, when the link is created or resent.233 /// plaintext is shown once, when the link is created or resent.
211 #[derive(Debug, Clone, PartialEq)]234 #[derive(Debug, Clone, PartialEq)]
@@ -323,6 +346,21 @@ pub struct MailRule {
323 pub include_task_details: bool,346 pub include_task_details: bool,
324 }347 }
325 348
349+/// A tag is the project a task belongs to. A task wears at most one, so the
350+/// link is a column on the task, not a join table. Tags belong to a board,
351+/// like the mail rules do, and their order is the admin's — set by hand, so
352+/// it is stored rather than derived. One tag per board is the default its
353+/// tasks fall back to, and it cannot be deleted — only renamed and
354+/// reordered.
355+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
356+pub struct Tag {
357+ pub id: String,
358+ pub board_id: String,
359+ pub name: String,
360+ pub position: i64,
361+ pub is_default: bool,
362+}
363+
326 /// Where one mail got to.364 /// Where one mail got to.
327 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]365 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
328 pub enum SendState {366 pub enum SendState {
@@ -585,6 +623,9 @@ pub struct ActivityEvent {
585 pub board_id: String,623 pub board_id: String,
586 pub kind: ActivityKind,624 pub kind: ActivityKind,
587 pub actor_id: String,625 pub actor_id: String,
626+ /// The person the line is about — the one just assigned, say — when it
627+ /// is about anyone in particular.
628+ pub subject_id: Option<String>,
588 pub detail: String,629 pub detail: String,
589 pub at: OffsetDateTime,630 pub at: OffsetDateTime,
590 }631 }
@@ -646,7 +687,6 @@ pub struct Recipient {
646 /// trait a test can wrap and count.687 /// trait a test can wrap and count.
647 #[async_trait]688 #[async_trait]
648 pub trait Store: BoardReads + DetailReads + 'static {689 pub trait Store: BoardReads + DetailReads + 'static {
649-
650 // -- live updates ------------------------------------------------------690 // -- live updates ------------------------------------------------------
651 691
652 /// A receiver of committed-write announcements. One [`Change`] per692 /// A receiver of committed-write announcements. One [`Change`] per
@@ -705,6 +745,7 @@ pub trait Store: BoardReads + DetailReads + 'static {
705 attachment_limit_bytes: u64,745 attachment_limit_bytes: u64,
706 photo_limit_bytes: u64,746 photo_limit_bytes: u64,
707 allowed_file_types: &[String],747 allowed_file_types: &[String],
748+ mail_batch_minutes: u32,
708 ) -> Result<()>;749 ) -> Result<()>;
709 750
710 // -- users -------------------------------------------------------------751 // -- users -------------------------------------------------------------
@@ -722,6 +763,12 @@ pub trait Store: BoardReads + DetailReads + 'static {
722 763
723 async fn count_users(&self, workspace_id: &str) -> Result<u64>;764 async fn count_users(&self, workspace_id: &str) -> Result<u64>;
724 765
766+ /// One person's totals, for their profile. A soft-deleted task counts
767+ /// nowhere: it has left the board, so it has left the person.
768+ ///
769+ /// This is a read, for looking: nothing announces.
770+ async fn user_stats(&self, user_id: &str) -> Result<UserStats>;
771+
725 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>;772 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>;
726 773
727 async fn set_profile(&self, user_id: &str, display_name: &str) -> Result<()>;774 async fn set_profile(&self, user_id: &str, display_name: &str) -> Result<()>;
@@ -964,10 +1011,13 @@ pub trait Store: BoardReads + DetailReads + 'static {
964 1011
965 /// Appends one line to a task's activity trail and returns its row id.1012 /// Appends one line to a task's activity trail and returns its row id.
966 /// `actor_id` is `None` when the system did it rather than a person.1013 /// `actor_id` is `None` when the system did it rather than a person.
1014+ /// `subject_id` is the person the line is ABOUT — the one just assigned,
1015+ /// say — and `None` for a line that is about nobody.
967 async fn record_activity(1016 async fn record_activity(
968 &self,1017 &self,
969 task_id: &str,1018 task_id: &str,
970 actor_id: Option<&str>,1019 actor_id: Option<&str>,
1020+ subject_id: Option<&str>,
971 kind: &ActivityKind,1021 kind: &ActivityKind,
972 detail: &str,1022 detail: &str,
973 at: OffsetDateTime,1023 at: OffsetDateTime,
@@ -1033,6 +1083,29 @@ pub trait Store: BoardReads + DetailReads + 'static {
1033 /// When each rule last got a mail accepted, for the "last sent" line.1083 /// When each rule last got a mail accepted, for the "last sent" line.
1034 async fn mail_rule_last_sent(&self, board_id: &str) -> Result<Vec<(String, OffsetDateTime)>>;1084 async fn mail_rule_last_sent(&self, board_id: &str) -> Result<Vec<(String, OffsetDateTime)>>;
1035 1085
1086+ // -- tags --------------------------------------------------------------
1087+
1088+ /// Every tag on the board, in the admin's hand-set order.
1089+ async fn tags(&self, board_id: &str) -> Result<Vec<Tag>>;
1090+
1091+ /// Appends a tag at the end of the board's order. The name is unique per
1092+ /// board: two tags with one name are one project spelled twice.
1093+ async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag>;
1094+
1095+ async fn rename_tag(&self, tag_id: &str, name: &str) -> Result<()>;
1096+
1097+ /// Deletes a tag. Its tasks move to the board's default tag; the default
1098+ /// itself is refused — it is where they would go.
1099+ async fn delete_tag(&self, tag_id: &str) -> Result<()>;
1100+
1101+ /// Swaps a tag with its neighbour in the order. A tag already at that end
1102+ /// stays put: nothing to swap is not an error.
1103+ async fn move_tag(&self, tag_id: &str, up: bool) -> Result<()>;
1104+
1105+ /// Sets the tag a task wears. A tag from another board is
1106+ /// [`StoreError::NotFound`] — it is not one of this board's projects at
1107+ /// all.
1108+ async fn set_task_tag(&self, task_id: &str, tag_id: &str) -> Result<()>;
1036 // -- the send ledger ---------------------------------------------------1109 // -- the send ledger ---------------------------------------------------
1037 1110
1038 /// Takes ownership of one mail by writing its row, and answers `None` if1111 /// Takes ownership of one mail by writing its row, and answers `None` if
@@ -1240,6 +1313,27 @@ pub trait Store: BoardReads + DetailReads + 'static {
1240 /// store, so no caller can mail one by forgetting to filter.1313 /// store, so no caller can mail one by forgetting to filter.
1241 async fn recipients_for_board(&self, board_id: &str) -> Result<Vec<Recipient>>;1314 async fn recipients_for_board(&self, board_id: &str) -> Result<Vec<Recipient>>;
1242 1315
1316+ /// Pushes every mail still merely owed about this task, for this person,
1317+ /// out to `until` — but never past `cap`, the moment the oldest of them
1318+ /// stops waiting no matter what.
1319+ ///
1320+ /// This is the debounce: each new trigger about a card postpones the mail
1321+ /// the card already owes, so a person is told once, after the work has
1322+ /// settled. Only rows that are still pending and have never been
1323+ /// attempted move — a mail already refused is on its own retry clock, and
1324+ /// a batch must not drag it back.
1325+ async fn hold_batch(
1326+ &self,
1327+ task_id: &str,
1328+ recipient: &str,
1329+ until: OffsetDateTime,
1330+ cap: Duration,
1331+ ) -> Result<()>;
1332+
1243 /// Whoever opened the task, unless they are a Viewer.1333 /// Whoever opened the task, unless they are a Viewer.
1244 async fn recipients_for_task_creator(&self, task_id: &str) -> Result<Vec<Recipient>>;1334 async fn recipients_for_task_creator(&self, task_id: &str) -> Result<Vec<Recipient>>;
1335+
1336+ /// One person by id, unless they are a Viewer — the subject of an
1337+ /// activity line, for a rule that mails the person the line is about.
1338+ async fn recipient(&self, user_id: &str) -> Result<Option<Recipient>>;
1245 }1339 }
crates/izlek-core/src/store/reconcile.rsadded+738 -0
@@ -0,0 +1,738 @@
1+//! Reconcile a live Turso database with the declared whole schema.
2+//!
3+//! The live file is never altered in place. Instead a new file is built from
4+//! `migrations/0001_init.sql`, the data is copied with an explicit per-table
5+//! column map, the copy is verified, and only then the files are swapped. The
6+//! original file is kept as a timestamped backup and is never deleted.
7+
8+use super::{Result, StoreError};
9+use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint};
10+use turso::{Builder, Connection, params};
11+use ulid::Ulid;
12+
13+/// How the caller wants to confirm the rebuild.
14+pub struct ReconcileOptions {
15+ /// Print the diff and plan, then stop without touching anything.
16+ pub dry_run: bool,
17+ /// Skip the interactive confirmation.
18+ pub yes: bool,
19+ /// Boot path: do not prompt, log what happened and proceed.
20+ pub auto: bool,
21+}
22+
23+/// Rebuilds the database at `path` to match the declared schema.
24+///
25+/// - Empty or already-current databases are a no-op.
26+/// - A differing database is backed up, rebuilt, verified and swapped into
27+/// place.
28+/// - A rebuild that fails verification deletes the `.rebuilt` file and leaves
29+/// the original untouched.
30+pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> {
31+ if path == ":memory:" {
32+ return Err(StoreError::Backend(
33+ "reconcile is not meaningful on an in-memory database".into(),
34+ ));
35+ }
36+ let db_path = std::path::Path::new(path);
37+ if !db_path.exists() {
38+ return Err(StoreError::Backend(format!("database not found: {}", path)));
39+ }
40+
41+ // Open the live database read-only to inspect its fingerprint.
42+ let old_db = Builder::new_local(path)
43+ .build()
44+ .await
45+ .map_err(|e| StoreError::Backend(e.to_string()))?;
46+ let old_conn = old_db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
47+
48+ let old_fp = fingerprint(&old_conn).await?;
49+ let new_fp = declared_fingerprint().await?;
50+
51+ if old_fp == new_fp {
52+ if !opts.auto {
53+ println!("database already matches the declared schema");
54+ }
55+ return Ok(());
56+ }
57+
58+ let diff = diff_report(&old_fp, &new_fp);
59+
60+ if opts.dry_run {
61+ println!("schema difference:\n{}", diff);
62+ println!("dry run: would rebuild {}", path);
63+ return Ok(());
64+ }
65+
66+ if opts.auto {
67+ eprintln!("database schema differs from declared schema; rebuilding automatically");
68+ eprintln!("difference:\n{}", diff);
69+ } else {
70+ println!("schema difference:\n{}", diff);
71+ if !opts.yes {
72+ print!("rebuild {}? [y/N] ", path);
73+ let _ = std::io::Write::flush(&mut std::io::stdout());
74+ let mut answer = String::new();
75+ match std::io::stdin().read_line(&mut answer) {
76+ Ok(_) if answer.trim().eq_ignore_ascii_case("y") => {}
77+ _ => {
78+ println!("rebuild cancelled");
79+ return Ok(());
80+ }
81+ }
82+ }
83+ }
84+
85+ let rebuilt_path = format!("{}.rebuilt", path);
86+ cleanup_rebuilt(&rebuilt_path);
87+
88+ let result = rebuild(path, &rebuilt_path, &old_conn).await;
89+
90+ // Close the read-only connection before any file moves; this also
91+ // releases the WAL locks on the original file.
92+ drop(old_conn);
93+ drop(old_db);
94+
95+ if let Err(e) = result {
96+ cleanup_rebuilt(&rebuilt_path);
97+ return Err(e);
98+ }
99+
100+ let backup_path = backup_name(path)?;
101+ std::fs::rename(path, &backup_path).map_err(|e| {
102+ StoreError::Backend(format!(
103+ "failed to move original database to backup {}: {}",
104+ backup_path, e
105+ ))
106+ })?;
107+ // SQLite WAL/SHM siblings belong to the main file; the backup must be a
108+ // complete database on its own, and the rebuilt file starts with none.
109+ rename_sibling(path, &backup_path, "-wal");
110+ rename_sibling(path, &backup_path, "-shm");
111+ if let Err(e) = std::fs::rename(&rebuilt_path, path) {
112+ // Best-effort undo so the live file is not gone. If this also fails,
113+ // the caller has both the backup and the rebuilt file to recover from.
114+ let _ = std::fs::rename(&backup_path, path);
115+ let _ = rename_sibling(&backup_path, path, "-wal");
116+ let _ = rename_sibling(&backup_path, path, "-shm");
117+ return Err(StoreError::Backend(format!(
118+ "failed to move rebuilt database into place {}: {}",
119+ rebuilt_path, e
120+ )));
121+ }
122+ // The rebuilt file was checkpointed before the swap, so its own sidecars
123+ // hold nothing — but a `.rebuilt-wal` left lying about would be adopted by
124+ // the NEXT rebuild's fresh `.rebuilt` file, which is how a stale WAL
125+ // corrupts a database that was otherwise fine.
126+ let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path));
127+ let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path));
128+
129+ if opts.auto {
130+ eprintln!("database rebuilt and verified; original backed up to {}", backup_path);
131+ eprintln!("rebuilt database now at {}", path);
132+ } else {
133+ println!("database rebuilt and verified");
134+ println!("original backed up to {}", backup_path);
135+ println!("rebuilt database now at {}", path);
136+ }
137+
138+ Ok(())
139+}
140+
141+/// Does the actual rebuild: creates `.rebuilt`, copies the data (seeding the
142+/// tags partway, where the foreign keys allow it), and verifies the result. On success the rebuilt file is complete and
143+/// checkpointed; on failure the caller deletes it.
144+async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Result<()> {
145+ // The copy runs as `INSERT ... SELECT FROM old.<table>`, which needs
146+ // ATTACH — still gated in this engine, and switched on only here, for the
147+ // one connection that does the rebuild. The verification afterwards is
148+ // what protects the data, not the copy's mechanism.
149+ let new_db = Builder::new_local(rebuilt_path)
150+ .experimental_attach(true)
151+ .build()
152+ .await
153+ .map_err(|e| StoreError::Backend(e.to_string()))?;
154+ let new_conn = new_db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
155+
156+ new_conn
157+ .execute("PRAGMA foreign_keys = ON", ())
158+ .await
159+ .map_err(|e| StoreError::Backend(e.to_string()))?;
160+ new_conn
161+ .execute_batch(SCHEMA)
162+ .await
163+ .map_err(|e| StoreError::Backend(e.to_string()))?;
164+
165+ copy_data(old_conn, &new_conn, path).await?;
166+ verify(old_conn, &new_conn).await?;
167+
168+ // A checkpoint PRAGMA answers with a row, so it is a query: `execute`
169+ // treats a row as a failure ("unexpected row during execution").
170+ let mut checkpoint = new_conn
171+ .query("PRAGMA wal_checkpoint(TRUNCATE)", ())
172+ .await
173+ .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?;
174+ while checkpoint
175+ .next()
176+ .await
177+ .map_err(|e| StoreError::Backend(format!("checkpoint: {e}")))?
178+ .is_some()
179+ {}
180+
181+ Ok(())
182+}
183+
184+/// Seeds one `General` tag per board into the new database, before `task`
185+/// is copied. The tag is the default for that board, so every task copied
186+/// afterwards can map its `tag_id` to it.
187+async fn seed_general_tags(old_conn: &Connection, new_conn: &Connection) -> Result<()> {
188+ let mut rows = old_conn
189+ .query("SELECT id, created_at FROM board", ())
190+ .await
191+ .map_err(|e| StoreError::Backend(e.to_string()))?;
192+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
193+ let board_id: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
194+ let created_at: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
195+ let id = Ulid::new().to_string();
196+ new_conn
197+ .execute(
198+ "INSERT INTO main.tag (id, board_id, name, position, is_default, created_at) \
199+ VALUES (?1, ?2, 'General', 0, 1, ?3)",
200+ params![id, board_id, created_at],
201+ )
202+ .await
203+ .map_err(|e| StoreError::Backend(e.to_string()))?;
204+ }
205+ Ok(())
206+}
207+
208+/// A per-table column map. Every destination column must appear exactly once;
209+/// `copy_data` validates this against the declared schema before inserting.
210+struct TableMap {
211+ name: &'static str,
212+ columns: Vec<(&'static str, String)>,
213+}
214+
215+/// Builds the explicit column map. Unchanged tables map every column to
216+/// `old.<col>`; the changed tables carry the migration-specific expressions.
217+fn build_maps(old_has_smtp_check: bool, old_has_batch_window: bool) -> Vec<TableMap> {
218+ let mut maps = Vec::new();
219+
220+ maps.push(TableMap {
221+ name: "workspace",
222+ columns: vec![
223+ ("id", "old.id".into()),
224+ ("name", "old.name".into()),
225+ ("created_at", "old.created_at".into()),
226+ ("attachment_limit_bytes", "old.attachment_limit_bytes".into()),
227+ ("photo_limit_bytes", "old.photo_limit_bytes".into()),
228+ ("allowed_file_types", "old.allowed_file_types".into()),
229+ (
230+ // A database written before notifications were batched has no
231+ // window of its own; it starts on the schema's own default
232+ // rather than on zero, which would keep the old behaviour by
233+ // accident and make the feature look broken.
234+ "mail_batch_minutes",
235+ if old_has_batch_window {
236+ "old.mail_batch_minutes".into()
237+ } else {
238+ "5".to_string()
239+ },
240+ ),
241+ ("smtp_host", "old.smtp_host".into()),
242+ ("smtp_port", "old.smtp_port".into()),
243+ ("smtp_username", "old.smtp_username".into()),
244+ ("smtp_password", "old.smtp_password".into()),
245+ ("smtp_from_name", "old.smtp_from_name".into()),
246+ ("smtp_from_address", "old.smtp_from_address".into()),
247+ ("smtp_test_at", "old.smtp_test_at".into()),
248+ ("smtp_test_ms", "old.smtp_test_ms".into()),
249+ ("smtp_test_error", "old.smtp_test_error".into()),
250+ (
251+ "smtp_check_at",
252+ if old_has_smtp_check {
253+ "old.smtp_check_at".into()
254+ } else {
255+ "NULL".into()
256+ },
257+ ),
258+ (
259+ "smtp_check_ms",
260+ if old_has_smtp_check {
261+ "old.smtp_check_ms".into()
262+ } else {
263+ "NULL".into()
264+ },
265+ ),
266+ (
267+ "smtp_check_error",
268+ if old_has_smtp_check {
269+ "old.smtp_check_error".into()
270+ } else {
271+ "NULL".into()
272+ },
273+ ),
274+ ("public_url", "old.public_url".into()),
275+ ],
276+ });
277+
278+ maps.push(TableMap {
279+ name: "user",
280+ columns: old_cols(&[
281+ "id",
282+ "workspace_id",
283+ "email",
284+ "display_name",
285+ "role",
286+ "password_hash",
287+ "invited_by",
288+ "timezone",
289+ "theme",
290+ "language",
291+ "ui",
292+ "photo",
293+ "photo_mime",
294+ "created_at",
295+ "last_signed_in_at",
296+ ]),
297+ });
298+ maps.push(TableMap {
299+ name: "workspace_owner",
300+ columns: old_cols(&["singleton", "user_id", "claimed_at"]),
301+ });
302+ maps.push(TableMap {
303+ name: "signin_link",
304+ columns: old_cols(&["id", "user_id", "token_hash", "created_at", "expires_at", "used_at"]),
305+ });
306+ maps.push(TableMap {
307+ name: "session",
308+ columns: old_cols(&["id", "user_id", "token_hash", "created_at", "expires_at", "revoked_at"]),
309+ });
310+ maps.push(TableMap {
311+ name: "auth_attempt",
312+ columns: old_cols(&["id", "bucket", "attempted_at"]),
313+ });
314+ maps.push(TableMap {
315+ name: "board",
316+ columns: old_cols(&["id", "workspace_id", "name", "task_prefix", "created_at"]),
317+ });
318+ maps.push(TableMap {
319+ name: "board_column",
320+ columns: old_cols(&["id", "board_id", "name", "position", "is_done"]),
321+ });
322+ // `tag` is seeded, not copied.
323+ maps.push(TableMap {
324+ name: "task",
325+ columns: vec![
326+ ("id", "old.id".into()),
327+ ("board_id", "old.board_id".into()),
328+ ("parent_id", "old.parent_id".into()),
329+ ("task_key", "old.task_key".into()),
330+ ("title", "old.title".into()),
331+ ("description", "old.description".into()),
332+ ("column_id", "old.column_id".into()),
333+ (
334+ "tag_id",
335+ "(SELECT id FROM main.tag WHERE board_id = old.board_id AND is_default = 1)".into(),
336+ ),
337+ ("deadline", "old.deadline".into()),
338+ ("position", "old.position".into()),
339+ ("created_by", "old.created_by".into()),
340+ ("created_at", "old.created_at".into()),
341+ ("updated_at", "old.updated_at".into()),
342+ ("done_at", "old.done_at".into()),
343+ ("deleted_at", "old.deleted_at".into()),
344+ ],
345+ });
346+ maps.push(TableMap {
347+ name: "task_assignee",
348+ columns: old_cols(&["task_id", "user_id"]),
349+ });
350+ maps.push(TableMap {
351+ name: "task_watcher",
352+ columns: old_cols(&["task_id", "user_id"]),
353+ });
354+ maps.push(TableMap {
355+ name: "task_dependency",
356+ columns: old_cols(&[
357+ "blocked_task_id",
358+ "blocking_task_id",
359+ "created_at",
360+ "cleared_at",
361+ ]),
362+ });
363+ maps.push(TableMap {
364+ name: "comment",
365+ columns: old_cols(&["id", "task_id", "author_id", "body", "created_at"]),
366+ });
367+ maps.push(TableMap {
368+ name: "attachment",
369+ columns: old_cols(&[
370+ "id",
371+ "task_id",
372+ "comment_id",
373+ "file_name",
374+ "mime_type",
375+ "size_bytes",
376+ "bytes",
377+ "uploaded_by",
378+ "created_at",
379+ ]),
380+ });
381+ maps.push(TableMap {
382+ name: "transition",
383+ columns: old_cols(&[
384+ "id",
385+ "task_id",
386+ "from_column",
387+ "to_column",
388+ "actor_id",
389+ "created_at",
390+ ]),
391+ });
392+ maps.push(TableMap {
393+ name: "freeing",
394+ columns: old_cols(&[
395+ "id",
396+ "board_id",
397+ "cause_key",
398+ "cause_title",
399+ "actor_id",
400+ "created_at",
401+ ]),
402+ });
403+ maps.push(TableMap {
404+ name: "activity",
405+ columns: vec![
406+ ("id", "old.id".into()),
407+ ("task_id", "old.task_id".into()),
408+ ("actor_id", "old.actor_id".into()),
409+ ("subject_id", "NULL".into()),
410+ ("kind", "old.kind".into()),
411+ ("detail", "old.detail".into()),
412+ ("created_at", "old.created_at".into()),
413+ ],
414+ });
415+ maps.push(TableMap {
416+ name: "mail_rule",
417+ columns: old_cols(&[
418+ "id",
419+ "board_id",
420+ "trigger_kind",
421+ "trigger_column",
422+ "subject",
423+ "audience",
424+ "enabled",
425+ "created_at",
426+ "include_task_details",
427+ ]),
428+ });
429+ maps.push(TableMap {
430+ name: "mail_send",
431+ columns: old_cols(&[
432+ "id",
433+ "rule_id",
434+ "event_id",
435+ "task_id",
436+ "recipient",
437+ "state",
438+ "attempts",
439+ "last_error",
440+ "claimed_at",
441+ "next_attempt_at",
442+ "sent_at",
443+ "kind",
444+ "subject",
445+ "body",
446+ ]),
447+ });
448+ maps.push(TableMap {
449+ name: "mail_decision",
450+ columns: old_cols(&[
451+ "id",
452+ "rule_id",
453+ "event_id",
454+ "task_id",
455+ "outcome",
456+ "detail",
457+ "created_at",
458+ ]),
459+ });
460+
461+ maps
462+}
463+
464+fn old_cols(cols: &[&'static str]) -> Vec<(&'static str, String)> {
465+ cols.iter().map(|c| (*c, format!("old.{}", c))).collect()
466+}
467+
468+/// Returns true if the attached old `workspace` table already carries the
469+/// sender-check columns added by the old 0002 migration.
470+async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {
471+ let mut rows = conn
472+ .query(&format!("PRAGMA table_info({table})"), ())
473+ .await
474+ .map_err(|e| StoreError::Backend(e.to_string()))?;
475+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
476+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
477+ if name == column {
478+ return Ok(true);
479+ }
480+ }
481+ Ok(false)
482+}
483+
484+/// Validates that every destination column is covered and that no map
485+/// references a column that does not exist. A missing column is a startup
486+/// error, never a silent NULL.
487+async fn validate_maps(conn: &Connection, maps: &[TableMap]) -> Result<()> {
488+ use std::collections::HashSet;
489+
490+ for map in maps {
491+ let sql = format!("PRAGMA table_info({})", map.name);
492+ let mut rows = conn
493+ .query(&sql, ())
494+ .await
495+ .map_err(|e| StoreError::Backend(e.to_string()))?;
496+ let mut actual = HashSet::new();
497+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
498+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
499+ actual.insert(name);
500+ }
501+
502+ for (col, _) in &map.columns {
503+ if !actual.contains(*col) {
504+ return Err(StoreError::Backend(format!(
505+ "reconcile map for {} references missing column {}",
506+ map.name, col
507+ )));
508+ }
509+ }
510+ for col in actual {
511+ if !map.columns.iter().any(|(c, _)| c == &col) {
512+ return Err(StoreError::Backend(format!(
513+ "reconcile map for {} is missing column {} (would become NULL)",
514+ map.name, col
515+ )));
516+ }
517+ }
518+ }
519+ Ok(())
520+}
521+
522+/// Copies every mapped table from the attached old database into the new
523+/// main schema, in foreign-key-safe order.
524+async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> Result<()> {
525+ let escaped = path.replace('\'', "''");
526+ new_conn
527+ .execute(&format!("ATTACH DATABASE '{}' AS old", escaped), ())
528+ .await
529+ .map_err(|e| StoreError::Backend(e.to_string()))?;
530+
531+ let has_smtp_check = old_has_column(old_conn, "workspace", "smtp_check_at").await?;
532+ let has_batch_window =
533+ old_has_column(old_conn, "workspace", "mail_batch_minutes").await?;
534+ let maps = build_maps(has_smtp_check, has_batch_window);
535+ validate_maps(new_conn, &maps).await?;
536+
537+ for map in maps {
538+ // The `General` tags are seeded between `board` and `task`: they point
539+ // at boards, so the boards must already be here, and the tasks that
540+ // will point back at them must not be here yet.
541+ if map.name == "task" {
542+ seed_general_tags(old_conn, new_conn).await?;
543+ }
544+ let cols = map.columns.iter().map(|(c, _)| *c).collect::<Vec<_>>().join(", ");
545+ // `old` is the attached SCHEMA, not a table, so `old.id` in a select
546+ // list reads as "table old, column id". The source table is aliased
547+ // and the maps' `old.` prefix rewritten onto that alias.
548+ let exprs = map
549+ .columns
550+ .iter()
551+ .map(|(_, e)| e.replace("old.", "src."))
552+ .collect::<Vec<_>>()
553+ .join(", ");
554+ let sql = format!(
555+ "INSERT INTO main.{} ({}) SELECT {} FROM old.{} AS src",
556+ map.name, cols, exprs, map.name
557+ );
558+ new_conn
559+ .execute(&sql, ())
560+ .await
561+ .map_err(|e| StoreError::Backend(format!("{} while copying {}: {}", e, map.name, sql)))?;
562+ }
563+
564+ new_conn
565+ .execute("DETACH DATABASE old", ())
566+ .await
567+ .map_err(|e| StoreError::Backend(e.to_string()))?;
568+
569+ Ok(())
570+}
571+
572+/// Verifies the rebuilt database before the swap.
573+async fn verify(old_conn: &Connection, new_conn: &Connection) -> Result<()> {
574+ let mut rows = new_conn
575+ .query("PRAGMA foreign_key_check", ())
576+ .await
577+ .map_err(|e| StoreError::Backend(e.to_string()))?;
578+ let mut fk_errors = Vec::new();
579+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
580+ let table: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
581+ let rowid: i64 = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
582+ let parent: String = row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?;
583+ let fkid: i64 = row.get(3).map_err(|e| StoreError::Backend(e.to_string()))?;
584+ fk_errors.push(format!(
585+ "{} rowid {} references {} (foreign key {})",
586+ table, rowid, parent, fkid
587+ ));
588+ }
589+ if !fk_errors.is_empty() {
590+ return Err(StoreError::Backend(format!(
591+ "foreign key check failed:\n{}",
592+ fk_errors.join("\n")
593+ )));
594+ }
595+
596+ let mut rows = new_conn
597+ .query("PRAGMA integrity_check", ())
598+ .await
599+ .map_err(|e| StoreError::Backend(e.to_string()))?;
600+ let mut integrity = Vec::new();
601+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
602+ let msg: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
603+ integrity.push(msg);
604+ }
605+ if integrity.len() != 1 || integrity[0] != "ok" {
606+ return Err(StoreError::Backend(format!(
607+ "integrity check failed: {:?}",
608+ integrity
609+ )));
610+ }
611+
612+ let tables = [
613+ "workspace",
614+ "user",
615+ "workspace_owner",
616+ "signin_link",
617+ "session",
618+ "auth_attempt",
619+ "board",
620+ "board_column",
621+ "task",
622+ "task_assignee",
623+ "task_watcher",
624+ "task_dependency",
625+ "comment",
626+ "attachment",
627+ "transition",
628+ "freeing",
629+ "activity",
630+ "mail_rule",
631+ "mail_send",
632+ "mail_decision",
633+ ];
634+ for table in tables {
635+ let old_count = count_rows(old_conn, table).await?;
636+ let new_count = count_rows(new_conn, table).await?;
637+ if old_count != new_count {
638+ return Err(StoreError::Backend(format!(
639+ "row count mismatch for {}: old {} new {}",
640+ table, old_count, new_count
641+ )));
642+ }
643+ }
644+
645+ // `tag` is new: one default tag per board.
646+ let board_count = count_rows(old_conn, "board").await?;
647+ let tag_count = count_rows(new_conn, "tag").await?;
648+ if tag_count != board_count {
649+ return Err(StoreError::Backend(format!(
650+ "tag row count {} does not match board count {}",
651+ tag_count, board_count
652+ )));
653+ }
654+
655+ Ok(())
656+}
657+
658+async fn count_rows(conn: &Connection, table: &str) -> Result<i64> {
659+ let sql = format!("SELECT COUNT(*) FROM {}", table);
660+ let mut rows = conn
661+ .query(&sql, ())
662+ .await
663+ .map_err(|e| StoreError::Backend(e.to_string()))?;
664+ let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? else {
665+ return Err(StoreError::Backend(format!(
666+ "could not count rows in {}",
667+ table
668+ )));
669+ };
670+ row.get::<i64>(0).map_err(|e| StoreError::Backend(e.to_string()))
671+}
672+
673+fn cleanup_rebuilt(rebuilt_path: &str) {
674+ let _ = std::fs::remove_file(rebuilt_path);
675+ let _ = std::fs::remove_file(format!("{}-wal", rebuilt_path));
676+ let _ = std::fs::remove_file(format!("{}-shm", rebuilt_path));
677+}
678+
679+/// Move a SQLite sidecar file (`-wal` or `-shm`) if it exists. A missing
680+/// sibling is fine: WAL mode may not have created one, and the backup is
681+/// still consistent without it.
682+fn rename_sibling(from: &str, to: &str, suffix: &str) {
683+ let from_path = format!("{}{}", from, suffix);
684+ let to_path = format!("{}{}", to, suffix);
685+ if std::path::Path::new(&from_path).exists() {
686+ let _ = std::fs::rename(&from_path, &to_path);
687+ }
688+}
689+
690+fn backup_name(path: &str) -> Result<String> {
691+ let format = time::format_description::parse_borrowed::<2>(
692+ "[year]-[month]-[day]T[hour][minute][second]Z",
693+ )
694+ .map_err(|e| StoreError::Backend(format!("invalid time format: {}", e)))?;
695+ let stamp = time::OffsetDateTime::now_utc()
696+ .format(&format)
697+ .map_err(|e| StoreError::Backend(format!("time format failed: {}", e)))?;
698+
699+ let candidate = format!("{}.backup-{}", path, stamp);
700+ if !std::path::Path::new(&candidate).exists() {
701+ return Ok(candidate);
702+ }
703+ let mut n = 1;
704+ loop {
705+ let candidate = format!("{}.backup-{}-{}", path, stamp, n);
706+ if !std::path::Path::new(&candidate).exists() {
707+ return Ok(candidate);
708+ }
709+ n += 1;
710+ if n > 1000 {
711+ return Err(StoreError::Backend(
712+ "could not find an unused backup name".into(),
713+ ));
714+ }
715+ }
716+}
717+
718+#[cfg(test)]
719+mod tests {
720+ use super::backup_name;
721+
722+ #[test]
723+ fn backup_name_has_no_colons_or_spaces() {
724+ let name = backup_name("/tmp/izlek.db").unwrap();
725+ assert!(name.starts_with("/tmp/izlek.db.backup-"));
726+ assert!(!name.contains(':'));
727+ assert!(!name.contains(' '));
728+ }
729+
730+ #[test]
731+ fn backup_name_avoids_collision() {
732+ let first = backup_name("/tmp/izlek.db").unwrap();
733+ std::fs::File::create(&first).unwrap();
734+ let second = backup_name("/tmp/izlek.db").unwrap();
735+ assert_ne!(first, second);
736+ std::fs::remove_file(&first).unwrap();
737+ }
738+}
crates/izlek-core/src/store/schema.rsadded+360 -0
@@ -0,0 +1,360 @@
1+//! Schema fingerprinting: compare the database SQLite actually has with the
2+//! declared whole schema in `migrations/0001_init.sql`.
3+//!
4+//! SQLite stores `CREATE` statements as written, comments and all, so two
5+//! databases built from the same logical schema but different comments or
6+//! whitespace would otherwise look different. The normaliser here strips the
7+//! cosmetic differences that do not change what the schema means.
8+
9+use super::{Result, StoreError};
10+use turso::Connection;
11+
12+/// The declared whole schema, applied to an empty database.
13+pub(crate) const SCHEMA: &str = include_str!("../../migrations/0001_init.sql");
14+
15+/// Reads and normalises the schema of the connected database.
16+///
17+/// The fingerprint is a deterministic text built from `sqlite_master`:
18+/// `type|name|normalised_sql` for every non-sqlite object, ordered by type
19+/// and name. Two schemas that mean the same thing produce the same string;
20+/// two schemas that differ in tables, indexes, columns or constraints do not.
21+pub async fn fingerprint(conn: &Connection) -> Result<String> {
22+ let mut rows = conn
23+ .query(
24+ "SELECT type, name, sql FROM sqlite_master \
25+ WHERE name NOT LIKE 'sqlite_%' \
26+ ORDER BY type, name",
27+ (),
28+ )
29+ .await
30+ .map_err(|e| StoreError::Backend(e.to_string()))?;
31+
32+ let mut out = String::new();
33+ while let Some(row) = rows.next().await.map_err(|e| StoreError::Backend(e.to_string()))? {
34+ let t: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
35+ let name: String = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
36+ let sql: Option<String> =
37+ row.get(2).map_err(|e| StoreError::Backend(e.to_string()))?;
38+ out.push_str(&t);
39+ out.push('|');
40+ out.push_str(&name);
41+ out.push('|');
42+ if let Some(sql) = sql {
43+ out.push_str(&normalize_schema(&sql));
44+ }
45+ out.push('\n');
46+ }
47+ Ok(out)
48+}
49+
50+/// Builds an in-memory database from the declared schema and fingerprints it.
51+pub async fn declared_fingerprint() -> Result<String> {
52+ let db = turso::Builder::new_local(":memory:")
53+ .build()
54+ .await
55+ .map_err(|e| StoreError::Backend(e.to_string()))?;
56+ let conn = db.connect().map_err(|e| StoreError::Backend(e.to_string()))?;
57+ conn.execute_batch(SCHEMA)
58+ .await
59+ .map_err(|e| StoreError::Backend(e.to_string()))?;
60+ fingerprint(&conn).await
61+}
62+
63+/// A single schema object for diff reporting.
64+#[derive(Debug, Clone)]
65+pub(crate) struct SchemaObject {
66+ pub(crate) kind: String,
67+ pub(crate) name: String,
68+ pub(crate) sql: String,
69+}
70+
71+/// Parses the normalised schema into objects keyed by (kind, name).
72+pub(crate) fn parse_objects(fingerprint: &str) -> Vec<SchemaObject> {
73+ fingerprint
74+ .lines()
75+ .filter(|line| !line.is_empty())
76+ .filter_map(|line| {
77+ let mut parts = line.splitn(3, '|');
78+ let kind = parts.next()?.to_string();
79+ let name = parts.next()?.to_string();
80+ let sql = parts.next().unwrap_or("").to_string();
81+ Some(SchemaObject { kind, name, sql })
82+ })
83+ .collect()
84+}
85+
86+/// Human-readable description of how two fingerprints differ.
87+pub(crate) fn diff_report(old: &str, new: &str) -> String {
88+ let old_objs = parse_objects(old);
89+ let new_objs = parse_objects(new);
90+
91+ let mut missing = Vec::new();
92+ let mut extra = Vec::new();
93+ let mut changed = Vec::new();
94+
95+ for old_obj in &old_objs {
96+ match new_objs.iter().find(|n| n.kind == old_obj.kind && n.name == old_obj.name) {
97+ Some(new_obj) if new_obj.sql != old_obj.sql => changed.push((old_obj, new_obj)),
98+ Some(_) => {}
99+ None => missing.push(old_obj),
100+ }
101+ }
102+ for new_obj in &new_objs {
103+ if !old_objs.iter().any(|o| o.kind == new_obj.kind && o.name == new_obj.name) {
104+ extra.push(new_obj);
105+ }
106+ }
107+
108+ let mut lines = Vec::new();
109+ for obj in missing {
110+ lines.push(format!("- {} {} (removed)", obj.kind, obj.name));
111+ }
112+ for obj in extra {
113+ lines.push(format!("+ {} {} (added)", obj.kind, obj.name));
114+ }
115+ for (old_obj, new_obj) in changed {
116+ lines.push(format!("~ {} {} (changed)", old_obj.kind, old_obj.name));
117+ if old_obj.kind == "table" {
118+ let old_cols = extract_column_names(&old_obj.sql);
119+ let new_cols = extract_column_names(&new_obj.sql);
120+ let added: Vec<&str> = new_cols
121+ .iter()
122+ .filter(|c| !old_cols.contains(c))
123+ .map(String::as_str)
124+ .collect();
125+ let removed: Vec<&str> = old_cols
126+ .iter()
127+ .filter(|c| !new_cols.contains(c))
128+ .map(String::as_str)
129+ .collect();
130+ if !added.is_empty() {
131+ lines.push(format!(" added columns: {}", added.join(", ")));
132+ }
133+ if !removed.is_empty() {
134+ lines.push(format!(" removed columns: {}", removed.join(", ")));
135+ }
136+ }
137+ }
138+
139+ if lines.is_empty() {
140+ "schemas differ (cosmetic normalisation only)".to_string()
141+ } else {
142+ lines.join("\n")
143+ }
144+}
145+
146+/// Extracts the column names from a normalised CREATE TABLE statement.
147+/// Constraints at the table level are ignored; only top-level definitions
148+/// that start with an identifier are collected.
149+fn extract_column_names(sql: &str) -> Vec<String> {
150+ let body = match sql.strip_prefix("CREATE TABLE ") {
151+ Some(rest) => rest,
152+ None => return Vec::new(),
153+ };
154+ let body = remove_if_not_exists(body);
155+ let Some(start) = body.find('(') else {
156+ return Vec::new();
157+ };
158+ let Some(end) = body.rfind(')') else {
159+ return Vec::new();
160+ };
161+ let body = &body[start + 1..end];
162+
163+ let mut cols = Vec::new();
164+ let mut depth = 0i32;
165+ let mut current = String::new();
166+ for ch in body.chars() {
167+ match ch {
168+ '(' => {
169+ depth += 1;
170+ current.push(ch);
171+ }
172+ ')' => {
173+ depth -= 1;
174+ current.push(ch);
175+ }
176+ ',' if depth == 0 => {
177+ if let Some(col) = first_identifier(&current) {
178+ cols.push(col);
179+ }
180+ current.clear();
181+ }
182+ _ => current.push(ch),
183+ }
184+ }
185+ if !current.is_empty() {
186+ if let Some(col) = first_identifier(&current) {
187+ cols.push(col);
188+ }
189+ }
190+ cols
191+}
192+
193+fn first_identifier(item: &str) -> Option<String> {
194+ let item = item.trim();
195+ if item.is_empty() {
196+ return None;
197+ }
198+ let first = item.split_whitespace().next()?;
199+ let first = first.to_lowercase();
200+ if first == "constraint"
201+ || first == "primary"
202+ || first == "unique"
203+ || first == "check"
204+ || first == "foreign"
205+ {
206+ return None;
207+ }
208+ Some(first)
209+}
210+
211+/// Normalises SQL text so that cosmetic differences disappear.
212+///
213+/// Differences deliberately ignored:
214+/// - whitespace runs collapse to a single space;
215+/// - SQL comments (`--` to end of line, `/* ... */`) are removed;
216+/// - `IF NOT EXISTS` is removed (case-insensitive, whole tokens only).
217+///
218+/// Differences deliberately preserved:
219+/// - identifier case and spelling;
220+/// - string literal contents, including any whitespace or comment-like text
221+/// inside them;
222+/// - numeric literals, keyword order and constraint text.
223+fn normalize_schema(sql: &str) -> String {
224+ let mut out = String::with_capacity(sql.len());
225+ let mut chars = sql.chars().peekable();
226+ let mut in_string = false;
227+ let mut prev_ws = false;
228+
229+ while let Some(ch) = chars.next() {
230+ if in_string {
231+ out.push(ch);
232+ if ch == '\'' {
233+ if chars.peek() == Some(&'\'') {
234+ out.push(chars.next().unwrap());
235+ } else {
236+ in_string = false;
237+ }
238+ }
239+ continue;
240+ }
241+
242+ if ch == '-' && chars.peek() == Some(&'-') {
243+ chars.next();
244+ while let Some(c) = chars.next() {
245+ if c == '\n' {
246+ break;
247+ }
248+ }
249+ prev_ws = true;
250+ continue;
251+ }
252+
253+ if ch == '/' && chars.peek() == Some(&'*') {
254+ chars.next();
255+ while let Some(c) = chars.next() {
256+ if c == '*' && chars.peek() == Some(&'/') {
257+ chars.next();
258+ break;
259+ }
260+ }
261+ prev_ws = true;
262+ continue;
263+ }
264+
265+ if ch == '\'' {
266+ in_string = true;
267+ out.push(ch);
268+ prev_ws = false;
269+ continue;
270+ }
271+
272+ if ch.is_whitespace() {
273+ prev_ws = true;
274+ continue;
275+ }
276+
277+ if prev_ws && !out.is_empty() {
278+ out.push(' ');
279+ }
280+ out.push(ch);
281+ prev_ws = false;
282+ }
283+
284+ remove_if_not_exists(&out)
285+}
286+
287+/// Strips a normalised `IF NOT EXISTS` token sequence, preserving whitespace
288+/// around it. Because `normalize_schema` has already collapsed whitespace, the
289+/// sequence appears as separate tokens separated by single spaces.
290+fn remove_if_not_exists(sql: &str) -> String {
291+ let tokens: Vec<&str> = sql.split(' ').collect();
292+ let mut out = Vec::with_capacity(tokens.len());
293+ let mut i = 0;
294+ while i < tokens.len() {
295+ if i + 2 < tokens.len()
296+ && tokens[i].eq_ignore_ascii_case("IF")
297+ && tokens[i + 1].eq_ignore_ascii_case("NOT")
298+ && tokens[i + 2].eq_ignore_ascii_case("EXISTS")
299+ {
300+ i += 3;
301+ } else {
302+ out.push(tokens[i]);
303+ i += 1;
304+ }
305+ }
306+ out.join(" ")
307+}
308+
309+#[cfg(test)]
310+mod tests {
311+ use super::{normalize_schema, parse_objects};
312+
313+ #[test]
314+ fn comments_and_whitespace_do_not_change_meaning() {
315+ let a = "CREATE TABLE foo (\n id INTEGER, -- the key\n name TEXT /* a comment */\n);";
316+ let b = "CREATE TABLE foo ( id INTEGER, name TEXT );";
317+ assert_eq!(normalize_schema(a), normalize_schema(b));
318+ }
319+
320+ #[test]
321+ fn if_not_exists_is_ignored() {
322+ let a = "CREATE TABLE IF NOT EXISTS foo (id INTEGER);";
323+ let b = "CREATE TABLE foo (id INTEGER);";
324+ assert_eq!(normalize_schema(a), normalize_schema(b));
325+ }
326+
327+ #[test]
328+ fn string_literals_are_preserved() {
329+ let a = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');";
330+ let b = "CREATE TABLE foo (name TEXT DEFAULT 'a -- b /* c */');";
331+ assert_eq!(normalize_schema(a), normalize_schema(b));
332+ }
333+
334+ #[test]
335+ fn real_differences_still_differ() {
336+ let a = "CREATE TABLE foo (id INTEGER);";
337+ let b = "CREATE TABLE foo (id TEXT);";
338+ assert_ne!(normalize_schema(a), normalize_schema(b));
339+ }
340+
341+ #[test]
342+ fn if_not_exists_does_not_corrupt_identifiers() {
343+ // The stripper looks for whole tokens; words that merely appear
344+ // inside identifiers or string literals must stay put.
345+ let a = "CREATE TABLE IF NOT EXISTS notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');";
346+ let b = "CREATE TABLE notification (if_not_exists TEXT DEFAULT 'IF NOT EXISTS');";
347+ assert_eq!(normalize_schema(a), normalize_schema(b));
348+ }
349+
350+ #[test]
351+ fn partial_index_where_clause_is_parsed_safely() {
352+ // Partial-index SQL contains a WHERE clause; diff_report must not
353+ // try to extract column names from it, and parsing must not panic.
354+ let fp = "index|tag_one_default|CREATE UNIQUE INDEX tag_one_default ON tag(board_id) WHERE is_default = 1\n";
355+ let objs = parse_objects(fp);
356+ assert_eq!(objs.len(), 1);
357+ assert_eq!(objs[0].kind, "index");
358+ assert_eq!(objs[0].name, "tag_one_default");
359+ }
360+}
crates/izlek-core/src/store/turso_store.rsmodified+723 -319
@@ -7,7 +7,7 @@
7 7
8 use async_trait::async_trait;8 use async_trait::async_trait;
9 use rand::Rng;9 use rand::Rng;
10-use time::OffsetDateTime;10+use time::{Duration, OffsetDateTime};
11 use time::format_description::well_known::Rfc3339;11 use time::format_description::well_known::Rfc3339;
12 use turso::transaction::TransactionBehavior;12 use turso::transaction::TransactionBehavior;
13 use turso::{Builder, Connection, Row, Value, params};13 use turso::{Builder, Connection, Row, Value, params};
@@ -15,32 +15,24 @@ use ulid::Ulid;
15 15
16 use super::secret;16 use super::secret;
17 use super::{17 use super::{
18- ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, CommentWritten, Deletion,18+ ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten,
19- ClaimedSend, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,19+ Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,
20- MailSend,20+ MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,
21- NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,21+ SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger,
22- SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, TaskCreated, Trigger, User,22+ User, UserStats, Workspace,
23- Workspace,
24 };23 };
24+use super::{reconcile, ReconcileOptions, schema};
25 use crate::Role;25 use crate::Role;
26-use crate::live::{Change, Topic};26+use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition};
27-use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition};
28 use crate::detail::{27 use crate::detail::{
29 ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine,28 ActivityEntry, ActivityKind, Comment, DeletionCost, DependencyEdge, DetailReads, FileLine,
30 SubtaskLine, TaskFacts,29 SubtaskLine, TaskFacts,
31 };30 };
31+use crate::live::{Change, Topic};
32 use time::Date;32 use time::Date;
33 use time::format_description::BorrowedFormatItem;33 use time::format_description::BorrowedFormatItem;
34 use time::macros::format_description;34 use time::macros::format_description;
35 35
36-/// Every migration, in order. There is one: nothing has been released, so a
37-/// schema change is made in `0001_init.sql` and the database recreated. A
38-/// second file is for the day there is data worth keeping.
39-const MIGRATIONS: &[(i64, &str)] = &[
40- (1, include_str!("../../migrations/0001_init.sql")),
41- (2, include_str!("../../migrations/0002_sender_check.sql")),
42-];
43-
44 /// The board a fresh workspace gets, and its columns. `Done` is the column36 /// The board a fresh workspace gets, and its columns. `Done` is the column
45 /// that stamps a card finished.37 /// that stamps a card finished.
46 const DEFAULT_BOARD_NAME: &str = "Board";38 const DEFAULT_BOARD_NAME: &str = "Board";
@@ -79,7 +71,10 @@ impl TursoStore {
79 /// would fill the log with the sound of an idle app.71 /// would fill the log with the sound of an idle app.
80 fn announce(&self, topics: impl IntoIterator<Item = Topic>) {72 fn announce(&self, topics: impl IntoIterator<Item = Topic>) {
81 for topic in topics {73 for topic in topics {
82- let _ = self.live.send(Change { topic, seq: crate::live::next_seq() });74+ let _ = self.live.send(Change {
75+ topic,
76+ seq: crate::live::next_seq(),
77+ });
83 }78 }
84 }79 }
85 80
@@ -87,6 +82,10 @@ impl TursoStore {
87 /// up to date. `:memory:` gives a throwaway database for tests.82 /// up to date. `:memory:` gives a throwaway database for tests.
88 pub async fn open(path: &str) -> Result<Self> {83 pub async fn open(path: &str) -> Result<Self> {
89 let existed = path != ":memory:" && std::path::Path::new(path).exists();84 let existed = path != ":memory:" && std::path::Path::new(path).exists();
85+ // Before anything holds this file open: a database of an older shape is
86+ // rebuilt now, while no handle of ours points at the file that the
87+ // rebuild is about to replace.
88+ Self::repair_if_stale(path).await?;
90 let db = Builder::new_local(path).build().await.map_err(backend)?;89 let db = Builder::new_local(path).build().await.map_err(backend)?;
91 let conn = db.connect().map_err(backend)?;90 let conn = db.connect().map_err(backend)?;
92 // Turso is a single-writer engine. Two connections on one Database91 // Turso is a single-writer engine. Two connections on one Database
@@ -117,9 +116,21 @@ impl TursoStore {
117 // the reader is told it lagged and resyncs, which is cheaper than the116 // the reader is told it lagged and resyncs, which is cheaper than the
118 // memory a larger buffer would cost to avoid saying so.117 // memory a larger buffer would cost to avoid saying so.
119 let (live, _) = tokio::sync::broadcast::channel(256);118 let (live, _) = tokio::sync::broadcast::channel(256);
120- let store = Self { conn: tokio::sync::Mutex::new(conn), db, key, live };119+ let store = Self {
121- store.migrate().await?;120+ conn: tokio::sync::Mutex::new(conn),
121+ db,
122+ key,
123+ live,
124+ };
125+ store.migrate(path).await?;
122 store.encrypt_plaintext_passwords().await?;126 store.encrypt_plaintext_passwords().await?;
127+ // The file may have been rebuilt from a backup; its permissions and
128+ // any transient WAL/SHM siblings should still be private.
129+ if path != ":memory:" {
130+ restrict_if_present(std::path::Path::new(path))?;
131+ restrict_if_present(&sibling(path, "-wal"))?;
132+ restrict_if_present(&sibling(path, "-shm"))?;
133+ }
123 Ok(store)134 Ok(store)
124 }135 }
125 136
@@ -151,107 +162,145 @@ impl TursoStore {
151 }162 }
152 for (id, plaintext) in pending {163 for (id, plaintext) in pending {
153 let sealed = secret::seal(&self.key, &plaintext);164 let sealed = secret::seal(&self.key, &plaintext);
154- conn165+ conn.execute(
155- .execute(166+ "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2",
156- "UPDATE workspace SET smtp_password = ?1 WHERE id = ?2",167+ params![sealed, id],
157- params![sealed, id],168+ )
158- )169+ .await
159- .await170+ .map_err(backend)?;
160- .map_err(backend)?;
161 }171 }
162 Ok(())172 Ok(())
163 }173 }
164 174
165- async fn migrate(&self) -> Result<()> {175+ /// Brings the database to the declared schema.
166- self.conn176+ ///
167- .lock()177+ /// - An empty database is created from `migrations/0001_init.sql`.
168- .await178+ /// - A database that already matches the declared schema is left alone.
169- .execute(179+ /// - A stale database is backed up, rebuilt, and re-verified once.
170- "CREATE TABLE IF NOT EXISTS schema_version (180+ /// If the rebuilt database still does not match, the process stops
171- version INTEGER PRIMARY KEY,181+ /// with the original backed up and untouched.
172- applied_at TEXT NOT NULL182+ ///
173- )",183+ /// SQLite's DDL is transactional, so a schema that dies halfway leaves
184+ /// nothing behind: a half-created database is a boot that starts over,
185+ /// not a database with a hole in it.
186+ async fn migrate(&self, path: &str) -> Result<()> {
187+ let conn = self.conn.lock().await;
188+ let mut rows = conn
189+ .query(
190+ "SELECT COUNT(*) FROM sqlite_master \
191+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
174 (),192 (),
175 )193 )
176 .await194 .await
177 .map_err(backend)?;195 .map_err(backend)?;
196+ let empty = match rows.next().await.map_err(backend)? {
197+ Some(row) => row.get::<i64>(0).map_err(backend)? == 0,
198+ None => true,
199+ };
200+ drop(rows);
178 201
179- let applied = self.applied_versions().await?;202+ if empty {
180- for (version, sql) in MIGRATIONS {203+ conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?;
181- if applied.contains(version) {204+ if let Err(e) = conn.execute_batch(super::schema::SCHEMA).await {
182- continue;205+ let _ = conn.execute("ROLLBACK", ()).await;
206+ return Err(backend(e));
183 }207 }
184- self.apply(*version, sql).await?;208+ return conn.execute("COMMIT", ()).await.map_err(backend).map(|_| ());
209+ }
210+
211+ if path == ":memory:" {
212+ // Tests own an in-memory database; its schema is whatever the
213+ // test created, and the open should not try to reconcile it.
214+ return Ok(());
215+ }
216+
217+ // `repair_if_stale` ran before this handle was ever opened, so by now
218+ // the file on disk matches. Saying so here is cheap and turns a
219+ // reordering mistake into a refusal to start rather than a store
220+ // running against a schema the code does not expect.
221+ let have = schema::fingerprint(&conn).await.map_err(backend)?;
222+ let want = schema::declared_fingerprint().await.map_err(backend)?;
223+ if have != want {
224+ return Err(StoreError::Backend(format!(
225+ "database does not match the declared schema and was not repaired; \
226+ do not restart. diff:\n{}",
227+ schema::diff_report(&have, &want)
228+ )));
185 }229 }
186 Ok(())230 Ok(())
187 }231 }
188 232
189- /// One migration and the row that says it ran, in one transaction.233+ /// Brings a database of an older shape onto the declared schema, BEFORE
234+ /// any long-lived handle is opened on it.
190 ///235 ///
191- /// A migration is not only a thing that can fail: one that rebuilds a236+ /// The order matters and is the whole reason this is not part of
192- /// table — which is how SQLite drops a CHECK or a foreign key — would237+ /// `migrate`: `reconcile` swaps a rebuilt file into place, so a
193- /// leave the table gone rather than merely unmigrated if it died between238+ /// `turso::Database` opened beforehand still refers to the file that is
194- /// the DROP and the RENAME. So the file and its `schema_version` row239+ /// now the backup. Reconnecting such a handle reads the old database and
195- /// commit together or not at all, and a half-applied migration is a boot240+ /// makes a successful rebuild look like a failed one.
196- /// that starts over rather than a database with a hole in it.241+ async fn repair_if_stale(path: &str) -> Result<()> {
197- ///242+ if path == ":memory:" || !std::path::Path::new(path).exists() {
198- /// SQLite's DDL is transactional, which is what makes this possible at all.243+ return Ok(());
199- async fn apply(&self, version: i64, sql: &str) -> Result<()> {
200- let conn = self.conn.lock().await;
201- conn
202- .execute("BEGIN IMMEDIATE", ())
203- .await
204- .map_err(backend)?;
205- let written = async {
206- conn.execute_batch(sql).await?;
207- conn
208- .execute(
209- "INSERT INTO schema_version (version, applied_at) VALUES (?1, ?2)",
210- params![
211- version,
212- now_text().map_err(|_| turso::Error::Misuse(
213- "the clock could not be read".to_string()
214- ))?
215- ],
216- )
217- .await?;
218- Ok::<_, turso::Error>(())
219 }244 }
220- .await;245+ let (have, empty) = {
221- match written {246+ let db = Builder::new_local(path).build().await.map_err(backend)?;
222- Ok(()) => conn247+ let conn = db.connect().map_err(backend)?;
223- .execute("COMMIT", ())248+ let mut rows = conn
249+ .query(
250+ "SELECT COUNT(*) FROM sqlite_master \
251+ WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
252+ (),
253+ )
224 .await254 .await
225- .map_err(backend)255+ .map_err(backend)?;
226- .map(|_| ()),256+ let empty = match rows.next().await.map_err(backend)? {
227- Err(e) => {257+ Some(row) => row.get::<i64>(0).map_err(backend)? == 0,
228- let _ = conn.execute("ROLLBACK", ()).await;258+ None => true,
229- Err(backend(e))259+ };
230- }260+ drop(rows);
261+ let have = if empty {
262+ String::new()
263+ } else {
264+ schema::fingerprint(&conn).await.map_err(backend)?
265+ };
266+ (have, empty)
267+ };
268+ if empty {
269+ return Ok(());
231 }270 }
232- }271+ let want = schema::declared_fingerprint().await.map_err(backend)?;
233-272+ if have == want {
234- async fn applied_versions(&self) -> Result<Vec<i64>> {273+ return Ok(());
235- let conn = self.conn.lock().await;
236- let mut rows = conn
237- .query("SELECT version FROM schema_version", ())
238- .await
239- .map_err(backend)?;
240- let mut out = Vec::new();
241- while let Some(row) = rows.next().await.map_err(backend)? {
242- out.push(row.get::<i64>(0).map_err(backend)?);
243 }274 }
244- Ok(out)
245- }
246 275
247- /// The schema version the database is actually at.276+ eprintln!(
248- pub async fn schema_version(&self) -> Result<i64> {277+ "database schema differs from the declared schema; rebuilding automatically\n{}",
249- Ok(self278+ schema::diff_report(&have, &want)
250- .applied_versions()279+ );
251- .await?280+ reconcile(
252- .into_iter()281+ path,
253- .max()282+ ReconcileOptions {
254- .unwrap_or(0))283+ dry_run: false,
284+ yes: false,
285+ auto: true,
286+ },
287+ )
288+ .await?;
289+
290+ // Check the result once, on a handle opened after the swap. A
291+ // normalisation bug that rebuilt forever would otherwise write a
292+ // full-size backup on every restart until the disk filled.
293+ let db = Builder::new_local(path).build().await.map_err(backend)?;
294+ let conn = db.connect().map_err(backend)?;
295+ let after = schema::fingerprint(&conn).await.map_err(backend)?;
296+ if after != want {
297+ return Err(StoreError::Backend(format!(
298+ "rebuild did not match the declared schema; the original is backed up beside it \
299+ and this is not retried. diff:\n{}",
300+ schema::diff_report(&after, &want)
301+ )));
302+ }
303+ Ok(())
255 }304 }
256 305
257 /// A connection of its own, for work that opens a transaction.306 /// 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,
376 425
377 fn decision_from(row: &Row) -> Result<MailDecision> {426 fn decision_from(row: &Row) -> Result<MailDecision> {
378 let raw = text(row, 4)?;427 let raw = text(row, 4)?;
379- let outcome =428+ let outcome = MailOutcome::parse(&raw)
380- MailOutcome::parse(&raw).ok_or_else(|| StoreError::Corrupt(format!("mail outcome {raw:?}")))?;429+ .ok_or_else(|| StoreError::Corrupt(format!("mail outcome {raw:?}")))?;
381 Ok(MailDecision {430 Ok(MailDecision {
382 id: text(row, 0)?,431 id: text(row, 0)?,
383 rule_id: text(row, 1)?,432 rule_id: text(row, 1)?,
@@ -575,6 +624,7 @@ fn workspace_from(row: &Row) -> Result<Workspace> {
575 attachment_limit_bytes: row.get::<i64>(3).map_err(backend)?.max(0) as u64,624 attachment_limit_bytes: row.get::<i64>(3).map_err(backend)?.max(0) as u64,
576 allowed_file_types,625 allowed_file_types,
577 photo_limit_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,626 photo_limit_bytes: row.get::<i64>(5).map_err(backend)?.max(0) as u64,
627+ mail_batch_minutes: row.get::<i64>(19).map_err(backend)?.max(0) as u32,
578 smtp_host: opt_text(row, 6)?,628 smtp_host: opt_text(row, 6)?,
579 smtp_port: row.get::<Option<u32>>(7).map_err(backend)?,629 smtp_port: row.get::<Option<u32>>(7).map_err(backend)?,
580 smtp_username: opt_text(row, 8)?,630 smtp_username: opt_text(row, 8)?,
@@ -609,7 +659,7 @@ const WORKSPACE_COLUMNS: &str = "id, name, created_at, attachment_limit_bytes, \
609 smtp_from_name, smtp_from_address, \659 smtp_from_name, smtp_from_address, \
610 (smtp_password IS NOT NULL AND smtp_password <> ''), \660 (smtp_password IS NOT NULL AND smtp_password <> ''), \
611 smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \661 smtp_test_at, smtp_test_ms, smtp_test_error, public_url, \
612- smtp_check_at, smtp_check_ms, smtp_check_error";662+ smtp_check_at, smtp_check_ms, smtp_check_error, mail_batch_minutes";
613 663
614 fn user_from(row: &Row) -> Result<User> {664 fn user_from(row: &Row) -> Result<User> {
615 Ok(User {665 Ok(User {
@@ -723,7 +773,7 @@ impl Store for TursoStore {
723 board_id.clone(),773 board_id.clone(),
724 workspace_id.clone(),774 workspace_id.clone(),
725 DEFAULT_BOARD_NAME,775 DEFAULT_BOARD_NAME,
726- now776+ now.clone(),
727 ],777 ],
728 )778 )
729 .await?;779 .await?;
@@ -741,6 +791,15 @@ impl Store for TursoStore {
741 )791 )
742 .await?;792 .await?;
743 }793 }
794+ // Every task must wear a tag, so the board comes with the one
795+ // that catches whatever loses its own — English, like the
796+ // columns beside it.
797+ tx.execute(
798+ "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \
799+ VALUES (?1, ?2, 'General', 0, 1, ?3)",
800+ params![Ulid::new().to_string(), board_id.clone(), now.clone()],
801+ )
802+ .await?;
744 Ok::<_, turso::Error>(())803 Ok::<_, turso::Error>(())
745 }804 }
746 .await;805 .await;
@@ -803,26 +862,28 @@ impl Store for TursoStore {
803 // Sealed here, not by the caller — the `Store` trait keeps passing862 // Sealed here, not by the caller — the `Store` trait keeps passing
804 // plaintext so nothing outside this file needs to know a cipher863 // plaintext so nothing outside this file needs to know a cipher
805 // exists. See `crate::store::secret`.864 // exists. See `crate::store::secret`.
806- let sealed_password = sender.password.as_deref().map(|p| secret::seal(&self.key, p));865+ let sealed_password = sender
807- conn866+ .password
808- .execute(867+ .as_deref()
809- "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \868+ .map(|p| secret::seal(&self.key, p));
869+ conn.execute(
870+ "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \
810 smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \871 smtp_password = COALESCE(?4, smtp_password), smtp_from_name = ?5, \
811 smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \872 smtp_from_address = ?6, smtp_test_at = NULL, smtp_test_ms = NULL, \
812 smtp_test_error = NULL, smtp_check_at = NULL, smtp_check_ms = NULL, \873 smtp_test_error = NULL, smtp_check_at = NULL, smtp_check_ms = NULL, \
813 smtp_check_error = NULL WHERE id = ?7",874 smtp_check_error = NULL WHERE id = ?7",
814- params![875+ params![
815- sender.host,876+ sender.host,
816- sender.port as i64,877+ sender.port as i64,
817- sender.username,878+ sender.username,
818- sealed_password,879+ sealed_password,
819- sender.from_name,880+ sender.from_name,
820- sender.from_address,881+ sender.from_address,
821- workspace_id882+ workspace_id
822- ],883+ ],
823- )884+ )
824- .await885+ .await
825- .map_err(backend)?;886+ .map_err(backend)?;
826 drop(conn);887 drop(conn);
827 self.announce([Topic::Settings]);888 self.announce([Topic::Settings]);
828 Ok(())889 Ok(())
@@ -830,19 +891,18 @@ impl Store for TursoStore {
830 891
831 async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()> {892 async fn record_sender_check(&self, workspace_id: &str, check: SenderCheck) -> Result<()> {
832 let conn = self.conn.lock().await;893 let conn = self.conn.lock().await;
833- conn894+ conn.execute(
834- .execute(895+ "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \
835- "UPDATE workspace SET smtp_check_at = ?1, smtp_check_ms = ?2, \
836 smtp_check_error = ?3 WHERE id = ?4",896 smtp_check_error = ?3 WHERE id = ?4",
837- params![897+ params![
838- stamp(check.at)?,898+ stamp(check.at)?,
839- check.took_ms as i64,899+ check.took_ms as i64,
840- check.error,900+ check.error,
841- workspace_id901+ workspace_id
842- ],902+ ],
843- )903+ )
844- .await904+ .await
845- .map_err(backend)?;905+ .map_err(backend)?;
846 drop(conn);906 drop(conn);
847 self.announce([Topic::Settings]);907 self.announce([Topic::Settings]);
848 Ok(())908 Ok(())
@@ -850,19 +910,18 @@ impl Store for TursoStore {
850 910
851 async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()> {911 async fn record_sender_test(&self, workspace_id: &str, test: SenderTest) -> Result<()> {
852 let conn = self.conn.lock().await;912 let conn = self.conn.lock().await;
853- conn913+ conn.execute(
854- .execute(914+ "UPDATE workspace SET smtp_test_at = ?1, smtp_test_ms = ?2, \
855- "UPDATE workspace SET smtp_test_at = ?1, smtp_test_ms = ?2, \
856 smtp_test_error = ?3 WHERE id = ?4",915 smtp_test_error = ?3 WHERE id = ?4",
857- params![916+ params![
858- stamp(test.at)?,917+ stamp(test.at)?,
859- test.took_ms as i64,918+ test.took_ms as i64,
860- test.error,919+ test.error,
861- workspace_id920+ workspace_id
862- ],921+ ],
863- )922+ )
864- .await923+ .await
865- .map_err(backend)?;924+ .map_err(backend)?;
866 drop(conn);925 drop(conn);
867 self.announce([Topic::Settings]);926 self.announce([Topic::Settings]);
868 Ok(())927 Ok(())
@@ -891,13 +950,12 @@ impl Store for TursoStore {
891 950
892 async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()> {951 async fn set_public_url(&self, workspace_id: &str, public_url: Option<&str>) -> Result<()> {
893 let conn = self.conn.lock().await;952 let conn = self.conn.lock().await;
894- conn953+ conn.execute(
895- .execute(954+ "UPDATE workspace SET public_url = ?1 WHERE id = ?2",
896- "UPDATE workspace SET public_url = ?1 WHERE id = ?2",955+ params![public_url, workspace_id],
897- params![public_url, workspace_id],956+ )
898- )957+ .await
899- .await958+ .map_err(backend)?;
900- .map_err(backend)?;
901 drop(conn);959 drop(conn);
902 self.announce([Topic::Settings]);960 self.announce([Topic::Settings]);
903 Ok(())961 Ok(())
@@ -909,23 +967,24 @@ impl Store for TursoStore {
909 attachment_limit_bytes: u64,967 attachment_limit_bytes: u64,
910 photo_limit_bytes: u64,968 photo_limit_bytes: u64,
911 allowed_file_types: &[String],969 allowed_file_types: &[String],
970+ mail_batch_minutes: u32,
912 ) -> Result<()> {971 ) -> Result<()> {
913 let conn = self.conn.lock().await;972 let conn = self.conn.lock().await;
914 let types = serde_json::to_string(allowed_file_types)973 let types = serde_json::to_string(allowed_file_types)
915 .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))?;974 .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))?;
916- conn975+ conn.execute(
917- .execute(976+ "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \
918- "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \977+ allowed_file_types = ?3, mail_batch_minutes = ?5 WHERE id = ?4",
919- allowed_file_types = ?3 WHERE id = ?4",978+ params![
920- params![979+ attachment_limit_bytes as i64,
921- attachment_limit_bytes as i64,980+ photo_limit_bytes as i64,
922- photo_limit_bytes as i64,981+ types,
923- types,982+ workspace_id,
924- workspace_id983+ i64::from(mail_batch_minutes)
925- ],984+ ],
926- )985+ )
927- .await986+ .await
928- .map_err(backend)?;987+ .map_err(backend)?;
929 drop(conn);988 drop(conn);
930 self.announce([Topic::Settings]);989 self.announce([Topic::Settings]);
931 Ok(())990 Ok(())
@@ -1018,6 +1077,46 @@ impl Store for TursoStore {
1018 }1077 }
1019 }1078 }
1020 1079
1080+ async fn user_stats(&self, user_id: &str) -> Result<UserStats> {
1081+ // One row of four scalars: a profile reads its whole summary in a
1082+ // single trip. `deleted_at` is excluded everywhere — a task off the
1083+ // board is off the person's page as well.
1084+ let row = self
1085+ .one_row(
1086+ "SELECT \
1087+ (SELECT COUNT(*) FROM task_assignee a \
1088+ JOIN task t ON t.id = a.task_id \
1089+ JOIN board_column c ON c.id = t.column_id \
1090+ WHERE a.user_id = ?1 AND t.deleted_at IS NULL AND c.is_done = 0), \
1091+ (SELECT COUNT(*) FROM task_assignee a \
1092+ JOIN task t ON t.id = a.task_id \
1093+ JOIN board_column c ON c.id = t.column_id \
1094+ WHERE a.user_id = ?1 AND t.deleted_at IS NULL AND c.is_done = 1), \
1095+ (SELECT COUNT(*) FROM task WHERE created_by = ?1 AND deleted_at IS NULL), \
1096+ (SELECT COUNT(*) FROM comment m JOIN task t ON t.id = m.task_id \
1097+ WHERE m.author_id = ?1 AND t.deleted_at IS NULL)",
1098+ params![user_id],
1099+ )
1100+ .await?;
1101+ let Some(row) = row else {
1102+ return Ok(UserStats {
1103+ assigned_open: 0,
1104+ assigned_done: 0,
1105+ created: 0,
1106+ comments: 0,
1107+ });
1108+ };
1109+ let at = |i: usize| -> Result<u32> {
1110+ row.get::<i64>(i).map_err(backend).map(|n| n.max(0) as u32)
1111+ };
1112+ Ok(UserStats {
1113+ assigned_open: at(0)?,
1114+ assigned_done: at(1)?,
1115+ created: at(2)?,
1116+ comments: at(3)?,
1117+ })
1118+ }
1119+
1021 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()> {1120 async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()> {
1022 let conn = self.conn.lock().await;1121 let conn = self.conn.lock().await;
1023 let n = conn1122 let n = conn
@@ -1125,7 +1224,13 @@ impl Store for TursoStore {
1125 params![email, user_id],1224 params![email, user_id],
1126 )1225 )
1127 .await1226 .await
1128- .map_err(|e| if is_constraint_violation(&e) { StoreError::Conflict("account") } else { backend(e) })?;1227+ .map_err(|e| {
1228+ if is_constraint_violation(&e) {
1229+ StoreError::Conflict("account")
1230+ } else {
1231+ backend(e)
1232+ }
1233+ })?;
1129 if n == 0 {1234 if n == 0 {
1130 Err(StoreError::NotFound)1235 Err(StoreError::NotFound)
1131 } else {1236 } else {
@@ -1355,13 +1460,12 @@ impl Store for TursoStore {
1355 // sign-in — traffic in exchange for a screen that would look identical.1460 // sign-in — traffic in exchange for a screen that would look identical.
1356 async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> {1461 async fn record_auth_attempt(&self, bucket: &str, at: OffsetDateTime) -> Result<()> {
1357 let conn = self.conn.lock().await;1462 let conn = self.conn.lock().await;
1358- conn1463+ conn.execute(
1359- .execute(1464+ "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)",
1360- "INSERT INTO auth_attempt (id, bucket, attempted_at) VALUES (?1, ?2, ?3)",1465+ params![Ulid::new().to_string(), bucket, stamp(at)?],
1361- params![Ulid::new().to_string(), bucket, stamp(at)?],1466+ )
1362- )1467+ .await
1363- .await1468+ .map_err(backend)?;
1364- .map_err(backend)?;
1365 Ok(())1469 Ok(())
1366 }1470 }
1367 1471
@@ -1382,25 +1486,23 @@ impl Store for TursoStore {
1382 1486
1383 async fn clear_auth_attempts(&self, bucket: &str) -> Result<()> {1487 async fn clear_auth_attempts(&self, bucket: &str) -> Result<()> {
1384 let conn = self.conn.lock().await;1488 let conn = self.conn.lock().await;
1385- conn1489+ conn.execute(
1386- .execute(1490+ "DELETE FROM auth_attempt WHERE bucket = ?1",
1387- "DELETE FROM auth_attempt WHERE bucket = ?1",1491+ params![bucket],
1388- params![bucket],1492+ )
1389- )1493+ .await
1390- .await1494+ .map_err(backend)?;
1391- .map_err(backend)?;
1392 Ok(())1495 Ok(())
1393 }1496 }
1394 1497
1395 async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result<u64> {1498 async fn prune_auth_attempts(&self, before: OffsetDateTime) -> Result<u64> {
1396 let conn = self.conn.lock().await;1499 let conn = self.conn.lock().await;
1397- conn1500+ conn.execute(
1398- .execute(1501+ "DELETE FROM auth_attempt WHERE attempted_at < ?1",
1399- "DELETE FROM auth_attempt WHERE attempted_at < ?1",1502+ params![stamp(before)?],
1400- params![stamp(before)?],1503+ )
1401- )1504+ .await
1402- .await1505+ .map_err(backend)
1403- .map_err(backend)
1404 }1506 }
1405 1507
1406 // -- board -------------------------------------------------------------1508 // -- board -------------------------------------------------------------
@@ -1414,14 +1516,13 @@ impl Store for TursoStore {
1414 ) -> Result<Column> {1516 ) -> Result<Column> {
1415 let conn = self.conn.lock().await;1517 let conn = self.conn.lock().await;
1416 let id = Ulid::new().to_string();1518 let id = Ulid::new().to_string();
1417- conn1519+ conn.execute(
1418- .execute(1520+ "INSERT INTO board_column (id, board_id, name, position, is_done) \
1419- "INSERT INTO board_column (id, board_id, name, position, is_done) \
1420 VALUES (?1, ?2, ?3, ?4, ?5)",1521 VALUES (?1, ?2, ?3, ?4, ?5)",
1421- params![id.clone(), board_id, name, position, i64::from(is_done)],1522+ params![id.clone(), board_id, name, position, i64::from(is_done)],
1422- )1523+ )
1423- .await1524+ .await
1424- .map_err(backend)?;1525+ .map_err(backend)?;
1425 drop(conn);1526 drop(conn);
1426 self.announce([Topic::Board]);1527 self.announce([Topic::Board]);
1427 Ok(Column {1528 Ok(Column {
@@ -1500,6 +1601,20 @@ impl Store for TursoStore {
1500 drop(rows);1601 drop(rows);
1501 let position = last + 1.0;1602 let position = last + 1.0;
1502 1603
1604+ // A task always wears a tag, so one is chosen here when nobody
1605+ // named one: the board's default. The NOT NULL on `task.tag_id`
1606+ // makes choosing it the write's job, not an afterthought.
1607+ let mut rows = tx
1608+ .query(
1609+ "SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1",
1610+ params![new.board_id],
1611+ )
1612+ .await?;
1613+ let default_tag = match rows.next().await? {
1614+ Some(row) => row.get::<String>(0)?,
1615+ None => return Ok(Err(StoreError::NotFound)),
1616+ };
1617+ drop(rows);
1503 // The key's tail is the end of this task's own id (a ULID —1618 // The key's tail is the end of this task's own id (a ULID —
1504 // Crockford-uppercase already, and the last chars are its random1619 // Crockford-uppercase already, and the last chars are its random
1505 // bits) rather than a per-board counter: a counter leaves visible1620 // bits) rather than a per-board counter: a counter leaves visible
@@ -1512,8 +1627,8 @@ impl Store for TursoStore {
1512 match tx1627 match tx
1513 .execute(1628 .execute(
1514 "INSERT INTO task (id, board_id, parent_id, task_key, title, description, \1629 "INSERT INTO task (id, board_id, parent_id, task_key, title, description, \
1515- column_id, deadline, position, created_by, created_at, updated_at) \1630+ column_id, tag_id, deadline, position, created_by, created_at, updated_at) \
1516- VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)",1631+ VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?12, ?7, ?8, ?9, ?10, ?10)",
1517 params![1632 params![
1518 id.clone(),1633 id.clone(),
1519 new.board_id,1634 new.board_id,
@@ -1525,7 +1640,8 @@ impl Store for TursoStore {
1525 position,1640 position,
1526 new.created_by,1641 new.created_by,
1527 now.clone(),1642 now.clone(),
1528- new.parent_id1643+ new.parent_id,
1644+ default_tag.clone()
1529 ],1645 ],
1530 )1646 )
1531 .await1647 .await
@@ -1539,8 +1655,8 @@ impl Store for TursoStore {
1539 }1655 }
1540 };1656 };
1541 tx.execute(1657 tx.execute(
1542- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \1658+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
1543- VALUES (?1, ?2, ?3, ?4, '', ?5)",1659+ VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)",
1544 params![1660 params![
1545 activity_id.clone(),1661 activity_id.clone(),
1546 id.clone(),1662 id.clone(),
@@ -1593,6 +1709,7 @@ impl Store for TursoStore {
1593 position,1709 position,
1594 done_at: None,1710 done_at: None,
1595 parent_id: new.parent_id.map(str::to_string),1711 parent_id: new.parent_id.map(str::to_string),
1712+ tag: None,
1596 },1713 },
1597 activity_id,1714 activity_id,
1598 transition: Transition {1715 transition: Transition {
@@ -1717,6 +1834,7 @@ impl Store for TursoStore {
1717 position: row.get::<f64>(5).unwrap_or(0.0),1834 position: row.get::<f64>(5).unwrap_or(0.0),
1718 done_at: opt_stamp(&row, 6)?,1835 done_at: opt_stamp(&row, 6)?,
1719 parent_id: Some(parent_id.to_string()),1836 parent_id: Some(parent_id.to_string()),
1837+ tag: None,
1720 });1838 });
1721 }1839 }
1722 Ok(out)1840 Ok(out)
@@ -1924,8 +2042,8 @@ impl Store for TursoStore {
1924 )2042 )
1925 .await?;2043 .await?;
1926 tx.execute(2044 tx.execute(
1927- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \2045+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
1928- VALUES (?1, ?2, ?3, ?4, '', ?5)",2046+ VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)",
1929 params![2047 params![
1930 activity_id.clone(),2048 activity_id.clone(),
1931 task_id,2049 task_id,
@@ -1956,25 +2074,24 @@ impl Store for TursoStore {
1956 let conn = self.conn.lock().await;2074 let conn = self.conn.lock().await;
1957 let id = Ulid::new().to_string();2075 let id = Ulid::new().to_string();
1958 let size = new.bytes.len() as i64;2076 let size = new.bytes.len() as i64;
1959- conn2077+ conn.execute(
1960- .execute(2078+ "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \
1961- "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \
1962 size_bytes, bytes, uploaded_by, created_at) \2079 size_bytes, bytes, uploaded_by, created_at) \
1963 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",2080 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
1964- params![2081+ params![
1965- id.clone(),2082+ id.clone(),
1966- new.task_id,2083+ new.task_id,
1967- new.comment_id,2084+ new.comment_id,
1968- new.file_name,2085+ new.file_name,
1969- new.mime_type,2086+ new.mime_type,
1970- size,2087+ size,
1971- new.bytes,2088+ new.bytes,
1972- new.uploaded_by,2089+ new.uploaded_by,
1973- stamp(new.at)?2090+ stamp(new.at)?
1974- ],2091+ ],
1975- )2092+ )
1976- .await2093+ .await
1977- .map_err(backend)?;2094+ .map_err(backend)?;
1978 drop(conn);2095 drop(conn);
1979 self.announce([Topic::Task(new.task_id.to_string())]);2096 self.announce([Topic::Task(new.task_id.to_string())]);
1980 Ok(id)2097 Ok(id)
@@ -2109,8 +2226,8 @@ impl Store for TursoStore {
2109 for (kind, detail) in lines {2226 for (kind, detail) in lines {
2110 let id = Ulid::new().to_string();2227 let id = Ulid::new().to_string();
2111 tx.execute(2228 tx.execute(
2112- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \2229+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2113- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",2230+ VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6)",
2114 params![id.clone(), task_id, actor_id, kind, detail, stamp.clone()],2231 params![id.clone(), task_id, actor_id, kind, detail, stamp.clone()],
2115 )2232 )
2116 .await?;2233 .await?;
@@ -2289,8 +2406,8 @@ impl Store for TursoStore {
2289 .await?;2406 .await?;
2290 2407
2291 tx.execute(2408 tx.execute(
2292- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \2409+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2293- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",2410+ VALUES (?1, ?2, ?3, NULL, ?4, ?5, ?6)",
2294 params![2411 params![
2295 Ulid::new().to_string(),2412 Ulid::new().to_string(),
2296 task_id,2413 task_id,
@@ -2413,8 +2530,8 @@ impl Store for TursoStore {
2413 .await?;2530 .await?;
2414 let deleted_activity_id = Ulid::new().to_string();2531 let deleted_activity_id = Ulid::new().to_string();
2415 tx.execute(2532 tx.execute(
2416- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \2533+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2417- VALUES (?1, ?2, ?3, ?4, '', ?5)",2534+ VALUES (?1, ?2, ?3, NULL, ?4, '', ?5)",
2418 params![2535 params![
2419 deleted_activity_id.clone(),2536 deleted_activity_id.clone(),
2420 task_id,2537 task_id,
@@ -2446,8 +2563,8 @@ impl Store for TursoStore {
2446 continue;2563 continue;
2447 }2564 }
2448 tx.execute(2565 tx.execute(
2449- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \2566+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2450- VALUES (?1, ?2, NULL, ?3, ?4, ?5)",2567+ VALUES (?1, ?2, NULL, NULL, ?3, ?4, ?5)",
2451 params![2568 params![
2452 Ulid::new().to_string(),2569 Ulid::new().to_string(),
2453 blocked.clone(),2570 blocked.clone(),
@@ -2599,27 +2716,28 @@ impl Store for TursoStore {
2599 &self,2716 &self,
2600 task_id: &str,2717 task_id: &str,
2601 actor_id: Option<&str>,2718 actor_id: Option<&str>,
2719+ subject_id: Option<&str>,
2602 kind: &ActivityKind,2720 kind: &ActivityKind,
2603 detail: &str,2721 detail: &str,
2604 at: OffsetDateTime,2722 at: OffsetDateTime,
2605 ) -> Result<String> {2723 ) -> Result<String> {
2606 let conn = self.conn.lock().await;2724 let conn = self.conn.lock().await;
2607 let id = Ulid::new().to_string();2725 let id = Ulid::new().to_string();
2608- conn2726+ conn.execute(
2609- .execute(2727+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2610- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \2728+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
2611- VALUES (?1, ?2, ?3, ?4, ?5, ?6)",2729+ params![
2612- params![2730+ id.clone(),
2613- id.clone(),2731+ task_id,
2614- task_id,2732+ actor_id,
2615- actor_id,2733+ subject_id,
2616- kind.as_str(),2734+ kind.as_str(),
2617- detail,2735+ detail,
2618- stamp(at)?2736+ stamp(at)?
2619- ],2737+ ],
2620- )2738+ )
2621- .await2739+ .await
2622- .map_err(backend)?;2740+ .map_err(backend)?;
2623 drop(conn);2741 drop(conn);
2624 // Task-scoped: the task's own trail and the workspace feed both grew.2742 // Task-scoped: the task's own trail and the workspace feed both grew.
2625 self.announce([Topic::Activity, Topic::Task(task_id.to_string())]);2743 self.announce([Topic::Activity, Topic::Task(task_id.to_string())]);
@@ -2635,14 +2753,13 @@ impl Store for TursoStore {
2635 ) -> Result<String> {2753 ) -> Result<String> {
2636 let conn = self.conn.lock().await;2754 let conn = self.conn.lock().await;
2637 let id = Ulid::new().to_string();2755 let id = Ulid::new().to_string();
2638- conn2756+ conn.execute(
2639- .execute(2757+ "INSERT INTO activity (id, task_id, actor_id, subject_id, kind, detail, created_at) \
2640- "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \2758+ VALUES (?1, NULL, ?2, NULL, ?3, ?4, ?5)",
2641- VALUES (?1, NULL, ?2, ?3, ?4, ?5)",2759+ params![id.clone(), actor_id, kind.as_str(), detail, stamp(at)?],
2642- params![id.clone(), actor_id, kind.as_str(), detail, stamp(at)?],2760+ )
2643- )2761+ .await
2644- .await2762+ .map_err(backend)?;
2645- .map_err(backend)?;
2646 drop(conn);2763 drop(conn);
2647 // Workspace-wide, belonging to no task — the feed only.2764 // Workspace-wide, belonging to no task — the feed only.
2648 self.announce([Topic::Activity]);2765 self.announce([Topic::Activity]);
@@ -2696,10 +2813,7 @@ impl Store for TursoStore {
2696 let sql = format!(2813 let sql = format!(
2697 "SELECT {RULE_COLUMNS} FROM mail_rule WHERE board_id = ?1 ORDER BY created_at, rowid"2814 "SELECT {RULE_COLUMNS} FROM mail_rule WHERE board_id = ?1 ORDER BY created_at, rowid"
2698 );2815 );
2699- let mut rows = conn2816+ let mut rows = conn.query(&sql, params![board_id]).await.map_err(backend)?;
2700- .query(&sql, params![board_id])
2701- .await
2702- .map_err(backend)?;
2703 let mut out = Vec::new();2817 let mut out = Vec::new();
2704 while let Some(row) = rows.next().await.map_err(backend)? {2818 while let Some(row) = rows.next().await.map_err(backend)? {
2705 out.push(rule_from(&row)?);2819 out.push(rule_from(&row)?);
@@ -2799,7 +2913,7 @@ impl Store for TursoStore {
2799 match self2913 match self
2800 .one_row(2914 .one_row(
2801 "SELECT activity.id, activity.task_id, task.board_id, activity.kind, \2915 "SELECT activity.id, activity.task_id, task.board_id, activity.kind, \
2802- activity.actor_id, activity.detail, activity.created_at \2916+ activity.actor_id, activity.subject_id, activity.detail, activity.created_at \
2803 FROM activity JOIN task ON task.id = activity.task_id \2917 FROM activity JOIN task ON task.id = activity.task_id \
2804 WHERE activity.id = ?1",2918 WHERE activity.id = ?1",
2805 params![event_id],2919 params![event_id],
@@ -2812,8 +2926,9 @@ impl Store for TursoStore {
2812 board_id: text(&row, 2)?,2926 board_id: text(&row, 2)?,
2813 kind: ActivityKind::parse(&text(&row, 3)?),2927 kind: ActivityKind::parse(&text(&row, 3)?),
2814 actor_id: opt_text(&row, 4)?.unwrap_or_default(),2928 actor_id: opt_text(&row, 4)?.unwrap_or_default(),
2815- detail: text(&row, 5)?,2929+ subject_id: opt_text(&row, 5)?,
2816- at: parse_stamp(&text(&row, 6)?)?,2930+ detail: text(&row, 6)?,
2931+ at: parse_stamp(&text(&row, 7)?)?,
2817 }))),2932 }))),
2818 None => Ok(None),2933 None => Ok(None),
2819 }2934 }
@@ -3187,14 +3302,13 @@ impl Store for TursoStore {
3187 3302
3188 async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()> {3303 async fn requeue_send(&self, send_id: &str, at: OffsetDateTime) -> Result<()> {
3189 let conn = self.conn.lock().await;3304 let conn = self.conn.lock().await;
3190- conn3305+ conn.execute(
3191- .execute(3306+ "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \
3192- "UPDATE mail_send SET state = 'pending', next_attempt_at = ?1 \
3193 WHERE id = ?2 AND state IN ('failed', 'abandoned')",3307 WHERE id = ?2 AND state IN ('failed', 'abandoned')",
3194- params![stamp(at)?, send_id],3308+ params![stamp(at)?, send_id],
3195- )3309+ )
3196- .await3310+ .await
3197- .map_err(backend)?;3311+ .map_err(backend)?;
3198 drop(conn);3312 drop(conn);
3199 self.announce([Topic::Queue]);3313 self.announce([Topic::Queue]);
3200 Ok(())3314 Ok(())
@@ -3213,16 +3327,23 @@ impl Store for TursoStore {
3213 ) -> Result<()> {3327 ) -> Result<()> {
3214 let conn = self.conn.lock().await;3328 let conn = self.conn.lock().await;
3215 let id = Ulid::new().to_string();3329 let id = Ulid::new().to_string();
3216- conn3330+ conn.execute(
3217- .execute(3331+ "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \
3218- "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \
3219 created_at) \3332 created_at) \
3220 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \3333 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) \
3221 ON CONFLICT (rule_id, event_id, task_id) DO NOTHING",3334 ON CONFLICT (rule_id, event_id, task_id) DO NOTHING",
3222- params![id, rule_id, event_id, task_id, outcome.as_str(), detail, stamp(at)?],3335+ params![
3223- )3336+ id,
3224- .await3337+ rule_id,
3225- .map_err(backend)?;3338+ event_id,
3339+ task_id,
3340+ outcome.as_str(),
3341+ detail,
3342+ stamp(at)?
3343+ ],
3344+ )
3345+ .await
3346+ .map_err(backend)?;
3226 drop(conn);3347 drop(conn);
3227 // A decision is what the rules page's decisions tab renders.3348 // A decision is what the rules page's decisions tab renders.
3228 self.announce([Topic::Rules]);3349 self.announce([Topic::Rules]);
@@ -3449,7 +3570,9 @@ impl Store for TursoStore {
3449 FeedPage::Newest => {3570 FeedPage::Newest => {
3450 vals.extend(filter_vals);3571 vals.extend(filter_vals);
3451 vals.push(i64::from(limit).into());3572 vals.push(i64::from(limit).into());
3452- format!("{SELECT} WHERE 1=1{filter_sql} ORDER BY a.created_at {base}, a.id {base} LIMIT ?")3573+ format!(
3574+ "{SELECT} WHERE 1=1{filter_sql} ORDER BY a.created_at {base}, a.id {base} LIMIT ?"
3575+ )
3453 }3576 }
3454 FeedPage::Before(cursor) => {3577 FeedPage::Before(cursor) => {
3455 // Further along in `dir`'s reading order: older when3578 // Further along in `dir`'s reading order: older when
@@ -3596,6 +3719,51 @@ impl Store for TursoStore {
3596 recipients_from(&mut rows).await3719 recipients_from(&mut rows).await
3597 }3720 }
3598 3721
3722+ async fn hold_batch(
3723+ &self,
3724+ task_id: &str,
3725+ recipient: &str,
3726+ until: OffsetDateTime,
3727+ cap: Duration,
3728+ ) -> Result<()> {
3729+ let conn = self.conn.lock().await;
3730+ // Read the rows and their birth moments first: the ceiling is per
3731+ // row — the oldest mail in the batch is the one whose patience runs
3732+ // out — and expressing that in SQL over RFC 3339 text would be a
3733+ // date-format trick rather than a calculation.
3734+ let mut rows = conn
3735+ .query(
3736+ "SELECT id, claimed_at FROM mail_send \
3737+ WHERE task_id = ?1 AND recipient = ?2 AND kind = 'rule' \
3738+ AND state = 'pending' AND attempts = 0 \
3739+ AND next_attempt_at IS NOT NULL",
3740+ params![task_id, recipient],
3741+ )
3742+ .await
3743+ .map_err(backend)?;
3744+ let mut held = Vec::new();
3745+ while let Some(row) = rows.next().await.map_err(backend)? {
3746+ let id = text(&row, 0)?;
3747+ let born = parse_stamp(&text(&row, 1)?)?;
3748+ held.push((id, born));
3749+ }
3750+ drop(rows);
3751+ for (id, born) in held {
3752+ let ceiling = born + cap;
3753+ let when = if until > ceiling { ceiling } else { until };
3754+ conn.execute(
3755+ "UPDATE mail_send SET next_attempt_at = ?1 \
3756+ WHERE id = ?2 AND state = 'pending' AND attempts = 0",
3757+ params![stamp(when)?, id],
3758+ )
3759+ .await
3760+ .map_err(backend)?;
3761+ }
3762+ drop(conn);
3763+ self.announce([Topic::Queue]);
3764+ Ok(())
3765+ }
3766+
3599 async fn recipients_for_task_creator(&self, task_id: &str) -> Result<Vec<Recipient>> {3767 async fn recipients_for_task_creator(&self, task_id: &str) -> Result<Vec<Recipient>> {
3600 let conn = self.conn.lock().await;3768 let conn = self.conn.lock().await;
3601 let mut rows = conn3769 let mut rows = conn
@@ -3609,6 +3777,268 @@ impl Store for TursoStore {
3609 .map_err(backend)?;3777 .map_err(backend)?;
3610 recipients_from(&mut rows).await3778 recipients_from(&mut rows).await
3611 }3779 }
3780+
3781+ async fn recipient(&self, user_id: &str) -> Result<Option<Recipient>> {
3782+ let conn = self.conn.lock().await;
3783+ let mut rows = conn
3784+ .query(
3785+ "SELECT u.id, u.email, u.display_name FROM user u \
3786+ WHERE u.id = ?1 AND u.role <> ?2",
3787+ params![user_id, Role::Viewer.as_str()],
3788+ )
3789+ .await
3790+ .map_err(backend)?;
3791+ Ok(recipients_from(&mut rows).await?.into_iter().next())
3792+ }
3793+
3794+ // -- tags --------------------------------------------------------------
3795+
3796+ async fn tags(&self, board_id: &str) -> Result<Vec<Tag>> {
3797+ let conn = self.conn.lock().await;
3798+ let mut rows = conn
3799+ .query(
3800+ "SELECT id, board_id, name, position, is_default FROM tag WHERE board_id = ?1 \
3801+ ORDER BY position",
3802+ params![board_id],
3803+ )
3804+ .await
3805+ .map_err(backend)?;
3806+ let mut out = Vec::new();
3807+ while let Some(row) = rows.next().await.map_err(backend)? {
3808+ out.push(Tag {
3809+ id: text(&row, 0)?,
3810+ board_id: text(&row, 1)?,
3811+ name: text(&row, 2)?,
3812+ position: row.get::<i64>(3).map_err(backend)?,
3813+ is_default: row.get::<i64>(4).map_err(backend)? != 0,
3814+ });
3815+ }
3816+ Ok(out)
3817+ }
3818+
3819+ async fn create_tag(&self, board_id: &str, name: &str, at: OffsetDateTime) -> Result<Tag> {
3820+ let id = Ulid::new().to_string();
3821+ let now = stamp(at)?;
3822+ let mut conn = self.tx_conn().await?;
3823+ let tx = conn
3824+ .transaction_with_behavior(TransactionBehavior::Immediate)
3825+ .await
3826+ .map_err(backend)?;
3827+
3828+ // A new tag lands at the end of the board's order. The name is the
3829+ // unique index's to police — a pre-read would only widen the race.
3830+ let written = async {
3831+ let mut rows = tx
3832+ .query(
3833+ "SELECT COALESCE(MAX(position), 0) FROM tag WHERE board_id = ?1",
3834+ params![board_id],
3835+ )
3836+ .await?;
3837+ let position = match rows.next().await? {
3838+ Some(row) => row.get::<i64>(0).unwrap_or(0) + 1,
3839+ None => 1,
3840+ };
3841+ drop(rows);
3842+ tx.execute(
3843+ "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \
3844+ VALUES (?1, ?2, ?3, ?4, 0, ?5)",
3845+ params![id.clone(), board_id, name, position, now],
3846+ )
3847+ .await?;
3848+ Ok::<_, turso::Error>(position)
3849+ }
3850+ .await;
3851+
3852+ let position = match written {
3853+ Ok(position) => position,
3854+ Err(e) => {
3855+ let _ = tx.rollback().await;
3856+ return Err(if is_constraint_violation(&e) {
3857+ StoreError::Conflict("tag")
3858+ } else {
3859+ backend(e)
3860+ });
3861+ }
3862+ };
3863+ tx.commit().await.map_err(backend)?;
3864+
3865+ self.announce([Topic::Board, Topic::Tags]);
3866+ Ok(Tag {
3867+ id,
3868+ board_id: board_id.to_string(),
3869+ name: name.to_string(),
3870+ position,
3871+ is_default: false,
3872+ })
3873+ }
3874+
3875+ async fn rename_tag(&self, tag_id: &str, name: &str) -> Result<()> {
3876+ let conn = self.conn.lock().await;
3877+ let n = conn
3878+ .execute(
3879+ "UPDATE tag SET name = ?1 WHERE id = ?2",
3880+ params![name, tag_id],
3881+ )
3882+ .await
3883+ .map_err(|e| {
3884+ if is_constraint_violation(&e) {
3885+ StoreError::Conflict("tag")
3886+ } else {
3887+ backend(e)
3888+ }
3889+ })?;
3890+ if n == 0 {
3891+ return Err(StoreError::NotFound);
3892+ }
3893+ drop(conn);
3894+ self.announce([Topic::Board, Topic::Tags]);
3895+ Ok(())
3896+ }
3897+
3898+ async fn delete_tag(&self, tag_id: &str) -> Result<()> {
3899+ let mut conn = self.tx_conn().await?;
3900+ let tx = conn
3901+ .transaction_with_behavior(TransactionBehavior::Immediate)
3902+ .await
3903+ .map_err(backend)?;
3904+ // The default is the board's fallback, not a project anyone can
3905+ // retire: deleting it would leave its board's tasks nowhere to go.
3906+ // Any other tag's tasks move to that default, in the one write set:
3907+ // no task is ever seen pointing at a project that is not there.
3908+ let deleted = async {
3909+ let mut rows = tx
3910+ .query(
3911+ "SELECT board_id, is_default FROM tag WHERE id = ?1",
3912+ params![tag_id],
3913+ )
3914+ .await?;
3915+ let Some(row) = rows.next().await? else {
3916+ return Ok::<_, turso::Error>(Err(StoreError::NotFound));
3917+ };
3918+ let board_id: String = row.get(0)?;
3919+ let is_default: i64 = row.get(1)?;
3920+ drop(rows);
3921+ if is_default != 0 {
3922+ return Ok(Err(StoreError::Conflict("default_tag")));
3923+ }
3924+ tx.execute(
3925+ "UPDATE task SET tag_id = \
3926+ (SELECT id FROM tag WHERE board_id = ?1 AND is_default = 1) \
3927+ WHERE tag_id = ?2",
3928+ params![board_id, tag_id],
3929+ )
3930+ .await?;
3931+ tx.execute("DELETE FROM tag WHERE id = ?1", params![tag_id])
3932+ .await?;
3933+ Ok(Ok(()))
3934+ }
3935+ .await;
3936+ match deleted {
3937+ Ok(Ok(())) => {}
3938+ Ok(Err(refused)) => {
3939+ let _ = tx.rollback().await;
3940+ return Err(refused);
3941+ }
3942+ Err(e) => {
3943+ let _ = tx.rollback().await;
3944+ return Err(backend(e));
3945+ }
3946+ }
3947+ tx.commit().await.map_err(backend)?;
3948+ self.announce([Topic::Board, Topic::Tags]);
3949+ Ok(())
3950+ }
3951+
3952+ async fn move_tag(&self, tag_id: &str, up: bool) -> Result<()> {
3953+ let mut conn = self.tx_conn().await?;
3954+ let tx = conn
3955+ .transaction_with_behavior(TransactionBehavior::Immediate)
3956+ .await
3957+ .map_err(backend)?;
3958+ let written = async {
3959+ let mut rows = tx
3960+ .query(
3961+ "SELECT board_id, position FROM tag WHERE id = ?1",
3962+ params![tag_id],
3963+ )
3964+ .await?;
3965+ let Some(row) = rows.next().await? else {
3966+ return Ok::<_, turso::Error>(Err(StoreError::NotFound));
3967+ };
3968+ let board_id: String = row.get(0)?;
3969+ let position: i64 = row.get(1)?;
3970+ drop(rows);
3971+ let other = if up { position - 1 } else { position + 1 };
3972+ let mut rows = tx
3973+ .query(
3974+ "SELECT id FROM tag WHERE board_id = ?1 AND position = ?2",
3975+ params![board_id, other],
3976+ )
3977+ .await?;
3978+ let Some(neighbour) = rows.next().await? else {
3979+ // Already at that end of the order: nothing to swap, and that
3980+ // is not an error.
3981+ return Ok(Ok(()));
3982+ };
3983+ let neighbour_id: String = neighbour.get(0)?;
3984+ drop(rows);
3985+ tx.execute(
3986+ "UPDATE tag SET position = ?1 WHERE id = ?2",
3987+ params![position, neighbour_id],
3988+ )
3989+ .await?;
3990+ tx.execute(
3991+ "UPDATE tag SET position = ?1 WHERE id = ?2",
3992+ params![other, tag_id],
3993+ )
3994+ .await?;
3995+ Ok(Ok(()))
3996+ }
3997+ .await;
3998+ match written {
3999+ Ok(Ok(())) => {}
4000+ Ok(Err(refused)) => {
4001+ let _ = tx.rollback().await;
4002+ return Err(refused);
4003+ }
4004+ Err(e) => {
4005+ let _ = tx.rollback().await;
4006+ return Err(backend(e));
4007+ }
4008+ }
4009+ tx.commit().await.map_err(backend)?;
4010+ self.announce([Topic::Board, Topic::Tags]);
4011+ Ok(())
4012+ }
4013+
4014+ async fn set_task_tag(&self, task_id: &str, tag_id: &str) -> Result<()> {
4015+ // A tag not of this task's board is NotFound, not refused: the
4016+ // asker named a thing that is not one of this board's projects.
4017+ let known = self
4018+ .one_row(
4019+ "SELECT g.id FROM tag g JOIN task t ON t.board_id = g.board_id \
4020+ WHERE g.id = ?1 AND t.id = ?2 AND t.deleted_at IS NULL",
4021+ params![tag_id, task_id],
4022+ )
4023+ .await?;
4024+ if known.is_none() {
4025+ return Err(StoreError::NotFound);
4026+ }
4027+ let conn = self.conn.lock().await;
4028+ let n = conn
4029+ .execute(
4030+ "UPDATE task SET tag_id = ?1 WHERE id = ?2 AND deleted_at IS NULL",
4031+ params![tag_id, task_id],
4032+ )
4033+ .await
4034+ .map_err(backend)?;
4035+ if n == 0 {
4036+ return Err(StoreError::NotFound);
4037+ }
4038+ drop(conn);
4039+ self.announce([Topic::Board, Topic::Task(task_id.to_string()), Topic::Tags]);
4040+ Ok(())
4041+ }
3612 }4042 }
3613 4043
3614 #[async_trait]4044 #[async_trait]
@@ -3617,8 +4047,10 @@ impl DetailReads for TursoStore {
3617 let row = self4047 let row = self
3618 .one_row(4048 .one_row(
3619 "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \4049 "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \
3620- t.done_at, t.description, t.board_id, b.workspace_id, t.parent_id \4050+ t.done_at, t.description, t.board_id, b.workspace_id, t.parent_id, \
3621- FROM task t JOIN board b ON b.id = t.board_id \4051+ t.tag_id, g.name \
4052+ FROM task t LEFT JOIN tag g ON g.id = t.tag_id \
4053+ JOIN board b ON b.id = t.board_id \
3622 WHERE t.id = ?1 AND t.deleted_at IS NULL",4054 WHERE t.id = ?1 AND t.deleted_at IS NULL",
3623 params![task_id],4055 params![task_id],
3624 )4056 )
@@ -3634,6 +4066,13 @@ impl DetailReads for TursoStore {
3634 position: row.get::<f64>(5).map_err(backend)?,4066 position: row.get::<f64>(5).map_err(backend)?,
3635 done_at: opt_stamp(&row, 6)?,4067 done_at: opt_stamp(&row, 6)?,
3636 parent_id: opt_text(&row, 10)?,4068 parent_id: opt_text(&row, 10)?,
4069+ tag: match opt_text(&row, 11)? {
4070+ Some(id) => Some(TagChip {
4071+ id,
4072+ name: text(&row, 12)?,
4073+ }),
4074+ None => None,
4075+ },
3637 },4076 },
3638 description: text(&row, 7)?,4077 description: text(&row, 7)?,
3639 board_id: text(&row, 8)?,4078 board_id: text(&row, 8)?,
@@ -3922,8 +4361,10 @@ impl BoardReads for TursoStore {
3922 let conn = self.conn.lock().await;4361 let conn = self.conn.lock().await;
3923 let mut rows = conn4362 let mut rows = conn
3924 .query(4363 .query(
3925- "SELECT id, task_key, title, column_id, deadline, position, done_at, parent_id \4364+ "SELECT t.id, t.task_key, t.title, t.column_id, t.deadline, t.position, \
3926- FROM task WHERE board_id = ?1 AND deleted_at IS NULL",4365+ t.done_at, t.parent_id, t.tag_id, g.name \
4366+ FROM task t LEFT JOIN tag g ON g.id = t.tag_id \
4367+ WHERE t.board_id = ?1 AND t.deleted_at IS NULL",
3927 params![board_id],4368 params![board_id],
3928 )4369 )
3929 .await4370 .await
@@ -3939,6 +4380,13 @@ impl BoardReads for TursoStore {
3939 position: row.get::<f64>(5).map_err(backend)?,4380 position: row.get::<f64>(5).map_err(backend)?,
3940 done_at: opt_stamp(&row, 6)?,4381 done_at: opt_stamp(&row, 6)?,
3941 parent_id: opt_text(&row, 7)?,4382 parent_id: opt_text(&row, 7)?,
4383+ tag: match opt_text(&row, 8)? {
4384+ Some(id) => Some(TagChip {
4385+ id,
4386+ name: text(&row, 9)?,
4387+ }),
4388+ None => None,
4389+ },
3942 });4390 });
3943 }4391 }
3944 Ok(out)4392 Ok(out)
@@ -4209,47 +4657,3 @@ mod probe {
4209 let _ = std::fs::remove_dir_all(&dir);4657 let _ = std::fs::remove_dir_all(&dir);
4210 }4658 }
4211 }4659 }
4212-
4213-#[cfg(test)]
4214-mod migration {
4215- use super::*;
4216-
4217- /// A migration that dies halfway leaves nothing behind — not a table it
4218- /// created, and not a version row saying it ran. 0005 drops `mail_send`
4219- /// before it renames the rebuilt table into place, so a migration that can
4220- /// only half-apply is a migration that can lose the mail ledger.
4221- #[tokio::test]
4222- async fn a_migration_that_fails_partway_leaves_nothing_behind() {
4223- let dir = std::env::temp_dir().join(format!("izlek-migration-{}", Ulid::new()));
4224- std::fs::create_dir_all(&dir).unwrap();
4225- let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap())
4226- .await
4227- .unwrap();
4228- let before = store.schema_version().await.unwrap();
4229-
4230- let broken = "CREATE TABLE half_applied (id TEXT);\n\
4231- INSERT INTO no_such_table (id) VALUES ('x');";
4232- assert!(
4233- store.apply(before + 1, broken).await.is_err(),
4234- "the second statement cannot succeed"
4235- );
4236-
4237- assert_eq!(
4238- store.schema_version().await.unwrap(),
4239- before,
4240- "a failed migration is not recorded as applied"
4241- );
4242- assert!(
4243- store
4244- .one_row(
4245- "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'half_applied'",
4246- (),
4247- )
4248- .await
4249- .unwrap()
4250- .is_none(),
4251- "and the table its first statement created is rolled back with it"
4252- );
4253- let _ = std::fs::remove_dir_all(&dir);
4254- }
4255-}
crates/izlek-core/tests/fixtures/pre-collapse/0001_init.sqladded+391 -0
@@ -0,0 +1,391 @@
1+-- Izlek's schema, whole, in one file.
2+--
3+-- Plain versioned SQL applied at boot: Turso has no migration runner of its
4+-- own, and keeping the schema as SQL is what makes the store trait swappable.
5+-- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by
6+-- creation, and Crockford-uppercase already, which is what lets a task key
7+-- borrow its tail.
8+--
9+-- This file is the whole schema, not the first link of a chain. Nothing has
10+-- been released, so a change to a table is made here, in the table, and the
11+-- database it describes is recreated — twenty migrations were collapsed into
12+-- this file once for that reason, and a twenty-first would start the same rot
13+-- over. The reasoning the old migrations carried is kept, on the tables it
14+-- explains. The day Izlek runs somewhere with data worth keeping, the next
15+-- change becomes 0002 and this note goes away.
16+
17+CREATE TABLE workspace (
18+ id TEXT PRIMARY KEY,
19+ name TEXT NOT NULL,
20+ created_at TEXT NOT NULL,
21+ -- Limits. Each states its consequence in the UI, not here. They are
22+ -- workspace content — an admin edits them, and no restart should be
23+ -- needed to raise an attachment ceiling.
24+ attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400,
25+ photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152,
26+ -- JSON array of allowed extensions. An empty array means every type.
27+ allowed_file_types TEXT NOT NULL DEFAULT '[]',
28+ -- The single sender every mail in the workspace goes through, written by
29+ -- the admin in Settings rather than by whoever has a shell on the box: a
30+ -- three-person team has those be different people, and the second one is
31+ -- not always awake.
32+ --
33+ -- `smtp_password` holds ciphertext, never the typed string. The server
34+ -- has to present the password to the mail host on every send, so a
35+ -- one-way hash is impossible; instead `store::secret` seals it under a
36+ -- key kept in `izlek.key` beside this file, so a database copied for a
37+ -- backup does not carry a working credential with it. No field on
38+ -- `Workspace` exposes it — it is written by `Store::set_sender` and read
39+ -- by `Store::smtp_password`, which only the mailer calls.
40+ smtp_host TEXT,
41+ smtp_port INTEGER,
42+ smtp_username TEXT,
43+ smtp_password TEXT,
44+ smtp_from_name TEXT,
45+ smtp_from_address TEXT,
46+ -- The result of the last "send a test mail to myself", kept rather than
47+ -- shown once: an admin fills the sender in, presses the button, and comes
48+ -- back tomorrow wondering whether it ever worked. `smtp_test_error` is the
49+ -- mail server's own words, so the admin can act on them; the mailer builds
50+ -- its errors from what the server said, never from the credentials it sent.
51+ smtp_test_at TEXT,
52+ smtp_test_ms INTEGER,
53+ smtp_test_error TEXT,
54+ -- The address mail links point at, when the one the process was
55+ -- configured with is not the one people reach. A box behind a proxy
56+ -- answers on localhost and is known by a public name, and only an admin
57+ -- knows which — so it is workspace content, and `config/izlek.toml`'s
58+ -- `base_url` is what an empty one falls back to.
59+ public_url TEXT
60+);
61+
62+CREATE TABLE user (
63+ id TEXT PRIMARY KEY,
64+ workspace_id TEXT NOT NULL REFERENCES workspace(id),
65+ email TEXT NOT NULL,
66+ display_name TEXT NOT NULL,
67+ -- 'admin' | 'member' | 'viewer'
68+ role TEXT NOT NULL,
69+ -- NULL until the person picks a password on first sign-in. The admin
70+ -- creates the account with a name and an address and nothing else.
71+ password_hash TEXT,
72+ -- Whoever made this account, so the first-sign-in screen can greet the
73+ -- invited person by the inviter's name instead of reading their own name
74+ -- back to them. NULL for the first account, which nobody invited. A
75+ -- reference rather than a copied name, so a later rename is reflected.
76+ invited_by TEXT REFERENCES user(id),
77+ -- Display preferences. Stored data everywhere else stays UTC and
78+ -- language-neutral; these only change how a browser renders it for the
79+ -- one person signed in as this user, and nothing stored depends on them.
80+ timezone TEXT NOT NULL DEFAULT 'UTC',
81+ theme TEXT NOT NULL DEFAULT 'light',
82+ language TEXT NOT NULL DEFAULT 'en',
83+ ui TEXT NOT NULL DEFAULT 'instrument',
84+ -- The profile picture lives here as bytes, the way an attachment does:
85+ -- no filesystem path survives a backup or a move.
86+ photo BLOB,
87+ photo_mime TEXT,
88+ created_at TEXT NOT NULL,
89+ last_signed_in_at TEXT
90+);
91+CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email);
92+
93+-- One workspace, one owner. The singleton column is the whole point: the row
94+-- can exist at most once, so a second claim cannot race a first one.
95+CREATE TABLE workspace_owner (
96+ singleton INTEGER PRIMARY KEY,
97+ user_id TEXT NOT NULL REFERENCES user(id),
98+ claimed_at TEXT NOT NULL
99+);
100+
101+-- First sign-in / resend links. Only the hash is stored: the plaintext is
102+-- shown once when the admin creates or resends it.
103+CREATE TABLE signin_link (
104+ id TEXT PRIMARY KEY,
105+ user_id TEXT NOT NULL REFERENCES user(id),
106+ token_hash TEXT NOT NULL,
107+ created_at TEXT NOT NULL,
108+ expires_at TEXT NOT NULL,
109+ used_at TEXT
110+);
111+CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash);
112+
113+CREATE TABLE session (
114+ id TEXT PRIMARY KEY,
115+ user_id TEXT NOT NULL REFERENCES user(id),
116+ token_hash TEXT NOT NULL,
117+ created_at TEXT NOT NULL,
118+ expires_at TEXT NOT NULL,
119+ revoked_at TEXT
120+);
121+CREATE UNIQUE INDEX session_token ON session(token_hash);
122+CREATE INDEX session_by_user ON session(user_id);
123+
124+-- The rate-limit ledger: one row per attempt, pruned by age.
125+CREATE TABLE auth_attempt (
126+ id TEXT PRIMARY KEY,
127+ bucket TEXT NOT NULL,
128+ attempted_at TEXT NOT NULL
129+);
130+CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at);
131+
132+CREATE TABLE board (
133+ id TEXT PRIMARY KEY,
134+ workspace_id TEXT NOT NULL REFERENCES workspace(id),
135+ name TEXT NOT NULL,
136+ -- The key prefix this board's tasks carry (`DZ-14`).
137+ task_prefix TEXT NOT NULL DEFAULT 'DZ',
138+ created_at TEXT NOT NULL
139+);
140+
141+CREATE TABLE board_column (
142+ id TEXT PRIMARY KEY,
143+ board_id TEXT NOT NULL REFERENCES board(id),
144+ name TEXT NOT NULL,
145+ position INTEGER NOT NULL,
146+ -- The column a finished task lands in; drives the "done Aug 14" card state.
147+ is_done INTEGER NOT NULL DEFAULT 0
148+);
149+
150+-- A task, and a subtask, which is the same thing with a parent.
151+--
152+-- `parent_id` is the whole of the subtask feature in this schema: a subtask
153+-- has every column a task has, so it carries assignees, a deadline, comments,
154+-- files, activity and mail exactly like anything else, and promoting one to
155+-- a task of its own is a single UPDATE rather than a move between tables.
156+--
157+-- Two rules the column cannot state itself, enforced in the store instead:
158+-- a parent must have `parent_id IS NULL` (one level, never a tree), and a
159+-- child sits on its parent's board. SQLite cannot ask, in a CHECK, whether
160+-- the row a foreign key points at has a NULL parent.
161+--
162+-- The board shows only rows with no parent; a subtask reaches its own detail
163+-- page through its parent's.
164+CREATE TABLE task (
165+ id TEXT PRIMARY KEY,
166+ board_id TEXT NOT NULL REFERENCES board(id),
167+ parent_id TEXT REFERENCES task(id),
168+ -- Human key from the mockups, e.g. DZ-14. The tail is the end of the
169+ -- task's own ULID rather than a per-board counter: a counter leaves
170+ -- visible gaps once tasks are deleted.
171+ task_key TEXT NOT NULL,
172+ title TEXT NOT NULL,
173+ description TEXT NOT NULL DEFAULT '',
174+ column_id TEXT NOT NULL REFERENCES board_column(id),
175+ deadline TEXT,
176+ position REAL NOT NULL DEFAULT 0,
177+ created_by TEXT NOT NULL REFERENCES user(id),
178+ created_at TEXT NOT NULL,
179+ updated_at TEXT NOT NULL,
180+ done_at TEXT,
181+ deleted_at TEXT
182+);
183+CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key);
184+CREATE INDEX task_by_column ON task(column_id);
185+CREATE INDEX task_by_parent ON task(parent_id);
186+
187+CREATE TABLE task_assignee (
188+ task_id TEXT NOT NULL REFERENCES task(id),
189+ user_id TEXT NOT NULL REFERENCES user(id),
190+ PRIMARY KEY (task_id, user_id)
191+);
192+
193+CREATE TABLE task_watcher (
194+ task_id TEXT NOT NULL REFERENCES task(id),
195+ user_id TEXT NOT NULL REFERENCES user(id),
196+ PRIMARY KEY (task_id, user_id)
197+);
198+
199+-- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the
200+-- blocking task finishes, which is what the "you can start now" rule reads.
201+--
202+-- The CHECK is new: a task blocking itself was only ever stopped in
203+-- application code, and a row like that would make a card permanently and
204+-- unfixably blocked by its own existence.
205+CREATE TABLE task_dependency (
206+ blocked_task_id TEXT NOT NULL REFERENCES task(id),
207+ blocking_task_id TEXT NOT NULL REFERENCES task(id),
208+ created_at TEXT NOT NULL,
209+ cleared_at TEXT,
210+ PRIMARY KEY (blocked_task_id, blocking_task_id),
211+ CHECK (blocked_task_id <> blocking_task_id)
212+);
213+-- The primary key answers "what is this task waiting on"; the other
214+-- direction — "who is waiting on this one", which every finish and every
215+-- delete asks — has no prefix of it to use.
216+CREATE INDEX task_dependency_by_blocking ON task_dependency(blocking_task_id);
217+
218+CREATE TABLE comment (
219+ id TEXT PRIMARY KEY,
220+ task_id TEXT NOT NULL REFERENCES task(id),
221+ author_id TEXT NOT NULL REFERENCES user(id),
222+ body TEXT NOT NULL,
223+ created_at TEXT NOT NULL
224+);
225+CREATE INDEX comment_by_task ON comment(task_id);
226+
227+-- Attachments live in the database file, not on disk beside it.
228+--
229+-- Izlek is one process over one file, and a second place to keep state is a
230+-- second thing to back up, to lock, and to get out of step with the rows that
231+-- name it. And a path is exactly where an uploaded file name must never end
232+-- up: `../../etc` is a valid file name and a terrible path. Keeping the bytes
233+-- here means `file_name` is only ever a label printed on a chip, never
234+-- anything the server resolves.
235+CREATE TABLE attachment (
236+ id TEXT PRIMARY KEY,
237+ task_id TEXT NOT NULL REFERENCES task(id),
238+ comment_id TEXT REFERENCES comment(id),
239+ file_name TEXT NOT NULL,
240+ mime_type TEXT NOT NULL,
241+ size_bytes INTEGER NOT NULL,
242+ bytes BLOB NOT NULL,
243+ uploaded_by TEXT NOT NULL REFERENCES user(id),
244+ created_at TEXT NOT NULL
245+);
246+CREATE INDEX attachment_by_task ON attachment(task_id);
247+
248+-- Every move of a card from one column to another, written as a fact in the
249+-- same transaction as the move itself.
250+--
251+-- The mail rules trigger on the transition, not on the task's current column:
252+-- a card that goes Review -> Done -> Review has crossed into Done once, and
253+-- nothing recomputed from `task.column_id` afterwards can tell you that.
254+--
255+-- `from_column` deliberately carries no REFERENCES: a task created straight
256+-- into a column writes a transition with `from_column = ''`, meaning "created
257+-- into", so a rule watching that column fires for a new card and not only for
258+-- one dragged in later. No column's id is ever ''.
259+CREATE TABLE transition (
260+ id TEXT PRIMARY KEY,
261+ task_id TEXT NOT NULL REFERENCES task(id),
262+ from_column TEXT NOT NULL,
263+ to_column TEXT NOT NULL REFERENCES board_column(id),
264+ actor_id TEXT NOT NULL REFERENCES user(id),
265+ created_at TEXT NOT NULL
266+);
267+CREATE INDEX transition_by_task ON transition(task_id, created_at);
268+
269+-- A deletion that let other tasks go, recorded as a fact.
270+--
271+-- The unblocked rule has two causes and only one of them is a crossing: a
272+-- blocker can finish, or a blocker can be deleted. The crossing already has a
273+-- row in `transition`; the deletion had nowhere to be written, so a mail owed
274+-- because of one had no event to hang from and no way to be rebuilt on a
275+-- retry. This is that row.
276+--
277+-- `cause_key` and `cause_title` are copied rather than joined: the task they
278+-- name is deleted, and a mail sent an hour later still has to be able to say
279+-- which task it was.
280+CREATE TABLE freeing (
281+ id TEXT PRIMARY KEY,
282+ board_id TEXT NOT NULL REFERENCES board(id),
283+ cause_key TEXT NOT NULL,
284+ cause_title TEXT NOT NULL,
285+ actor_id TEXT NOT NULL REFERENCES user(id),
286+ created_at TEXT NOT NULL
287+);
288+CREATE INDEX freeing_by_board ON freeing(board_id, created_at);
289+
290+-- The activity strip in the task detail: who did what. `task_id` is nullable
291+-- because account and admin events — sign-ins, invites, role changes — have
292+-- no task to sit under, and still have to be loggable.
293+CREATE TABLE activity (
294+ id TEXT PRIMARY KEY,
295+ task_id TEXT REFERENCES task(id),
296+ actor_id TEXT REFERENCES user(id),
297+ kind TEXT NOT NULL,
298+ detail TEXT NOT NULL DEFAULT '',
299+ created_at TEXT NOT NULL
300+);
301+CREATE INDEX activity_by_task ON activity(task_id);
302+CREATE INDEX activity_recent ON activity(created_at);
303+
304+-- Mail rules are written only by the admin.
305+--
306+-- `trigger_kind` carries no CHECK on purpose: the set of triggers grows
307+-- without a schema change. `audience` does carry one, because those three
308+-- values are the only audiences the engine knows how to resolve.
309+CREATE TABLE mail_rule (
310+ id TEXT PRIMARY KEY,
311+ board_id TEXT NOT NULL REFERENCES board(id),
312+ trigger_kind TEXT NOT NULL,
313+ trigger_column TEXT REFERENCES board_column(id),
314+ subject TEXT NOT NULL,
315+ -- 'assignees' — the people the card points at; 'board' — everyone who can
316+ -- write on the board; 'creator' — whoever opened the card.
317+ audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board', 'creator')),
318+ enabled INTEGER NOT NULL DEFAULT 1,
319+ -- Fold the task's own facts into the body instead of the subject line
320+ -- being all the recipient reads. Off by default.
321+ include_task_details INTEGER NOT NULL DEFAULT 0,
322+ created_at TEXT NOT NULL,
323+ -- Only a status rule names a column, and a status rule that names none
324+ -- watches every column. The check is here so a rule that names a column
325+ -- it could not act on cannot be stored at all.
326+ CHECK (trigger_column IS NULL OR trigger_kind = 'status')
327+);
328+CREATE INDEX mail_rule_by_board ON mail_rule(board_id);
329+
330+-- One row per mail owed, from the moment it is claimed until it is sent or
331+-- abandoned.
332+--
333+-- Three shapes share the table. A 'rule' send is owed to somebody because a
334+-- rule matched an event on a task, and carries all three. An 'invite' or a
335+-- 'notice' has none of them — a person is invited before they have a task, a
336+-- transition, or a rule to owe them anything — and carries its own subject
337+-- and body instead of getting them from `mail_rule`. The two CHECKs make the
338+-- shapes exclusive, so a half-built row cannot be stored.
339+--
340+-- `event_id` names a transition or a freeing without a foreign key: two
341+-- tables can cause a send, so the column cannot point at either and hold both.
342+CREATE TABLE mail_send (
343+ id TEXT PRIMARY KEY,
344+ rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE,
345+ event_id TEXT,
346+ task_id TEXT REFERENCES task(id),
347+ recipient TEXT NOT NULL,
348+ state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')),
349+ attempts INTEGER NOT NULL DEFAULT 0,
350+ last_error TEXT,
351+ claimed_at TEXT NOT NULL,
352+ next_attempt_at TEXT,
353+ sent_at TEXT,
354+ kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')),
355+ subject TEXT,
356+ body TEXT,
357+ CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)),
358+ CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL))
359+);
360+CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient);
361+CREATE INDEX mail_send_owed ON mail_send(next_attempt_at);
362+CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at);
363+-- The task's own mail strip reads by task, which neither index above starts
364+-- with: both lead on `rule_id`, and an invite has none.
365+CREATE INDEX mail_send_by_task ON mail_send(task_id);
366+
367+-- What the mail engine decided, for every rule and every event, not just the
368+-- mails it sent.
369+--
370+-- `mail_send` only exists once a mail is owed and claimed; a card that moved
371+-- but matched no rule, a rule that was disabled, a task deleted before its
372+-- mail could go out — none of that left a trace. This is that trace, so "why
373+-- did nobody get mailed" has an answer that is not "look at the logs from
374+-- that day".
375+--
376+-- `task_id` carries no foreign key on purpose: a `task_gone` row exists
377+-- precisely because the task it names no longer does, and it has to keep
378+-- saying so afterwards.
379+CREATE TABLE mail_decision (
380+ id TEXT PRIMARY KEY,
381+ rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE,
382+ event_id TEXT NOT NULL,
383+ task_id TEXT NOT NULL,
384+ outcome TEXT NOT NULL CHECK (outcome IN
385+ ('owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone')),
386+ detail TEXT NOT NULL DEFAULT '',
387+ created_at TEXT NOT NULL
388+);
389+CREATE UNIQUE INDEX mail_decision_once ON mail_decision(rule_id, event_id, task_id);
390+CREATE INDEX mail_decision_recent ON mail_decision(created_at);
391+CREATE INDEX mail_decision_by_task ON mail_decision(task_id);
crates/izlek-core/migrations/0002_sender_check.sql → crates/izlek-core/tests/fixtures/pre-collapse/0002_sender_check.sqlrenamed+0 -0
crates/izlek-core/tests/store.rsmodified+1737 -194

Diff too large; view file

@@ -9,8 +9,8 @@ use std::path::PathBuf;
9 use izlek_core::Role;9 use izlek_core::Role;
10 use izlek_core::auth::{Token, hash_password};10 use izlek_core::auth::{Token, hash_password};
11 use izlek_core::store::{11 use izlek_core::store::{
12- Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind,12+ Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState,
13- SendState, Store, StoreError, Trigger, TursoStore, User,13+ Store, StoreError, Trigger, TursoStore, User,
14 };14 };
15 use time::{Duration, OffsetDateTime};15 use time::{Duration, OffsetDateTime};
16 use ulid::Ulid;16 use ulid::Ulid;
@@ -95,24 +95,19 @@ async fn member(store: &TursoStore, workspace_id: &str, email: &str, name: &str)
95 }95 }
96 96
97 #[tokio::test]97 #[tokio::test]
98-async fn migrations_apply_once_and_survive_reopen() {98+async fn the_schema_is_created_once_and_survives_reopen() {
99 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));99 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
100 std::fs::create_dir_all(&dir).unwrap();100 std::fs::create_dir_all(&dir).unwrap();
101 let path = dir.join("izlek.db").to_string_lossy().into_owned();101 let path = dir.join("izlek.db").to_string_lossy().into_owned();
102 102
103 let first = TursoStore::open(&path).await.unwrap();103 let first = TursoStore::open(&path).await.unwrap();
104- // Whatever the newest migration is — pinning the number here only means
105- // editing this line every time one is added, which tests the constant
106- // rather than the behaviour.
107- let applied = first.schema_version().await.unwrap();
108- assert!(applied >= 1, "no migration applied at all");
109 claim(&first).await;104 claim(&first).await;
110 drop(first);105 drop(first);
111 106
112- // Re-opening must not re-run a migration (0001's CREATE TABLE would fail)107+ // Re-opening a database that already has tables must not re-run the
113- // and must not lose what the first open wrote.108+ // schema (its CREATE TABLE would fail on the first one) and must not
109+ // lose what the first open wrote.
114 let second = TursoStore::open(&path).await.unwrap();110 let second = TursoStore::open(&path).await.unwrap();
115- assert_eq!(second.schema_version().await.unwrap(), applied);
116 assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek");111 assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek");
117 drop(second);112 drop(second);
118 let _ = std::fs::remove_dir_all(&dir);113 let _ = std::fs::remove_dir_all(&dir);
@@ -169,7 +164,15 @@ async fn subtasks_go_one_level_deep() {
169 let board = scratch.store.board(&workspace).await.unwrap().unwrap();164 let board = scratch.store.board(&workspace).await.unwrap().unwrap();
170 let column_id = column_named(&scratch.store, &workspace, "Backlog").await;165 let column_id = column_named(&scratch.store, &workspace, "Backlog").await;
171 166
172- let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await;167+ let parent = add_task(
168+ &scratch.store,
169+ &workspace,
170+ "Backlog",
171+ "Parent",
172+ None,
173+ &admin,
174+ )
175+ .await;
173 let child = scratch176 let child = scratch
174 .store177 .store
175 .create_task(NewTask {178 .create_task(NewTask {
@@ -238,10 +241,22 @@ async fn a_task_cannot_be_its_own_parent() {
238 async fn parenting_and_promoting_are_each_one_write() {241 async fn parenting_and_promoting_are_each_one_write() {
239 let scratch = Scratch::open().await;242 let scratch = Scratch::open().await;
240 let (workspace, admin) = claim(&scratch.store).await;243 let (workspace, admin) = claim(&scratch.store).await;
241- let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await;244+ let parent = add_task(
245+ &scratch.store,
246+ &workspace,
247+ "Backlog",
248+ "Parent",
249+ None,
250+ &admin,
251+ )
252+ .await;
242 let loose = add_task(&scratch.store, &workspace, "Review", "Loose", None, &admin).await;253 let loose = add_task(&scratch.store, &workspace, "Review", "Loose", None, &admin).await;
243 254
244- scratch.store.set_parent(&loose, Some(&parent)).await.unwrap();255+ scratch
256+ .store
257+ .set_parent(&loose, Some(&parent))
258+ .await
259+ .unwrap();
245 let children = scratch.store.subtasks(&parent).await.unwrap();260 let children = scratch.store.subtasks(&parent).await.unwrap();
246 assert_eq!(children.len(), 1);261 assert_eq!(children.len(), 1);
247 assert_eq!(children[0].id, loose);262 assert_eq!(children[0].id, loose);
@@ -277,7 +292,15 @@ async fn a_parent_and_one_subtask(
277 workspace: &str,292 workspace: &str,
278 admin: &str,293 admin: &str,
279 ) -> (String, String) {294 ) -> (String, String) {
280- let parent = add_task(store, workspace, "Backlog", "Ship the exporter", None, admin).await;295+ let parent = add_task(
296+ store,
297+ workspace,
298+ "Backlog",
299+ "Ship the exporter",
300+ None,
301+ admin,
302+ )
303+ .await;
281 let board = store.board(workspace).await.unwrap().unwrap();304 let board = store.board(workspace).await.unwrap().unwrap();
282 let column_id = column_named(store, workspace, "Backlog").await;305 let column_id = column_named(store, workspace, "Backlog").await;
283 let child = store306 let child = store
@@ -328,7 +351,15 @@ async fn a_parent_does_not_finish_before_its_subtasks_do() {
328 );351 );
329 352
330 // The subtask finishing is what lets the parent through.353 // The subtask finishing is what lets the parent through.
331- moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await;354+ moved_to(
355+ &scratch.store,
356+ &workspace,
357+ &child,
358+ "Backlog",
359+ "Done",
360+ &admin,
361+ )
362+ .await;
332 let recorded = scratch363 let recorded = scratch
333 .store364 .store
334 .move_task(&parent, &backlog, &done, &admin, OffsetDateTime::now_utc())365 .move_task(&parent, &backlog, &done, &admin, OffsetDateTime::now_utc())
@@ -379,7 +410,15 @@ async fn a_subtask_finishes_on_its_own_account() {
379 let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;410 let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;
380 411
381 // The rule is about a parent's parts, not about being somebody's part.412 // The rule is about a parent's parts, not about being somebody's part.
382- moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await;413+ moved_to(
414+ &scratch.store,
415+ &workspace,
416+ &child,
417+ "Backlog",
418+ "Done",
419+ &admin,
420+ )
421+ .await;
383 }422 }
384 423
385 #[tokio::test]424 #[tokio::test]
@@ -395,7 +434,15 @@ async fn a_deleted_subtask_stops_holding_its_parent() {
395 .delete_task(&child, &admin, OffsetDateTime::now_utc())434 .delete_task(&child, &admin, OffsetDateTime::now_utc())
396 .await435 .await
397 .unwrap();436 .unwrap();
398- moved_to(&scratch.store, &workspace, &parent, "Backlog", "Done", &admin).await;437+ moved_to(
438+ &scratch.store,
439+ &workspace,
440+ &parent,
441+ "Backlog",
442+ "Done",
443+ &admin,
444+ )
445+ .await;
399 }446 }
400 447
401 #[tokio::test]448 #[tokio::test]
@@ -405,7 +452,15 @@ async fn a_promoted_subtask_stops_holding_its_parent() {
405 let (parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;452 let (parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;
406 453
407 scratch.store.set_parent(&child, None).await.unwrap();454 scratch.store.set_parent(&child, None).await.unwrap();
408- moved_to(&scratch.store, &workspace, &parent, "Backlog", "Done", &admin).await;455+ moved_to(
456+ &scratch.store,
457+ &workspace,
458+ &parent,
459+ "Backlog",
460+ "Done",
461+ &admin,
462+ )
463+ .await;
409 }464 }
410 465
411 #[tokio::test]466 #[tokio::test]
@@ -424,7 +479,15 @@ async fn the_board_counts_subtasks_instead_of_carding_them() {
424 assert_eq!(cards[0].subtask_label().as_deref(), Some("0/1"));479 assert_eq!(cards[0].subtask_label().as_deref(), Some("0/1"));
425 assert!(cards[0].holds_on_subtasks());480 assert!(cards[0].holds_on_subtasks());
426 481
427- moved_to(&scratch.store, &workspace, &child, "Backlog", "Done", &admin).await;482+ moved_to(
483+ &scratch.store,
484+ &workspace,
485+ &child,
486+ "Backlog",
487+ "Done",
488+ &admin,
489+ )
490+ .await;
428 let board = load(&scratch.store, &workspace).await.unwrap().unwrap();491 let board = load(&scratch.store, &workspace).await.unwrap().unwrap();
429 let card = board492 let card = board
430 .columns493 .columns
@@ -453,7 +516,15 @@ async fn a_subtask_blocking_a_card_still_names_itself_on_it() {
453 let scratch = Scratch::open().await;516 let scratch = Scratch::open().await;
454 let (workspace, admin) = claim(&scratch.store).await;517 let (workspace, admin) = claim(&scratch.store).await;
455 let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;518 let (_parent, child) = a_parent_and_one_subtask(&scratch.store, &workspace, &admin).await;
456- let other = add_task(&scratch.store, &workspace, "Backlog", "Waiting", None, &admin).await;519+ let other = add_task(
520+ &scratch.store,
521+ &workspace,
522+ "Backlog",
523+ "Waiting",
524+ None,
525+ &admin,
526+ )
527+ .await;
457 scratch528 scratch
458 .store529 .store
459 .add_dependency(&other, &child, OffsetDateTime::now_utc())530 .add_dependency(&other, &child, OffsetDateTime::now_utc())
@@ -699,9 +770,9 @@ async fn many_concurrent_callers_never_see_concurrent_use_forbidden() {
699 }770 }
700 771
701 for task in tasks {772 for task in tasks {
702- task.await773+ task.await.unwrap().expect(
703- .unwrap()774+ "concurrent store access must never surface Misuse(\"concurrent use forbidden\")",
704- .expect("concurrent store access must never surface Misuse(\"concurrent use forbidden\")");775+ );
705 }776 }
706 777
707 drop(store);778 drop(store);
@@ -784,7 +855,11 @@ async fn a_save_with_no_password_typed_keeps_the_stored_one() {
784 from_name: "İzlek".into(),855 from_name: "İzlek".into(),
785 from_address: "izlek@izlek.sh".into(),856 from_address: "izlek@izlek.sh".into(),
786 };857 };
787- scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap();858+ scratch
859+ .store
860+ .set_sender(&ws_id, sender.clone())
861+ .await
862+ .unwrap();
788 863
789 sender.port = 465;864 sender.port = 465;
790 sender.password = None;865 sender.password = None;
@@ -794,7 +869,12 @@ async fn a_save_with_no_password_typed_keeps_the_stored_one() {
794 assert_eq!(ws.smtp_port, Some(465), "the edit did not land");869 assert_eq!(ws.smtp_port, Some(465), "the edit did not land");
795 assert!(ws.smtp_password_set, "the password was blanked by an edit");870 assert!(ws.smtp_password_set, "the password was blanked by an edit");
796 assert_eq!(871 assert_eq!(
797- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),872+ scratch
873+ .store
874+ .smtp_password(&ws_id)
875+ .await
876+ .unwrap()
877+ .as_deref(),
798 Some("keep-me")878 Some("keep-me")
799 );879 );
800 }880 }
@@ -812,12 +892,21 @@ async fn a_typed_password_replaces_the_stored_one() {
812 from_name: "İzlek".into(),892 from_name: "İzlek".into(),
813 from_address: "izlek@izlek.sh".into(),893 from_address: "izlek@izlek.sh".into(),
814 };894 };
815- scratch.store.set_sender(&ws_id, sender.clone()).await.unwrap();895+ scratch
896+ .store
897+ .set_sender(&ws_id, sender.clone())
898+ .await
899+ .unwrap();
816 sender.password = Some("the-new-one".into());900 sender.password = Some("the-new-one".into());
817 scratch.store.set_sender(&ws_id, sender).await.unwrap();901 scratch.store.set_sender(&ws_id, sender).await.unwrap();
818 902
819 assert_eq!(903 assert_eq!(
820- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),904+ scratch
905+ .store
906+ .smtp_password(&ws_id)
907+ .await
908+ .unwrap()
909+ .as_deref(),
821 Some("the-new-one")910 Some("the-new-one")
822 );911 );
823 }912 }
@@ -846,7 +935,10 @@ async fn the_stored_password_is_not_the_plaintext_on_disk() {
846 935
847 let conn = raw_conn(&scratch).await;936 let conn = raw_conn(&scratch).await;
848 let mut rows = conn937 let mut rows = conn
849- .query("SELECT smtp_password FROM workspace WHERE id = ?1", turso::params![ws_id.clone()])938+ .query(
939+ "SELECT smtp_password FROM workspace WHERE id = ?1",
940+ turso::params![ws_id.clone()],
941+ )
850 .await942 .await
851 .unwrap();943 .unwrap();
852 let row = rows.next().await.unwrap().unwrap();944 let row = rows.next().await.unwrap().unwrap();
@@ -855,11 +947,19 @@ async fn the_stored_password_is_not_the_plaintext_on_disk() {
855 !column.contains("a-very-secret-string"),947 !column.contains("a-very-secret-string"),
856 "the plaintext is sitting in the column: {column}"948 "the plaintext is sitting in the column: {column}"
857 );949 );
858- assert!(column.starts_with("v1:"), "expected the sealed envelope, got: {column}");950+ assert!(
951+ column.starts_with("v1:"),
952+ "expected the sealed envelope, got: {column}"
953+ );
859 954
860 // And the read path still gets the real password back.955 // And the read path still gets the real password back.
861 assert_eq!(956 assert_eq!(
862- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),957+ scratch
958+ .store
959+ .smtp_password(&ws_id)
960+ .await
961+ .unwrap()
962+ .as_deref(),
863 Some("a-very-secret-string")963 Some("a-very-secret-string")
864 );964 );
865 }965 }
@@ -921,7 +1021,12 @@ async fn a_password_that_will_not_decrypt_reads_back_as_none() {
921 .await1021 .await
922 .unwrap();1022 .unwrap();
923 assert_eq!(1023 assert_eq!(
924- scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(),1024+ scratch
1025+ .store
1026+ .smtp_password(&ws_id)
1027+ .await
1028+ .unwrap()
1029+ .as_deref(),
925 Some("a-fresh-password"),1030 Some("a-fresh-password"),
926 "retyping the password heals a store that could not decrypt it"1031 "retyping the password heals a store that could not decrypt it"
927 );1032 );
@@ -942,7 +1047,12 @@ async fn the_database_and_key_file_are_owner_only() {
942 .permissions()1047 .permissions()
943 .mode()1048 .mode()
944 & 0o777;1049 & 0o777;
945- assert_eq!(mode, 0o600, "{} is not owner-only: {mode:o}", path.display());1050+ assert_eq!(
1051+ mode,
1052+ 0o600,
1053+ "{} is not owner-only: {mode:o}",
1054+ path.display()
1055+ );
946 }1056 }
947 }1057 }
948 1058
@@ -952,7 +1062,7 @@ async fn limits_round_trip_including_the_file_type_list() {
952 let types = vec!["png".to_string(), "pdf".to_string()];1062 let types = vec!["png".to_string(), "pdf".to_string()];
953 scratch1063 scratch
954 .store1064 .store
955- .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types)1065+ .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types, 5)
956 .await1066 .await
957 .unwrap();1067 .unwrap();
958 let ws = scratch.store.workspace().await.unwrap().unwrap();1068 let ws = scratch.store.workspace().await.unwrap().unwrap();
@@ -1119,11 +1229,26 @@ async fn email_change_persists_and_refuses_a_taken_address() {
1119 .await1229 .await
1120 .unwrap();1230 .unwrap();
1121 // Case-folded the same way sign-in matches an address.1231 // Case-folded the same way sign-in matches an address.
1122- assert!(store.user_by_email(&ws_id, "grace.new@izlek.sh").await.unwrap().is_some());1232+ assert!(
1123- assert!(store.user_by_email(&ws_id, "grace@izlek.sh").await.unwrap().is_none());1233+ store
1234+ .user_by_email(&ws_id, "grace.new@izlek.sh")
1235+ .await
1236+ .unwrap()
1237+ .is_some()
1238+ );
1239+ assert!(
1240+ store
1241+ .user_by_email(&ws_id, "grace@izlek.sh")
1242+ .await
1243+ .unwrap()
1244+ .is_none()
1245+ );
1124 1246
1125 // Taken by the admin already claimed above.1247 // Taken by the admin already claimed above.
1126- let err = store.set_email(&user_id, &ws_id, "ada@izlek.sh").await.unwrap_err();1248+ let err = store
1249+ .set_email(&user_id, &ws_id, "ada@izlek.sh")
1250+ .await
1251+ .unwrap_err();
1127 assert!(matches!(err, StoreError::Conflict("account")));1252 assert!(matches!(err, StoreError::Conflict("account")));
1128 user_id1253 user_id
1129 };1254 };
@@ -1650,7 +1775,11 @@ async fn adding_a_member_queues_the_mail_that_carries_the_link() {
1650 .await1775 .await
1651 .unwrap();1776 .unwrap();
1652 1777
1653- let queue = accounts.store().mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();1778+ let queue = accounts
1779+ .store()
1780+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
1781+ .await
1782+ .unwrap();
1654 let queued = queue1783 let queued = queue
1655 .iter()1784 .iter()
1656 .find(|s| s.recipient == "grace@izlek.sh")1785 .find(|s| s.recipient == "grace@izlek.sh")
@@ -2356,7 +2485,10 @@ async fn count_and_filtered_keyset_walk_cover_exactly_the_filtered_set() {
2356 .unwrap();2485 .unwrap();
2357 }2486 }
2358 2487
2359- let filter = ActivityFilter { actor: Some(admin.clone()), ..Default::default() };2488+ let filter = ActivityFilter {
2489+ actor: Some(admin.clone()),
2490+ ..Default::default()
2491+ };
2360 let total = store.count_activity(&filter).await.unwrap();2492 let total = store.count_activity(&filter).await.unwrap();
2361 assert_eq!(total, 10);2493 assert_eq!(total, 10);
2362 2494
@@ -2371,17 +2503,27 @@ async fn count_and_filtered_keyset_walk_cover_exactly_the_filtered_set() {
2371 break;2503 break;
2372 }2504 }
2373 let last = rows.last().unwrap();2505 let last = rows.last().unwrap();
2374- page = FeedPage::Before(FeedCursor { at: last.at, id: last.id.clone() });2506+ page = FeedPage::Before(FeedCursor {
2507+ at: last.at,
2508+ id: last.id.clone(),
2509+ });
2375 walked.extend(rows);2510 walked.extend(rows);
2376 }2511 }
2377 assert_eq!(walked.len(), 10);2512 assert_eq!(walked.len(), 10);
2378- assert!(walked.iter().all(|r| r.actor_name.as_deref() == Some("Ada")));2513+ assert!(
2514+ walked
2515+ .iter()
2516+ .all(|r| r.actor_name.as_deref() == Some("Ada"))
2517+ );
2379 2518
2380 let preceding = store2519 let preceding = store
2381 .count_activity_preceding(2520 .count_activity_preceding(
2382 &filter,2521 &filter,
2383 Dir::Newest,2522 Dir::Newest,
2384- Some(&FeedCursor { at: walked[3].at, id: walked[3].id.clone() }),2523+ Some(&FeedCursor {
2524+ at: walked[3].at,
2525+ id: walked[3].id.clone(),
2526+ }),
2385 )2527 )
2386 .await2528 .await
2387 .unwrap();2529 .unwrap();
@@ -2413,11 +2555,16 @@ async fn a_claimed_workspace_starts_with_four_named_columns() {
2413 /// comes off the task's own id now, not a per-board counter, so exact keys2555 /// comes off the task's own id now, not a per-board counter, so exact keys
2414 /// are no longer predictable — only the shape and per-board uniqueness are.2556 /// are no longer predictable — only the shape and per-board uniqueness are.
2415 fn is_task_key_shaped(key: &str, prefix: &str) -> bool {2557 fn is_task_key_shaped(key: &str, prefix: &str) -> bool {
2416- let Some(tail) = key.strip_prefix(prefix).and_then(|rest| rest.strip_prefix('-')) else {2558+ let Some(tail) = key
2559+ .strip_prefix(prefix)
2560+ .and_then(|rest| rest.strip_prefix('-'))
2561+ else {
2417 return false;2562 return false;
2418 };2563 };
2419 (5..=7).contains(&tail.len())2564 (5..=7).contains(&tail.len())
2420- && tail.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())2565+ && tail
2566+ .chars()
2567+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
2421 }2568 }
2422 2569
2423 #[tokio::test]2570 #[tokio::test]
@@ -2432,7 +2579,10 @@ async fn tasks_get_key_tails_off_their_own_id_not_a_board_counter() {
2432 let keys: Vec<&str> = board.cards().map(|card| card.task_key.as_str()).collect();2579 let keys: Vec<&str> = board.cards().map(|card| card.task_key.as_str()).collect();
2433 assert_eq!(keys.len(), 2);2580 assert_eq!(keys.len(), 2);
2434 for key in &keys {2581 for key in &keys {
2435- assert!(is_task_key_shaped(key, "DZ"), "key {key} is not shaped like DZ-<5..7 chars>");2582+ assert!(
2583+ is_task_key_shaped(key, "DZ"),
2584+ "key {key} is not shaped like DZ-<5..7 chars>"
2585+ );
2436 }2586 }
2437 assert_ne!(keys[0], keys[1], "two tasks never share a key");2587 assert_ne!(keys[0], keys[1], "two tasks never share a key");
2438 }2588 }
@@ -2487,7 +2637,12 @@ async fn a_card_carries_its_assignees_comments_and_dependency_keys() {
2487 }2637 }
2488 2638
2489 let board = board_of(store, &workspace).await;2639 let board = board_of(store, &workspace).await;
2490- let blocked_key = board.cards().find(|card| card.id == blocked).unwrap().task_key.clone();2640+ let blocked_key = board
2641+ .cards()
2642+ .find(|card| card.id == blocked)
2643+ .unwrap()
2644+ .task_key
2645+ .clone();
2491 let card = board.cards().find(|card| card.id == blocking).unwrap();2646 let card = board.cards().find(|card| card.id == blocking).unwrap();
2492 assert_eq!(card.assignees.len(), 2);2647 assert_eq!(card.assignees.len(), 2);
2493 assert_eq!(card.comment_count, 3);2648 assert_eq!(card.comment_count, 3);
@@ -2617,10 +2772,28 @@ async fn a_board_costs_six_queries_whatever_its_size() {
2617 .unwrap();2772 .unwrap();
2618 }2773 }
2619 }2774 }
2775+ // A tag rides the task query as a join: the sweep stays at six.
2776+ let board_meta = store.board(&workspace).await.unwrap().unwrap();
2777+ let tag = store
2778+ .create_tag(&board_meta.id, "shipping", OffsetDateTime::now_utc())
2779+ .await
2780+ .unwrap();
2781+ let tagged = previous.expect("the loop created tasks");
2782+ store.set_task_tag(&tagged, &tag.id).await.unwrap();
2620 2783
2621 let big = CountingReads::new(store);2784 let big = CountingReads::new(store);
2622 let board = load(&big, &workspace).await.unwrap().unwrap();2785 let board = load(&big, &workspace).await.unwrap().unwrap();
2623 assert_eq!(board.task_count(), 40);2786 assert_eq!(board.task_count(), 40);
2787+ let tagged_card = board
2788+ .columns
2789+ .iter()
2790+ .flat_map(|column| column.cards.iter())
2791+ .find(|card| card.id == tagged)
2792+ .unwrap();
2793+ assert_eq!(
2794+ tagged_card.tag.as_ref().map(|t| t.name.as_str()),
2795+ Some("shipping")
2796+ );
2624 assert_eq!(2797 assert_eq!(
2625 big.count(),2798 big.count(),
2626 6,2799 6,
@@ -2628,99 +2801,339 @@ async fn a_board_costs_six_queries_whatever_its_size() {
2628 );2801 );
2629 }2802 }
2630 2803
2631-#[test]2804+// -- tags -------------------------------------------------------------------
2632-fn initials_fall_back_to_two_letters() {
2633- let person = |name: &str| Person {
2634- id: "u".into(),
2635- display_name: name.into(),
2636- has_photo: false,
2637- };
2638- assert_eq!(person("Mel Duarte").initials(), "MD");
2639- assert_eq!(person("Ada").initials(), "A");
2640- assert_eq!(person(" ").initials(), "?");
2641-}
2642-
2643-// -- task detail ------------------------------------------------------------
2644 2805
2645-use izlek_core::detail::{2806+#[tokio::test]
2646- ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts,2807+async fn tags_are_created_in_order_renamed_moved_and_deleted() {
2647- load as load_detail,2808+ let (scratch, workspace, _admin) = workspace_with_admin().await;
2648-};2809+ let store = &scratch.store;
2810+ let board = store.board(&workspace).await.unwrap().unwrap();
2811+ let at = OffsetDateTime::now_utc();
2649 2812
2650-/// The same trick as [`CountingReads`], for the detail screen: the round trips2813+ let alpha = store.create_tag(&board.id, "alpha", at).await.unwrap();
2651-/// one task costs must not follow how much it carries.2814+ let beta = store.create_tag(&board.id, "beta", at).await.unwrap();
2652-struct CountingDetail<'a> {2815+ let gamma = store.create_tag(&board.id, "gamma", at).await.unwrap();
2653- inner: &'a TursoStore,2816+ assert_eq!((alpha.position, beta.position, gamma.position), (1, 2, 3));
2654- calls: AtomicUsize,
2655-}
2656 2817
2657-impl<'a> CountingDetail<'a> {2818+ store.rename_tag(&beta.id, "beta2").await.unwrap();
2658- fn new(inner: &'a TursoStore) -> Self {2819+ assert_eq!(
2659- Self {2820+ tag_order(&store.tags(&board.id).await.unwrap()),
2660- inner,2821+ ["General", "alpha", "beta2", "gamma"]
2661- calls: AtomicUsize::new(0),2822+ );
2662- }
2663- }
2664 2823
2665- fn count(&self) -> usize {2824+ // Swapping moves one place, never to the far end.
2666- self.calls.load(Ordering::Relaxed)2825+ store.move_tag(&beta.id, true).await.unwrap();
2667- }2826+ assert_eq!(
2827+ tag_order(&store.tags(&board.id).await.unwrap()),
2828+ ["General", "beta2", "alpha", "gamma"]
2829+ );
2830+ // A tag already at that end stays put: nothing to swap is not an error.
2831+ store.move_tag(&gamma.id, false).await.unwrap();
2832+ assert_eq!(
2833+ tag_order(&store.tags(&board.id).await.unwrap()),
2834+ ["General", "beta2", "alpha", "gamma"]
2835+ );
2836+ store.move_tag(&beta.id, true).await.unwrap();
2837+ assert_eq!(
2838+ tag_order(&store.tags(&board.id).await.unwrap()),
2839+ ["beta2", "General", "alpha", "gamma"]
2840+ );
2841+ store.move_tag(&alpha.id, true).await.unwrap();
2842+ assert_eq!(
2843+ tag_order(&store.tags(&board.id).await.unwrap()),
2844+ ["beta2", "alpha", "General", "gamma"]
2845+ );
2668 2846
2669- fn tick(&self) {2847+ store.delete_tag(&beta.id).await.unwrap();
2670- self.calls.fetch_add(1, Ordering::Relaxed);2848+ assert_eq!(
2671- }2849+ tag_order(&store.tags(&board.id).await.unwrap()),
2850+ ["alpha", "General", "gamma"]
2851+ );
2852+ assert!(matches!(
2853+ store.delete_tag(&beta.id).await,
2854+ Err(StoreError::NotFound)
2855+ ));
2672 }2856 }
2673 2857
2674-#[async_trait::async_trait]2858+#[tokio::test]
2675-impl DetailReads for CountingDetail<'_> {2859+async fn a_boards_tags_have_unique_names() {
2676- async fn task(&self, task_id: &str) -> Result<Option<TaskFacts>, StoreError> {2860+ let (scratch, workspace, _admin) = workspace_with_admin().await;
2677- self.tick();2861+ let store = &scratch.store;
2678- self.inner.task(task_id).await2862+ let board = store.board(&workspace).await.unwrap().unwrap();
2679- }2863+ let at = OffsetDateTime::now_utc();
2680-
2681- async fn columns_for_board(
2682- &self,
2683- board_id: &str,
2684- ) -> Result<Vec<izlek_core::Column>, StoreError> {
2685- self.tick();
2686- self.inner.columns_for_board(board_id).await
2687- }
2688 2864
2689- async fn assignees_for_task(&self, task_id: &str) -> Result<Vec<Person>, StoreError> {2865+ store.create_tag(&board.id, "ops", at).await.unwrap();
2690- self.tick();2866+ assert!(
2691- self.inner.assignees_for_task(task_id).await2867+ matches!(
2692- }2868+ store.create_tag(&board.id, "ops", at).await,
2869+ Err(StoreError::Conflict("tag"))
2870+ ),
2871+ "two tags with one name are one project spelled twice"
2872+ );
2693 2873
2694- async fn assignable_people(&self, workspace_id: &str) -> Result<Vec<Person>, StoreError> {2874+ // The same name on another board is a different project.
2695- self.tick();2875+ let other = Scratch::open().await;
2696- self.inner.assignable_people(workspace_id).await2876+ let (other_ws, _other_admin) = claim(&other.store).await;
2697- }2877+ let other_board = other.store.board(&other_ws).await.unwrap().unwrap();
2878+ other
2879+ .store
2880+ .create_tag(&other_board.id, "ops", at)
2881+ .await
2882+ .unwrap();
2698 2883
2699- async fn dependencies_for_task(2884+ // A rename into a clash refuses the same way.
2700- &self,2885+ let ship = store.create_tag(&board.id, "ship", at).await.unwrap();
2701- task_id: &str,2886+ assert!(matches!(
2702- ) -> Result<Vec<(bool, DependencyEdge)>, StoreError> {2887+ store.rename_tag(&ship.id, "ops").await,
2703- self.tick();2888+ Err(StoreError::Conflict("tag"))
2704- self.inner.dependencies_for_task(task_id).await2889+ ));
2705- }2890+}
2706 2891
2707- async fn comments_for_task(&self, task_id: &str) -> Result<Vec<Comment>, StoreError> {2892+fn tag_order(tags: &[izlek_core::store::Tag]) -> Vec<&str> {
2708- self.tick();2893+ tags.iter().map(|t| t.name.as_str()).collect()
2709- self.inner.comments_for_task(task_id).await2894+}
2710- }
2711 2895
2712- async fn files_for_task(2896+fn card_of<'a>(
2713- &self,2897+ view: &'a izlek_core::board::BoardView,
2714- task_id: &str,2898+ task: &str,
2715- ) -> Result<Vec<izlek_core::detail::FileLine>, StoreError> {2899+) -> &'a izlek_core::board::TaskCard {
2716- self.tick();2900+ view.columns
2717- self.inner.files_for_task(task_id).await2901+ .iter()
2718- }2902+ .flat_map(|column| column.cards.iter())
2903+ .find(|card| card.id == task)
2904+ .unwrap()
2905+}
2719 2906
2720- async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>, StoreError> {2907+#[tokio::test]
2721- self.tick();2908+async fn deleting_a_tag_moves_its_tasks_to_the_default_and_a_foreign_tag_is_not_found() {
2722- self.inner.activity_for_task(task_id).await2909+ let (scratch, workspace, admin) = workspace_with_admin().await;
2723- }2910+ let store = &scratch.store;
2911+ let board = store.board(&workspace).await.unwrap().unwrap();
2912+ let tag = store
2913+ .create_tag(&board.id, "ops", OffsetDateTime::now_utc())
2914+ .await
2915+ .unwrap();
2916+ let task = add_task(store, &workspace, "Backlog", "tagged", None, &admin).await;
2917+
2918+ // The task came wearing the default; moving it to `ops` shows in the
2919+ // card and the detail alike.
2920+ let view = board_of(store, &workspace).await;
2921+ assert_eq!(
2922+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2923+ Some("General")
2924+ );
2925+ store.set_task_tag(&task, &tag.id).await.unwrap();
2926+ let view = board_of(store, &workspace).await;
2927+ assert_eq!(
2928+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2929+ Some("ops")
2930+ );
2931+ let detail = load_detail(store, &workspace, &task)
2932+ .await
2933+ .unwrap()
2934+ .unwrap();
2935+ assert_eq!(
2936+ detail.tag.as_ref().map(|t| t.id.as_str()),
2937+ Some(tag.id.as_str())
2938+ );
2939+
2940+ // A tag from another board — or one that never existed — is not found,
2941+ // not refused: it is not one of this board's projects at all.
2942+ let other = Scratch::open().await;
2943+ let (other_ws, _other_admin) = claim(&other.store).await;
2944+ let other_board = other.store.board(&other_ws).await.unwrap().unwrap();
2945+ let foreign = other
2946+ .store
2947+ .create_tag(&other_board.id, "foreign", OffsetDateTime::now_utc())
2948+ .await
2949+ .unwrap();
2950+ assert!(matches!(
2951+ store.set_task_tag(&task, &foreign.id).await,
2952+ Err(StoreError::NotFound)
2953+ ));
2954+ assert!(matches!(
2955+ store.set_task_tag(&task, "no-such-tag").await,
2956+ Err(StoreError::NotFound)
2957+ ));
2958+
2959+ // Deleting a worn tag leaves the task on the board's default, and the
2960+ // task survives.
2961+ store.delete_tag(&tag.id).await.unwrap();
2962+ let view = board_of(store, &workspace).await;
2963+ assert_eq!(
2964+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2965+ Some("General")
2966+ );
2967+}
2968+
2969+#[tokio::test]
2970+async fn a_fresh_board_comes_with_a_default_tag_and_new_tasks_wear_it() {
2971+ let (scratch, workspace, admin) = workspace_with_admin().await;
2972+ let store = &scratch.store;
2973+ let board = store.board(&workspace).await.unwrap().unwrap();
2974+
2975+ let tags = store.tags(&board.id).await.unwrap();
2976+ assert_eq!(tags.len(), 1, "a claimed board seeds exactly one tag");
2977+ assert!(tags[0].is_default, "the seeded tag is the default");
2978+ assert_eq!((tags[0].name.as_str(), tags[0].position), ("General", 0));
2979+
2980+ // Nobody chose a tag; the task wears the board's default all the same.
2981+ let task = add_task(store, &workspace, "Backlog", "first", None, &admin).await;
2982+ let view = board_of(store, &workspace).await;
2983+ assert_eq!(
2984+ card_of(&view, &task).tag.as_ref().map(|t| t.name.as_str()),
2985+ Some("General")
2986+ );
2987+}
2988+
2989+#[tokio::test]
2990+async fn the_default_tag_cannot_be_deleted_but_renames_and_moves_like_any_other() {
2991+ let (scratch, workspace, _admin) = workspace_with_admin().await;
2992+ let store = &scratch.store;
2993+ let board = store.board(&workspace).await.unwrap().unwrap();
2994+ let default = &store.tags(&board.id).await.unwrap()[0];
2995+
2996+ assert!(matches!(
2997+ store.delete_tag(&default.id).await,
2998+ Err(StoreError::Conflict("default_tag"))
2999+ ));
3000+
3001+ store.rename_tag(&default.id, "Projects").await.unwrap();
3002+ store
3003+ .create_tag(&board.id, "alpha", OffsetDateTime::now_utc())
3004+ .await
3005+ .unwrap();
3006+ store.move_tag(&default.id, false).await.unwrap();
3007+ assert_eq!(
3008+ tag_order(&store.tags(&board.id).await.unwrap()),
3009+ ["alpha", "Projects"]
3010+ );
3011+}
3012+
3013+#[tokio::test]
3014+async fn a_board_cannot_hold_two_defaults_and_a_task_cannot_go_tagless() {
3015+ let (scratch, workspace, _admin) = workspace_with_admin().await;
3016+ let board = scratch.store.board(&workspace).await.unwrap().unwrap();
3017+
3018+ // Two defaults is a schema rule, so it is the schema that refuses —
3019+ // exercised raw, because the store's own writes never try it.
3020+ let conn = raw_conn(&scratch).await;
3021+ let _ = conn
3022+ .execute(
3023+ "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \
3024+ VALUES ('t2', ?1, 'second', 9, 1, '2026-01-01T00:00:00Z')",
3025+ turso::params![board.id.clone()],
3026+ )
3027+ .await
3028+ .expect_err("a second default tag violates tag_one_default");
3029+
3030+ // And a task's tag_id is NOT NULL in the declared schema itself, not a
3031+ // habit of the write path.
3032+ let _ = conn
3033+ .execute(
3034+ "INSERT INTO task (id, board_id, task_key, title, column_id, tag_id, position, \
3035+ created_by, created_at, updated_at) \
3036+ VALUES ('tk', ?1, 'DZ-99', 'raw', (SELECT id FROM board_column LIMIT 1), NULL, 0, \
3037+ (SELECT id FROM user LIMIT 1), '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z')",
3038+ turso::params![board.id.clone()],
3039+ )
3040+ .await
3041+ .expect_err("task.tag_id is NOT NULL");
3042+}
3043+
3044+#[test]
3045+fn initials_fall_back_to_two_letters() {
3046+ let person = |name: &str| Person {
3047+ id: "u".into(),
3048+ display_name: name.into(),
3049+ has_photo: false,
3050+ };
3051+ assert_eq!(person("Mel Duarte").initials(), "MD");
3052+ assert_eq!(person("Ada").initials(), "A");
3053+ assert_eq!(person(" ").initials(), "?");
3054+}
3055+
3056+// -- task detail ------------------------------------------------------------
3057+
3058+use izlek_core::detail::{
3059+ ActivityEntry, ActivityKind, Comment, DependencyEdge, DetailReads, TaskFacts,
3060+ load as load_detail,
3061+};
3062+
3063+/// The same trick as [`CountingReads`], for the detail screen: the round trips
3064+/// one task costs must not follow how much it carries.
3065+struct CountingDetail<'a> {
3066+ inner: &'a TursoStore,
3067+ calls: AtomicUsize,
3068+}
3069+
3070+impl<'a> CountingDetail<'a> {
3071+ fn new(inner: &'a TursoStore) -> Self {
3072+ Self {
3073+ inner,
3074+ calls: AtomicUsize::new(0),
3075+ }
3076+ }
3077+
3078+ fn count(&self) -> usize {
3079+ self.calls.load(Ordering::Relaxed)
3080+ }
3081+
3082+ fn tick(&self) {
3083+ self.calls.fetch_add(1, Ordering::Relaxed);
3084+ }
3085+}
3086+
3087+#[async_trait::async_trait]
3088+impl DetailReads for CountingDetail<'_> {
3089+ async fn task(&self, task_id: &str) -> Result<Option<TaskFacts>, StoreError> {
3090+ self.tick();
3091+ self.inner.task(task_id).await
3092+ }
3093+
3094+ async fn columns_for_board(
3095+ &self,
3096+ board_id: &str,
3097+ ) -> Result<Vec<izlek_core::Column>, StoreError> {
3098+ self.tick();
3099+ self.inner.columns_for_board(board_id).await
3100+ }
3101+
3102+ async fn assignees_for_task(&self, task_id: &str) -> Result<Vec<Person>, StoreError> {
3103+ self.tick();
3104+ self.inner.assignees_for_task(task_id).await
3105+ }
3106+
3107+ async fn assignable_people(&self, workspace_id: &str) -> Result<Vec<Person>, StoreError> {
3108+ self.tick();
3109+ self.inner.assignable_people(workspace_id).await
3110+ }
3111+
3112+ async fn dependencies_for_task(
3113+ &self,
3114+ task_id: &str,
3115+ ) -> Result<Vec<(bool, DependencyEdge)>, StoreError> {
3116+ self.tick();
3117+ self.inner.dependencies_for_task(task_id).await
3118+ }
3119+
3120+ async fn comments_for_task(&self, task_id: &str) -> Result<Vec<Comment>, StoreError> {
3121+ self.tick();
3122+ self.inner.comments_for_task(task_id).await
3123+ }
3124+
3125+ async fn files_for_task(
3126+ &self,
3127+ task_id: &str,
3128+ ) -> Result<Vec<izlek_core::detail::FileLine>, StoreError> {
3129+ self.tick();
3130+ self.inner.files_for_task(task_id).await
3131+ }
3132+
3133+ async fn activity_for_task(&self, task_id: &str) -> Result<Vec<ActivityEntry>, StoreError> {
3134+ self.tick();
3135+ self.inner.activity_for_task(task_id).await
3136+ }
2724 3137
2725 async fn family_for_task(3138 async fn family_for_task(
2726 &self,3139 &self,
@@ -2830,7 +3243,6 @@ async fn a_dependency_that_would_close_a_circle_is_refused() {
2830 Err(StoreError::Cycle)3243 Err(StoreError::Cycle)
2831 ));3244 ));
2832 3245
2833- // The refusal wrote nothing.
2834 let detail = load_detail(store, &workspace, &c).await.unwrap().unwrap();3246 let detail = load_detail(store, &workspace, &c).await.unwrap().unwrap();
2835 assert!(detail.blocked_by.is_empty());3247 assert!(detail.blocked_by.is_empty());
2836 }3248 }
@@ -2987,7 +3399,11 @@ async fn saving_a_task_records_only_what_changed() {
2987 )3399 )
2988 .await3400 .await
2989 .unwrap();3401 .unwrap();
2990- assert_eq!(ids, Vec::<String>::new(), "a save that changed nothing writes nothing");3402+ assert_eq!(
3403+ ids,
3404+ Vec::<String>::new(),
3405+ "a save that changed nothing writes nothing"
3406+ );
2991 let detail = load_detail(store, &workspace, &task)3407 let detail = load_detail(store, &workspace, &task)
2992 .await3408 .await
2993 .unwrap()3409 .unwrap()
@@ -3078,6 +3494,7 @@ async fn a_task_detail_costs_nine_queries_whatever_it_carries() {
3078 .record_activity(3494 .record_activity(
3079 &heavy,3495 &heavy,
3080 Some(&person.id),3496 Some(&person.id),
3497+ None,
3081 &ActivityKind::Moved,3498 &ActivityKind::Moved,
3082 "to Review",3499 "to Review",
3083 now,3500 now,
@@ -3104,10 +3521,7 @@ async fn a_task_detail_costs_nine_queries_whatever_it_carries() {
3104 assert_eq!(detail.subtasks.len(), 20);3521 assert_eq!(detail.subtasks.len(), 20);
3105 assert!(detail.parent.is_none());3522 assert!(detail.parent.is_none());
3106 assert!(3523 assert!(
3107- detail3524+ detail.subtasks.iter().all(|part| part.assignees.len() == 1),
3108- .subtasks
3109- .iter()
3110- .all(|part| part.assignees.len() == 1),
3111 "a subtask row carries who holds it"3525 "a subtask row carries who holds it"
3112 );3526 );
3113 // Twenty comments (each its own Commented line), twenty moves, plus the3527 // 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() {
3561 "You can start now",3975 "You can start now",
3562 Audience::Assignees,3976 Audience::Assignees,
3563 OffsetDateTime::now_utc(),3977 OffsetDateTime::now_utc(),
3564- false,3978+ false,
3565 )3979 )
3566 .await3980 .await
3567 .expect("an unblocked rule is whole without a column");3981 .expect("an unblocked rule is whole without a column");
@@ -3924,7 +4338,7 @@ async fn deleting_a_rule_takes_its_ledger_with_it() {
3924 4338
3925 // -- the engine ------------------------------------------------------------4339 // -- the engine ------------------------------------------------------------
3926 4340
3927-use izlek_core::mail::{Engine, MailError, Mailer, Outgoing, backoff};4341+use izlek_core::mail::{Engine, MailError, Mailer, Outgoing, Report, backoff};
3928 use std::sync::Mutex;4342 use std::sync::Mutex;
3929 4343
3930 /// A mail server that remembers instead of sending, and refuses when told to.4344 /// A mail server that remembers instead of sending, and refuses when told to.
@@ -3965,8 +4379,16 @@ impl Mailer for Remembering {
3965 }4379 }
3966 }4380 }
3967 4381
3968-/// A store shared between the tests and an engine.4382+/// A store shared between the tests and an engine, with no quiet window: a
4383+/// trigger is a mail, sent the moment it is owed. That is what every test
4384+/// below the batching ones is about, and it is what `mail_batch_minutes = 0`
4385+/// means. The batching tests open theirs with `waiting`.
3969 async fn shared() -> (PathBuf, Arc<TursoStore>, String, String) {4386 async fn shared() -> (PathBuf, Arc<TursoStore>, String, String) {
4387+ waiting(0).await
4388+}
4389+
4390+/// The same, with a quiet window of `minutes` on the workspace.
4391+async fn waiting(minutes: u32) -> (PathBuf, Arc<TursoStore>, String, String) {
3970 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));4392 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
3971 std::fs::create_dir_all(&dir).unwrap();4393 std::fs::create_dir_all(&dir).unwrap();
3972 let store = Arc::new(4394 let store = Arc::new(
@@ -3975,6 +4397,17 @@ async fn shared() -> (PathBuf, Arc<TursoStore>, String, String) {
3975 .unwrap(),4397 .unwrap(),
3976 );4398 );
3977 let (workspace, admin) = claim(&store).await;4399 let (workspace, admin) = claim(&store).await;
4400+ let limits = store.workspace().await.unwrap().unwrap();
4401+ store
4402+ .set_limits(
4403+ &workspace,
4404+ limits.attachment_limit_bytes,
4405+ limits.photo_limit_bytes,
4406+ &limits.allowed_file_types,
4407+ minutes,
4408+ )
4409+ .await
4410+ .unwrap();
3978 (dir, store, workspace, admin)4411 (dir, store, workspace, admin)
3979 }4412 }
3980 4413
@@ -4293,7 +4726,7 @@ async fn you_can_start_now_waits_for_the_last_blocker() {
4293 "You can start now",4726 "You can start now",
4294 Audience::Assignees,4727 Audience::Assignees,
4295 now,4728 now,
4296- false,4729+ false,
4297 )4730 )
4298 .await4731 .await
4299 .unwrap();4732 .unwrap();
@@ -4365,7 +4798,7 @@ async fn a_deleted_blocker_also_says_you_can_start_now() {
4365 "You can start now",4798 "You can start now",
4366 Audience::Assignees,4799 Audience::Assignees,
4367 now,4800 now,
4368- false,4801+ false,
4369 )4802 )
4370 .await4803 .await
4371 .unwrap();4804 .unwrap();
@@ -4431,7 +4864,7 @@ async fn a_delete_that_leaves_somebody_still_waiting_mails_nobody() {
4431 "You can start now",4864 "You can start now",
4432 Audience::Assignees,4865 Audience::Assignees,
4433 now,4866 now,
4434- false,4867+ false,
4435 )4868 )
4436 .await4869 .await
4437 .unwrap();4870 .unwrap();
@@ -4478,7 +4911,7 @@ async fn a_mail_owed_by_a_delete_is_rebuilt_from_the_delete_on_a_retry() {
4478 "You can start now",4911 "You can start now",
4479 Audience::Assignees,4912 Audience::Assignees,
4480 now,4913 now,
4481- false,4914+ false,
4482 )4915 )
4483 .await4916 .await
4484 .unwrap();4917 .unwrap();
@@ -4551,7 +4984,10 @@ async fn a_rule_that_owed_nobody_still_says_so() {
4551 let transition = moved_to(&store, &workspace, &task, "Backlog", "Done", &mate).await;4984 let transition = moved_to(&store, &workspace, &task, "Backlog", "Done", &mate).await;
4552 engine.on_transition(&transition).await.unwrap();4985 engine.on_transition(&transition).await.unwrap();
4553 4986
4554- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();4987+ let decisions = store
4988+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
4989+ .await
4990+ .unwrap();
4555 let row = decisions4991 let row = decisions
4556 .iter()4992 .iter()
4557 .find(|d| d.rule_id == rule.id && d.task_id == task)4993 .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() {
4573 let transition = moved_to(&store, &workspace, &task, "Backlog", "Review", &admin).await;5009 let transition = moved_to(&store, &workspace, &task, "Backlog", "Review", &admin).await;
4574 engine.on_transition(&transition).await.unwrap();5010 engine.on_transition(&transition).await.unwrap();
4575 5011
4576- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();5012+ let decisions = store
5013+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
5014+ .await
5015+ .unwrap();
4577 let row = decisions5016 let row = decisions
4578 .iter()5017 .iter()
4579 .find(|d| d.rule_id == rule.id && d.task_id == task)5018 .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() {
4603 assert_eq!(report, Default::default());5042 assert_eq!(report, Default::default());
4604 assert!(mailer.sent().is_empty());5043 assert!(mailer.sent().is_empty());
4605 5044
4606- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();5045+ let decisions = store
5046+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
5047+ .await
5048+ .unwrap();
4607 let row = decisions5049 let row = decisions
4608 .iter()5050 .iter()
4609 .find(|d| d.rule_id == rule.id && d.task_id == task)5051 .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() {
4670 "A word the board speaks",5112 "A word the board speaks",
4671 Audience::Assignees,5113 Audience::Assignees,
4672 OffsetDateTime::now_utc(),5114 OffsetDateTime::now_utc(),
4673- false,5115+ false,
4674 )5116 )
4675 .await5117 .await
4676 .unwrap();5118 .unwrap();
@@ -4703,20 +5145,19 @@ async fn updating_a_rule_leaves_its_identity_and_ledger_alone() {
4703 let now = OffsetDateTime::now_utc();5145 let now = OffsetDateTime::now_utc();
4704 scratch5146 scratch
4705 .store5147 .store
4706- .record_mail_decision(5148+ .record_mail_decision(&rule.id, &transition.id, &task, MailOutcome::Owed, "", now)
4707- &rule.id,
4708- &transition.id,
4709- &task,
4710- MailOutcome::Owed,
4711- "",
4712- now,
4713- )
4714 .await5149 .await
4715 .unwrap();5150 .unwrap();
4716 5151
4717 scratch5152 scratch
4718 .store5153 .store
4719- .update_mail_rule(&rule.id, &Trigger::Unblocked, "New subject", Audience::Board, false)5154+ .update_mail_rule(
5155+ &rule.id,
5156+ &Trigger::Unblocked,
5157+ "New subject",
5158+ Audience::Board,
5159+ false,
5160+ )
4720 .await5161 .await
4721 .unwrap();5162 .unwrap();
4722 5163
@@ -4728,7 +5169,11 @@ async fn updating_a_rule_leaves_its_identity_and_ledger_alone() {
4728 assert_eq!(updated.enabled, rule.enabled);5169 assert_eq!(updated.enabled, rule.enabled);
4729 assert_eq!(updated.created_at, rule.created_at);5170 assert_eq!(updated.created_at, rule.created_at);
4730 5171
4731- let decisions = scratch.store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();5172+ let decisions = scratch
5173+ .store
5174+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
5175+ .await
5176+ .unwrap();
4732 assert!(5177 assert!(
4733 decisions.iter().any(|d| d.rule_id == rule.id),5178 decisions.iter().any(|d| d.rule_id == rule.id),
4734 "the pre-existing decision no longer joins to the rule"5179 "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() {
4778 .await5223 .await
4779 .unwrap();5224 .unwrap();
4780 assert_eq!(5225 assert_eq!(
4781- creators.iter().map(|p| p.user_id.as_str()).collect::<Vec<_>>(),5226+ creators
5227+ .iter()
5228+ .map(|p| p.user_id.as_str())
5229+ .collect::<Vec<_>>(),
4782 [admin.as_str()]5230 [admin.as_str()]
4783 );5231 );
4784 5232
@@ -4839,7 +5287,9 @@ async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() {
4839 5287
4840 // Bytes that are not text and are not valid UTF-8, because an attachment5288 // Bytes that are not text and are not valid UTF-8, because an attachment
4841 // is not a string and the column it lives in must not treat it as one.5289 // is not a string and the column it lives in must not treat it as one.
4842- let bytes: Vec<u8> = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe];5290+ let bytes: Vec<u8> = vec![
5291+ 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe,
5292+ ];
4843 let id = store5293 let id = store
4844 .add_attachment(NewAttachment {5294 .add_attachment(NewAttachment {
4845 task_id: &task,5295 task_id: &task,
@@ -5006,7 +5456,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
5006 let now = OffsetDateTime::now_utc();5456 let now = OffsetDateTime::now_utc();
5007 5457
5008 let pending = store5458 let pending = store
5009- .claim_send(&rule.id, &transition.id, &task, "pending@izlek.sh", now, now)5459+ .claim_send(
5460+ &rule.id,
5461+ &transition.id,
5462+ &task,
5463+ "pending@izlek.sh",
5464+ now,
5465+ now,
5466+ )
5010 .await5467 .await
5011 .unwrap()5468 .unwrap()
5012 .unwrap();5469 .unwrap();
@@ -5029,7 +5486,14 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
5029 store.record_send_accepted(&sent.id, now).await.unwrap();5486 store.record_send_accepted(&sent.id, now).await.unwrap();
5030 5487
5031 let abandoned = store5488 let abandoned = store
5032- .claim_send(&rule.id, &transition.id, &task, "abandoned@izlek.sh", now, now)5489+ .claim_send(
5490+ &rule.id,
5491+ &transition.id,
5492+ &task,
5493+ "abandoned@izlek.sh",
5494+ now,
5495+ now,
5496+ )
5033 .await5497 .await
5034 .unwrap()5498 .unwrap()
5035 .unwrap();5499 .unwrap();
@@ -5038,7 +5502,10 @@ async fn the_queue_shows_what_is_owed_and_not_what_is_done() {
5038 .await5502 .await
5039 .unwrap();5503 .unwrap();
5040 5504
5041- let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();5505+ let queue = store
5506+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
5507+ .await
5508+ .unwrap();
5042 let ids: Vec<&str> = queue.iter().map(|s| s.id.as_str()).collect();5509 let ids: Vec<&str> = queue.iter().map(|s| s.id.as_str()).collect();
5043 assert!(ids.contains(&pending.id.as_str()));5510 assert!(ids.contains(&pending.id.as_str()));
5044 assert!(ids.contains(&failed.id.as_str()));5511 assert!(ids.contains(&failed.id.as_str()));
@@ -5063,7 +5530,10 @@ async fn an_invite_mail_is_owed_without_a_rule() {
5063 let found = owed.iter().find(|s| s.id == invite.id).unwrap();5530 let found = owed.iter().find(|s| s.id == invite.id).unwrap();
5064 assert_eq!(found.rule_id, None);5531 assert_eq!(found.rule_id, None);
5065 5532
5066- let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();5533+ let queue = store
5534+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
5535+ .await
5536+ .unwrap();
5067 let found = queue.iter().find(|s| s.id == invite.id).unwrap();5537 let found = queue.iter().find(|s| s.id == invite.id).unwrap();
5068 assert_eq!(found.rule_id, None);5538 assert_eq!(found.rule_id, None);
5069 }5539 }
@@ -5083,7 +5553,10 @@ async fn an_invite_mail_with_no_sender_is_held_not_failed() {
5083 assert_eq!(report.held, 1);5553 assert_eq!(report.held, 1);
5084 assert_eq!(report.sent, 0);5554 assert_eq!(report.sent, 0);
5085 5555
5086- let queue = store.mail_queue(10, izlek_core::store::FeedPage::Newest).await.unwrap();5556+ let queue = store
5557+ .mail_queue(10, izlek_core::store::FeedPage::Newest)
5558+ .await
5559+ .unwrap();
5087 let held = queue5560 let held = queue
5088 .iter()5561 .iter()
5089 .find(|s| s.recipient == "newcomer@izlek.sh")5562 .find(|s| s.recipient == "newcomer@izlek.sh")
@@ -5128,10 +5601,7 @@ async fn two_passes_over_one_owed_mail_send_it_once() {
5128 // request's pass and the sweep's.5601 // request's pass and the sweep's.
5129 let request = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");5602 let request = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5130 let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");5603 let sweep = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5131- let (a, b) = tokio::join!(5604+ let (a, b) = tokio::join!(request.deliver_owed(now, 10), sweep.deliver_owed(now, 10),);
5132- request.deliver_owed(now, 10),
5133- sweep.deliver_owed(now, 10),
5134- );
5135 let (a, b) = (a.unwrap(), b.unwrap());5605 let (a, b) = (a.unwrap(), b.unwrap());
5136 5606
5137 let sent = mailer.sent.lock().unwrap().len();5607 let sent = mailer.sent.lock().unwrap().len();
@@ -5249,13 +5719,14 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() {
5249 let t0 = OffsetDateTime::now_utc();5719 let t0 = OffsetDateTime::now_utc();
5250 5720
5251 store5721 store
5252- .record_activity(&task_a, Some(&admin), &ActivityKind::Created, "", t0)5722+ .record_activity(&task_a, Some(&admin), None, &ActivityKind::Created, "", t0)
5253 .await5723 .await
5254 .unwrap();5724 .unwrap();
5255 store5725 store
5256 .record_activity(5726 .record_activity(
5257 &task_b,5727 &task_b,
5258 Some(&other),5728 Some(&other),
5729+ None,
5259 &ActivityKind::Retitled,5730 &ActivityKind::Retitled,
5260 "new title",5731 "new title",
5261 t0 + Duration::seconds(1),5732 t0 + Duration::seconds(1),
@@ -5263,7 +5734,15 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() {
5263 .await5734 .await
5264 .unwrap();5735 .unwrap();
5265 5736
5266- let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();5737+ let feed = store
5738+ .recent_activity(
5739+ 10,
5740+ izlek_core::store::FeedPage::Newest,
5741+ izlek_core::store::Dir::Newest,
5742+ &izlek_core::store::ActivityFilter::default(),
5743+ )
5744+ .await
5745+ .unwrap();
5267 // Two "created" lines came free with the two tasks; the two just recorded5746 // Two "created" lines came free with the two tasks; the two just recorded
5268 // sit newest first, ahead of both of those.5747 // sit newest first, ahead of both of those.
5269 assert_eq!(feed.len(), 4);5748 assert_eq!(feed.len(), 4);
@@ -5299,13 +5778,29 @@ async fn keyset_paging_covers_every_activity_row_once() {
5299 }5778 }
5300 let _ = workspace;5779 let _ = workspace;
5301 5780
5302- let whole = store.recent_activity(100, FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();5781+ let whole = store
5782+ .recent_activity(
5783+ 100,
5784+ FeedPage::Newest,
5785+ izlek_core::store::Dir::Newest,
5786+ &izlek_core::store::ActivityFilter::default(),
5787+ )
5788+ .await
5789+ .unwrap();
5303 assert_eq!(whole.len(), 23);5790 assert_eq!(whole.len(), 23);
5304 5791
5305 let mut walked = Vec::new();5792 let mut walked = Vec::new();
5306 let mut page = FeedPage::Newest;5793 let mut page = FeedPage::Newest;
5307 loop {5794 loop {
5308- let rows = store.recent_activity(7, page, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();5795+ let rows = store
5796+ .recent_activity(
5797+ 7,
5798+ page,
5799+ izlek_core::store::Dir::Newest,
5800+ &izlek_core::store::ActivityFilter::default(),
5801+ )
5802+ .await
5803+ .unwrap();
5309 if rows.is_empty() {5804 if rows.is_empty() {
5310 break;5805 break;
5311 }5806 }
@@ -5329,7 +5824,7 @@ async fn an_account_event_rides_the_feed_without_a_task() {
5329 let t0 = OffsetDateTime::now_utc();5824 let t0 = OffsetDateTime::now_utc();
5330 5825
5331 store5826 store
5332- .record_activity(&task, Some(&admin), &ActivityKind::Created, "", t0)5827+ .record_activity(&task, Some(&admin), None, &ActivityKind::Created, "", t0)
5333 .await5828 .await
5334 .unwrap();5829 .unwrap();
5335 store5830 store
@@ -5342,7 +5837,15 @@ async fn an_account_event_rides_the_feed_without_a_task() {
5342 .await5837 .await
5343 .unwrap();5838 .unwrap();
5344 5839
5345- let feed = store.recent_activity(10, izlek_core::store::FeedPage::Newest, izlek_core::store::Dir::Newest, &izlek_core::store::ActivityFilter::default()).await.unwrap();5840+ let feed = store
5841+ .recent_activity(
5842+ 10,
5843+ izlek_core::store::FeedPage::Newest,
5844+ izlek_core::store::Dir::Newest,
5845+ &izlek_core::store::ActivityFilter::default(),
5846+ )
5847+ .await
5848+ .unwrap();
5346 // The sign-in sits newest with no task on it; the task's own lines below5849 // The sign-in sits newest with no task on it; the task's own lines below
5347 // still name theirs.5850 // still name theirs.
5348 assert_eq!(feed[0].kind, ActivityKind::SignedIn);5851 assert_eq!(feed[0].kind, ActivityKind::SignedIn);
@@ -5440,7 +5943,7 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() {
5440 "You were assigned",5943 "You were assigned",
5441 Audience::Assignees,5944 Audience::Assignees,
5442 OffsetDateTime::now_utc(),5945 OffsetDateTime::now_utc(),
5443- false,5946+ false,
5444 )5947 )
5445 .await5948 .await
5446 .unwrap();5949 .unwrap();
@@ -5453,6 +5956,7 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() {
5453 .record_activity(5956 .record_activity(
5454 &task,5957 &task,
5455 Some(&admin),5958 Some(&admin),
5959+ None,
5456 &ActivityKind::Assigned,5960 &ActivityKind::Assigned,
5457 "Emre",5961 "Emre",
5458 OffsetDateTime::now_utc(),5962 OffsetDateTime::now_utc(),
@@ -5477,31 +5981,175 @@ async fn an_assignment_mails_the_assignees_minus_the_actor() {
5477 }5981 }
5478 5982
5479 #[tokio::test]5983 #[tokio::test]
5480-async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_commented() {5984+async fn assigning_one_person_mails_that_person_not_every_assignee() {
5481 let (dir, store, workspace, admin) = shared().await;5985 let (dir, store, workspace, admin) = shared().await;
5482- let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await;5986+ let first = member(&store, &workspace, "grace@izlek.sh", "Grace").await;
5987+ let second = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
5988+ let third = member(&store, &workspace, "linus@izlek.sh", "Linus").await;
5483 let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;5989 let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
5990+ store.assign_task(&task, &first).await.unwrap();
5991+ store.assign_task(&task, &second).await.unwrap();
5992+ store.assign_task(&task, &third).await.unwrap();
5484 let board = store.board(&workspace).await.unwrap().unwrap();5993 let board = store.board(&workspace).await.unwrap().unwrap();
5485 store5994 store
5486 .create_mail_rule(5995 .create_mail_rule(
5487 &board.id,5996 &board.id,
5488- &Trigger::Commented,5997+ &Trigger::Assigned,
5489- "A comment landed",5998+ "You were assigned",
5490- Audience::Creator,5999+ Audience::Assignees,
5491 OffsetDateTime::now_utc(),6000 OffsetDateTime::now_utc(),
5492- false,6001+ false,
5493 )6002 )
5494 .await6003 .await
5495 .unwrap();6004 .unwrap();
5496 6005
5497 let mailer = Remembering::taking_everything();6006 let mailer = Remembering::taking_everything();
5498 let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");6007 let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
5499-6008+ // Ada assigns Yusuf to a card that already carries three people: the line
6009+ // is about Yusuf, so Yusuf is the audience — not the three already there.
6010+ let fourth = member(&store, &workspace, "yusuf@izlek.sh", "Yusuf").await;
6011+ let activity_id = store
6012+ .record_activity(
6013+ &task,
6014+ Some(&admin),
6015+ Some(&fourth),
6016+ &ActivityKind::Assigned,
6017+ "Yusuf",
6018+ OffsetDateTime::now_utc(),
6019+ )
6020+ .await
6021+ .unwrap();
6022+ let event = activity_event(&store, &activity_id).await;
6023+
6024+ let report = engine.on_activity(&event).await.unwrap();
6025+ assert_eq!(report.sent, 1, "one assignment, one mail");
6026+ let sent = mailer.sent();
6027+ assert_eq!(sent.len(), 1);
6028+ assert_eq!(sent[0].to, "yusuf@izlek.sh");
6029+ let _ = std::fs::remove_dir_all(&dir);
6030+}
6031+
6032+#[tokio::test]
6033+async fn an_unassignment_mails_the_person_removed_not_the_rest() {
6034+ let (dir, store, workspace, admin) = shared().await;
6035+ let staying = member(&store, &workspace, "grace@izlek.sh", "Grace").await;
6036+ let leaving = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
6037+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
6038+ store.assign_task(&task, &staying).await.unwrap();
6039+ store.assign_task(&task, &leaving).await.unwrap();
6040+ let board = store.board(&workspace).await.unwrap().unwrap();
6041+ store
6042+ .create_mail_rule(
6043+ &board.id,
6044+ &Trigger::Unassigned,
6045+ "You were unassigned",
6046+ Audience::Assignees,
6047+ OffsetDateTime::now_utc(),
6048+ false,
6049+ )
6050+ .await
6051+ .unwrap();
6052+
6053+ let mailer = Remembering::taking_everything();
6054+ let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
6055+ store.unassign_task(&task, &leaving).await.unwrap();
6056+ let activity_id = store
6057+ .record_activity(
6058+ &task,
6059+ Some(&admin),
6060+ Some(&leaving),
6061+ &ActivityKind::Unassigned,
6062+ "Emre",
6063+ OffsetDateTime::now_utc(),
6064+ )
6065+ .await
6066+ .unwrap();
6067+ let event = activity_event(&store, &activity_id).await;
6068+
6069+ let report = engine.on_activity(&event).await.unwrap();
6070+ assert_eq!(report.sent, 1, "one removal, one mail");
6071+ let sent = mailer.sent();
6072+ assert_eq!(sent.len(), 1);
6073+ assert_eq!(
6074+ sent[0].to, "emre@izlek.sh",
6075+ "the mail is for the one removed"
6076+ );
6077+ let _ = std::fs::remove_dir_all(&dir);
6078+}
6079+
6080+#[tokio::test]
6081+async fn a_rule_whose_line_has_no_subject_still_mails_every_assignee() {
6082+ let (dir, store, workspace, admin) = shared().await;
6083+ let first = member(&store, &workspace, "grace@izlek.sh", "Grace").await;
6084+ let second = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
6085+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
6086+ store.assign_task(&task, &first).await.unwrap();
6087+ store.assign_task(&task, &second).await.unwrap();
6088+ let board = store.board(&workspace).await.unwrap().unwrap();
6089+ store
6090+ .create_mail_rule(
6091+ &board.id,
6092+ &Trigger::Commented,
6093+ "There was movement",
6094+ Audience::Assignees,
6095+ OffsetDateTime::now_utc(),
6096+ false,
6097+ )
6098+ .await
6099+ .unwrap();
6100+
6101+ let mailer = Remembering::taking_everything();
6102+ let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
6103+ // A comment has no subject: the audience stays the whole assignee list,
6104+ // minus the actor, exactly as before the subject column existed.
6105+ let activity_id = store
6106+ .record_activity(
6107+ &task,
6108+ Some(&admin),
6109+ None,
6110+ &ActivityKind::Commented,
6111+ "",
6112+ OffsetDateTime::now_utc(),
6113+ )
6114+ .await
6115+ .unwrap();
6116+ let event = activity_event(&store, &activity_id).await;
6117+
6118+ let report = engine.on_activity(&event).await.unwrap();
6119+ assert_eq!(report.sent, 2, "both assignees, the old breadth");
6120+ let mut to: Vec<_> = mailer.sent().iter().map(|m| m.to.clone()).collect();
6121+ to.sort();
6122+ assert_eq!(to, vec!["emre@izlek.sh", "grace@izlek.sh"]);
6123+ let _ = std::fs::remove_dir_all(&dir);
6124+}
6125+
6126+#[tokio::test]
6127+async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_commented() {
6128+ let (dir, store, workspace, admin) = shared().await;
6129+ let mate = member(&store, &workspace, "emre@izlek.sh", "Emre").await;
6130+ let task = add_task(&store, &workspace, "Backlog", "Ship it", None, &admin).await;
6131+ let board = store.board(&workspace).await.unwrap().unwrap();
6132+ store
6133+ .create_mail_rule(
6134+ &board.id,
6135+ &Trigger::Commented,
6136+ "A comment landed",
6137+ Audience::Creator,
6138+ OffsetDateTime::now_utc(),
6139+ false,
6140+ )
6141+ .await
6142+ .unwrap();
6143+
6144+ let mailer = Remembering::taking_everything();
6145+ let engine = Engine::new(store.clone(), mailer.clone(), "https://izlek.sh");
6146+
5500 // Emre comments on Ada's task: Ada, the creator, gets mailed.6147 // Emre comments on Ada's task: Ada, the creator, gets mailed.
5501 let commented_by_mate = store6148 let commented_by_mate = store
5502 .record_activity(6149 .record_activity(
5503 &task,6150 &task,
5504 Some(&mate),6151 Some(&mate),
6152+ None,
5505 &ActivityKind::Commented,6153 &ActivityKind::Commented,
5506 "",6154 "",
5507 OffsetDateTime::now_utc(),6155 OffsetDateTime::now_utc(),
@@ -5521,6 +6169,7 @@ async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_c
5521 .record_activity(6169 .record_activity(
5522 &task,6170 &task,
5523 Some(&admin),6171 Some(&admin),
6172+ None,
5524 &ActivityKind::Commented,6173 &ActivityKind::Commented,
5525 "",6174 "",
5526 OffsetDateTime::now_utc(),6175 OffsetDateTime::now_utc(),
@@ -5532,7 +6181,10 @@ async fn a_creator_audience_rule_mails_the_creator_and_nobody_when_the_creator_c
5532 assert_eq!(report, Default::default());6181 assert_eq!(report, Default::default());
5533 assert_eq!(mailer.sent().len(), 1, "no second mail went out");6182 assert_eq!(mailer.sent().len(), 1, "no second mail went out");
5534 6183
5535- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();6184+ let decisions = store
6185+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
6186+ .await
6187+ .unwrap();
5536 let row = decisions6188 let row = decisions
5537 .iter()6189 .iter()
5538 .find(|d| d.event_id == commented_by_creator)6190 .find(|d| d.event_id == commented_by_creator)
@@ -5554,6 +6206,7 @@ async fn a_created_activity_does_not_fire_a_status_rule() {
5554 .record_activity(6206 .record_activity(
5555 &task,6207 &task,
5556 Some(&admin),6208 Some(&admin),
6209+ None,
5557 &ActivityKind::Created,6210 &ActivityKind::Created,
5558 "",6211 "",
5559 OffsetDateTime::now_utc(),6212 OffsetDateTime::now_utc(),
@@ -5566,7 +6219,10 @@ async fn a_created_activity_does_not_fire_a_status_rule() {
5566 assert_eq!(report, Default::default());6219 assert_eq!(report, Default::default());
5567 assert!(mailer.sent().is_empty());6220 assert!(mailer.sent().is_empty());
5568 6221
5569- let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap();6222+ let decisions = store
6223+ .recent_mail_decisions(10, izlek_core::store::FeedPage::Newest)
6224+ .await
6225+ .unwrap();
5570 let row = decisions6226 let row = decisions
5571 .iter()6227 .iter()
5572 .find(|d| d.rule_id == rule.id && d.task_id == task)6228 .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() {
5609 .unwrap()6265 .unwrap()
5610 .unwrap();6266 .unwrap();
5611 store6267 store
5612- .claim_send(&rule.id, &other_transition.id, &other_task, "emre@izlek.sh", now, now)6268+ .claim_send(
6269+ &rule.id,
6270+ &other_transition.id,
6271+ &other_task,
6272+ "emre@izlek.sh",
6273+ now,
6274+ now,
6275+ )
5613 .await6276 .await
5614 .unwrap();6277 .unwrap();
5615 6278
@@ -5658,10 +6321,17 @@ async fn requeuing_a_send_puts_it_back_in_play_but_leaves_a_sent_one_alone() {
5658 assert!(reread_failed.next_attempt_at.is_some_and(|at| at <= now));6321 assert!(reread_failed.next_attempt_at.is_some_and(|at| at <= now));
5659 6322
5660 let reread_sent = sends.iter().find(|s| s.id == sent.id).unwrap();6323 let reread_sent = sends.iter().find(|s| s.id == sent.id).unwrap();
5661- assert_eq!(reread_sent.state, SendState::Sent, "a sent send is untouched");6324+ assert_eq!(
6325+ reread_sent.state,
6326+ SendState::Sent,
6327+ "a sent send is untouched"
6328+ );
5662 6329
5663 let owed = store.sends_owed(now, 10).await.unwrap();6330 let owed = store.sends_owed(now, 10).await.unwrap();
5664- assert!(owed.iter().any(|s| s.id == failed.id), "the requeued send is now due");6331+ assert!(
6332+ owed.iter().any(|s| s.id == failed.id),
6333+ "the requeued send is now due"
6334+ );
5665 }6335 }
5666 6336
5667 #[tokio::test]6337 #[tokio::test]
@@ -5723,7 +6393,10 @@ async fn the_engine_delivers_a_notice_that_owes_no_rule() {
5723 .sends_owed(now + Duration::hours(2), 10)6393 .sends_owed(now + Duration::hours(2), 10)
5724 .await6394 .await
5725 .unwrap();6395 .unwrap();
5726- assert!(owed.is_empty(), "a delivered notice is no longer owed: {owed:?}");6396+ assert!(
6397+ owed.is_empty(),
6398+ "a delivered notice is no longer owed: {owed:?}"
6399+ );
5727 std::fs::remove_dir_all(dir).ok();6400 std::fs::remove_dir_all(dir).ok();
5728 }6401 }
5729 6402
@@ -5750,8 +6423,16 @@ async fn a_tasks_activity_reads_newest_first() {
5750 );6423 );
5751 // Creation is the oldest thing that ever happens to a task, so it is last6424 // Creation is the oldest thing that ever happens to a task, so it is last
5752 // now; a comment — the most recent act here — leads.6425 // now; a comment — the most recent act here — leads.
5753- assert_eq!(activity.first().map(|line| line.kind.clone()), Some(ActivityKind::Commented), "{activity:?}");6426+ assert_eq!(
5754- assert_eq!(activity.last().map(|line| line.kind.clone()), Some(ActivityKind::Created), "{activity:?}");6427+ activity.first().map(|line| line.kind.clone()),
6428+ Some(ActivityKind::Commented),
6429+ "{activity:?}"
6430+ );
6431+ assert_eq!(
6432+ activity.last().map(|line| line.kind.clone()),
6433+ Some(ActivityKind::Created),
6434+ "{activity:?}"
6435+ );
5755 }6436 }
5756 6437
5757 /// A status rule with no column watches the whole board: every crossing fires6438 /// 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() {
5786 6467
5787 let sent = mailer.sent();6468 let sent = mailer.sent();
5788 assert_eq!(6469 assert_eq!(
5789- sent.iter().filter(|mail| mail.subject == "It moved").count(),6470+ sent.iter()
6471+ .filter(|mail| mail.subject == "It moved")
6472+ .count(),
5790 2,6473 2,
5791 "both crossings fired the every-column rule: {sent:?}"6474 "both crossings fired the every-column rule: {sent:?}"
5792 );6475 );
@@ -5942,7 +6625,9 @@ async fn every_kind_of_write_announces_its_surface() {
5942 .unwrap();6625 .unwrap();
5943 6626
5944 let seen = announced(&mut rx);6627 let seen = announced(&mut rx);
5945- for topic in ["board", "task", "members", "queue", "rules", "settings", "activity"] {6628+ for topic in [
6629+ "board", "task", "members", "queue", "rules", "settings", "activity",
6630+ ] {
5946 assert!(6631 assert!(
5947 seen.iter().any(|k| k == topic),6632 seen.iter().any(|k| k == topic),
5948 "no {topic} announcement; heard {seen:?}"6633 "no {topic} announcement; heard {seen:?}"
@@ -6056,7 +6741,12 @@ async fn the_next_due_moment_is_the_earliest_one() {
6056 .await6741 .await
6057 .unwrap();6742 .unwrap();
6058 store6743 store
6059- .queue_notice("soon@izlek.sh", "Sooner", "body", now + Duration::minutes(5))6744+ .queue_notice(
6745+ "soon@izlek.sh",
6746+ "Sooner",
6747+ "body",
6748+ now + Duration::minutes(5),
6749+ )
6060 .await6750 .await
6061 .unwrap();6751 .unwrap();
6062 6752
@@ -6085,21 +6775,32 @@ async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() {
6085 from_name: "İzlek".into(),6775 from_name: "İzlek".into(),
6086 from_address: "izlek@izlek.sh".into(),6776 from_address: "izlek@izlek.sh".into(),
6087 };6777 };
6088- store.set_sender(&workspace, sender("smtp.one.test")).await.unwrap();6778+ store
6779+ .set_sender(&workspace, sender("smtp.one.test"))
6780+ .await
6781+ .unwrap();
6089 6782
6090 // A login that worked, and a mail that did not: both true at once, and6783 // A login that worked, and a mail that did not: both true at once, and
6091 // neither may be rendered as the other.6784 // neither may be rendered as the other.
6092 store6785 store
6093 .record_sender_check(6786 .record_sender_check(
6094 &workspace,6787 &workspace,
6095- izlek_core::store::SenderCheck { at: now, took_ms: 120, error: None },6788+ izlek_core::store::SenderCheck {
6789+ at: now,
6790+ took_ms: 120,
6791+ error: None,
6792+ },
6096 )6793 )
6097 .await6794 .await
6098 .unwrap();6795 .unwrap();
6099 store6796 store
6100 .record_sender_test(6797 .record_sender_test(
6101 &workspace,6798 &workspace,
6102- izlek_core::store::SenderTest { at: now, took_ms: 0, error: Some("550 not allowed".into()) },6799+ izlek_core::store::SenderTest {
6800+ at: now,
6801+ took_ms: 0,
6802+ error: Some("550 not allowed".into()),
6803+ },
6103 )6804 )
6104 .await6805 .await
6105 .unwrap();6806 .unwrap();
@@ -6115,8 +6816,850 @@ async fn a_sender_check_is_recorded_apart_from_a_test_and_cleared_on_edit() {
6115 );6816 );
6116 6817
6117 // Point it at a different server: what was known is now about nothing.6818 // Point it at a different server: what was known is now about nothing.
6118- store.set_sender(&workspace, sender("smtp.two.test")).await.unwrap();6819+ store
6820+ .set_sender(&workspace, sender("smtp.two.test"))
6821+ .await
6822+ .unwrap();
6119 let ws = store.workspace().await.unwrap().unwrap();6823 let ws = store.workspace().await.unwrap().unwrap();
6120- assert!(ws.sender_check.is_none(), "a stale handshake survived an edit");6824+ assert!(
6825+ ws.sender_check.is_none(),
6826+ "a stale handshake survived an edit"
6827+ );
6121 assert!(ws.sender_test.is_none(), "a stale test survived an edit");6828 assert!(ws.sender_test.is_none(), "a stale test survived an edit");
6122 }6829 }
6830+
6831+// ---------------------------------------------------------------------------
6832+// izlek reconcile — bringing a database of the OLD shape onto the declared
6833+// schema. These tests carry the user's rule (2026-08-31): a table alteration
6834+// owes both a proof that the alteration holds and a proof that reconcile
6835+// carries a live-shaped database across it.
6836+// ---------------------------------------------------------------------------
6837+
6838+/// Builds a database at the PRE-COLLAPSE schema — the shape İzlek was actually
6839+/// deployed with, kept verbatim in `tests/fixtures/` — and fills it with the
6840+/// kinds of row a live workspace holds, blobs included.
6841+async fn live_shaped_database() -> (PathBuf, String) {
6842+ let dir = std::env::temp_dir().join(format!("izlek-reconcile-{}", Ulid::new()));
6843+ std::fs::create_dir_all(&dir).unwrap();
6844+ let path = dir.join("izlek.db").to_str().unwrap().to_string();
6845+
6846+ let db = turso::Builder::new_local(&path).build().await.unwrap();
6847+ let conn = db.connect().unwrap();
6848+ conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap();
6849+ conn.execute_batch(include_str!("fixtures/pre-collapse/0001_init.sql"))
6850+ .await
6851+ .unwrap();
6852+ conn.execute_batch(include_str!("fixtures/pre-collapse/0002_sender_check.sql"))
6853+ .await
6854+ .unwrap();
6855+
6856+ let now = "2026-08-30T12:00:00Z";
6857+ let mut sql = String::new();
6858+ sql.push_str(&format!(
6859+ "INSERT INTO workspace (id, name, created_at) VALUES ('W1', 'Dizey', '{now}');"
6860+ ));
6861+ for (id, email, name) in [
6862+ ("U1", "one@example.com", "One"),
6863+ ("U2", "two@example.com", "Two"),
6864+ ] {
6865+ sql.push_str(&format!(
6866+ "INSERT INTO user (id, workspace_id, email, display_name, role, created_at) \
6867+ VALUES ('{id}', 'W1', '{email}', '{name}', 'member', '{now}');"
6868+ ));
6869+ }
6870+ sql.push_str(&format!(
6871+ "INSERT INTO workspace_owner (singleton, user_id, claimed_at) VALUES (1, 'U1', '{now}');"
6872+ ));
6873+ // Two boards, so a task landing on the WRONG board's default tag is
6874+ // visible rather than accidentally correct.
6875+ for b in ["B1", "B2"] {
6876+ sql.push_str(&format!(
6877+ "INSERT INTO board (id, workspace_id, name, created_at) VALUES ('{b}', 'W1', '{b}', '{now}');"
6878+ ));
6879+ sql.push_str(&format!(
6880+ "INSERT INTO board_column (id, board_id, name, position, is_done) \
6881+ VALUES ('C{b}', '{b}', 'Backlog', 0, 0);"
6882+ ));
6883+ }
6884+ for (t, b) in [("T1", "B1"), ("T2", "B1"), ("T3", "B2")] {
6885+ sql.push_str(&format!(
6886+ "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, updated_at) \
6887+ VALUES ('{t}', '{b}', '{t}', 'a task', 'C{b}', 'U1', '{now}', '{now}');"
6888+ ));
6889+ sql.push_str(&format!(
6890+ "INSERT INTO task_assignee (task_id, user_id) VALUES ('{t}', 'U2');"
6891+ ));
6892+ sql.push_str(&format!(
6893+ "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \
6894+ VALUES ('A{t}', '{t}', 'U1', 'created', '', '{now}');"
6895+ ));
6896+ }
6897+ // A soft-deleted task still belongs to a tag afterwards.
6898+ sql.push_str(&format!(
6899+ "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, updated_at, deleted_at) \
6900+ VALUES ('T4', 'B2', 'T4', 'gone', 'CB2', 'U1', '{now}', '{now}', '{now}');"
6901+ ));
6902+ conn.execute_batch(&sql).await.unwrap();
6903+
6904+ // A blob, because an attachment that survives as NULL would pass a row
6905+ // count and lose the user's file.
6906+ let bytes: Vec<u8> = (0u8..=255).cycle().take(5000).collect();
6907+ conn.execute(
6908+ "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, bytes, uploaded_by, created_at) \
6909+ VALUES ('F1', 'T1', 'a.bin', 'application/octet-stream', ?1, ?2, 'U1', ?3)",
6910+ turso::params![bytes.len() as i64, bytes.clone(), now],
6911+ )
6912+ .await
6913+ .unwrap();
6914+
6915+ (dir, path)
6916+}
6917+
6918+async fn scalar(path: &str, sql: &str) -> i64 {
6919+ let db = turso::Builder::new_local(path).build().await.unwrap();
6920+ let conn = db.connect().unwrap();
6921+ let mut rows = conn.query(sql, ()).await.unwrap();
6922+ rows.next().await.unwrap().unwrap().get::<i64>(0).unwrap()
6923+}
6924+
6925+fn backups_beside(dir: &PathBuf) -> Vec<String> {
6926+ let mut found: Vec<String> = std::fs::read_dir(dir)
6927+ .unwrap()
6928+ .filter_map(|e| e.ok())
6929+ .map(|e| e.file_name().to_string_lossy().to_string())
6930+ .filter(|n| n.contains(".backup-") && !n.ends_with("-wal") && !n.ends_with("-shm"))
6931+ .collect();
6932+ found.sort();
6933+ found
6934+}
6935+
6936+#[tokio::test]
6937+async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() {
6938+ let (dir, path) = live_shaped_database().await;
6939+
6940+ izlek_core::store::reconcile(
6941+ &path,
6942+ izlek_core::store::ReconcileOptions {
6943+ dry_run: false,
6944+ yes: true,
6945+ auto: true,
6946+ },
6947+ )
6948+ .await
6949+ .expect("reconcile refused a database of the shape we actually deployed");
6950+
6951+ let db = turso::Builder::new_local(&path).build().await.unwrap();
6952+ let conn = db.connect().unwrap();
6953+
6954+ // The schema is now the declared one, exactly.
6955+ let after = izlek_core::store::schema::fingerprint(&conn).await.unwrap();
6956+ let declared = izlek_core::store::schema::declared_fingerprint().await.unwrap();
6957+ assert_eq!(after, declared, "the rebuilt schema is not the declared one");
6958+
6959+ // Nothing was dropped on the floor.
6960+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM user").await, 2);
6961+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM board").await, 2);
6962+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task").await, 4);
6963+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task_assignee").await, 3);
6964+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM activity").await, 3);
6965+
6966+ // Every task wears its OWN board's default tag — the step no schema diff
6967+ // could have derived.
6968+ assert_eq!(
6969+ scalar(&path, "SELECT COUNT(*) FROM task WHERE tag_id IS NULL").await,
6970+ 0,
6971+ "a task came out of the rebuild with no tag"
6972+ );
6973+ assert_eq!(
6974+ scalar(
6975+ &path,
6976+ "SELECT COUNT(*) FROM task t JOIN tag g ON g.id = t.tag_id \
6977+ WHERE g.board_id = t.board_id AND g.is_default = 1",
6978+ )
6979+ .await,
6980+ 4,
6981+ "a task was given another board's tag"
6982+ );
6983+ assert_eq!(
6984+ scalar(&path, "SELECT COUNT(*) FROM tag").await,
6985+ 2,
6986+ "each board owes exactly one default tag"
6987+ );
6988+
6989+ // The blob survived byte for byte.
6990+ assert_eq!(
6991+ scalar(&path, "SELECT length(bytes) FROM attachment WHERE id = 'F1'").await,
6992+ 5000
6993+ );
6994+ assert_eq!(
6995+ scalar(
6996+ &path,
6997+ "SELECT COUNT(*) FROM attachment WHERE id = 'F1' AND hex(substr(bytes, 1, 4)) = '00010203'",
6998+ )
6999+ .await,
7000+ 1,
7001+ "the attachment's bytes changed in the rebuild"
7002+ );
7003+
7004+ // The quiet window is a column the old shape never had: a workspace that
7005+ // crosses over gets the declared default rather than a NULL the app would
7006+ // have to read around.
7007+ assert_eq!(
7008+ scalar(&path, "SELECT mail_batch_minutes FROM workspace WHERE id = 'W1'").await,
7009+ 5,
7010+ "the workspace came across without a quiet window"
7011+ );
7012+
7013+ // And the references all still point at something.
7014+ let mut broken = conn.query("PRAGMA foreign_key_check", ()).await.unwrap();
7015+ assert!(
7016+ broken.next().await.unwrap().is_none(),
7017+ "the rebuilt database has dangling references"
7018+ );
7019+
7020+ // The original is beside it, still holding the old shape.
7021+ let backups = backups_beside(&dir);
7022+ assert_eq!(backups.len(), 1, "the rebuild did not keep a backup");
7023+ let backup = dir.join(&backups[0]).to_str().unwrap().to_string();
7024+ assert_eq!(
7025+ scalar(
7026+ &backup,
7027+ "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'tag'",
7028+ )
7029+ .await,
7030+ 0,
7031+ "the backup is not the old-shaped database we started from"
7032+ );
7033+ assert_eq!(
7034+ scalar(&backup, "SELECT COUNT(*) FROM task").await,
7035+ 4,
7036+ "the backup lost rows"
7037+ );
7038+
7039+ let _ = std::fs::remove_dir_all(&dir);
7040+}
7041+
7042+#[tokio::test]
7043+async fn reconciling_a_database_that_already_matches_changes_nothing() {
7044+ let scratch = Scratch::open().await;
7045+ let path = scratch.dir.join("izlek.db").to_str().unwrap().to_string();
7046+
7047+ izlek_core::store::reconcile(
7048+ &path,
7049+ izlek_core::store::ReconcileOptions {
7050+ dry_run: false,
7051+ yes: true,
7052+ auto: true,
7053+ },
7054+ )
7055+ .await
7056+ .expect("reconcile refused a current database");
7057+
7058+ assert!(
7059+ backups_beside(&scratch.dir).is_empty(),
7060+ "a database that needed nothing was backed up anyway"
7061+ );
7062+}
7063+
7064+#[tokio::test]
7065+async fn opening_a_stale_database_repairs_it() {
7066+ let (dir, path) = live_shaped_database().await;
7067+
7068+ // The boot path: no flag, no prompt — the store comes up on a database of
7069+ // the old shape, having repaired it on the way.
7070+ let store = TursoStore::open(&path)
7071+ .await
7072+ .expect("the store would not open a database it was supposed to repair");
7073+ drop(store);
7074+
7075+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7076+ let conn = db.connect().unwrap();
7077+ assert_eq!(
7078+ izlek_core::store::schema::fingerprint(&conn).await.unwrap(),
7079+ izlek_core::store::schema::declared_fingerprint().await.unwrap(),
7080+ );
7081+ assert_eq!(scalar(&path, "SELECT COUNT(*) FROM task").await, 4);
7082+ assert_eq!(backups_beside(&dir).len(), 1);
7083+
7084+ // Opening it again finds it current and leaves it alone.
7085+ let store = TursoStore::open(&path).await.unwrap();
7086+ drop(store);
7087+ assert_eq!(
7088+ backups_beside(&dir).len(),
7089+ 1,
7090+ "a second open rebuilt a database that already matched"
7091+ );
7092+
7093+ let _ = std::fs::remove_dir_all(&dir);
7094+}
7095+
7096+#[tokio::test]
7097+async fn two_repairs_leave_two_backups() {
7098+ let (dir, path) = live_shaped_database().await;
7099+ let opts = || izlek_core::store::ReconcileOptions {
7100+ dry_run: false,
7101+ yes: true,
7102+ auto: true,
7103+ };
7104+
7105+ izlek_core::store::reconcile(&path, opts()).await.unwrap();
7106+ assert_eq!(backups_beside(&dir).len(), 1);
7107+
7108+ // Put the database back to the old shape and repair it again: the first
7109+ // backup must still be there. He keeps every one of them.
7110+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7111+ let conn = db.connect().unwrap();
7112+ conn.execute("DROP TABLE tag_stub_check", ()).await.ok();
7113+ conn.execute("CREATE TABLE stray (id TEXT PRIMARY KEY)", ())
7114+ .await
7115+ .unwrap();
7116+ drop(conn);
7117+ drop(db);
7118+
7119+ izlek_core::store::reconcile(&path, opts()).await.unwrap();
7120+ let backups = backups_beside(&dir);
7121+ assert_eq!(
7122+ backups.len(),
7123+ 2,
7124+ "the second repair overwrote the first backup: {backups:?}"
7125+ );
7126+
7127+ let _ = std::fs::remove_dir_all(&dir);
7128+}
7129+/// The other half of the alteration: a database that ALREADY carries the
7130+/// quiet window keeps the number its admin set, rather than being handed the
7131+/// default a fresh workspace gets.
7132+#[tokio::test]
7133+async fn a_rebuild_keeps_a_window_the_admin_already_set() {
7134+ let scratch = Scratch::open().await;
7135+ let path = scratch.dir.join("izlek.db").to_str().unwrap().to_string();
7136+ let (workspace, _) = claim(&scratch.store).await;
7137+ let limits = scratch.store.workspace().await.unwrap().unwrap();
7138+ scratch
7139+ .store
7140+ .set_limits(
7141+ &workspace,
7142+ limits.attachment_limit_bytes,
7143+ limits.photo_limit_bytes,
7144+ &limits.allowed_file_types,
7145+ 17,
7146+ )
7147+ .await
7148+ .unwrap();
7149+
7150+ // Something the declared schema does not know about: enough to make the
7151+ // database stale, so the rebuild actually runs.
7152+ let db = turso::Builder::new_local(&path).build().await.unwrap();
7153+ let conn = db.connect().unwrap();
7154+ conn.execute("CREATE TABLE stray (id TEXT PRIMARY KEY)", ())
7155+ .await
7156+ .unwrap();
7157+ drop(conn);
7158+ drop(db);
7159+
7160+ izlek_core::store::reconcile(
7161+ &path,
7162+ izlek_core::store::ReconcileOptions {
7163+ dry_run: false,
7164+ yes: true,
7165+ auto: true,
7166+ },
7167+ )
7168+ .await
7169+ .unwrap();
7170+
7171+ assert_eq!(
7172+ scalar(&path, "SELECT mail_batch_minutes FROM workspace").await,
7173+ 17,
7174+ "the rebuild reset a window the admin had chosen"
7175+ );
7176+ assert_eq!(
7177+ scalar(
7178+ &path,
7179+ "SELECT COUNT(*) FROM sqlite_master WHERE name = 'stray'",
7180+ )
7181+ .await,
crates/izlek-web/src/board.rsmodified+48 -3
@@ -214,6 +214,11 @@ fn valid_sort(sort: Option<&str>) -> &'static str {
214 _ => "deadline",214 _ => "deadline",
215 }215 }
216 }216 }
217+/// The `?tag=` filter: an id only counts while it names a tag on this
218+/// board — a stale or hand-edited query string falls back to all.
219+fn valid_tag(tag: Option<&str>, tags: &[izlek_core::store::Tag]) -> Option<String> {
220+ tag.and_then(|id| tags.iter().find(|t| t.id == id).map(|t| t.id.clone()))
221+}
217 222
218 /// `deadline` is the order [`izlek_core::board::load`] already hands back223 /// `deadline` is the order [`izlek_core::board::load`] already hands back
219 /// (soonest first); the other two re-order in place here so core stays free224 /// (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) {
228 }233 }
229 234
230 /// The whole column list.235 /// The whole column list.
231-async fn board_columns(cx: &Cx, sort: String) -> Result {236+async fn board_columns(
237+ cx: &Cx,
238+ sort: String,
239+ tag_filter: Option<String>,
240+ default_tag_id: Option<&str>,
241+) -> Result {
232 let user = match require_user(cx).await {242 let user = match require_user(cx).await {
233 Ok(user) => user,243 Ok(user) => user,
234 Err(refusal) => {244 Err(refusal) => {
@@ -251,6 +261,11 @@ async fn board_columns(cx: &Cx, sort: String) -> Result {
251 };261 };
252 for column in &mut view_data.columns {262 for column in &mut view_data.columns {
253 sort_column_cards(&mut column.cards, &sort);263 sort_column_cards(&mut column.cards, &sort);
264+ if let Some(tag_id) = &tag_filter {
265+ column
266+ .cards
267+ .retain(|card| card.tag.as_ref().is_some_and(|tag| tag.id == *tag_id));
268+ }
254 }269 }
255 let today = OffsetDateTime::now_utc().date();270 let today = OffsetDateTime::now_utc().date();
256 let may_write = user.role.can_write_tasks();271 let may_write = user.role.can_write_tasks();
@@ -262,7 +277,7 @@ async fn board_columns(cx: &Cx, sort: String) -> Result {
262 .collect();277 .collect();
263 let mut columns = Vec::new();278 let mut columns = Vec::new();
264 for column in view_data.columns {279 for column in view_data.columns {
265- columns.push(render_column(cx, column, today, may_write, &all_columns, lang).await?);280+ columns.push(render_column(cx, column, today, may_write, &all_columns, default_tag_id, lang).await?);
266 }281 }
267 282
268 view! {283 view! {
@@ -277,6 +292,7 @@ async fn render_column(
277 today: Date,292 today: Date,
278 may_write: bool,293 may_write: bool,
279 all_columns: &[(String, String)],294 all_columns: &[(String, String)],
295+ default_tag_id: Option<&str>,
280 lang: Lang,296 lang: Lang,
281 ) -> Result {297 ) -> Result {
282 let column_id = column.column.id;298 let column_id = column.column.id;
@@ -295,6 +311,7 @@ async fn render_column(
295 &column_id,311 &column_id,
296 may_write,312 may_write,
297 all_columns,313 all_columns,
314+ default_tag_id,
298 lang,315 lang,
299 )316 )
300 .await?,317 .await?,
@@ -327,6 +344,7 @@ async fn render_card(
327 column_id: &str,344 column_id: &str,
328 may_write: bool,345 may_write: bool,
329 all_columns: &[(String, String)],346 all_columns: &[(String, String)],
347+ default_tag_id: Option<&str>,
330 lang: Lang,348 lang: Lang,
331 ) -> Result {349 ) -> Result {
332 let blocks = card.blocks.len();350 let blocks = card.blocks.len();
@@ -381,6 +399,11 @@ async fn render_card(
381 <span data-tick=(dated.then_some("")) class=(class!("card-deadline", "card-deadline-overdue" if overdue, "card-deadline-none" if !dated))>399 <span data-tick=(dated.then_some("")) class=(class!("card-deadline", "card-deadline-overdue" if overdue, "card-deadline-none" if !dated))>
382 (deadline)400 (deadline)
383 </span>401 </span>
402+ if let Some(tag) = &card.tag {
403+ if Some(tag.id.as_str()) != default_tag_id {
404+ <span class="card-tag">(tag.name.clone())</span>
405+ }
406+ }
384 if let Some(parts) = subtasks.clone() {407 if let Some(parts) = subtasks.clone() {
385 <span class=(class!("card-subtasks", "card-subtasks-open" if subtasks_open))>(format!("{parts} \u{2630}"))</span>408 <span class=(class!("card-subtasks", "card-subtasks-open" if subtasks_open))>(format!("{parts} \u{2630}"))</span>
386 }409 }
@@ -509,6 +532,7 @@ struct BoardQuery {
509 sort: Option<String>,532 sort: Option<String>,
510 confirm: Option<String>,533 confirm: Option<String>,
511 new: Option<String>,534 new: Option<String>,
535+ tag: Option<String>,
512 }536 }
513 537
514 /// The noun a sort key shows in the `<select>` — terse, no explainer.538 /// The noun a sort key shows in the `<select>` — terse, no explainer.
@@ -535,6 +559,10 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
535 <main class="scaffold-note"><p>(t(lang, Key::SomethingWentWrong))</p></main>559 <main class="scaffold-note"><p>(t(lang, Key::SomethingWentWrong))</p></main>
536 };560 };
537 };561 };
562+ let tags = {
563+ let store = accounts(cx).store().clone();
564+ store.tags(&view_data.board.id).await?
565+ };
538 let today = OffsetDateTime::now_utc().date();566 let today = OffsetDateTime::now_utc().date();
539 let overdue = view_data.overdue_count(today);567 let overdue = view_data.overdue_count(today);
540 let blocked = view_data.blocked_count();568 let blocked = view_data.blocked_count();
@@ -567,6 +595,8 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
567 // an open task wins and `new` is ignored.595 // an open task wins and `new` is ignored.
568 let open_new = may_write && query.new.is_some() && open_task.is_none();596 let open_new = may_write && query.new.is_some() && open_task.is_none();
569 let sort = valid_sort(query.sort.as_deref()).to_string();597 let sort = valid_sort(query.sort.as_deref()).to_string();
598+ let tag_filter = valid_tag(query.tag.as_deref(), &tags);
599+ let default_tag_id = tags.iter().find(|tag| tag.is_default).map(|tag| tag.id.as_str());
570 let refusal = match (query.on.as_deref(), query.refusal.as_deref()) {600 let refusal = match (query.on.as_deref(), query.refusal.as_deref()) {
571 (Some("create_task") | Some("move_card"), Some(code)) => Refusal::from_code(code),601 (Some("create_task") | Some("move_card"), Some(code)) => Refusal::from_code(code),
572 _ => None,602 _ => None,
@@ -598,6 +628,20 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
598 <path d="M4 6l4 4 4-4"></path>628 <path d="M4 6l4 4 4-4"></path>
599 </svg>629 </svg>
600 </form>630 </form>
631+ <form class="field-box field-box-sort" method="get" action="/">
632+ <span class="field-text">(t(lang, Key::Project))</span>
633+ <select class="status-select" name="tag" data-autosubmit="">
634+ <option value="" selected=(tag_filter.is_none())>(t(lang, Key::AllTags))</option>
635+ for tag in &tags {
636+ <option value=(tag.id.clone()) selected=(tag_filter.as_deref() == Some(tag.id.as_str()))>(tag.name.clone())</option>
637+ }
638+ </select>
639+ <svg class="glyph" width="14" height="14" viewBox="0 0 16 16" fill="none"
640+ stroke="currentColor" stroke-width="1.5" stroke-linecap="round"
641+ stroke-linejoin="round" aria-hidden="true">
642+ <path d="M4 6l4 4 4-4"></path>
643+ </svg>
644+ </form>
601 <div class="spacer"></div>645 <div class="spacer"></div>
602 if overdue > 0 { <span class="chip chip-overdue">(format!("{overdue} {}", t(lang, Key::Overdue)))</span> }646 if overdue > 0 { <span class="chip chip-overdue">(format!("{overdue} {}", t(lang, Key::Overdue)))</span> }
603 if blocked > 0 { <span class="chip chip-blocked">(format!("{blocked} {}", t(lang, Key::Blocked)))</span> }647 if blocked > 0 { <span class="chip chip-blocked">(format!("{blocked} {}", t(lang, Key::Blocked)))</span> }
@@ -607,7 +651,7 @@ pub async fn board_page(cx: &Cx, user: &User) -> Result {
607 }651 }
608 <main class="board-stage">652 <main class="board-stage">
609 <div class="board-columns">653 <div class="board-columns">
610- (board_columns(cx, sort.clone()).await?)654+ (board_columns(cx, sort.clone(), tag_filter.clone(), default_tag_id).await?)
611 </div>655 </div>
612 </main>656 </main>
613 if let Some(task_id) = &open_task {657 if let Some(task_id) = &open_task {
@@ -644,6 +688,7 @@ mod sort_tests {
644 blocks: Vec::new(),688 blocks: Vec::new(),
645 subtask_total: 0,689 subtask_total: 0,
646 subtask_done: 0,690 subtask_done: 0,
691+ tag: None,
647 }692 }
648 }693 }
649 694
crates/izlek-web/src/detail.rsmodified+65 -0
@@ -88,6 +88,9 @@ pub struct DetailSnapshot {
88 pub attachment_limit_mb: u64,88 pub attachment_limit_mb: u64,
89 pub notifications: Vec<NotificationLine>,89 pub notifications: Vec<NotificationLine>,
90 pub may_administer: bool,90 pub may_administer: bool,
91+ /// Every tag on this workspace's board, in the admin's hand-set order —
92+ /// the tag field reads both its options and its current value from here.
93+ pub tags: Vec<izlek_core::store::Tag>,
91 }94 }
92 95
93 /// One send's fate, joined to the sends of its decision's event.96 /// One send's fate, joined to the sends of its decision's event.
@@ -360,6 +363,13 @@ async fn load_snapshot(
360 linkable.sort_by(|a, b| a.id.cmp(&b.id));363 linkable.sort_by(|a, b| a.id.cmp(&b.id));
361 }364 }
362 365
366+ // The tag field's options: every tag on the board, in the admin's
367+ // hand-set order. A workspace with no board yet has no tags either.
368+ let tags = match store.board(&user.workspace_id).await? {
369+ Some(board) => store.tags(&board.id).await?,
370+ None => Vec::new(),
371+ };
372+
363 let may_write = user.role.can_write_tasks();373 let may_write = user.role.can_write_tasks();
364 let may_administer = user.role.can_administer();374 let may_administer = user.role.can_administer();
365 let lang = Lang::from_code(&user.language);375 let lang = Lang::from_code(&user.language);
@@ -446,6 +456,7 @@ async fn load_snapshot(
446 allowed_file_types,456 allowed_file_types,
447 attachment_limit_mb,457 attachment_limit_mb,
448 notifications,458 notifications,
459+ tags,
449 may_administer,460 may_administer,
450 me: Me::from(&user),461 me: Me::from(&user),
451 today: OffsetDateTime::now_utc().date(),462 today: OffsetDateTime::now_utc().date(),
@@ -515,6 +526,34 @@ async fn save_task(cx: &Cx, Form(input): Form<SaveTaskForm>) -> Redirect {
515 redirect(cx, None)526 redirect(cx, None)
516 }527 }
517 528
529+#[derive(Deserialize)]
530+struct SetTaskTagForm {
531+ task_id: String,
532+ tag_id: String,
533+}
534+
535+/// Files a task under a tag. A Viewer can read tags but not set them; the
536+/// tag has to be this workspace board's own. No activity is recorded and no
537+/// mail follows — re-labeling a card is not a thing anybody needs told
538+/// about.
539+#[route(POST "/api/set_task_tag")]
540+async fn set_task_tag(cx: &Cx, Form(input): Form<SetTaskTagForm>) -> Redirect {
541+ let (actor, _) = match writer_and_task(cx, &input.task_id).await {
542+ Ok(pair) => pair,
543+ Err(refusal) => return redirect(cx, Some(refusal)),
544+ };
545+ let store = accounts(cx).store().clone();
546+ let Some(board) = store.board(&actor.workspace_id).await? else {
547+ return redirect(cx, Some(Refusal::Unavailable));
548+ };
549+ let tags = store.tags(&board.id).await?;
550+ if !tags.iter().any(|tag| tag.id == input.tag_id) {
551+ return redirect(cx, Some(Refusal::NotFound));
552+ }
553+ store.set_task_tag(&input.task_id, &input.tag_id).await?;
554+ redirect(cx, None)
555+}
556+
518 /// Puts someone on a task. A Viewer can neither do this nor be the target.557 /// Puts someone on a task. A Viewer can neither do this nor be the target.
519 #[route(POST "/api/assign")]558 #[route(POST "/api/assign")]
520 async fn assign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {559 async fn assign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
@@ -542,6 +581,7 @@ async fn assign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
542 .record_activity(581 .record_activity(
543 &input.task_id,582 &input.task_id,
544 Some(&actor.id),583 Some(&actor.id),
584+ Some(&person.id),
545 &ActivityKind::Assigned,585 &ActivityKind::Assigned,
546 &person.display_name,586 &person.display_name,
547 OffsetDateTime::now_utc(),587 OffsetDateTime::now_utc(),
@@ -573,6 +613,7 @@ async fn unassign(cx: &Cx, Form(input): Form<PersonForm>) -> Redirect {
573 .record_activity(613 .record_activity(
574 &input.task_id,614 &input.task_id,
575 Some(&actor.id),615 Some(&actor.id),
616+ Some(&person.id),
576 &ActivityKind::Unassigned,617 &ActivityKind::Unassigned,
577 &person.display_name,618 &person.display_name,
578 OffsetDateTime::now_utc(),619 OffsetDateTime::now_utc(),
@@ -611,6 +652,7 @@ async fn link_tasks(cx: &Cx, Form(input): Form<LinkForm>) -> Redirect {
611 .record_activity(652 .record_activity(
612 &input.task_id,653 &input.task_id,
613 Some(&actor.id),654 Some(&actor.id),
655+ None,
614 &ActivityKind::Linked,656 &ActivityKind::Linked,
615 &other.row.task_key,657 &other.row.task_key,
616 now,658 now,
@@ -644,6 +686,7 @@ async fn unlink_tasks(cx: &Cx, Form(input): Form<LinkForm>) -> Redirect {
644 .record_activity(686 .record_activity(
645 &input.task_id,687 &input.task_id,
646 Some(&actor.id),688 Some(&actor.id),
689+ None,
647 &ActivityKind::Unlinked,690 &ActivityKind::Unlinked,
648 &other.row.task_key,691 &other.row.task_key,
649 now,692 now,
@@ -742,6 +785,7 @@ async fn set_parent(cx: &Cx, Form(input): Form<ParentForm>) -> Redirect {
742 .record_activity(785 .record_activity(
743 &input.task_id,786 &input.task_id,
744 Some(&actor.id),787 Some(&actor.id),
788+ None,
745 &kind,789 &kind,
746 &other_key,790 &other_key,
747 OffsetDateTime::now_utc(),791 OffsetDateTime::now_utc(),
@@ -852,6 +896,7 @@ async fn delete_file(cx: &Cx, Form(input): Form<FileIdForm>) -> Redirect {
852 .record_activity(896 .record_activity(
853 &attachment.task_id,897 &attachment.task_id,
854 Some(&user.id),898 Some(&user.id),
899+ None,
855 &izlek_core::detail::ActivityKind::FileRemoved,900 &izlek_core::detail::ActivityKind::FileRemoved,
856 &attachment.file_name,901 &attachment.file_name,
857 time::OffsetDateTime::now_utc(),902 time::OffsetDateTime::now_utc(),
@@ -1694,6 +1739,7 @@ pub async fn task_modal(cx: &Cx, task_id: &str, confirm_delete: bool, tab: Tab)
1694 allowed_file_types,1739 allowed_file_types,
1695 attachment_limit_mb: _,1740 attachment_limit_mb: _,
1696 notifications,1741 notifications,
1742+ tags,
1697 may_administer: _,1743 may_administer: _,
1698 } = snapshot;1744 } = snapshot;
1699 let lang = Lang::from_code(&me.language);1745 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)
1828 </span>1874 </span>
1829 }1875 }
1830 </div>1876 </div>
1877+ <div class="detail-field detail-field-tag">
1878+ <span class="detail-label">(t(lang, Key::Project))</span>
1879+ if may_write {
1880+ <form class="status-form" method="post" action="/api/set_task_tag">
1881+ <input type="hidden" name="task_id" value=(detail.id.clone())>
1882+ <select class="status-select" name="tag_id" data-autosubmit="">
1883+ for tag in &tags {
1884+ <option value=(tag.id.clone()) selected=(Some(tag.id.as_str()) == detail.tag.as_ref().map(|t| t.id.as_str()))>(tag.name.clone())</option>
1885+ }
1886+ </select>
1887+ </form>
1888+ } else {
1889+ <span class="field-box">
1890+ <span class="field-text">(
1891+ detail.tag.as_ref().map(|tag| tag.name.clone()).unwrap_or_default()
1892+ )</span>
1893+ </span>
1894+ }
1895+ </div>
1831 <div class="detail-field">1896 <div class="detail-field">
1832 <span class="detail-label">(t(lang, Key::Deadline))</span>1897 <span class="detail-label">(t(lang, Key::Deadline))</span>
1833 (deadline_control(cx, &detail, today, may_write, lang).await?)1898 (deadline_control(cx, &detail, today, may_write, lang).await?)
crates/izlek-web/src/files.rsmodified+1 -0
@@ -424,6 +424,7 @@ async fn upload(
424 .record_activity(424 .record_activity(
425 &task_id,425 &task_id,
426 Some(&user.id),426 Some(&user.id),
427+ None,
427 &izlek_core::detail::ActivityKind::FileAdded,428 &izlek_core::detail::ActivityKind::FileAdded,
428 &label,429 &label,
429 OffsetDateTime::now_utc(),430 OffsetDateTime::now_utc(),
crates/izlek-web/src/i18n.rsmodified+55 -0
@@ -102,10 +102,23 @@ pub enum Key {
102 // Topbar nav / chrome shared by board.rs, rules.rs, logs.rs, settings.rs.102 // Topbar nav / chrome shared by board.rs, rules.rs, logs.rs, settings.rs.
103 NavBoard,103 NavBoard,
104 NavMailRules,104 NavMailRules,
105+ NavTags,
105 NavLogs,106 NavLogs,
106 NavSettings,107 NavSettings,
107 AdminOnly,108 AdminOnly,
108 109
110+ // tags.rs — Project/AllTags also serve board.rs's filter and detail.rs.
111+ NewTag,
112+ NameLabel,
113+ AddTag,
114+ SaveTag,
115+ EditThisTag,
116+ DeleteThisTag,
117+ MoveTagUp,
118+ MoveTagDown,
119+ Project,
120+ AllTags,
121+
109 // settings.rs122 // settings.rs
110 YourProfile,123 YourProfile,
111 Remove,124 Remove,
@@ -329,6 +342,13 @@ pub enum Key {
329 Oldest,342 Oldest,
330 From,343 From,
331 To,344 To,
345+ // people.rs
346+ TasksOpenLabel,
347+ TasksDoneLabel,
348+ TasksCreatedLabel,
349+ CommentsLabel,
350+ RecentActivity,
351+ MailBatchLabel,
332 }352 }
333 353
334 /// The lone templated phrase — a name in the middle reads worse as two354 /// 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 {
497 (AdminOnly, En) => "Admin only",517 (AdminOnly, En) => "Admin only",
498 (AdminOnly, Tr) => "Sadece yönetici",518 (AdminOnly, Tr) => "Sadece yönetici",
499 519
520+ (NavTags, En) => "Tags",
521+ (NavTags, Tr) => "Etiketler",
522+ (NewTag, En) => "New tag",
523+ (NewTag, Tr) => "Yeni etiket",
524+ (NameLabel, En) => "NAME",
525+ (NameLabel, Tr) => "İSİM",
526+ (AddTag, En) => "Add tag",
527+ (AddTag, Tr) => "Etiket ekle",
528+ (SaveTag, En) => "Save tag",
529+ (SaveTag, Tr) => "Etiketi kaydet",
530+ (EditThisTag, En) => "Edit this tag",
531+ (EditThisTag, Tr) => "Bu etiketi düzenle",
532+ (DeleteThisTag, En) => "Delete this tag",
533+ (DeleteThisTag, Tr) => "Bu etiketi sil",
534+ (MoveTagUp, En) => "Move up",
535+ (MoveTagUp, Tr) => "Yukarı taşı",
536+ (MoveTagDown, En) => "Move down",
537+ (MoveTagDown, Tr) => "Aşağı taşı",
538+ (Project, En) => "Project",
539+ (Project, Tr) => "Proje",
540+ (AllTags, En) => "All",
541+ (AllTags, Tr) => "Tümü",
542+
500 (YourProfile, En) => "Your profile",543 (YourProfile, En) => "Your profile",
501 (YourProfile, Tr) => "Profilin",544 (YourProfile, Tr) => "Profilin",
502 (Remove, En) => "Remove",545 (Remove, En) => "Remove",
@@ -936,6 +979,18 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
936 (From, Tr) => "Başlangıç",979 (From, Tr) => "Başlangıç",
937 (To, En) => "To",980 (To, En) => "To",
938 (To, Tr) => "Bitiş",981 (To, Tr) => "Bitiş",
982+ (TasksOpenLabel, En) => "Open tasks",
983+ (TasksOpenLabel, Tr) => "Açık görevler",
984+ (TasksDoneLabel, En) => "Done tasks",
985+ (TasksDoneLabel, Tr) => "Biten görevler",
986+ (TasksCreatedLabel, En) => "Tasks created",
987+ (TasksCreatedLabel, Tr) => "Oluşturulan görevler",
988+ (CommentsLabel, En) => "Comments",
989+ (CommentsLabel, Tr) => "Yorumlar",
990+ (RecentActivity, En) => "Recent activity",
991+ (RecentActivity, Tr) => "Son etkinlik",
992+ (MailBatchLabel, En) => "Mail delay (minutes)",
993+ (MailBatchLabel, Tr) => "Posta gecikmesi (dakika)",
939 }994 }
940 }995 }
941 996
crates/izlek-web/src/layout.rsmodified+11 -5
@@ -124,6 +124,7 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result {
124 <div class="user-menu-name">(me.display_name.clone())</div>124 <div class="user-menu-name">(me.display_name.clone())</div>
125 <div class="user-menu-email">(me.email.clone())</div>125 <div class="user-menu-email">(me.email.clone())</div>
126 <div class="user-menu-role">(t(lang, role_key))</div>126 <div class="user-menu-role">(t(lang, role_key))</div>
127+ <a class="user-menu-item" href=(format!("/people/{}", me.id))>(t(lang, Key::YourProfile))</a>
127 <form class="user-menu-item-form" method="post" action="/api/sign_out" data-hard="">128 <form class="user-menu-item-form" method="post" action="/api/sign_out" data-hard="">
128 <button class="user-menu-item" type="submit">(t(lang, Key::SignOut))</button>129 <button class="user-menu-item" type="submit">(t(lang, Key::SignOut))</button>
129 </form>130 </form>
@@ -132,23 +133,25 @@ pub async fn user_menu(cx: &Cx, me: &crate::detail::Me, lang: Lang) -> Result {
132 }133 }
133 }134 }
134 135
135-/// The four signed-in pages, as the topbar nav links between them.136+/// The five signed-in pages, as the topbar nav links between them.
136 #[derive(Clone, Copy, PartialEq)]137 #[derive(Clone, Copy, PartialEq)]
137 pub enum NavPage {138 pub enum NavPage {
138 Board,139 Board,
139 Rules,140 Rules,
140 Logs,141 Logs,
142+ Tags,
141 Settings,143 Settings,
142 }144 }
143 145
144 impl NavPage {146 impl NavPage {
145- const ALL: [Self; 4] = [Self::Board, Self::Rules, Self::Logs, Self::Settings];147+ const ALL: [Self; 5] = [Self::Board, Self::Rules, Self::Logs, Self::Tags, Self::Settings];
146 148
147 fn href(self) -> &'static str {149 fn href(self) -> &'static str {
148 match self {150 match self {
149 Self::Board => "/",151 Self::Board => "/",
150 Self::Rules => "/rules",152 Self::Rules => "/rules",
151 Self::Logs => "/logs",153 Self::Logs => "/logs",
154+ Self::Tags => "/tags",
152 Self::Settings => "/settings",155 Self::Settings => "/settings",
153 }156 }
154 }157 }
@@ -158,13 +161,14 @@ impl NavPage {
158 Self::Board => Key::NavBoard,161 Self::Board => Key::NavBoard,
159 Self::Rules => Key::NavMailRules,162 Self::Rules => Key::NavMailRules,
160 Self::Logs => Key::NavLogs,163 Self::Logs => Key::NavLogs,
164+ Self::Tags => Key::NavTags,
161 Self::Settings => Key::NavSettings,165 Self::Settings => Key::NavSettings,
162 }166 }
163 }167 }
164 }168 }
165 169
166-/// The topbar's page nav, shared by every signed-in page: the four pages170+/// The topbar's page nav, shared by every signed-in page: the five pages
167-/// with the current one marked, the admin-only ones (rules, logs) shown171+/// with the current one marked, the admin-only ones (rules, logs, tags) shown
168 /// only to roles that can administer. Plain `<a>`s — the soft-nav forwarder172 /// only to roles that can administer. Plain `<a>`s — the soft-nav forwarder
169 /// swaps them like any same-origin link, so `data-hard` stays off.173 /// swaps them like any same-origin link, so `data-hard` stays off.
170 pub async fn topbar_nav(cx: &Cx, active: NavPage, role: izlek_core::Role, lang: Lang) -> Result {174 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:
172 cx =>176 cx =>
173 <nav class="topbar-nav-links">177 <nav class="topbar-nav-links">
174 for page in NavPage::ALL {178 for page in NavPage::ALL {
175- if role.can_administer() || !matches!(page, NavPage::Rules | NavPage::Logs) {179+ if role.can_administer() || !matches!(page, NavPage::Rules | NavPage::Logs | NavPage::Tags) {
176 <a180 <a
177 class=(if page == active { "topbar-nav topbar-nav-on" } else { "topbar-nav" })181 class=(if page == active { "topbar-nav topbar-nav-on" } else { "topbar-nav" })
178 href=(page.href())182 href=(page.href())
@@ -637,7 +641,9 @@ pub async fn live_script(cx: &Cx) -> Result {
637 var path = window.location.pathname; \641 var path = window.location.pathname; \
638 if (path === '/logs') { return topic !== 'board' && topic !== 'task'; } \642 if (path === '/logs') { return topic !== 'board' && topic !== 'task'; } \
639 if (path === '/rules') { return topic === 'rules' || topic === 'members'; } \643 if (path === '/rules') { return topic === 'rules' || topic === 'members'; } \
644+ if (path === '/tags') { return topic === 'tags' || topic === 'members'; } \
640 if (path === '/settings') { return topic === 'settings' || topic === 'members'; } \645 if (path === '/settings') { return topic === 'settings' || topic === 'members'; } \
646+ if (path.indexOf('/people/') === 0) { return topic === 'members'; } \
641 return topic === 'board' || topic === 'task' || topic === 'members'; \647 return topic === 'board' || topic === 'task' || topic === 'members'; \
642 } \648 } \
643 try { \649 try { \
crates/izlek-web/src/lib.rsmodified+2 -0
@@ -13,9 +13,11 @@ pub mod layout;
13 pub mod live;13 pub mod live;
14 pub mod logs;14 pub mod logs;
15 pub mod pages;15 pub mod pages;
16+pub mod people;
16 pub mod photo;17 pub mod photo;
17 pub mod rules;18 pub mod rules;
18 pub mod server;19 pub mod server;
19 pub mod settings;20 pub mod settings;
20 pub mod sheet;21 pub mod sheet;
21 pub mod smtp;22 pub mod smtp;
23+pub mod tags;
crates/izlek-web/src/live.rsmodified+3 -1
@@ -56,7 +56,9 @@ pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
56 /// moved, because being told is itself knowing something about the queue.56 /// moved, because being told is itself knowing something about the queue.
57 fn may_hear(topic: &Topic, admin: bool) -> bool {57 fn may_hear(topic: &Topic, admin: bool) -> bool {
58 match topic {58 match topic {
59- Topic::Board | Topic::Task(_) | Topic::Members => true,59+ // Tags ride with the board: every member sees a card's tag, so being
60+ // told the tags moved tells them nothing they cannot already read.
61+ Topic::Board | Topic::Task(_) | Topic::Members | Topic::Tags => true,
60 Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin,62 Topic::Queue | Topic::Rules | Topic::Settings | Topic::Activity => admin,
61 }63 }
62 }64 }
crates/izlek-web/src/main.rsmodified+37 -0
@@ -13,6 +13,43 @@ async fn healthz() -> Result<&'static str> {
13 13
14 #[tokio::main]14 #[tokio::main]
15 async fn main() {15 async fn main() {
16+ let args: Vec<String> = std::env::args().collect();
17+ if args.get(1).map(|s| s.as_str()) == Some("reconcile") {
18+ let mut dry_run = false;
19+ let mut yes = false;
20+ for arg in &args[2..] {
21+ match arg.as_str() {
22+ "--dry-run" => dry_run = true,
23+ "--yes" => yes = true,
24+ _ => {
25+ eprintln!("izlek reconcile: unknown option {arg}");
26+ std::process::exit(2);
27+ }
28+ }
29+ }
30+ let config = match izlek_core::Config::load() {
31+ Ok(config) => config,
32+ Err(problem) => {
33+ eprintln!("izlek: {problem}");
34+ std::process::exit(2);
35+ }
36+ };
37+ if let Err(problem) = izlek_core::store::reconcile(
38+ &config.database.to_string_lossy(),
39+ izlek_core::store::ReconcileOptions {
40+ dry_run,
41+ yes,
42+ auto: false,
43+ },
44+ )
45+ .await
46+ {
47+ eprintln!("izlek reconcile: {problem}");
48+ std::process::exit(1);
49+ }
50+ return;
51+ }
52+
16 // config/izlek.toml is read here, before anything is opened, and written with53 // config/izlek.toml is read here, before anything is opened, and written with
17 // development defaults if it is not there yet. A broken key stops the54 // development defaults if it is not there yet. A broken key stops the
18 // boot with its name in the message: the failure this prevents is not an55 // boot with its name in the message: the failure this prevents is not an
crates/izlek-web/src/people.rsadded+171 -0
@@ -0,0 +1,171 @@
1+//! A member's profile: who they are, and what they have done here. Any
2+//! signed-in member of the workspace may read it, and nothing on the page
3+//! writes — the one editor a profile has stays where it already lives, on
4+//! `/settings?section=profile`, which the page links to for its own person
5+//! and nowhere else. A stranger and a missing id read the same: the router's
6+//! own not-found, never a `403` — `photo.rs` keeps the same rule for bytes.
7+
8+use topcoat::Result;
9+use topcoat::context::Cx;
10+use topcoat::router::error::not_found;
11+use topcoat::router::{page, path_param};
12+use topcoat::view::view;
13+
14+use izlek_core::detail::ActivityKind;
15+use izlek_core::store::{ActivityFilter, Dir, FeedPage};
16+
17+use crate::i18n::{Key, Lang, t};
18+use crate::server::{accounts, require_user};
19+
20+path_param!(user_id);
21+
22+/// The account line the members table renders, read the same way here: a
23+/// named state (owner, invited) while there is nothing newer to say, and the
24+/// last-seen day once there is.
25+fn account_line(lang: Lang, is_owner: bool, has_signed_in: bool, last_day: Option<String>) -> String {
26+ if is_owner {
27+ t(lang, Key::OwnerStatus).to_string()
28+ } else if !has_signed_in {
29+ t(lang, Key::InvitedStatus).to_string()
30+ } else if let Some(day) = last_day {
31+ crate::i18n::last_seen_label(lang, &day)
32+ } else {
33+ t(lang, Key::ActiveStatus).to_string()
34+ }
35+}
36+
37+/// The verb a feed line opens with. The task kinds read through
38+/// [`crate::i18n::activity_kind_word`]; the account kinds are not all in that
39+/// table and would fall through as raw tokens (`profile_saved`), so the ones
40+/// with a translated word take it here.
41+fn kind_word(lang: Lang, kind: &ActivityKind) -> String {
42+ match kind {
43+ ActivityKind::WorkspaceClaimed => t(lang, Key::ActWorkspaceClaimed).into(),
44+ ActivityKind::Joined => t(lang, Key::ActJoined).into(),
45+ ActivityKind::SignedIn => t(lang, Key::ActSignedIn).into(),
46+ ActivityKind::SignedOut => t(lang, Key::ActSignedOut).into(),
47+ ActivityKind::PasswordChanged => t(lang, Key::ActPasswordChanged).into(),
48+ ActivityKind::ProfileSaved => t(lang, Key::ActProfileSaved).into(),
49+ ActivityKind::SenderSaved => t(lang, Key::ActSenderSaved).into(),
50+ ActivityKind::LimitsSaved => t(lang, Key::ActLimitsSaved).into(),
51+ ActivityKind::TestMailSent => t(lang, Key::ActTestMailSent).into(),
52+ ActivityKind::MessageSent => t(lang, Key::ActMessageSent).into(),
53+ other => crate::i18n::activity_kind_word(lang, other.as_str()),
54+ }
55+}
56+
57+/// A person's page. `/people/{user_id}`.
58+#[page("/people/{user_id}")]
59+async fn people_page(cx: &Cx) -> Result {
60+ let user = match require_user(cx).await {
61+ Ok(user) => user,
62+ Err(_) => return Err(not_found().into()),
63+ };
64+ let lang = Lang::from_code(&user.language);
65+ let store = accounts(cx).store().clone();
66+ let target_id: &str = path_param::<UserId>(cx);
67+ let Some(person) = store.user(target_id).await? else {
68+ return Err(not_found().into());
69+ };
70+ if person.workspace_id != user.workspace_id {
71+ return Err(not_found().into());
72+ }
73+
74+ let zone = izlek_core::detail::parse_zone(&user.timezone);
75+ let mine = person.id == user.id;
76+ let who = izlek_core::board::Person {
77+ id: person.id.clone(),
78+ display_name: person.display_name.clone(),
79+ has_photo: person.has_photo,
80+ };
81+ let is_owner = store
82+ .owner()
83+ .await?
84+ .is_some_and(|owner| owner.id == person.id);
85+ let account = account_line(
86+ lang,
87+ is_owner,
88+ person.has_signed_in(),
89+ person
90+ .last_signed_in_at
91+ .map(|at| izlek_core::board::day_label(at.to_offset(zone).date())),
92+ );
93+ let role_key = match person.role {
94+ izlek_core::Role::Admin => Key::RoleAdminOption,
95+ izlek_core::Role::Member => Key::RoleMemberOption,
96+ izlek_core::Role::Viewer => Key::RoleViewerOption,
97+ };
98+ let stats = store.user_stats(&person.id).await?;
99+ // A short list, not the feed: the newest few lines are enough to see what
100+ // the person has been near lately; the whole trail already has a page.
101+ let feed = store
102+ .recent_activity(
103+ 8,
104+ FeedPage::Newest,
105+ Dir::Newest,
106+ &ActivityFilter { actor: Some(person.id.clone()), ..Default::default() },
107+ )
108+ .await?;
109+
110+ view! {
111+ cx =>
112+ <header class="topbar">
113+ (crate::layout::mark(cx).await?)
114+ (crate::layout::topbar_nav(cx, crate::layout::NavPage::Settings, user.role, lang).await?)
115+ <div class="spacer"></div>
116+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?)
117+ </header>
118+
119+ <main class="people-shell">
120+ <section class="panel" id="profile">
121+ <div class="panel-head">
122+ (crate::layout::avatar(cx, &who, "avatar-lg").await?)
123+ <h2 class="panel-title">(person.display_name.clone())</h2>
124+ <span class="chip chip-role">(t(lang, role_key))</span>
125+ if mine {
126+ <a class="quiet" href="/settings?section=profile">(t(lang, Key::EditLabel))</a>
127+ }
128+ </div>
129+ <div class="panel-body">
130+ <p>(person.email.clone())</p>
131+ <p>(account)</p>
132+ </div>
133+ </section>
134+
135+ <section class="panel">
136+ <div class="panel-body">
137+ <dl class="people-stats">
138+ <div><dt>(t(lang, Key::TasksOpenLabel))</dt><dd>(stats.assigned_open)</dd></div>
139+ <div><dt>(t(lang, Key::TasksDoneLabel))</dt><dd>(stats.assigned_done)</dd></div>
140+ <div><dt>(t(lang, Key::TasksCreatedLabel))</dt><dd>(stats.created)</dd></div>
141+ <div><dt>(t(lang, Key::CommentsLabel))</dt><dd>(stats.comments)</dd></div>
142+ </dl>
143+ </div>
144+ </section>
145+
146+ <section class="panel">
147+ <div class="panel-head">
148+ <h2 class="panel-title">(t(lang, Key::RecentActivity))</h2>
149+ </div>
150+ <div class="panel-body">
151+ if feed.is_empty() {
152+ <p>(t(lang, Key::NothingYet))</p>
153+ }
154+ <ul class="people-feed">
155+ for line in feed {
156+ <li>
157+ <span>(kind_word(lang, &line.kind))</span>
158+ if let Some(title) = line.title {
159+ <span>(title)</span>
160+ }
161+ <span class="people-feed-day">(izlek_core::board::day_label(line.at.to_offset(zone).date()))</span>
162+ </li>
163+ }
164+ </ul>
165+ </div>
166+ </section>
167+ </main>
168+
169+ (crate::layout::escape_script(cx).await?)
170+ }
171+}
crates/izlek-web/src/server.rsmodified+6 -0
@@ -357,6 +357,8 @@ pub enum Refusal {
357 NotAnImage,357 NotAnImage,
358 /// A rule with no subject line: the mail it sends would arrive blank.358 /// A rule with no subject line: the mail it sends would arrive blank.
359 EmptySubject,359 EmptySubject,
360+ /// A tag with no name is not a tag the board can show.
361+ EmptyTag,
360 /// A message with no body: there is nothing for the recipient to read.362 /// A message with no body: there is nothing for the recipient to read.
361 EmptyBody,363 EmptyBody,
362 /// The date field did not hold a date.364 /// The date field did not hold a date.
@@ -419,6 +421,7 @@ impl Refusal {
419 }421 }
420 Refusal::NotAnImage => "That is not an image.".to_string(),422 Refusal::NotAnImage => "That is not an image.".to_string(),
421 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),423 Refusal::EmptySubject => "Give the rule a subject line.".to_string(),
424+ Refusal::EmptyTag => "Give the tag a name.".to_string(),
422 Refusal::EmptyBody => "Write something first.".to_string(),425 Refusal::EmptyBody => "Write something first.".to_string(),
423 Refusal::BadDeadline => "That is not a date.".to_string(),426 Refusal::BadDeadline => "That is not a date.".to_string(),
424 Refusal::Cycle => "That link would put this task behind itself.".to_string(),427 Refusal::Cycle => "That link would put this task behind itself.".to_string(),
@@ -477,6 +480,7 @@ impl Refusal {
477 // language off of, so it falls back to English like the rest.480 // language off of, so it falls back to English like the rest.
478 Refusal::BadSender(_) => self.message(),481 Refusal::BadSender(_) => self.message(),
479 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),482 Refusal::EmptySubject => "Kurala bir konu ver.".to_string(),
483+ Refusal::EmptyTag => "Etikete bir ad ver.".to_string(),
480 Refusal::EmptyBody => "Önce bir şey yaz.".to_string(),484 Refusal::EmptyBody => "Önce bir şey yaz.".to_string(),
481 Refusal::Rejected => "Bu işe yaramadı.".to_string(),485 Refusal::Rejected => "Bu işe yaramadı.".to_string(),
482 Refusal::RateLimited => {486 Refusal::RateLimited => {
@@ -526,6 +530,7 @@ impl Refusal {
526 "file-type" => Refusal::FileTypeNotAllowed,530 "file-type" => Refusal::FileTypeNotAllowed,
527 "not-an-image" => Refusal::NotAnImage,531 "not-an-image" => Refusal::NotAnImage,
528 "empty-subject" => Refusal::EmptySubject,532 "empty-subject" => Refusal::EmptySubject,
533+ "empty-tag" => Refusal::EmptyTag,
529 "empty-body" => Refusal::EmptyBody,534 "empty-body" => Refusal::EmptyBody,
530 "bad-deadline" => Refusal::BadDeadline,535 "bad-deadline" => Refusal::BadDeadline,
531 "cycle" => Refusal::Cycle,536 "cycle" => Refusal::Cycle,
@@ -581,6 +586,7 @@ impl Refusal {
581 Refusal::FileTypeNotAllowed => "file-type",586 Refusal::FileTypeNotAllowed => "file-type",
582 Refusal::NotAnImage => "not-an-image",587 Refusal::NotAnImage => "not-an-image",
583 Refusal::EmptySubject => "empty-subject",588 Refusal::EmptySubject => "empty-subject",
589+ Refusal::EmptyTag => "empty-tag",
584 Refusal::EmptyBody => "empty-body",590 Refusal::EmptyBody => "empty-body",
585 Refusal::BadDeadline => "bad-deadline",591 Refusal::BadDeadline => "bad-deadline",
586 Refusal::Cycle => "cycle",592 Refusal::Cycle => "cycle",
crates/izlek-web/src/settings.rsmodified+26 -5
@@ -39,6 +39,9 @@ use crate::server::{Refusal, accounts, mail, require_admin, require_user};
39 /// one (per the settings lane's note there).39 /// one (per the settings lane's note there).
40 pub const WIDEST_ATTACHMENT_MB: u64 = 500;40 pub const WIDEST_ATTACHMENT_MB: u64 = 500;
41 pub const WIDEST_PHOTO_MB: u64 = 20;41 pub const WIDEST_PHOTO_MB: u64 = 20;
42+/// The longest a notification may be held waiting for the rest of its
43+/// workflow. Two hours is already far past the point where a mail is news.
44+pub const LONGEST_BATCH_MINUTES: u32 = 120;
42 45
43 const MB: u64 = 1024 * 1024;46 const MB: u64 = 1024 * 1024;
44 47
@@ -277,6 +280,7 @@ struct SaveLimitsForm {
277 attachment_limit_mb: u64,280 attachment_limit_mb: u64,
278 photo_limit_mb: u64,281 photo_limit_mb: u64,
279 allowed_file_types: String,282 allowed_file_types: String,
283+ mail_batch_minutes: u32,
280 }284 }
281 285
282 /// Changes the workspace's limits. Admin-only, checked here.286 /// Changes the workspace's limits. Admin-only, checked here.
@@ -297,6 +301,7 @@ async fn save_limits(
297 || input.photo_limit_mb == 0301 || input.photo_limit_mb == 0
298 || input.attachment_limit_mb > WIDEST_ATTACHMENT_MB302 || input.attachment_limit_mb > WIDEST_ATTACHMENT_MB
299 || input.photo_limit_mb > WIDEST_PHOTO_MB303 || input.photo_limit_mb > WIDEST_PHOTO_MB
304+ || input.mail_batch_minutes > LONGEST_BATCH_MINUTES
300 {305 {
301 return Ok(saved_or_refused("save_limits", Some(Refusal::BadLimit)));306 return Ok(saved_or_refused("save_limits", Some(Refusal::BadLimit)));
302 }307 }
@@ -310,6 +315,7 @@ async fn save_limits(
310 input.attachment_limit_mb * MB,315 input.attachment_limit_mb * MB,
311 input.photo_limit_mb * MB,316 input.photo_limit_mb * MB,
312 &types,317 &types,
318+ input.mail_batch_minutes,
313 )319 )
314 .await;320 .await;
315 let refusal = match outcome {321 let refusal = match outcome {
@@ -926,7 +932,7 @@ async fn members_now(cx: &Cx, asking: &User) -> Result<Vec<Member>> {
926 .collect())932 .collect())
927 }933 }
928 934
929-async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String>)> {935+async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String>, u32)> {
930 let workspace = accounts(cx)936 let workspace = accounts(cx)
931 .store()937 .store()
932 .workspace()938 .workspace()
@@ -937,6 +943,7 @@ async fn limits_now(cx: &Cx, workspace_id: &str) -> Result<(u64, u64, Vec<String
937 workspace.attachment_limit_bytes / MB,943 workspace.attachment_limit_bytes / MB,
938 workspace.photo_limit_bytes / MB,944 workspace.photo_limit_bytes / MB,
939 workspace.allowed_file_types,945 workspace.allowed_file_types,
946+ workspace.mail_batch_minutes,
940 ))947 ))
941 }948 }
942 949
@@ -1171,8 +1178,8 @@ async fn settings_page(cx: &Cx) -> Result {
1171 None1178 None
1172 };1179 };
1173 let (limits, allowed_types) = if administers {1180 let (limits, allowed_types) = if administers {
1174- let (attachment, photo, types) = limits_now(cx, &user.workspace_id).await?;1181+ let (attachment, photo, types, batch) = limits_now(cx, &user.workspace_id).await?;
1175- (Some((attachment, photo)), types)1182+ (Some((attachment, photo, batch)), types)
1176 } else {1183 } else {
1177 (None, Vec::new())1184 (None, Vec::new())
1178 };1185 };
@@ -1466,7 +1473,9 @@ async fn settings_page(cx: &Cx) -> Result {
1466 </section>1473 </section>
1467 }1474 }
1468 1475
1469- if section == Section::Limits && let Some((attachment_limit_mb, photo_limit_mb)) = limits {1476+ if section == Section::Limits
1477+ && let Some((attachment_limit_mb, photo_limit_mb, mail_batch_minutes)) = limits
1478+ {
1470 <section class="panel" id="limits">1479 <section class="panel" id="limits">
1471 <div class="panel-head">1480 <div class="panel-head">
1472 <h2 class="panel-title">(t(lang, Key::WorkspaceLimits))</h2>1481 <h2 class="panel-title">(t(lang, Key::WorkspaceLimits))</h2>
@@ -1499,6 +1508,18 @@ async fn settings_page(cx: &Cx) -> Result {
1499 >1508 >
1500 </label>1509 </label>
1501 </div>1510 </div>
1511+ <label class="field">
1512+ <span class="field-label">(t(lang, Key::MailBatchLabel))</span>
1513+ <input
1514+ class="field-input"
1515+ type="number"
1516+ name="mail_batch_minutes"
1517+ min="0"
1518+ max=(LONGEST_BATCH_MINUTES.to_string())
1519+ value=(mail_batch_minutes.to_string())
1520+ required=""
1521+ >
1522+ </label>
1502 <label class="field">1523 <label class="field">
1503 <span class="field-label">(t(lang, Key::AllowedFileTypesLabel))</span>1524 <span class="field-label">(t(lang, Key::AllowedFileTypesLabel))</span>
1504 <input1525 <input
@@ -1558,7 +1579,7 @@ async fn settings_page(cx: &Cx) -> Result {
1558 <td class="member-col-name member-name">1579 <td class="member-col-name member-name">
1559 <span class="member-name-row">1580 <span class="member-name-row">
1560 (crate::layout::avatar(cx, &member_person, "avatar-sm").await?)1581 (crate::layout::avatar(cx, &member_person, "avatar-sm").await?)
1561- (member.display_name.clone())1582+ <a href=(format!("/people/{}", member.id))>(member.display_name.clone())</a>
1562 if member.is_you {1583 if member.is_you {
1563 <span class="member-you">(t(lang, Key::You))</span>1584 <span class="member-you">(t(lang, Key::You))</span>
1564 }1585 }
crates/izlek-web/src/tags.rsadded+364 -0
@@ -0,0 +1,364 @@
1+//! Task tags, ported from `izlek-web/src/rules.rs` onto topcoat's
2+//! server-rendered pages.
3+//!
4+//! The screen is the admin's, and so is every call behind it: a tag renames
5+//! what every member sees on the board and in the task modal, so writing one
6+//! is not something a Member may do even if they reach the endpoint directly.
7+//! The chip in the artboard says "Admin only"; the guard is in the handlers.
8+//!
9+//! There is no client-side signal here to hold which row is being edited —
10+//! every topcoat page is rendered fresh, server-side, on every request. Which
11+//! tag (if any) is open for editing rides `?edit=<tag_id>` on `/tags`
12+//! itself: the row renders as the rename form server-side instead of the
13+//! display row, no script required.
14+//!
15+//! The board's default tag ships no delete control: the store refuses the
16+//! delete anyway (every task falls back to it), and a control that cannot
17+//! act is not drawn.
18+
19+use std::sync::Arc;
20+
21+use serde::{Deserialize, Serialize};
22+use topcoat::Result;
23+use topcoat::context::Cx;
24+use topcoat::router::content::{Form, Json};
25+use topcoat::router::request::headers;
26+use topcoat::router::{HeaderName, StatusCode, header, page, query_params, route};
27+use topcoat::view::view;
28+
29+use izlek_core::store::{Store, Tag, User};
30+
31+use crate::i18n::{Key, Lang, t};
32+use crate::server::{Refusal, accounts, refusal_of, require_admin};
33+
34+/// One tag as the screen reads it: a name, an order and whether it is the
35+/// default every task wears when nothing else is chosen.
36+#[derive(Clone, Debug, Serialize)]
37+struct TagLine {
38+ id: String,
39+ name: String,
40+ position: i64,
41+ is_default: bool,
42+}
43+
44+/// Every tag on the workspace's own board, in the admin's hand-set order.
45+async fn tags_of(
46+ store: &Arc<dyn Store>,
47+ user: &User,
48+) -> std::result::Result<Vec<TagLine>, Refusal> {
49+ let Some(board) = store
50+ .board(&user.workspace_id)
51+ .await
52+ .map_err(|_| Refusal::Unavailable)?
53+ else {
54+ return Err(Refusal::Unavailable);
55+ };
56+ Ok(store
57+ .tags(&board.id)
58+ .await
59+ .map_err(|_| Refusal::Unavailable)?
60+ .into_iter()
61+ .map(|tag| TagLine {
62+ id: tag.id,
63+ name: tag.name,
64+ position: tag.position,
65+ is_default: tag.is_default,
66+ })
67+ .collect())
68+}
69+
70+/// The admin's store, once the tag id has been shown to name a tag on this
71+/// workspace's own board.
72+///
73+/// A tag id is opaque and arrives from the browser, so "not yours" and "not a
74+/// tag" are the same answer: neither tells the caller whether the id exists
75+/// somewhere else.
76+async fn tag_of_this_workspace(
77+ cx: &Cx,
78+ tag_id: &str,
79+) -> std::result::Result<(Arc<dyn Store>, User, Tag), Refusal> {
80+ let user = require_admin(cx).await?;
81+ let store = accounts(cx).store().clone();
82+ let board = store
83+ .board(&user.workspace_id)
84+ .await
85+ .map_err(|_| Refusal::Unavailable)?
86+ .ok_or(Refusal::Unavailable)?;
87+ let tag = store
88+ .tags(&board.id)
89+ .await
90+ .map_err(|_| Refusal::Unavailable)?
91+ .into_iter()
92+ .find(|tag| tag.id == tag_id)
93+ .ok_or(Refusal::NotFound)?;
94+ Ok((store, user, tag))
95+}
96+
97+/// The page a browser without script is sent back to on a 303: the page the
98+/// form was posted from, or home when there is no `Referer` to read.
99+fn back_to(cx: &Cx) -> String {
100+ headers(cx)
101+ .get(header::REFERER)
102+ .and_then(|value| value.to_str().ok())
103+ .unwrap_or("/")
104+ .to_string()
105+}
106+
107+/// A 303 to [`back_to`], carrying `refusal` as the body for
108+/// `crate::server::carry_refusal_on_redirect` to read and copy onto the query.
109+type Redirect = Result<(StatusCode, [(HeaderName, String); 1], Json<Option<Refusal>>)>;
110+
111+fn redirect(cx: &Cx, refusal: Option<Refusal>) -> Redirect {
112+ Ok((
113+ StatusCode::SEE_OTHER,
114+ [(header::LOCATION, back_to(cx))],
115+ Json(refusal),
116+ ))
117+}
118+
119+#[derive(Deserialize)]
120+struct CreateTagForm {
121+ name: String,
122+}
123+
124+/// Writes one tag. A duplicate name is the store's `Conflict`, which lands
125+/// here like every other store error: the admin sees "something went wrong"
126+/// and the list still shows the tag they collide with.
127+#[route(POST "/api/create_tag")]
128+async fn create_tag(cx: &Cx, Form(input): Form<CreateTagForm>) -> Redirect {
129+ let user = match require_admin(cx).await {
130+ Ok(user) => user,
131+ Err(refusal) => return redirect(cx, Some(refusal)),
132+ };
133+ let name = input.name.trim().to_string();
134+ if name.is_empty() {
135+ return redirect(cx, Some(Refusal::EmptyTag));
136+ }
137+ let store = accounts(cx).store().clone();
138+ let board = match store.board(&user.workspace_id).await {
139+ Ok(Some(board)) => board,
140+ _ => return redirect(cx, Some(Refusal::Unavailable)),
141+ };
142+ if store
143+ .create_tag(&board.id, &name, time::OffsetDateTime::now_utc())
144+ .await
145+ .is_err()
146+ {
147+ return redirect(cx, Some(Refusal::Unavailable));
148+ }
149+ redirect(cx, None)
150+}
151+
152+#[derive(Deserialize)]
153+struct RenameTagForm {
154+ tag_id: String,
155+ name: String,
156+}
157+
158+/// Rewrites a tag's name in place, guarded exactly like the rest — the tag
159+/// itself has to be this workspace's, or an id from elsewhere could be
160+/// renamed by an admin who never owned it.
161+#[route(POST "/api/rename_tag")]
162+async fn rename_tag(cx: &Cx, Form(input): Form<RenameTagForm>) -> Redirect {
163+ let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {
164+ Ok(triple) => triple,
165+ Err(refusal) => return redirect(cx, Some(refusal)),
166+ };
167+ let name = input.name.trim().to_string();
168+ if name.is_empty() {
169+ return redirect(cx, Some(Refusal::EmptyTag));
170+ }
171+ if store.rename_tag(&input.tag_id, &name).await.is_err() {
172+ return redirect(cx, Some(Refusal::Unavailable));
173+ }
174+ redirect(cx, None)
175+}
176+
177+#[derive(Deserialize)]
178+struct DeleteTagForm {
179+ tag_id: String,
180+}
181+
182+/// Removes a tag. The store refuses to delete the default — every task
183+/// without a tag wears it — and that refusal lands here as "unavailable";
184+/// the row itself ships no delete control in the first place.
185+#[route(POST "/api/delete_tag")]
186+async fn delete_tag(cx: &Cx, Form(input): Form<DeleteTagForm>) -> Redirect {
187+ let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {
188+ Ok(triple) => triple,
189+ Err(refusal) => return redirect(cx, Some(refusal)),
190+ };
191+ if store.delete_tag(&input.tag_id).await.is_err() {
192+ return redirect(cx, Some(Refusal::Unavailable));
193+ }
194+ redirect(cx, None)
195+}
196+
197+#[derive(Deserialize)]
198+struct MoveTagForm {
199+ tag_id: String,
200+ direction: String,
201+}
202+
203+/// Steps a tag up or down the board's hand-set order. A move off either end
204+/// is the store's no-op, not an error; a direction that is neither word is a
205+/// form gone wrong, and does nothing.
206+#[route(POST "/api/move_tag")]
207+async fn move_tag(cx: &Cx, Form(input): Form<MoveTagForm>) -> Redirect {
208+ let (store, _, _) = match tag_of_this_workspace(cx, &input.tag_id).await {
209+ Ok(triple) => triple,
210+ Err(refusal) => return redirect(cx, Some(refusal)),
211+ };
212+ let up = match input.direction.as_str() {
213+ "up" => true,
214+ "down" => false,
215+ _ => return redirect(cx, None),
216+ };
217+ if store.move_tag(&input.tag_id, up).await.is_err() {
218+ return redirect(cx, Some(Refusal::Unavailable));
219+ }
220+ redirect(cx, None)
221+}
222+
223+/// Which tag (if any) `/tags` renders open for editing.
224+#[query_params(error = redirect("/tags"))]
225+struct TagsQuery {
226+ edit: Option<String>,
227+}
228+
229+/// The "New tag" control and the form inside it. A `<details>` rather than
230+/// anything script-driven, so a browser with no script can still open it and
231+/// post the form.
232+async fn composer(cx: &Cx, refusal: Option<&Refusal>, lang: Lang) -> Result {
233+ view! {
234+ cx =>
235+ <details class="tag-new">
236+ <summary class="tag-new-open">(t(lang, Key::NewTag))</summary>
237+ <form class="tag-form" method="post" action="/api/create_tag">
238+ <label class="tag-field">
239+ <span class="field-label">(t(lang, Key::NameLabel))</span>
240+ <input class="field-input" type="text" name="name" maxlength="60" required="">
241+ </label>
242+ <div class="panel-foot">
243+ if let Some(refusal) = refusal {
244+ <span class="field-error">(refusal.message_in(lang))</span>
245+ }
246+ <button class="primary" type="submit">(t(lang, Key::AddTag))</button>
247+ </div>
248+ </form>
249+ </details>
250+ }
251+}
252+
253+/// One tag's row: the rename form in place of it when `editing`, its display
254+/// otherwise. The default tag draws no delete form — the store would refuse
255+/// it, and a control that cannot act is not drawn.
256+async fn tag_row(cx: &Cx, tag: &TagLine, editing: bool, refusal: Option<&Refusal>, lang: Lang) -> Result {
257+ if editing {
258+ return view! {
259+ cx =>
260+ <div class="tag-row">
261+ <form class="tag-form" method="post" action="/api/rename_tag">
262+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
263+ <label class="tag-field">
264+ <span class="field-label">(t(lang, Key::NameLabel))</span>
265+ <input class="field-input" type="text" name="name" maxlength="60" required="" value=(tag.name.clone())>
266+ </label>
267+ <div class="panel-foot">
268+ if let Some(refusal) = refusal {
269+ <span class="field-error">(refusal.message_in(lang))</span>
270+ }
271+ <a class="quiet" href="/tags">(t(lang, Key::Cancel))</a>
272+ <button class="primary" type="submit">(t(lang, Key::SaveTag))</button>
273+ </div>
274+ </form>
275+ </div>
276+ };
277+ }
278+
279+ view! {
280+ cx =>
281+ <div class="tag-row">
282+ <span class="tag-name">(tag.name.clone())</span>
283+
284+ <a class="quiet" href=(format!("/tags?edit={}", tag.id)) title=(t(lang, Key::EditThisTag))>(t(lang, Key::EditLabel))</a>
285+
286+ <form method="post" action="/api/move_tag">
287+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
288+ <input type="hidden" name="direction" value="up">
289+ <button class="quiet" type="submit" title=(t(lang, Key::MoveTagUp)) aria-label=(t(lang, Key::MoveTagUp))>("\u{2191}")</button>
290+ </form>
291+ <form method="post" action="/api/move_tag">
292+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
293+ <input type="hidden" name="direction" value="down">
294+ <button class="quiet" type="submit" title=(t(lang, Key::MoveTagDown)) aria-label=(t(lang, Key::MoveTagDown))>("\u{2193}")</button>
295+ </form>
296+
297+ if !tag.is_default {
298+ <form method="post" action="/api/delete_tag">
299+ <input type="hidden" name="tag_id" value=(tag.id.clone())>
300+ <button class="quiet quiet-danger" type="submit" title=(t(lang, Key::DeleteThisTag))>(t(lang, Key::Delete))</button>
301+ </form>
302+ }
303+ </div>
304+ }
305+}
306+
307+#[page("/tags")]
308+async fn tags_page(cx: &Cx) -> Result {
309+ let user = match require_admin(cx).await {
310+ Ok(user) => user,
311+ Err(refusal) => {
312+ return view! {
313+ <main class="scaffold-note">
314+ <p>(refusal.message())</p>
315+ <p><a href="/">(t(Lang::En, Key::BackToBoard))</a></p>
316+ </main>
317+ };
318+ }
319+ };
320+ let lang = Lang::from_code(&user.language);
321+ let store = accounts(cx).store().clone();
322+ let tags = match tags_of(&store, &user).await {
323+ Ok(tags) => tags,
324+ Err(refusal) => {
325+ return view! {
326+ <main class="scaffold-note">
327+ <p>(refusal.message_in(lang))</p>
328+ <p><a href="/">(t(lang, Key::BackToBoard))</a></p>
329+ </main>
330+ };
331+ }
332+ };
333+ let edit_id = query_params::<TagsQuery>(cx)?.edit.clone();
334+ let create_refusal = refusal_of(cx, "create_tag");
335+ let rename_refusal = refusal_of(cx, "rename_tag");
336+
337+ view! {
338+ <header class="topbar">
339+ (crate::layout::mark(cx).await?)
340+ (crate::layout::topbar_nav(cx, crate::layout::NavPage::Tags, user.role, lang).await?)
341+ <div class="spacer"></div>
342+ (crate::layout::user_menu(cx, &crate::detail::Me::from(&user), lang).await?)
343+ </header>
344+
345+ <div class="settings-shell">
346+ <main class="settings-stage">
347+ <div class="settings-head">
348+ <h1 class="settings-title">(t(lang, Key::NavTags))</h1>
349+ <span class="chip chip-admin">(t(lang, Key::AdminOnly))</span>
350+ </div>
351+
352+ (composer(cx, create_refusal.as_ref(), lang).await?)
353+
354+ <div class="tag-list">
355+ for tag in &tags {
356+ (tag_row(cx, tag, edit_id.as_deref() == Some(tag.id.as_str()), rename_refusal.as_ref(), lang).await?)
357+ }
358+ </div>
359+ </main>
360+ (crate::dropdown::dropdown_script(cx).await?)
361+ (crate::layout::escape_script(cx).await?)
362+ </div>
363+ }
364+}
crates/izlek-web/tests/http.rsmodified+357 -0
@@ -2477,6 +2477,7 @@ async fn a_member_who_posts_new_limits_anyway_is_refused() {
2477 ("attachment_limit_mb", "400"),2477 ("attachment_limit_mb", "400"),
2478 ("photo_limit_mb", "19"),2478 ("photo_limit_mb", "19"),
2479 ("allowed_file_types", "png"),2479 ("allowed_file_types", "png"),
2480+ ("mail_batch_minutes", "5"),
2480 ],2481 ],
2481 )2482 )
2482 .await;2483 .await;
@@ -2508,6 +2509,7 @@ async fn an_admin_changes_the_limits_and_they_stay_changed() {
2508 ("attachment_limit_mb", "10"),2509 ("attachment_limit_mb", "10"),
2509 ("photo_limit_mb", "1"),2510 ("photo_limit_mb", "1"),
2510 ("allowed_file_types", ".PNG, png, pdf"),2511 ("allowed_file_types", ".PNG, png, pdf"),
2512+ ("mail_batch_minutes", "5"),
2511 ],2513 ],
2512 )2514 )
2513 .await;2515 .await;
@@ -2544,6 +2546,7 @@ async fn a_limit_outside_what_the_disk_should_promise_is_refused() {
2544 ("attachment_limit_mb", attachment),2546 ("attachment_limit_mb", attachment),
2545 ("photo_limit_mb", photo),2547 ("photo_limit_mb", photo),
2546 ("allowed_file_types", ""),2548 ("allowed_file_types", ""),
2549+ ("mail_batch_minutes", "5"),
2547 ],2550 ],
2548 )2551 )
2549 .await;2552 .await;
@@ -2575,6 +2578,7 @@ async fn a_file_type_that_is_not_an_extension_is_refused() {
2575 ("attachment_limit_mb", "25"),2578 ("attachment_limit_mb", "25"),
2576 ("photo_limit_mb", "2"),2579 ("photo_limit_mb", "2"),
2577 ("allowed_file_types", "../etc/passwd"),2580 ("allowed_file_types", "../etc/passwd"),
2581+ ("mail_batch_minutes", "5"),
2578 ],2582 ],
2579 )2583 )
2580 .await;2584 .await;
@@ -4112,6 +4116,7 @@ async fn a_file_past_the_workspace_limit_is_refused_before_it_is_kept() {
4112 ("attachment_limit_mb", "1"),4116 ("attachment_limit_mb", "1"),
4113 ("photo_limit_mb", "2"),4117 ("photo_limit_mb", "2"),
4114 ("allowed_file_types", ""),4118 ("allowed_file_types", ""),
4119+ ("mail_batch_minutes", "5"),
4115 ],4120 ],
4116 )4121 )
4117 .await;4122 .await;
@@ -4165,6 +4170,7 @@ async fn a_file_type_off_the_list_is_refused() {
4165 ("attachment_limit_mb", "25"),4170 ("attachment_limit_mb", "25"),
4166 ("photo_limit_mb", "2"),4171 ("photo_limit_mb", "2"),
4167 ("allowed_file_types", "png"),4172 ("allowed_file_types", "png"),
4173+ ("mail_batch_minutes", "5"),
4168 ],4174 ],
4169 )4175 )
4170 .await;4176 .await;
@@ -5347,6 +5353,7 @@ async fn a_photo_over_the_workspace_limit_is_refused_and_stores_nothing() {
5347 ("attachment_limit_mb", "25"),5353 ("attachment_limit_mb", "25"),
5348 ("photo_limit_mb", "1"),5354 ("photo_limit_mb", "1"),
5349 ("allowed_file_types", ""),5355 ("allowed_file_types", ""),
5356+ ("mail_batch_minutes", "5"),
5350 ],5357 ],
5351 )5358 )
5352 .await;5359 .await;
@@ -7304,6 +7311,220 @@ async fn a_member_may_not_check_the_sender() {
7304 assert_ne!(answer.body, "null", "a member was allowed to dial the server");7311 assert_ne!(answer.body, "null", "a member was allowed to dial the server");
7305 }7312 }
7306 7313
7314+// --- tags -------------------------------------------------------------------
7315+
7316+/// Makes a tag over HTTP and hands the store row back — the tests need the
7317+/// id, and the mutation itself is still a real post.
7318+async fn a_tag(app: &App, cookie: &str, name: &str) -> izlek_core::store::Tag {
7319+ let answer = app.post("/api/create_tag", Some(cookie), &[("name", name)]).await;
7320+ assert_eq!(answer.body, "null", "the tag was refused: {}", answer.body);
7321+ let workspace_id = app.workspace_id().await;
7322+ let board = app
7323+ .store
7324+ .board(&workspace_id)
7325+ .await
7326+ .unwrap()
7327+ .expect("no board");
7328+ app.store
7329+ .tags(&board.id)
7330+ .await
7331+ .unwrap()
7332+ .into_iter()
7333+ .find(|tag| tag.name == name)
7334+ .expect("the new tag is not on the board")
7335+}
7336+
7337+#[tokio::test]
7338+async fn a_non_admin_cannot_create_rename_delete_or_move_a_tag() {
7339+ let app = App::open().await;
7340+ let admin_cookie = admin(&app).await;
7341+ let member = invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7342+
7343+ let create = app.post("/api/create_tag", Some(&member), &[("name", "Sneak")]).await;
7344+ assert!(create.body.contains("Forbidden"), "{}", create.body);
7345+ let rename = app
7346+ .post(
7347+ "/api/rename_tag",
7348+ Some(&member),
7349+ &[("tag_id", "t1"), ("name", "Sneak")],
7350+ )
7351+ .await;
7352+ assert!(rename.body.contains("Forbidden"), "{}", rename.body);
7353+ let delete = app.post("/api/delete_tag", Some(&member), &[("tag_id", "t1")]).await;
7354+ assert!(delete.body.contains("Forbidden"), "{}", delete.body);
7355+ let move_it = app
7356+ .post(
7357+ "/api/move_tag",
7358+ Some(&member),
7359+ &[("tag_id", "t1"), ("direction", "up")],
7360+ )
7361+ .await;
7362+ assert!(move_it.body.contains("Forbidden"), "{}", move_it.body);
7363+}
7364+
7365+#[tokio::test]
7366+async fn a_viewer_cannot_set_a_task_tag() {
7367+ let app = App::open().await;
7368+ let admin_cookie = admin(&app).await;
7369+ let viewer = invited(&app, &admin_cookie, "hush@izlek.sh", "Hush Rao", Role::Viewer).await;
7370+ let column = first_column(&app).await;
7371+ let task = a_task(&app, &admin_cookie, &column, "Label me not").await;
7372+ let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7373+
7374+ let answer = app
7375+ .post(
7376+ "/api/set_task_tag",
7377+ Some(&viewer),
7378+ &[("task_id", &task), ("tag_id", &aurora.id)],
7379+ )
7380+ .await;
7381+ assert!(answer.body.contains("Forbidden"), "{}", answer.body);
7382+}
7383+
7384+#[tokio::test]
7385+async fn the_task_modal_lists_every_tag_and_names_the_current_one() {
7386+ let app = App::open().await;
7387+ let admin_cookie = admin(&app).await;
7388+ let column = first_column(&app).await;
7389+ let task = a_task(&app, &admin_cookie, &column, "Sort into color").await;
7390+ let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7391+
7392+ let workspace_id = app.workspace_id().await;
7393+ let board = app
7394+ .store
7395+ .board(&workspace_id)
7396+ .await
7397+ .unwrap()
7398+ .expect("no board");
7399+ let default_id = app
7400+ .store
7401+ .tags(&board.id)
7402+ .await
7403+ .unwrap()
7404+ .into_iter()
7405+ .find(|tag| tag.is_default)
7406+ .expect("no default tag")
7407+ .id;
7408+ let selected = |html: &str, id: &str| html.contains(&format!(r#"value="{id}" selected"#));
7409+
7410+ let page = String::from_utf8(
7411+ app.get(&format!("/?task={task}"), Some(&admin_cookie)).await.bytes,
7412+ )
7413+ .unwrap();
7414+ assert!(page.contains(r#"name="tag_id""#), "no tag field in the modal: {page}");
7415+ assert!(page.contains("General"), "the default tag is not offered: {page}");
7416+ assert!(page.contains("Aurora"), "the new tag is not offered: {page}");
7417+ assert!(selected(&page, &default_id), "the current tag is not named: {page}");
7418+ assert!(!selected(&page, &aurora.id), "an unchosen tag reads as current: {page}");
7419+
7420+ let switched = app
7421+ .post(
7422+ "/api/set_task_tag",
7423+ Some(&admin_cookie),
7424+ &[("task_id", &task), ("tag_id", &aurora.id)],
7425+ )
7426+ .await;
7427+ assert_eq!(switched.body, "null", "the switch was refused: {}", switched.body);
7428+
7429+ let page = String::from_utf8(
7430+ app.get(&format!("/?task={task}"), Some(&admin_cookie)).await.bytes,
7431+ )
7432+ .unwrap();
7433+ assert!(selected(&page, &aurora.id), "the switch did not name Aurora: {page}");
7434+ assert!(!selected(&page, &default_id), "the old tag still reads current: {page}");
7435+}
7436+
7437+#[tokio::test]
7438+async fn the_board_tag_filter_narrows_cards_and_an_unknown_tag_falls_back_to_all() {
7439+ let app = App::open().await;
7440+ let admin_cookie = admin(&app).await;
7441+ let column = first_column(&app).await;
7442+ let first = a_task(&app, &admin_cookie, &column, "Aurora work").await;
7443+ let second = a_task(&app, &admin_cookie, &column, "Boreal work").await;
7444+ let aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7445+ let boreal = a_tag(&app, &admin_cookie, "Boreal").await;
7446+
7447+ let switched = app
7448+ .post(
7449+ "/api/set_task_tag",
7450+ Some(&admin_cookie),
7451+ &[("task_id", &second), ("tag_id", &boreal.id)],
7452+ )
7453+ .await;
7454+ assert_eq!(switched.body, "null", "the switch was refused: {}", switched.body);
7455+
7456+ let tagged = app
7457+ .post(
7458+ "/api/set_task_tag",
7459+ Some(&admin_cookie),
7460+ &[("task_id", &first), ("tag_id", &aurora.id)],
7461+ )
7462+ .await;
7463+ assert_eq!(tagged.body, "null", "the first switch was refused: {}", tagged.body);
7464+
7465+ let filtered = String::from_utf8(
7466+ app.get(&format!("/?tag={}", aurora.id), Some(&admin_cookie))
7467+ .await
7468+ .bytes,
7469+ )
7470+ .unwrap();
7471+ assert!(filtered.contains("Aurora work"), "the tagged card is gone: {filtered}");
7472+ assert!(
7473+ !filtered.contains("Boreal work"),
7474+ "the other card did not filter out: {filtered}"
7475+ );
7476+
7477+ let everything = String::from_utf8(
7478+ app.get("/?tag=bogus", Some(&admin_cookie)).await.bytes,
7479+ )
7480+ .unwrap();
7481+ assert!(
7482+ everything.contains("Aurora work") && everything.contains("Boreal work"),
7483+ "an unknown tag did not fall back to all: {everything}"
7484+ );
7485+ assert!(
7486+ everything.contains("General"),
7487+ "the default tag is not an option in the filter: {everything}"
7488+ );
7489+}
7490+
7491+#[tokio::test]
7492+async fn the_default_tag_cannot_be_deleted_and_ships_no_delete_button() {
7493+ let app = App::open().await;
7494+ let admin_cookie = admin(&app).await;
7495+ let _aurora = a_tag(&app, &admin_cookie, "Aurora").await;
7496+
7497+ let workspace_id = app.workspace_id().await;
7498+ let board = app
7499+ .store
7500+ .board(&workspace_id)
7501+ .await
7502+ .unwrap()
7503+ .expect("no board");
7504+ let default_id = app
7505+ .store
7506+ .tags(&board.id)
7507+ .await
7508+ .unwrap()
7509+ .into_iter()
7510+ .find(|tag| tag.is_default)
7511+ .expect("no default tag")
7512+ .id;
7513+
7514+ let refused = app
7515+ .post("/api/delete_tag", Some(&admin_cookie), &[("tag_id", &default_id)])
7516+ .await;
7517+ assert!(refused.body.contains("Unavailable"), "{}", refused.body);
7518+
7519+ let page = String::from_utf8(app.get("/tags", Some(&admin_cookie)).await.bytes).unwrap();
7520+ assert_eq!(
7521+ page.matches(r#"action="/api/delete_tag""#).count(),
7522+ 1,
7523+ "the default tag's row ships a delete control: {page}"
7524+ );
7525+ assert!(page.contains("Aurora"), "the created tag is not listed: {page}");
7526+}
7527+
7307 /// An open live stream must not be something the shutdown has to wait out.7528 /// An open live stream must not be something the shutdown has to wait out.
7308 ///7529 ///
7309 /// The server stops accepting connections and then gives in-flight requests7530 /// 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() {
7338 .await;7559 .await;
7339 assert!(ended.is_ok(), "the stream outlived the stop");7560 assert!(ended.is_ok(), "the stream outlived the stop");
7340 }7561 }
7562+// --- profile page -----------------------------------------------------------
7563+
7564+/// One task row id, for the profile fixture. Fixture setup goes through the
7565+/// store directly, the way `record_sender_check`'s test does.
7566+async fn a_task_by(app: &App, board_id: &str, column_id: &str, title: &str, creator: &str) -> String {
7567+ app.store
7568+ .create_task(izlek_core::store::NewTask {
7569+ board_id,
7570+ column_id,
7571+ parent_id: None,
7572+ title,
7573+ description: "",
7574+ deadline: None,
7575+ created_by: creator,
7576+ })
7577+ .await
7578+ .unwrap()
7579+ .row
7580+ .id
7581+}
7582+
7583+/// Two tasks on Mem's plate, one finished under her, three she opened, four
7584+/// comments — the numbers the profile page has to show: 2 / 1 / 3 / 4.
7585+async fn profile_counts_fixture(app: &App, member: &str, admin: &str) {
7586+ let workspace = app.workspace_id().await;
7587+ let board = app.store.board(&workspace).await.unwrap().expect("no board");
7588+ let columns = app.store.columns(&board.id).await.unwrap();
7589+ let open = columns
7590+ .iter()
7591+ .find(|column| !column.is_done)
7592+ .expect("no open column")
7593+ .id
7594+ .clone();
7595+ let done = columns
7596+ .iter()
7597+ .find(|column| column.is_done)
7598+ .expect("no done column")
7599+ .id
7600+ .clone();
7601+ let now = time::OffsetDateTime::now_utc();
7602+
7603+ let hold = a_task_by(app, &board.id, &open, "Hold the door", admin).await;
7604+ app.store.assign_task(&hold, member).await.unwrap();
7605+ let other = a_task_by(app, &board.id, &open, "Oil the hinges", admin).await;
7606+ app.store.assign_task(&other, member).await.unwrap();
7607+ let finished = a_task_by(app, &board.id, &open, "Paint the frame", admin).await;
7608+ app.store.assign_task(&finished, member).await.unwrap();
7609+ app.store.move_task(&finished, &open, &done, admin, now).await.unwrap();
7610+ for title in ["Sweep", "Mop", "Dust"] {
7611+ a_task_by(app, &board.id, &open, title, member).await;
7612+ }
7613+ for _ in 0..4 {
7614+ app.store.add_comment(&hold, member, "a note", now).await.unwrap();
7615+ }
7616+}
7617+
7618+#[tokio::test]
7619+async fn a_member_may_read_another_members_profile_name_address_and_counts() {
7620+ let app = App::open().await;
7621+ let admin_cookie = admin(&app).await;
7622+ invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7623+ let reader = invited(&app, &admin_cookie, "ivy@izlek.sh", "Ivy Lear", Role::Member).await;
7624+ let mem_id = user_id(&app, "mem@izlek.sh").await;
7625+ let admin_id = app
7626+ .store
7627+ .users(&app.workspace_id().await)
7628+ .await
7629+ .unwrap()
7630+ .into_iter()
7631+ .find(|user| user.role == Role::Admin)
7632+ .unwrap()
7633+ .id;
7634+ profile_counts_fixture(&app, &mem_id, &admin_id).await;
7635+
7636+ let page = app.get(&format!("/people/{mem_id}"), Some(&reader)).await;
7637+ assert_eq!(page.status.as_u16(), 200);
7638+ let html = String::from_utf8(page.bytes).unwrap();
7639+ assert!(html.contains("Mem Ber"), "{html}");
7640+ assert!(html.contains("mem@izlek.sh"), "{html}");
7641+ for count in [2, 1, 3, 4] {
7642+ assert_eq!(
7643+ html.matches(&format!(">{count}</dd>")).count(),
7644+ 1,
7645+ "the {count} stat is not on the page once: {html}"
7646+ );
7647+ }
7648+}
7649+
7650+#[tokio::test]
7651+async fn a_profile_is_not_found_signed_out_or_outside_the_workspace() {
7652+ let app = App::open().await;
7653+ let admin_cookie = admin(&app).await;
7654+ invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7655+ let mem_id = user_id(&app, "mem@izlek.sh").await;
7656+
7657+ let signed_out = app.get(&format!("/people/{mem_id}"), None).await;
7658+ assert_eq!(signed_out.status.as_u16(), 404, "never a 403, never a page");
7659+
7660+ // A person who exists, but in another workspace, reads exactly like a
7661+ // missing one — the id is not looked at twice.
7662+ let other = App::open().await;
7663+ // A workspace has to be claimed before it holds anybody to be a stranger.
7664+ let _ = admin(&other).await;
7665+ let stranger = other.store.users(&other.workspace_id().await).await.unwrap()[0]
7666+ .id
7667+ .clone();
7668+ let foreign = app.get(&format!("/people/{stranger}"), Some(&admin_cookie)).await;
7669+ assert_eq!(foreign.status.as_u16(), 404);
7670+
7671+ let missing = app.get("/people/nobody", Some(&admin_cookie)).await;
7672+ assert_eq!(missing.status.as_u16(), 404);
7673+}
7674+
7675+#[tokio::test]
7676+async fn only_your_own_profile_offers_the_edit_link() {
7677+ let app = App::open().await;
7678+ let admin_cookie = admin(&app).await;
7679+ invited(&app, &admin_cookie, "mem@izlek.sh", "Mem Ber", Role::Member).await;
7680+ let mem_id = user_id(&app, "mem@izlek.sh").await;
7681+ let ivy = invited(&app, &admin_cookie, "ivy@izlek.sh", "Ivy Lear", Role::Member).await;
7682+ let ivy_id = user_id(&app, "ivy@izlek.sh").await;
7683+
7684+ let own = app.get(&format!("/people/{ivy_id}"), Some(&ivy)).await;
7685+ let own_html = String::from_utf8(own.bytes).unwrap();
7686+ assert!(
7687+ own_html.contains(r#"href="/settings?section=profile""#),
7688+ "no edit link on your own profile: {own_html}"
7689+ );
7690+
7691+ let theirs = app.get(&format!("/people/{mem_id}"), Some(&ivy)).await;
7692+ let theirs_html = String::from_utf8(theirs.bytes).unwrap();
7693+ assert!(
7694+ !theirs_html.contains("settings?section=profile"),
7695+ "someone else's profile grew an editor: {theirs_html}"
7696+ );
7697+}
\ No newline at end of file\ No newline at end of file
style/_ledger.scssmodified+8 -0
@@ -103,6 +103,14 @@
103 &-off { background: transparent; }103 &-off { background: transparent; }
104 }104 }
105 105
106+ .tag-row {
107+ background: transparent;
108+ border: none;
109+ border-bottom: 1px solid var(--border);
110+ border-radius: 0;
111+ padding: 14px 2px;
112+ }
113+
106 // Activity log reads as a ruled ledger column too: no boxes, the actor114 // Activity log reads as a ruled ledger column too: no boxes, the actor
107 // named in the display face like .member-name.115 // named in the display face like .member-name.
108 .log-row {116 .log-row {
style/main.scssmodified+143 -0
@@ -348,6 +348,18 @@ body:has(.settings-shell) {
348 > .settings-shell { flex: 1; min-height: 0; }348 > .settings-shell { flex: 1; min-height: 0; }
349 }349 }
350 350
351+// A profile is one column of its own; it pans inside itself like every other
352+// page here, and the document never grows a scrollbar.
353+body:has(.people-shell) {
354+ height: 100vh;
355+ overflow: hidden;
356+ display: flex;
357+ flex-direction: column;
358+
359+ > * { flex: none; }
360+ > .people-shell { flex: 1; min-height: 0; }
361+}
362+
351 a {363 a {
352 color: var(--accent);364 color: var(--accent);
353 transition: color var(--dur-fast) var(--ease);365 transition: color var(--dur-fast) var(--ease);
@@ -882,6 +894,15 @@ a {
882 color: var(--muted);894 color: var(--muted);
883 }895 }
884 896
897+.card-tag {
898+ font-family: var(--font-mono);
899+ font-size: 11px;
900+ color: var(--muted);
901+ background: var(--surface-sunken);
902+ border-radius: var(--radius-sm);
903+ padding: 2px 6px;
904+}
905+
885 /// Parts still open is the same warning the blocker chips carry: this card906 /// Parts still open is the same warning the blocker chips carry: this card
886 /// cannot reach the done column yet.907 /// cannot reach the done column yet.
887 .card-subtasks-open { color: var(--warn-ink); }908 .card-subtasks-open { color: var(--warn-ink); }
@@ -3461,3 +3482,125 @@ input[type="radio"] {
3461 flex-direction: column;3482 flex-direction: column;
3462 gap: 6px;3483 gap: 6px;
3463 }3484 }
3485+
3486+.tag-list {
3487+ display: flex;
3488+ flex-direction: column;
3489+ gap: 10px;
3490+}
3491+
3492+.tag-row {
3493+ display: flex;
3494+ align-items: center;
3495+ gap: 14px;
3496+ padding: 16px;
3497+ background: var(--surface);
3498+ border: 1px solid var(--border);
3499+ border-radius: var(--radius-md);
3500+}
3501+
3502+.tag-name {
3503+ flex-grow: 1;
3504+ min-width: 0;
3505+ font-size: 13px;
3506+ overflow: hidden;
3507+ text-overflow: ellipsis;
3508+ white-space: nowrap;
3509+}
3510+
3511+.tag-new {
3512+ background: var(--surface);
3513+ border: 1px solid var(--border);
3514+ border-radius: var(--radius-lg);
3515+}
3516+
3517+.tag-new-open {
3518+ display: flex;
3519+ align-items: center;
3520+ height: var(--control-h);
3521+ padding: 0 16px;
3522+ font-size: 13px;
3523+ font-weight: 600;
3524+ color: var(--accent-ink);
3525+ cursor: pointer;
3526+ list-style: none;
3527+
3528+ &::marker, &::-webkit-details-marker { display: none; }
3529+ &::before { content: '+'; margin-right: 8px; font-size: 13px; }
3530+}
3531+
3532+.tag-form {
3533+ display: flex;
3534+ flex-direction: column;
3535+ gap: 20px;
3536+ padding: 0 16px 16px;
3537+ border-top: 1px solid var(--border);
3538+ padding-top: 16px;
3539+}
3540+
3541+.tag-field {
3542+ display: flex;
3543+ flex-direction: column;
3544+ gap: 6px;
3545+}
3546+
3547+// --- Profile (a member's page) ----------------------------------------------
3548+
3549+.people-shell {
3550+ width: 100%;
3551+ max-width: 860px;
3552+ margin: 0 auto;
3553+ padding: 24px 32px 40px;
3554+ display: flex;
3555+ flex-direction: column;
3556+ gap: 20px;
3557+ overflow-y: auto;
3558+ scrollbar-width: none;
3559+
3560+ &::-webkit-scrollbar { display: none; }
3561+ > * { flex: none; }
3562+}
3563+
3564+.people-stats {
3565+ display: flex;
3566+ flex-wrap: wrap;
3567+ gap: 28px;
3568+ margin: 0;
3569+
3570+ dt {
3571+ font-size: 11px;
3572+ letter-spacing: 0.08em;
3573+ text-transform: uppercase;
3574+ color: var(--muted);
3575+ }
3576+
3577+ dd {
3578+ margin: 0;
3579+ font-size: 20px;
3580+ font-weight: 600;
3581+ font-variant-numeric: tabular-nums;
3582+ }
3583+}
3584+
3585+.people-feed {
3586+ list-style: none;
3587+ margin: 0;
3588+ padding: 0;
3589+ display: flex;
3590+ flex-direction: column;
3591+ gap: 8px;
3592+
3593+ li {
3594+ display: flex;
3595+ align-items: baseline;
3596+ gap: 10px;
3597+ }
3598+}
3599+
3600+.people-feed-day {
3601+ margin-left: auto;
3602+ flex: none;
3603+ white-space: nowrap;
3604+ color: var(--muted);
3605+ font-size: 12px;
3606+}