diff --git a/crates/izlek-core/migrations/0001_init.sql b/crates/izlek-core/migrations/0001_init.sql index f4893a5..3133615 100644 --- a/crates/izlek-core/migrations/0001_init.sql +++ b/crates/izlek-core/migrations/0001_init.sql @@ -1,26 +1,55 @@ --- Izlek initial schema. +-- Izlek's schema, whole, in one file. -- -- Plain versioned SQL applied at boot: Turso has no migration runner of its -- own, and keeping the schema as SQL is what makes the store trait swappable. --- Timestamps are RFC 3339 text in UTC. Ids are UUIDs as text. +-- Timestamps are RFC 3339 text in UTC. Ids are ULIDs as text — sortable by +-- creation, and Crockford-uppercase already, which is what lets a task key +-- borrow its tail. +-- +-- This file replaces a chain of twenty migrations. Three of them (the old +-- 0013, 0014, 0019) did not tweak a table but rebuilt it — SQLite cannot drop +-- a CHECK or a foreign key in place — so the shape a reader found here no +-- longer matched the shape a running database had. Nothing has been released, +-- so the chain was collapsed into this: the tables as they actually are. The +-- reasoning those migrations carried is kept, on the tables it explains. CREATE TABLE workspace ( id TEXT PRIMARY KEY, name TEXT NOT NULL, created_at TEXT NOT NULL, - -- The single sender every mail in the workspace goes through. Written by - -- the admin in Settings; the password is never returned to the client. + -- Limits. Each states its consequence in the UI, not here. They are + -- workspace content — an admin edits them, and no restart should be + -- needed to raise an attachment ceiling. + attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400, + photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, + -- JSON array of allowed extensions. An empty array means every type. + allowed_file_types TEXT NOT NULL DEFAULT '[]', + -- The single sender every mail in the workspace goes through, written by + -- the admin in Settings rather than by whoever has a shell on the box: a + -- three-person team has those be different people, and the second one is + -- not always awake. + -- + -- `smtp_password` holds ciphertext, never the typed string. The server + -- has to present the password to the mail host on every send, so a + -- one-way hash is impossible; instead `store::secret` seals it under a + -- key kept in `izlek.key` beside this file, so a database copied for a + -- backup does not carry a working credential with it. No field on + -- `Workspace` exposes it — it is written by `Store::set_sender` and read + -- by `Store::smtp_password`, which only the mailer calls. smtp_host TEXT, smtp_port INTEGER, smtp_username TEXT, smtp_password TEXT, smtp_from_name TEXT, smtp_from_address TEXT, - -- Limits. Each states its consequence in the UI, not here. - attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400, - photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, - -- JSON array of allowed extensions. An empty array means every type. - allowed_file_types TEXT NOT NULL DEFAULT '[]' + -- The result of the last "send a test mail to myself", kept rather than + -- shown once: an admin fills the sender in, presses the button, and comes + -- back tomorrow wondering whether it ever worked. `smtp_test_error` is the + -- mail server's own words, so the admin can act on them; the mailer builds + -- its errors from what the server said, never from the credentials it sent. + smtp_test_at INTEGER, + smtp_test_ms INTEGER, + smtp_test_error TEXT ); CREATE TABLE user ( @@ -33,14 +62,37 @@ CREATE TABLE user ( -- NULL until the person picks a password on first sign-in. The admin -- creates the account with a name and an address and nothing else. password_hash TEXT, - photo_path TEXT, + -- Whoever made this account, so the first-sign-in screen can greet the + -- invited person by the inviter's name instead of reading their own name + -- back to them. NULL for the first account, which nobody invited. A + -- reference rather than a copied name, so a later rename is reflected. + invited_by TEXT REFERENCES user(id), + -- Display preferences. Stored data everywhere else stays UTC and + -- language-neutral; these only change how a browser renders it for the + -- one person signed in as this user, and nothing stored depends on them. + timezone TEXT NOT NULL DEFAULT 'UTC', + theme TEXT NOT NULL DEFAULT 'light', + language TEXT NOT NULL DEFAULT 'en', + ui TEXT NOT NULL DEFAULT 'instrument', + -- The profile picture lives here as bytes, the way an attachment does: + -- no filesystem path survives a backup or a move. + photo BLOB, + photo_mime TEXT, created_at TEXT NOT NULL, last_signed_in_at TEXT ); CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email); --- First sign-in / resend links. Only the hash is stored: the plaintext is shown --- once when the admin creates or resends it. +-- One workspace, one owner. The singleton column is the whole point: the row +-- can exist at most once, so a second claim cannot race a first one. +CREATE TABLE workspace_owner ( + singleton INTEGER PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + claimed_at TEXT NOT NULL +); + +-- First sign-in / resend links. Only the hash is stored: the plaintext is +-- shown once when the admin creates or resends it. CREATE TABLE signin_link ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES user(id), @@ -51,10 +103,30 @@ CREATE TABLE signin_link ( ); CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash); +CREATE TABLE session ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES user(id), + token_hash TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + revoked_at TEXT +); +CREATE UNIQUE INDEX session_token ON session(token_hash); +CREATE INDEX session_by_user ON session(user_id); + +-- The rate-limit ledger: one row per attempt, pruned by age. +CREATE TABLE auth_attempt ( + id TEXT PRIMARY KEY, + bucket TEXT NOT NULL, + attempted_at TEXT NOT NULL +); +CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at); + CREATE TABLE board ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL REFERENCES workspace(id), name TEXT NOT NULL, + -- The key prefix this board's tasks carry (`DZ-14`). task_prefix TEXT NOT NULL DEFAULT 'DZ', created_at TEXT NOT NULL ); @@ -68,10 +140,27 @@ CREATE TABLE board_column ( is_done INTEGER NOT NULL DEFAULT 0 ); +-- A task, and a subtask, which is the same thing with a parent. +-- +-- `parent_id` is the whole of the subtask feature in this schema: a subtask +-- has every column a task has, so it carries assignees, a deadline, comments, +-- files, activity and mail exactly like anything else, and promoting one to +-- a task of its own is a single UPDATE rather than a move between tables. +-- +-- Two rules the column cannot state itself, enforced in the store instead: +-- a parent must have `parent_id IS NULL` (one level, never a tree), and a +-- child sits on its parent's board. SQLite cannot ask, in a CHECK, whether +-- the row a foreign key points at has a NULL parent. +-- +-- The board shows only rows with no parent; a subtask reaches its own detail +-- page through its parent's. CREATE TABLE task ( id TEXT PRIMARY KEY, board_id TEXT NOT NULL REFERENCES board(id), - -- Human key from the mockups, e.g. DZ-14. + parent_id TEXT REFERENCES task(id), + -- Human key from the mockups, e.g. DZ-14. The tail is the end of the + -- task's own ULID rather than a per-board counter: a counter leaves + -- visible gaps once tasks are deleted. task_key TEXT NOT NULL, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', @@ -86,6 +175,7 @@ CREATE TABLE task ( ); CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key); CREATE INDEX task_by_column ON task(column_id); +CREATE INDEX task_by_parent ON task(parent_id); CREATE TABLE task_assignee ( task_id TEXT NOT NULL REFERENCES task(id), @@ -101,12 +191,17 @@ CREATE TABLE task_watcher ( -- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the -- blocking task finishes, which is what the "you can start now" rule reads. +-- +-- The CHECK is new: a task blocking itself was only ever stopped in +-- application code, and a row like that would make a card permanently and +-- unfixably blocked by its own existence. CREATE TABLE task_dependency ( blocked_task_id TEXT NOT NULL REFERENCES task(id), blocking_task_id TEXT NOT NULL REFERENCES task(id), created_at TEXT NOT NULL, cleared_at TEXT, - PRIMARY KEY (blocked_task_id, blocking_task_id) + PRIMARY KEY (blocked_task_id, blocking_task_id), + CHECK (blocked_task_id <> blocking_task_id) ); CREATE TABLE comment ( @@ -118,6 +213,14 @@ CREATE TABLE comment ( ); CREATE INDEX comment_by_task ON comment(task_id); +-- Attachments live in the database file, not on disk beside it. +-- +-- Izlek is one process over one file, and a second place to keep state is a +-- second thing to back up, to lock, and to get out of step with the rows that +-- name it. And a path is exactly where an uploaded file name must never end +-- up: `../../etc` is a valid file name and a terrible path. Keeping the bytes +-- here means `file_name` is only ever a label printed on a chip, never +-- anything the server resolves. CREATE TABLE attachment ( id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES task(id), @@ -125,54 +228,155 @@ CREATE TABLE attachment ( file_name TEXT NOT NULL, mime_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, - stored_path TEXT NOT NULL, + bytes BLOB NOT NULL, uploaded_by TEXT NOT NULL REFERENCES user(id), created_at TEXT NOT NULL ); +CREATE INDEX attachment_by_task ON attachment(task_id); --- The activity strip in the task detail: who did what, and whether it mailed. +-- Every move of a card from one column to another, written as a fact in the +-- same transaction as the move itself. +-- +-- The mail rules trigger on the transition, not on the task's current column: +-- a card that goes Review -> Done -> Review has crossed into Done once, and +-- nothing recomputed from `task.column_id` afterwards can tell you that. +-- +-- `from_column` deliberately carries no REFERENCES: a task created straight +-- into a column writes a transition with `from_column = ''`, meaning "created +-- into", so a rule watching that column fires for a new card and not only for +-- one dragged in later. No column's id is ever ''. +CREATE TABLE transition ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL REFERENCES task(id), + from_column TEXT NOT NULL, + to_column TEXT NOT NULL REFERENCES board_column(id), + actor_id TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); +CREATE INDEX transition_by_task ON transition(task_id, created_at); + +-- A deletion that let other tasks go, recorded as a fact. +-- +-- The unblocked rule has two causes and only one of them is a crossing: a +-- blocker can finish, or a blocker can be deleted. The crossing already has a +-- row in `transition`; the deletion had nowhere to be written, so a mail owed +-- because of one had no event to hang from and no way to be rebuilt on a +-- retry. This is that row. +-- +-- `cause_key` and `cause_title` are copied rather than joined: the task they +-- name is deleted, and a mail sent an hour later still has to be able to say +-- which task it was. +CREATE TABLE freeing ( + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + cause_key TEXT NOT NULL, + cause_title TEXT NOT NULL, + actor_id TEXT NOT NULL REFERENCES user(id), + created_at TEXT NOT NULL +); +CREATE INDEX freeing_by_board ON freeing(board_id, created_at); + +-- The activity strip in the task detail: who did what. `task_id` is nullable +-- because account and admin events — sign-ins, invites, role changes — have +-- no task to sit under, and still have to be loggable. CREATE TABLE activity ( id TEXT PRIMARY KEY, - task_id TEXT NOT NULL REFERENCES task(id), + task_id TEXT REFERENCES task(id), actor_id TEXT REFERENCES user(id), kind TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL ); CREATE INDEX activity_by_task ON activity(task_id); +CREATE INDEX activity_recent ON activity(created_at); --- Mail rules are written only by the admin and are always on. A rule that --- addresses an external address stays off until that address confirms. +-- Mail rules are written only by the admin. +-- +-- `trigger_kind` carries no CHECK on purpose: the set of triggers grows +-- without a schema change. `audience` does carry one, because those three +-- values are the only audiences the engine knows how to resolve. CREATE TABLE mail_rule ( - id TEXT PRIMARY KEY, - workspace_id TEXT NOT NULL REFERENCES workspace(id), - board_id TEXT REFERENCES board(id), - -- 'status_becomes' | 'deadline_in' | 'unblocked' - trigger_kind TEXT NOT NULL, - trigger_value TEXT NOT NULL, - subject TEXT NOT NULL, - -- 'assignees' | 'assignees_watchers' | 'everyone' | 'external' - audience TEXT NOT NULL, - external_address TEXT, - external_confirmed INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - last_sent_at TEXT + id TEXT PRIMARY KEY, + board_id TEXT NOT NULL REFERENCES board(id), + trigger_kind TEXT NOT NULL, + trigger_column TEXT REFERENCES board_column(id), + subject TEXT NOT NULL, + -- 'assignees' — the people the card points at; 'board' — everyone who can + -- write on the board; 'creator' — whoever opened the card. + audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board', 'creator')), + enabled INTEGER NOT NULL DEFAULT 1, + -- Fold the task's own facts into the body instead of the subject line + -- being all the recipient reads. Off by default. + include_task_details INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + -- A status rule names a column and an unblocked rule does not. The check + -- is here so a half-written rule cannot be stored at all. + CHECK ((trigger_kind = 'status') = (trigger_column IS NOT NULL)) ); +CREATE INDEX mail_rule_by_board ON mail_rule(board_id); --- One row per (rule, task, transition) actually sent, so a revert-then-redo --- does not mail twice. +-- One row per mail owed, from the moment it is claimed until it is sent or +-- abandoned. +-- +-- Three shapes share the table. A 'rule' send is owed to somebody because a +-- rule matched an event on a task, and carries all three. An 'invite' or a +-- 'notice' has none of them — a person is invited before they have a task, a +-- transition, or a rule to owe them anything — and carries its own subject +-- and body instead of getting them from `mail_rule`. The two CHECKs make the +-- shapes exclusive, so a half-built row cannot be stored. +-- +-- `event_id` names a transition or a freeing without a foreign key: two +-- tables can cause a send, so the column cannot point at either and hold both. CREATE TABLE mail_send ( + id TEXT PRIMARY KEY, + rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE, + event_id TEXT, + task_id TEXT REFERENCES task(id), + recipient TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + claimed_at TEXT NOT NULL, + next_attempt_at TEXT, + sent_at TEXT, + kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')), + subject TEXT, + body TEXT, + CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)), + CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL)) +); +CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient); +CREATE INDEX mail_send_owed ON mail_send(next_attempt_at); +CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at); + +-- What the mail engine decided, for every rule and every event, not just the +-- mails it sent. +-- +-- `mail_send` only exists once a mail is owed and claimed; a card that moved +-- but matched no rule, a rule that was disabled, a task deleted before its +-- mail could go out — none of that left a trace. This is that trace, so "why +-- did nobody get mailed" has an answer that is not "look at the logs from +-- that day". +-- +-- `task_id` carries no foreign key on purpose: a `task_gone` row exists +-- precisely because the task it names no longer does, and it has to keep +-- saying so afterwards. +CREATE TABLE mail_decision ( id TEXT PRIMARY KEY, - rule_id TEXT NOT NULL REFERENCES mail_rule(id), - task_id TEXT NOT NULL REFERENCES task(id), - transition TEXT NOT NULL, - sent_at TEXT NOT NULL + rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE, + event_id TEXT NOT NULL, + task_id TEXT NOT NULL, + outcome TEXT NOT NULL CHECK (outcome IN + ('owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone')), + detail TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL ); -CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, task_id, transition); +CREATE UNIQUE INDEX mail_decision_once ON mail_decision(rule_id, event_id, task_id); +CREATE INDEX mail_decision_recent ON mail_decision(created_at); -- Read-only links: izlek.sh/v/. Only the hash of the token is stored, so a -- database copy does not hand out working links; revoking is server-side and --- immediate. +-- immediate. Designed but not yet built — no store method writes this table. CREATE TABLE view_link ( id TEXT PRIMARY KEY, workspace_id TEXT NOT NULL REFERENCES workspace(id), diff --git a/crates/izlek-core/migrations/0002_auth.sql b/crates/izlek-core/migrations/0002_auth.sql deleted file mode 100644 index ed87248..0000000 --- a/crates/izlek-core/migrations/0002_auth.sql +++ /dev/null @@ -1,33 +0,0 @@ --- Sessions, the single-owner claim, and the rate-limit ledger. - --- Exactly one row, ever. The primary key is the whole point: two requests --- racing to claim an empty workspace both try to insert singleton = 1 and the --- database picks the winner, inside the same transaction that writes the --- workspace and its admin. -CREATE TABLE workspace_owner ( - singleton INTEGER PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES user(id), - claimed_at TEXT NOT NULL -); - --- A signed-in browser. Only the hash of the cookie token is stored, exactly --- like sign-in links and read-only links. -CREATE TABLE session ( - id TEXT PRIMARY KEY, - user_id TEXT NOT NULL REFERENCES user(id), - token_hash TEXT NOT NULL, - created_at TEXT NOT NULL, - expires_at TEXT NOT NULL, - revoked_at TEXT -); -CREATE UNIQUE INDEX session_token ON session(token_hash); -CREATE INDEX session_by_user ON session(user_id); - --- Sign-in attempts and link redemptions, one row per attempt, counted over a --- window. The bucket is the address or the client address, never the password. -CREATE TABLE auth_attempt ( - id TEXT PRIMARY KEY, - bucket TEXT NOT NULL, - attempted_at TEXT NOT NULL -); -CREATE INDEX auth_attempt_by_bucket ON auth_attempt(bucket, attempted_at); diff --git a/crates/izlek-core/migrations/0003_transition.sql b/crates/izlek-core/migrations/0003_transition.sql deleted file mode 100644 index 0c575bf..0000000 --- a/crates/izlek-core/migrations/0003_transition.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Every move of a card from one column to another, written as a fact in the --- same transaction as the move itself. --- --- The mail rules trigger on the transition, not on the task's current column: --- a card that goes Review -> Done -> Review has crossed into Done once, and --- nothing recomputed from `task.column_id` afterwards can tell you that. So --- this table is the record, and the rules read it. -CREATE TABLE transition ( - id TEXT PRIMARY KEY, - task_id TEXT NOT NULL REFERENCES task(id), - from_column TEXT NOT NULL REFERENCES board_column(id), - to_column TEXT NOT NULL REFERENCES board_column(id), - actor_id TEXT NOT NULL REFERENCES user(id), - created_at TEXT NOT NULL -); - -CREATE INDEX transition_by_task ON transition(task_id, created_at); diff --git a/crates/izlek-core/migrations/0004_mail.sql b/crates/izlek-core/migrations/0004_mail.sql deleted file mode 100644 index 0ab410b..0000000 --- a/crates/izlek-core/migrations/0004_mail.sql +++ /dev/null @@ -1,64 +0,0 @@ --- Mail rules and the ledger of what they sent. --- --- 0001 sketched both tables before there was an engine to read them, and the --- sketch is not the shape the engine needs: a rule needs a column id rather --- than a free-text trigger value, and a send needs a recipient, a state and an --- attempt count so a mail that failed can be tried again and seen. Nothing has --- ever written a row to either table -- no store method touched them until --- this migration -- so they are rebuilt rather than migrated in place. -DROP INDEX IF EXISTS mail_send_once; -DROP TABLE IF EXISTS mail_send; -DROP TABLE IF EXISTS mail_rule; - -CREATE TABLE mail_rule ( - id TEXT PRIMARY KEY, - board_id TEXT NOT NULL REFERENCES board(id), - -- 'status' fires when a card crosses into `trigger_column`; 'unblocked' - -- fires for a task whose last blocker just finished. - trigger_kind TEXT NOT NULL CHECK (trigger_kind IN ('status', 'unblocked')), - trigger_column TEXT REFERENCES board_column(id), - subject TEXT NOT NULL, - -- 'assignees' — the people the card points at; 'board' — everyone who can - -- write on the board. A Viewer is in neither: a Viewer is never mailed. - audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board')), - enabled INTEGER NOT NULL DEFAULT 1, - created_at TEXT NOT NULL, - -- A status rule names a column and an unblocked rule does not. The check - -- is here so a half-written rule cannot be stored at all. - CHECK ((trigger_kind = 'status') = (trigger_column IS NOT NULL)) -); - -CREATE INDEX mail_rule_by_board ON mail_rule(board_id); - --- One row per (rule, event, task, recipient). The row is written BEFORE the --- mail is handed to the server, and the unique index below is what decides --- whether this process owns the send: an insert that conflicts means somebody --- else already owns it, and this process sends nothing. A check-then-insert --- would let the engine running twice mail the same person twice. --- --- `event_id` is the transition that caused the send. It is what the engine calls --- of "the same happening", so a transition replayed on a restart lands on the --- rows that already exist rather than on new ones. -CREATE TABLE mail_send ( - id TEXT PRIMARY KEY, - rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE, - event_id TEXT NOT NULL REFERENCES transition(id), - task_id TEXT NOT NULL REFERENCES task(id), - recipient TEXT NOT NULL, - -- 'pending' — owned, not yet accepted by the server - -- 'sent' — the server took it - -- 'failed' — the server refused in a way worth trying again - -- 'abandoned' — refused in a way that will not change, or out of attempts - state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), - attempts INTEGER NOT NULL DEFAULT 0, - last_error TEXT, - claimed_at TEXT NOT NULL, - -- When a failed send may be tried again. NULL once it is sent or given up - -- on, so "what is owed" is one indexed read. - next_attempt_at TEXT, - sent_at TEXT -); - -CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient); -CREATE INDEX mail_send_owed ON mail_send(next_attempt_at); -CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at); diff --git a/crates/izlek-core/migrations/0005_freeing.sql b/crates/izlek-core/migrations/0005_freeing.sql deleted file mode 100644 index 0fd7fde..0000000 --- a/crates/izlek-core/migrations/0005_freeing.sql +++ /dev/null @@ -1,56 +0,0 @@ --- A deletion that let other tasks go, recorded as a fact. --- --- The unblocked rule has two causes and only one of them is a crossing: a --- blocker can finish, or a blocker can be deleted. The crossing already has a --- row in `transition`; the deletion had nowhere to be written, so a mail owed --- because of one had no event to hang from and no way to be rebuilt on a --- retry. This is that row. --- --- `cause_key` and `cause_title` are copied rather than joined: the task they --- name is deleted, and a mail sent an hour later still has to be able to say --- which task it was. -CREATE TABLE freeing ( - id TEXT PRIMARY KEY, - board_id TEXT NOT NULL REFERENCES board(id), - cause_key TEXT NOT NULL, - cause_title TEXT NOT NULL, - actor_id TEXT NOT NULL REFERENCES user(id), - created_at TEXT NOT NULL -); - -CREATE INDEX freeing_by_board ON freeing(board_id, created_at); - --- `mail_send.event_id` pointed at `transition(id)` alone. A freeing is an event --- too, so the column names one of two tables and the foreign key has to go. --- SQLite cannot drop a constraint in place, so the table is rebuilt and its --- rows are carried over. -CREATE TABLE mail_send_next ( - id TEXT PRIMARY KEY, - rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE, - -- The transition or the freeing that caused it. Which table it is in is - -- answered by looking, and a send is rebuilt from whichever one has it. - event_id TEXT NOT NULL, - task_id TEXT NOT NULL REFERENCES task(id), - recipient TEXT NOT NULL, - state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), - attempts INTEGER NOT NULL DEFAULT 0, - last_error TEXT, - claimed_at TEXT NOT NULL, - next_attempt_at TEXT, - sent_at TEXT -); - -INSERT INTO mail_send_next -SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error, - claimed_at, next_attempt_at, sent_at -FROM mail_send; - -DROP INDEX IF EXISTS mail_send_once; -DROP INDEX IF EXISTS mail_send_owed; -DROP INDEX IF EXISTS mail_send_by_rule; -DROP TABLE mail_send; -ALTER TABLE mail_send_next RENAME TO mail_send; - -CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient); -CREATE INDEX mail_send_owed ON mail_send(next_attempt_at); -CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at); diff --git a/crates/izlek-core/migrations/0006_sender_is_config.sql b/crates/izlek-core/migrations/0006_sender_is_config.sql deleted file mode 100644 index fcad583..0000000 --- a/crates/izlek-core/migrations/0006_sender_is_config.sql +++ /dev/null @@ -1,37 +0,0 @@ --- The sender moves out of the database entirely. --- --- `workspace` carried six `smtp_*` columns, one of them the password. A --- password in a row is a password an admin session can ask for: any handler --- that can read the workspace record is one bug away from returning it, and a --- database file that is copied for a backup carries it along. The sender is --- infrastructure, not workspace content — it is the same for everyone in the --- workspace, it changes when the deployment changes, and it is already read --- from `IZLEK_SMTP_HOST`, `IZLEK_SMTP_PORT`, `IZLEK_SMTP_USERNAME`, --- `IZLEK_SMTP_PASSWORD` and `IZLEK_MAIL_FROM` at boot. --- --- So the columns go. Settings shows what the process is configured with and --- says the password lives in the server's configuration; changing it means --- changing the environment variable and restarting. --- --- The limits stay: they are workspace content, an admin edits them, and no --- restart should be needed to raise an attachment ceiling. --- --- SQLite cannot drop several columns and their comments in place here, so the --- table is rebuilt. Other tables reference `workspace` by name, and the name --- is what the rename restores. -CREATE TABLE workspace_next ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL, - created_at TEXT NOT NULL, - attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400, - photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, - -- JSON array of allowed extensions. An empty array means every type. - allowed_file_types TEXT NOT NULL DEFAULT '[]' -); - -INSERT INTO workspace_next -SELECT id, name, created_at, attachment_limit_bytes, photo_limit_bytes, allowed_file_types -FROM workspace; - -DROP TABLE workspace; -ALTER TABLE workspace_next RENAME TO workspace; diff --git a/crates/izlek-core/migrations/0007_who_invited.sql b/crates/izlek-core/migrations/0007_who_invited.sql deleted file mode 100644 index 06821a4..0000000 --- a/crates/izlek-core/migrations/0007_who_invited.sql +++ /dev/null @@ -1,8 +0,0 @@ --- The first-sign-in screen greets the invited person with the name of whoever --- made the account. Nothing recorded that, so the screen was reading the --- invitee's own name back to them: "Kay Watcher made you an account". --- --- The column is nullable and stays null for the first account, which nobody --- invited. It references user(id) rather than copying a name, so a later --- rename is reflected rather than frozen at invite time. -ALTER TABLE user ADD COLUMN invited_by TEXT REFERENCES user(id); diff --git a/crates/izlek-core/migrations/0008_sender_is_settings.sql b/crates/izlek-core/migrations/0008_sender_is_settings.sql deleted file mode 100644 index c9f33f6..0000000 --- a/crates/izlek-core/migrations/0008_sender_is_settings.sql +++ /dev/null @@ -1,31 +0,0 @@ --- The sender comes back into the table, because the admin sets it from the --- Settings screen and not from the server's environment. --- --- Migration 0006 moved these columns out on the argument that a password in a --- row is a password a handler can be made to return. That argument is sound --- and the mitigations survive: the password has no field on `Workspace`, so --- no query that loads a workspace can carry it; it is written by --- `Store::set_sender` and read by `Store::smtp_password`, which only the --- mailer calls; and nothing that reaches a page ever holds it. --- --- What it cost was the artboard's own screen: `SMTP HOST`, `PORT`, --- `USERNAME`, `PASSWORD`, `FROM NAME`, `FROM ADDRESS` and a Save button, with --- the sender changed by whoever runs the workspace rather than by whoever has --- a shell on the box. A three-person team has those be different people, and --- the second one is not always awake. --- --- The password is stored as it is typed. It has to be: the server presents it --- to the mail host on every send, so a one-way hash would make sending --- impossible, and encrypting it under a key that also lives on this disk moves --- the problem without shrinking it. The consequence is stated rather than --- dressed up — whoever holds a copy of this file holds the sender's password, --- so it belongs to a sending account and to nothing else. --- --- Added rather than rebuilt: `ALTER TABLE ... ADD COLUMN` works in place, and --- every one of these is nullable, which is what a workspace with no sender is. -ALTER TABLE workspace ADD COLUMN smtp_host TEXT; -ALTER TABLE workspace ADD COLUMN smtp_port INTEGER; -ALTER TABLE workspace ADD COLUMN smtp_username TEXT; -ALTER TABLE workspace ADD COLUMN smtp_password TEXT; -ALTER TABLE workspace ADD COLUMN smtp_from_name TEXT; -ALTER TABLE workspace ADD COLUMN smtp_from_address TEXT; diff --git a/crates/izlek-core/migrations/0009_sender_test.sql b/crates/izlek-core/migrations/0009_sender_test.sql deleted file mode 100644 index e5d2c92..0000000 --- a/crates/izlek-core/migrations/0009_sender_test.sql +++ /dev/null @@ -1,14 +0,0 @@ --- The result of the last "send test mail to myself", kept on the workspace. --- --- It is kept rather than shown once because of what the panel is for: an admin --- fills the sender in, presses the button, and comes back tomorrow wondering --- whether it ever worked. A result that vanished on reload would answer that --- question with silence, and silence is what the whole mail ledger exists to --- avoid. --- --- `smtp_test_error` is the mail server's own words, kept so the admin can act --- on them. Nothing writes the password into it: the mailer builds its errors --- from what the server said, never from the credentials it sent. -ALTER TABLE workspace ADD COLUMN smtp_test_at INTEGER; -ALTER TABLE workspace ADD COLUMN smtp_test_ms INTEGER; -ALTER TABLE workspace ADD COLUMN smtp_test_error TEXT; diff --git a/crates/izlek-core/migrations/0010_attachments_live_in_the_file.sql b/crates/izlek-core/migrations/0010_attachments_live_in_the_file.sql deleted file mode 100644 index bab7a84..0000000 --- a/crates/izlek-core/migrations/0010_attachments_live_in_the_file.sql +++ /dev/null @@ -1,30 +0,0 @@ --- Attachments, moved off the filesystem and into the database file. --- --- The table 0001 wrote kept a `stored_path`, and nothing ever filled it in. --- A path is the wrong shape for two reasons. Izlek is one process over one --- database file, and a second place to keep state is a second thing to back --- up, to lock, and to get out of step with the rows that name it. And a path --- is exactly where an uploaded file name must never end up: `../../etc` is a --- valid file name and a terrible path. Keeping the bytes here means the name --- is only ever a label printed on a chip, never anything the server resolves. --- --- Nothing has ever been written to the old table, so it goes rather than --- being migrated. -DROP TABLE attachment; - -CREATE TABLE attachment ( - id TEXT PRIMARY KEY, - task_id TEXT NOT NULL REFERENCES task(id), - -- The comment this file was posted with, when it was posted with one. - comment_id TEXT REFERENCES comment(id), - -- What the browser called it, kept for display only. - file_name TEXT NOT NULL, - -- What the server decided it is, from the bytes. Never what the upload - -- claimed. - mime_type TEXT NOT NULL, - size_bytes INTEGER NOT NULL, - bytes BLOB NOT NULL, - uploaded_by TEXT NOT NULL REFERENCES user(id), - created_at TEXT NOT NULL -); -CREATE INDEX attachment_by_task ON attachment(task_id); diff --git a/crates/izlek-core/migrations/0011_what_the_mail_decided.sql b/crates/izlek-core/migrations/0011_what_the_mail_decided.sql deleted file mode 100644 index 91985aa..0000000 --- a/crates/izlek-core/migrations/0011_what_the_mail_decided.sql +++ /dev/null @@ -1,42 +0,0 @@ --- What the mail engine decided, for every rule and every event, not just the --- mails it sent. --- --- `mail_send` only exists once a mail is owed and claimed; a card that moved --- but matched no rule, a rule that was disabled, a task deleted before its --- mail could go out — none of that left a trace. This table is that trace: --- one row per (rule, event, task), win or not, so "why did nobody get --- mailed" has an answer that is not "look at the logs from that day". --- --- `event_id` names a transition or a freeing the same way `mail_send.event_id` --- does and for the same reason (0005_freeing.sql:23-26): two tables can cause --- a decision, so the column cannot point a foreign key at either one and --- still hold both. `task_id` carries no foreign key either, on purpose: a --- `task_gone` row exists precisely because the task it names no longer does, --- and it has to keep saying so after the row it would have pointed at is --- deleted. -CREATE TABLE mail_decision ( - id TEXT PRIMARY KEY, - rule_id TEXT NOT NULL REFERENCES mail_rule(id) ON DELETE CASCADE, - event_id TEXT NOT NULL, - task_id TEXT NOT NULL, - -- 'owed' — a send was claimed for this - -- 'already_owed' — a send already existed; this is a replay - -- 'no_recipients' — the audience resolved to nobody - -- 'not_matched' — the event did not fire this rule - -- 'disabled' — the rule was off when the event happened - -- 'task_gone' — the task named by the event is deleted - outcome TEXT NOT NULL CHECK (outcome IN - ('owed', 'already_owed', 'no_recipients', 'not_matched', 'disabled', 'task_gone')), - detail TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL -); - --- Same event, same rule, same task decided twice is a bug worth refusing at --- the schema rather than finding in a report: a retry has to land on the --- decision that is already there, not beside it. -CREATE UNIQUE INDEX mail_decision_once ON mail_decision(rule_id, event_id, task_id); -CREATE INDEX mail_decision_recent ON mail_decision(created_at); - --- The activity strip's own index was never added when the table was: reading --- the most recent activity has been a full scan since 0001. -CREATE INDEX activity_recent ON activity(created_at); diff --git a/crates/izlek-core/migrations/0012_a_mail_that_owes_no_rule.sql b/crates/izlek-core/migrations/0012_a_mail_that_owes_no_rule.sql deleted file mode 100644 index 8e4eeba..0000000 --- a/crates/izlek-core/migrations/0012_a_mail_that_owes_no_rule.sql +++ /dev/null @@ -1,50 +0,0 @@ --- An invite is a mail with nobody it is owed to on the board and no event --- that caused it — a person is invited before they have a task, a --- transition, or a rule to owe them anything. `mail_send` has assumed all --- three since 0004_mail.sql; this rebuild lets a row go without them. --- --- `rule_id`/`event_id`/`task_id` become nullable, `rule_id`'s foreign key --- kept for the rows that still have one. `kind` says which shape a row is, --- and the two CHECKs make the shapes exclusive: a 'rule' send still has to --- carry all three of its old columns, an 'invite' send has to carry the --- subject and body a rule send gets from `mail_rule`/`compose` instead. --- --- SQLite cannot loosen a column's NOT NULL or add a CHECK in place, so the --- table is rebuilt again, same shape of migration as 0005_freeing.sql. -CREATE TABLE mail_send_next ( - id TEXT PRIMARY KEY, - rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE, - event_id TEXT, - task_id TEXT REFERENCES task(id), - recipient TEXT NOT NULL, - state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), - attempts INTEGER NOT NULL DEFAULT 0, - last_error TEXT, - claimed_at TEXT NOT NULL, - next_attempt_at TEXT, - sent_at TEXT, - kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite')), - subject TEXT, - body TEXT, - CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)), - CHECK ((kind = 'invite') = (subject IS NOT NULL AND body IS NOT NULL)) -); - -INSERT INTO mail_send_next -SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error, - claimed_at, next_attempt_at, sent_at, 'rule', NULL, NULL -FROM mail_send; - -DROP INDEX IF EXISTS mail_send_once; -DROP INDEX IF EXISTS mail_send_owed; -DROP INDEX IF EXISTS mail_send_by_rule; -DROP TABLE mail_send; -ALTER TABLE mail_send_next RENAME TO mail_send; - --- NULLs are distinct in a SQLite unique index, so two invite rows (whose --- rule_id/event_id/task_id are all NULL) never collide here — each invite --- send is its own row, which is intended: a resend is a new mail, not a --- replay of the same one. -CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient); -CREATE INDEX mail_send_owed ON mail_send(next_attempt_at); -CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at); diff --git a/crates/izlek-core/migrations/0013_more_than_a_move.sql b/crates/izlek-core/migrations/0013_more_than_a_move.sql deleted file mode 100644 index ba72185..0000000 --- a/crates/izlek-core/migrations/0013_more_than_a_move.sql +++ /dev/null @@ -1,48 +0,0 @@ --- The rule table named its two triggers in a CHECK: 'status' or 'unblocked', --- nothing else. Every new trigger has meant a migration just to widen that --- list. This rebuild drops the CHECK on `trigger_kind` entirely — a future --- trigger is a value, not a schema change — and widens `audience` to add --- 'creator' the same way 0004_mail.sql wrote it in the first place. --- --- SQLite cannot drop or relax a CHECK in place, so the table is rebuilt, --- same shape of migration as 0005_freeing.sql and 0012. --- --- `mail_send.rule_id` and `mail_decision.rule_id` both point at `mail_rule` --- with ON DELETE CASCADE, and every connection this store opens runs with --- foreign keys on. SQLite performs an implicit DELETE FROM before a DROP --- TABLE takes effect, and that implicit delete walks ON DELETE CASCADE like --- any other — dropping `mail_rule` with rows in it would carry every send and --- every decision away with it. `PRAGMA foreign_keys` is documented as a --- no-op inside a transaction, which is where every migration in this file --- runs, so the pragma is set here anyway and then proven by the reopen test --- rather than trusted from the manual. -PRAGMA foreign_keys = OFF; - -CREATE TABLE mail_rule_next ( - id TEXT PRIMARY KEY, - board_id TEXT NOT NULL REFERENCES board(id), - -- No CHECK list: the set of triggers grows without a schema change now. - trigger_kind TEXT NOT NULL, - trigger_column TEXT REFERENCES board_column(id), - subject TEXT NOT NULL, - -- 'assignees' — the people the card points at; 'board' — everyone who can - -- write on the board; 'creator' — whoever opened the card. - audience TEXT NOT NULL CHECK (audience IN ('assignees', 'board', 'creator')), - enabled INTEGER NOT NULL DEFAULT 1, - created_at TEXT NOT NULL, - -- A status rule names a column and an unblocked rule does not. The check - -- is here so a half-written rule cannot be stored at all. - CHECK ((trigger_kind = 'status') = (trigger_column IS NOT NULL)) -); - -INSERT INTO mail_rule_next -SELECT id, board_id, trigger_kind, trigger_column, subject, audience, enabled, created_at -FROM mail_rule; - -DROP INDEX IF EXISTS mail_rule_by_board; -DROP TABLE mail_rule; -ALTER TABLE mail_rule_next RENAME TO mail_rule; - -CREATE INDEX mail_rule_by_board ON mail_rule(board_id); - -PRAGMA foreign_keys = ON; diff --git a/crates/izlek-core/migrations/0014_created_into_a_column_is_a_transition.sql b/crates/izlek-core/migrations/0014_created_into_a_column_is_a_transition.sql deleted file mode 100644 index e3290ec..0000000 --- a/crates/izlek-core/migrations/0014_created_into_a_column_is_a_transition.sql +++ /dev/null @@ -1,32 +0,0 @@ --- A task created directly into a column never wrote a transition, so a rule --- watching that column ("When status becomes In Progress") never fired for --- it — only a later move into the column did. `create_task` now writes a --- transition in the same statement as the insert, with `from_column` set to --- '' (empty string) meaning "created into", never a real column. --- --- `from_column` carried `REFERENCES board_column(id)`, and no column's id is --- ever ''. SQLite cannot drop a column's foreign key in place, so the table --- is rebuilt, same shape as 0005_freeing.sql and 0013. -PRAGMA foreign_keys = OFF; - -CREATE TABLE transition_next ( - id TEXT PRIMARY KEY, - task_id TEXT NOT NULL REFERENCES task(id), - -- No REFERENCES: '' means "created into", and is never a column id. - from_column TEXT NOT NULL, - to_column TEXT NOT NULL REFERENCES board_column(id), - actor_id TEXT NOT NULL REFERENCES user(id), - created_at TEXT NOT NULL -); - -INSERT INTO transition_next -SELECT id, task_id, from_column, to_column, actor_id, created_at -FROM transition; - -DROP INDEX IF EXISTS transition_by_task; -DROP TABLE transition; -ALTER TABLE transition_next RENAME TO transition; - -CREATE INDEX transition_by_task ON transition(task_id, created_at); - -PRAGMA foreign_keys = ON; diff --git a/crates/izlek-core/migrations/0015_task_details_in_the_mail.sql b/crates/izlek-core/migrations/0015_task_details_in_the_mail.sql deleted file mode 100644 index 4e3fb4e..0000000 --- a/crates/izlek-core/migrations/0015_task_details_in_the_mail.sql +++ /dev/null @@ -1,5 +0,0 @@ --- A rule can opt into folding the task's own facts into the mail body, --- instead of the rule's subject line being the only thing the recipient --- reads. Off by default, so every existing rule keeps sending exactly what --- it always sent. -ALTER TABLE mail_rule ADD COLUMN include_task_details INTEGER NOT NULL DEFAULT 0; diff --git a/crates/izlek-core/migrations/0016_display_preferences.sql b/crates/izlek-core/migrations/0016_display_preferences.sql deleted file mode 100644 index f38c5b0..0000000 --- a/crates/izlek-core/migrations/0016_display_preferences.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Per-user display preferences. Stored data everywhere else stays UTC and --- language-neutral; these three columns only ever change how a browser --- renders that data for the one person signed in as this user. -ALTER TABLE user ADD COLUMN timezone TEXT NOT NULL DEFAULT 'UTC'; -ALTER TABLE user ADD COLUMN theme TEXT NOT NULL DEFAULT 'light'; -ALTER TABLE user ADD COLUMN language TEXT NOT NULL DEFAULT 'en'; diff --git a/crates/izlek-core/migrations/0017_ui_preference.sql b/crates/izlek-core/migrations/0017_ui_preference.sql deleted file mode 100644 index 0774e06..0000000 --- a/crates/izlek-core/migrations/0017_ui_preference.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Which interface this person uses. Display-only, as the preferences before --- it: no stored data depends on it. -ALTER TABLE user ADD COLUMN ui TEXT NOT NULL DEFAULT 'instrument'; diff --git a/crates/izlek-core/migrations/0018_photo_in_the_user.sql b/crates/izlek-core/migrations/0018_photo_in_the_user.sql deleted file mode 100644 index bef9f75..0000000 --- a/crates/izlek-core/migrations/0018_photo_in_the_user.sql +++ /dev/null @@ -1,5 +0,0 @@ --- A profile picture lives in the database as bytes, the way an attachment --- lives in its file (0010): no filesystem path survives a backup or a move. --- `photo_path` (0001) never carried a value and is left behind, dead. -ALTER TABLE user ADD COLUMN photo BLOB; -ALTER TABLE user ADD COLUMN photo_mime TEXT; diff --git a/crates/izlek-core/migrations/0019_events_without_a_task.sql b/crates/izlek-core/migrations/0019_events_without_a_task.sql deleted file mode 100644 index e90c3ff..0000000 --- a/crates/izlek-core/migrations/0019_events_without_a_task.sql +++ /dev/null @@ -1,23 +0,0 @@ --- Account and admin events — sign-ins, invites, role changes — have no task --- to sit under, and `activity.task_id` being NOT NULL left them unloggable. --- The table is rebuilt with the task column nullable. -CREATE TABLE activity_next ( - id TEXT PRIMARY KEY, - task_id TEXT REFERENCES task(id), - actor_id TEXT REFERENCES user(id), - kind TEXT NOT NULL, - detail TEXT NOT NULL DEFAULT '', - created_at TEXT NOT NULL -); - -INSERT INTO activity_next -SELECT id, task_id, actor_id, kind, detail, created_at -FROM activity; - -DROP INDEX IF EXISTS activity_by_task; -DROP INDEX IF EXISTS activity_recent; -DROP TABLE activity; -ALTER TABLE activity_next RENAME TO activity; - -CREATE INDEX activity_by_task ON activity(task_id); -CREATE INDEX activity_recent ON activity(created_at); diff --git a/crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sql b/crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sql deleted file mode 100644 index 7502abc..0000000 --- a/crates/izlek-core/migrations/0020_a_notice_owes_no_rule_either.sql +++ /dev/null @@ -1,38 +0,0 @@ --- A notice is an admin's own mail to a member — same shape as an invite: --- no rule, no event, no task, just a subject and a body. 0012's CHECK only --- named 'invite' alongside 'rule', so a 'notice' row would fail it. SQLite --- cannot widen a CHECK in place, so the table is rebuilt again, same shape --- of migration as 0012/0013. -CREATE TABLE mail_send_next ( - id TEXT PRIMARY KEY, - rule_id TEXT REFERENCES mail_rule(id) ON DELETE CASCADE, - event_id TEXT, - task_id TEXT REFERENCES task(id), - recipient TEXT NOT NULL, - state TEXT NOT NULL CHECK (state IN ('pending', 'sent', 'failed', 'abandoned')), - attempts INTEGER NOT NULL DEFAULT 0, - last_error TEXT, - claimed_at TEXT NOT NULL, - next_attempt_at TEXT, - sent_at TEXT, - kind TEXT NOT NULL DEFAULT 'rule' CHECK (kind IN ('rule', 'invite', 'notice')), - subject TEXT, - body TEXT, - CHECK ((kind = 'rule') = (rule_id IS NOT NULL AND event_id IS NOT NULL AND task_id IS NOT NULL)), - CHECK ((kind IN ('invite', 'notice')) = (subject IS NOT NULL AND body IS NOT NULL)) -); - -INSERT INTO mail_send_next -SELECT id, rule_id, event_id, task_id, recipient, state, attempts, last_error, - claimed_at, next_attempt_at, sent_at, kind, subject, body -FROM mail_send; - -DROP INDEX IF EXISTS mail_send_once; -DROP INDEX IF EXISTS mail_send_owed; -DROP INDEX IF EXISTS mail_send_by_rule; -DROP TABLE mail_send; -ALTER TABLE mail_send_next RENAME TO mail_send; - -CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, event_id, task_id, recipient); -CREATE INDEX mail_send_owed ON mail_send(next_attempt_at); -CREATE INDEX mail_send_by_rule ON mail_send(rule_id, sent_at); diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 2cd625c..12b0e0f 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -33,6 +33,13 @@ pub enum StoreError { /// The dependency asked for would put a task behind itself. #[error("that link would make a circle")] Cycle, + /// Subtasks are one level deep. Either the would-be parent is itself a + /// subtask, or the task being parented already has subtasks of its own. + #[error("subtasks go one level deep")] + NotNestable, + /// A parent and its subtask live on the same board. + #[error("that task is on another board")] + OtherBoard, } pub type Result = std::result::Result; @@ -209,6 +216,9 @@ impl Session { pub struct NewTask<'a> { pub board_id: &'a str, pub column_id: &'a str, + /// The task this one is a subtask of, if any. It must be on the same + /// board and must not itself be a subtask. + pub parent_id: Option<&'a str>, pub title: &'a str, pub description: &'a str, pub deadline: Option, @@ -740,6 +750,21 @@ pub trait Store: BoardReads + DetailReads + 'static { async fn create_task(&self, new: NewTask<'_>) -> Result; /// Idempotent: assigning someone twice is not an error. + /// Makes `task_id` a subtask of `parent_id`, or `None` to promote it back + /// to a task of its own. Both directions are one write: that is the whole + /// reason a subtask is a task with a parent rather than a row in a table + /// of its own. + /// + /// Refuses with [`StoreError::NotNestable`] when the move would make two + /// levels — the parent is already somebody's subtask, or the task being + /// parented has subtasks of its own — and with [`StoreError::OtherBoard`] + /// when the two are not on the same board. + async fn set_parent(&self, task_id: &str, parent_id: Option<&str>) -> Result<()>; + + /// The live subtasks of `parent_id`, oldest first. Empty for a task that + /// has none, and for a subtask, which cannot have any. + async fn subtasks(&self, parent_id: &str) -> Result>; + async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()>; async fn unassign_task(&self, task_id: &str, user_id: &str) -> Result<()>; diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 6edabb4..19877e8 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -33,49 +33,6 @@ use time::macros::format_description; /// Every migration, in order. Adding one means appending a file and a line. const MIGRATIONS: &[(i64, &str)] = &[ (1, include_str!("../../migrations/0001_init.sql")), - (2, include_str!("../../migrations/0002_auth.sql")), - (3, include_str!("../../migrations/0003_transition.sql")), - (4, include_str!("../../migrations/0004_mail.sql")), - (5, include_str!("../../migrations/0005_freeing.sql")), - (6, include_str!("../../migrations/0006_sender_is_config.sql")), - (7, include_str!("../../migrations/0007_who_invited.sql")), - (8, include_str!("../../migrations/0008_sender_is_settings.sql")), - (9, include_str!("../../migrations/0009_sender_test.sql")), - ( - 10, - include_str!("../../migrations/0010_attachments_live_in_the_file.sql"), - ), - ( - 11, - include_str!("../../migrations/0011_what_the_mail_decided.sql"), - ), - ( - 12, - include_str!("../../migrations/0012_a_mail_that_owes_no_rule.sql"), - ), - ( - 13, - include_str!("../../migrations/0013_more_than_a_move.sql"), - ), - ( - 14, - include_str!("../../migrations/0014_created_into_a_column_is_a_transition.sql"), - ), - ( - 15, - include_str!("../../migrations/0015_task_details_in_the_mail.sql"), - ), - ( - 16, - include_str!("../../migrations/0016_display_preferences.sql"), - ), - (17, include_str!("../../migrations/0017_ui_preference.sql")), - (18, include_str!("../../migrations/0018_photo_in_the_user.sql")), - (19, include_str!("../../migrations/0019_events_without_a_task.sql")), - ( - 20, - include_str!("../../migrations/0020_a_notice_owes_no_rule_either.sql"), - ), ]; /// The board a fresh workspace gets, and its columns. `Done` is the column @@ -1375,11 +1332,35 @@ impl Store for TursoStore { ) .await?; let Some(row) = rows.next().await? else { - return Ok(None); + return Ok(Err(StoreError::NotFound)); }; let prefix = row.get::(0)?; drop(rows); + // A subtask is checked before anything is written: the parent has + // to exist, sit on this board, and not be a subtask itself. + if let Some(parent) = new.parent_id { + let mut rows = tx + .query( + "SELECT board_id, parent_id FROM task \ + WHERE id = ?1 AND deleted_at IS NULL", + params![parent], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(Err(StoreError::NotFound)); + }; + let parent_board = row.get::(0)?; + let grandparent = row.get::>(1)?; + drop(rows); + if parent_board != new.board_id { + return Ok(Err(StoreError::OtherBoard)); + } + if grandparent.is_some() { + return Ok(Err(StoreError::NotNestable)); + } + } + // New cards land at the end of their column. let mut rows = tx .query( @@ -1405,9 +1386,9 @@ impl Store for TursoStore { let candidate = format!("{prefix}-{}", &id[id.len() - tail_len..]); match tx .execute( - "INSERT INTO task (id, board_id, task_key, title, description, column_id, \ - deadline, position, created_by, created_at, updated_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)", + "INSERT INTO task (id, board_id, parent_id, task_key, title, description, \ + column_id, deadline, position, created_by, created_at, updated_at) \ + VALUES (?1, ?2, ?11, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)", params![ id.clone(), new.board_id, @@ -1418,7 +1399,8 @@ impl Store for TursoStore { deadline.clone(), position, new.created_by, - now.clone() + now.clone(), + new.parent_id ], ) .await @@ -1456,15 +1438,15 @@ impl Store for TursoStore { ], ) .await?; - Ok::<_, turso::Error>(Some((task_key, position))) + Ok::<_, turso::Error>(Ok((task_key, position))) } .await; let written = match written { - Ok(Some(written)) => written, - Ok(None) => { + Ok(Ok(written)) => written, + Ok(Err(refused)) => { let _ = tx.rollback().await; - return Err(StoreError::NotFound); + return Err(refused); } Err(e) => { let _ = tx.rollback().await; @@ -1496,6 +1478,120 @@ impl Store for TursoStore { }) } + async fn set_parent(&self, task_id: &str, parent_id: Option<&str>) -> Result<()> { + let mut conn = self.tx_conn().await?; + // IMMEDIATE: the one-level rule is read-then-write. Two concurrent + // parentings each read a NULL parent, each pass, and the pair leaves a + // grandchild neither of them could see. + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + let outcome = async { + let mut rows = tx + .query( + "SELECT board_id FROM task WHERE id = ?1 AND deleted_at IS NULL", + params![task_id], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(Err(StoreError::NotFound)); + }; + let board_id = row.get::(0)?; + drop(rows); + + if let Some(parent) = parent_id { + if parent == task_id { + return Ok(Err(StoreError::Cycle)); + } + let mut rows = tx + .query( + "SELECT board_id, parent_id FROM task \ + WHERE id = ?1 AND deleted_at IS NULL", + params![parent], + ) + .await?; + let Some(row) = rows.next().await? else { + return Ok(Err(StoreError::NotFound)); + }; + let parent_board = row.get::(0)?; + let grandparent = row.get::>(1)?; + drop(rows); + if parent_board != board_id { + return Ok(Err(StoreError::OtherBoard)); + } + if grandparent.is_some() { + return Ok(Err(StoreError::NotNestable)); + } + + // The other half of the same rule: a task that already has + // subtasks cannot become one, or its own children become + // grandchildren without ever being touched. + let mut rows = tx + .query( + "SELECT 1 FROM task WHERE parent_id = ?1 AND deleted_at IS NULL LIMIT 1", + params![task_id], + ) + .await?; + let has_children = rows.next().await?.is_some(); + drop(rows); + if has_children { + return Ok(Err(StoreError::NotNestable)); + } + } + + tx.execute( + "UPDATE task SET parent_id = ?2 WHERE id = ?1", + params![task_id, parent_id], + ) + .await?; + Ok::<_, turso::Error>(Ok(())) + } + .await; + + match outcome { + Ok(Ok(())) => { + tx.commit().await.map_err(backend)?; + Ok(()) + } + Ok(Err(refused)) => { + let _ = tx.rollback().await; + Err(refused) + } + Err(e) => { + let _ = tx.rollback().await; + Err(backend(e)) + } + } + } + + async fn subtasks(&self, parent_id: &str) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, task_key, title, column_id, deadline, position, done_at \ + FROM task WHERE parent_id = ?1 AND deleted_at IS NULL \ + ORDER BY created_at", + params![parent_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(TaskRow { + id: text(&row, 0)?, + task_key: text(&row, 1)?, + title: text(&row, 2)?, + column_id: text(&row, 3)?, + deadline: opt_day(&row, 4)?, + position: row.get::(5).unwrap_or(0.0), + done_at: opt_stamp(&row, 6)?, + }); + } + Ok(out) + } + async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()> { let conn = self.conn.lock().await; conn diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index cb5ad53..a063b76 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -94,141 +94,6 @@ async fn member(store: &TursoStore, workspace_id: &str, email: &str, name: &str) .id } -/// Builds a database file shaped like schema version 12 — every migration -/// through 0012 applied, nothing after — by replaying the migration files -/// straight off disk on a raw connection, the same way [`TursoStore::apply`] -/// does it one at a time. Used only to put a rule, a send and a decision in -/// place before 0013 exists, so 0013 runs against real rows rather than an -/// empty table. -async fn a_pre_0013_store_with_a_rule_send_and_decision() --> (PathBuf, String, String, String, String) { - let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("izlek.db").to_string_lossy().into_owned(); - - let db = turso::Builder::new_local(&path).build().await.unwrap(); - let conn = db.connect().unwrap(); - conn.execute("PRAGMA foreign_keys = ON", ()).await.unwrap(); - conn.execute( - "CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)", - (), - ) - .await - .unwrap(); - - let migrations_dir = - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("migrations"); - let mut files: Vec<_> = std::fs::read_dir(&migrations_dir) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| { - p.file_name() - .and_then(|n| n.to_str()) - .map(|n| n < "0013") - .unwrap_or(false) - }) - .collect(); - files.sort(); - for (i, file) in files.iter().enumerate() { - let sql = std::fs::read_to_string(file).unwrap(); - conn.execute_batch(&sql).await.unwrap(); - conn.execute( - "INSERT INTO schema_version (version, applied_at) VALUES (?1, '2026-08-26T00:00:00Z')", - turso::params![(i + 1) as i64], - ) - .await - .unwrap(); - } - - let workspace = Ulid::new().to_string(); - let admin = Ulid::new().to_string(); - let board = Ulid::new().to_string(); - let backlog = Ulid::new().to_string(); - let done = Ulid::new().to_string(); - let task = Ulid::new().to_string(); - let rule = Ulid::new().to_string(); - let transition = Ulid::new().to_string(); - conn.execute( - "INSERT INTO workspace (id, name, created_at) VALUES (?1, 'Izlek', '2026-08-26T00:00:00Z')", - turso::params![workspace.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO user (id, workspace_id, email, display_name, role, password_hash, \ - created_at) VALUES (?1, ?2, 'ada@izlek.sh', 'Ada', 'admin', 'x', '2026-08-26T00:00:00Z')", - turso::params![admin.clone(), workspace.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO board (id, workspace_id, name, created_at) VALUES (?1, ?2, 'Board', \ - '2026-08-26T00:00:00Z')", - turso::params![board.clone(), workspace.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO board_column (id, board_id, name, position, is_done) VALUES (?1, ?2, \ - 'Backlog', 0, 0)", - turso::params![backlog.clone(), board.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO board_column (id, board_id, name, position, is_done) VALUES (?1, ?2, \ - 'Done', 1, 1)", - turso::params![done.clone(), board.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO task (id, board_id, task_key, title, column_id, created_by, created_at, \ - updated_at) VALUES (?1, ?2, 'DZ-1', 'Ship it', ?3, ?4, '2026-08-26T00:00:00Z', '2026-08-26T00:00:00Z')", - turso::params![task.clone(), board.clone(), done.clone(), admin.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO transition (id, task_id, from_column, to_column, actor_id, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, '2026-08-26T00:00:00Z')", - turso::params![ - transition.clone(), - task.clone(), - backlog.clone(), - done.clone(), - admin.clone() - ], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO mail_rule (id, board_id, trigger_kind, trigger_column, subject, audience, \ - enabled, created_at) VALUES (?1, ?2, 'status', ?3, 'Task completed', 'assignees', 1, \ - '2026-08-26T00:00:00Z')", - turso::params![rule.clone(), board.clone(), done.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO mail_send (id, rule_id, event_id, task_id, recipient, state, attempts, \ - claimed_at) VALUES ('s1', ?1, ?2, ?3, 'ada@izlek.sh', 'pending', 0, '2026-08-26T00:00:00Z')", - turso::params![rule.clone(), transition.clone(), task.clone()], - ) - .await - .unwrap(); - conn.execute( - "INSERT INTO mail_decision (id, rule_id, event_id, task_id, outcome, detail, \ - created_at) VALUES ('d1', ?1, ?2, ?3, 'owed', '', '2026-08-26T00:00:00Z')", - turso::params![rule.clone(), transition.clone(), task.clone()], - ) - .await - .unwrap(); - drop(conn); - - (PathBuf::from(path), workspace, board, rule, task) -} - #[tokio::test] async fn migrations_apply_once_and_survive_reopen() { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); @@ -236,52 +101,170 @@ async fn migrations_apply_once_and_survive_reopen() { let path = dir.join("izlek.db").to_string_lossy().into_owned(); let first = TursoStore::open(&path).await.unwrap(); - assert_eq!(first.schema_version().await.unwrap(), 20); + assert_eq!(first.schema_version().await.unwrap(), 1); claim(&first).await; drop(first); // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and // must not lose what the first open wrote. let second = TursoStore::open(&path).await.unwrap(); - assert_eq!(second.schema_version().await.unwrap(), 20); + assert_eq!(second.schema_version().await.unwrap(), 1); assert_eq!(second.workspace().await.unwrap().unwrap().name, "Izlek"); drop(second); let _ = std::fs::remove_dir_all(&dir); } #[tokio::test] -async fn migration_0013_rebuilds_mail_rule_without_losing_its_ledger() { - // `mail_send.rule_id` and `mail_decision.rule_id` both carry ON DELETE - // CASCADE at `mail_rule`, and every connection this store opens runs with - // foreign keys on. Rebuilding `mail_rule` — dropping the old table while - // rows still point at it — would, without a guard, cascade the drop - // straight through this rule's own send and its own decision. - let (path, workspace, board, rule, task) = - a_pre_0013_store_with_a_rule_send_and_decision().await; +async fn a_subtask_is_a_task_with_a_parent() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let parent = add_task( + &scratch.store, + &workspace, + "Backlog", + "Ship the exporter", + None, + &admin, + ) + .await; - let store = TursoStore::open(path.to_str().unwrap()).await.unwrap(); - assert_eq!(store.schema_version().await.unwrap(), 20); - assert_eq!(store.board(&workspace).await.unwrap().unwrap().id, board); + let board = scratch.store.board(&workspace).await.unwrap().unwrap(); + let column_id = column_named(&scratch.store, &workspace, "Backlog").await; + let child = scratch + .store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + parent_id: Some(&parent), + title: "Write the CSV writer", + description: "", + deadline: None, + created_by: &admin, + }) + .await + .unwrap() + .row; - let rules = store.mail_rules(&board).await.unwrap(); - assert_eq!(rules.len(), 1, "the rule survived the rebuild"); - assert_eq!(rules[0].id, rule); - assert_eq!(rules[0].audience, Audience::Assignees); + // It gets a key of its own from the same prefix, not a derived DZ-14.1. + assert!(child.task_key.starts_with("DZ-")); + assert_ne!(child.task_key, parent); - let sends = store.sends_for_rule(&rule, 10).await.unwrap(); - assert_eq!(sends.len(), 1, "the send survived, joined to its rule"); - assert_eq!(sends[0].task_id, Some(task.clone())); + let children = scratch.store.subtasks(&parent).await.unwrap(); + assert_eq!(children.len(), 1); + assert_eq!(children[0].id, child.id); + assert!( + scratch.store.subtasks(&child.id).await.unwrap().is_empty(), + "a subtask has none of its own" + ); +} - let decisions = store.recent_mail_decisions(10, izlek_core::store::FeedPage::Newest).await.unwrap(); +#[tokio::test] +async fn subtasks_go_one_level_deep() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let board = scratch.store.board(&workspace).await.unwrap().unwrap(); + let column_id = column_named(&scratch.store, &workspace, "Backlog").await; + + let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await; + let child = scratch + .store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + parent_id: Some(&parent), + title: "Child", + description: "", + deadline: None, + created_by: &admin, + }) + .await + .unwrap() + .row + .id; + + // Creating under a subtask is refused outright. + let grandchild = scratch + .store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + parent_id: Some(&child), + title: "Grandchild", + description: "", + deadline: None, + created_by: &admin, + }) + .await; + assert!(matches!(grandchild, Err(StoreError::NotNestable))); + + // And so is reaching the same shape from the other side: an existing task + // cannot be filed under a subtask ... + let loose = add_task(&scratch.store, &workspace, "Backlog", "Loose", None, &admin).await; + assert!(matches!( + scratch.store.set_parent(&loose, Some(&child)).await, + Err(StoreError::NotNestable) + )); + + // ... nor can a task that already has children become one itself. + assert!(matches!( + scratch.store.set_parent(&parent, Some(&loose)).await, + Err(StoreError::NotNestable) + )); + + // Nothing was written by any of the three refusals. + assert_eq!(scratch.store.subtasks(&parent).await.unwrap().len(), 1); + assert!(scratch.store.subtasks(&child).await.unwrap().is_empty()); + assert!(scratch.store.subtasks(&loose).await.unwrap().is_empty()); +} + +#[tokio::test] +async fn a_task_cannot_be_its_own_parent() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let task = add_task(&scratch.store, &workspace, "Backlog", "Alone", None, &admin).await; + + assert!(matches!( + scratch.store.set_parent(&task, Some(&task)).await, + Err(StoreError::Cycle) + )); + assert!(scratch.store.subtasks(&task).await.unwrap().is_empty()); +} + +#[tokio::test] +async fn parenting_and_promoting_are_each_one_write() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let parent = add_task(&scratch.store, &workspace, "Backlog", "Parent", None, &admin).await; + let loose = add_task(&scratch.store, &workspace, "Review", "Loose", None, &admin).await; + + scratch.store.set_parent(&loose, Some(&parent)).await.unwrap(); + let children = scratch.store.subtasks(&parent).await.unwrap(); + assert_eq!(children.len(), 1); + assert_eq!(children[0].id, loose); + // It kept everything a task has: it did not move column to become one. assert_eq!( - decisions.len(), - 1, - "the decision survived, joined to its rule" + children[0].column_id, + column_named(&scratch.store, &workspace, "Review").await ); - assert_eq!(decisions[0].rule_id, rule); - drop(store); - let _ = std::fs::remove_dir_all(path.parent().unwrap()); + scratch.store.set_parent(&loose, None).await.unwrap(); + assert!(scratch.store.subtasks(&parent).await.unwrap().is_empty()); +} + +#[tokio::test] +async fn parenting_a_task_that_is_not_there_is_not_found() { + let scratch = Scratch::open().await; + let (workspace, admin) = claim(&scratch.store).await; + let task = add_task(&scratch.store, &workspace, "Backlog", "Alone", None, &admin).await; + + assert!(matches!( + scratch.store.set_parent(&task, Some("nope")).await, + Err(StoreError::NotFound) + )); + assert!(matches!( + scratch.store.set_parent("nope", None).await, + Err(StoreError::NotFound) + )); } #[tokio::test] @@ -2033,6 +2016,7 @@ async fn add_task( .create_task(NewTask { board_id: &board.id, column_id: &column_id, + parent_id: None, title, description: "", deadline, @@ -3705,6 +3689,7 @@ async fn a_task_created_straight_into_a_watched_column_mails_too() { .create_task(NewTask { board_id: &board.id, column_id: &column_id, + parent_id: None, title: "Wire the exporter", description: "", deadline: None, @@ -4920,6 +4905,7 @@ async fn a_created_task_s_activity_id_resolves_as_an_event() { let created = store .create_task(NewTask { + parent_id: None, board_id: &board.id, column_id: &column_id, title: "brand new", diff --git a/crates/izlek-web/src/board.rs b/crates/izlek-web/src/board.rs index 8fb1fb9..2e635c6 100644 --- a/crates/izlek-web/src/board.rs +++ b/crates/izlek-web/src/board.rs @@ -110,6 +110,7 @@ async fn create_task_shared( .create_task(NewTask { board_id: &board.id, column_id, + parent_id: None, title, description: description.trim(), deadline,