Schema, migration runner and Turso store behind a trait
Browse files at this commit9cf2cb5ad0b9d76cb459356d93bcb1331806630eParent: 7acf2ce- feat
- schema, migration runner and Turso store behind a trait
9 changed files +1414 -1
- Cargo.lock +4 -0
- Cargo.toml +2 -1
- crates/dizey-core/Cargo.toml +7 -0
- crates/dizey-core/migrations/0001_init.sql +192 -0
- crates/dizey-core/src/lib.rs +2 -0
- crates/dizey-core/src/role.rs +10 -0
- crates/dizey-core/src/store/mod.rs +202 -0
- crates/dizey-core/src/store/turso_store.rs +628 -0
- crates/dizey-core/tests/store.rs +367 -0
Cargo.lockmodified+4 -0
| @@ -859,9 +859,13 @@ dependencies = [ | |||
| 859 | name = "dizey-core" | 859 | name = "dizey-core" |
| 860 | version = "0.1.0" | 860 | version = "0.1.0" |
| 861 | dependencies = [ | 861 | dependencies = [ |
| 862 | + "async-trait", | ||
| 862 | "serde", | 863 | "serde", |
| 864 | + "serde_json", | ||
| 863 | "thiserror", | 865 | "thiserror", |
| 864 | "time", | 866 | "time", |
| 867 | + "tokio", | ||
| 868 | + "turso", | ||
| 865 | "uuid", | 869 | "uuid", |
| 866 | ] | 870 | ] |
| 867 | 871 | ||
Cargo.tomlmodified+2 -1
| @@ -11,11 +11,12 @@ repository = "https://github.com/DizeyLab/izlek" | |||
| 11 | [workspace.dependencies] | 11 | [workspace.dependencies] |
| 12 | dizey-core = { path = "crates/dizey-core" } | 12 | dizey-core = { path = "crates/dizey-core" } |
| 13 | serde = { version = "1.0.229", features = ["derive"] } | 13 | serde = { version = "1.0.229", features = ["derive"] } |
| 14 | +serde_json = "1.0.145" | ||
| 14 | thiserror = "2.0.20" | 15 | thiserror = "2.0.20" |
| 15 | uuid = { version = "1.25.0", features = ["v4", "serde"] } | 16 | uuid = { version = "1.25.0", features = ["v4", "serde"] } |
| 16 | time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] } | 17 | time = { version = "0.3.55", features = ["serde", "formatting", "parsing", "macros"] } |
| 17 | tokio = { version = "1.53.1", features = ["full"] } | 18 | tokio = { version = "1.53.1", features = ["full"] } |
| 18 | -turso = "0.8.0-pre.7" | 19 | +turso = "=0.8.0-pre.7" |
| 19 | 20 | ||
| 20 | [profile.release] | 21 | [profile.release] |
| 21 | codegen-units = 1 | 22 | codegen-units = 1 |
crates/dizey-core/Cargo.tomlmodified+7 -0
| @@ -7,7 +7,14 @@ repository.workspace = true | |||
| 7 | description = "Domain model and storage for Dizey" | 7 | description = "Domain model and storage for Dizey" |
| 8 | 8 | ||
| 9 | [dependencies] | 9 | [dependencies] |
| 10 | +async-trait = "0.1.92" | ||
| 10 | serde.workspace = true | 11 | serde.workspace = true |
| 12 | +serde_json.workspace = true | ||
| 11 | thiserror.workspace = true | 13 | thiserror.workspace = true |
| 12 | time.workspace = true | 14 | time.workspace = true |
| 15 | +turso.workspace = true | ||
| 13 | uuid.workspace = true | 16 | uuid.workspace = true |
| 17 | + | ||
| 18 | +[dev-dependencies] | ||
| 19 | +serde_json.workspace = true | ||
| 20 | +tokio = { workspace = true } | ||
crates/dizey-core/migrations/0001_init.sqladded+192 -0
| @@ -0,0 +1,192 @@ | |||
| 1 | +-- Dizey initial schema. | ||
| 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 UUIDs as text. | ||
| 6 | + | ||
| 7 | +CREATE TABLE workspace ( | ||
| 8 | + id TEXT PRIMARY KEY, | ||
| 9 | + name TEXT NOT NULL, | ||
| 10 | + created_at TEXT NOT NULL, | ||
| 11 | + -- The single sender every mail in the workspace goes through. Written by | ||
| 12 | + -- the admin in Settings; the password is never returned to the client. | ||
| 13 | + smtp_host TEXT, | ||
| 14 | + smtp_port INTEGER, | ||
| 15 | + smtp_username TEXT, | ||
| 16 | + smtp_password TEXT, | ||
| 17 | + smtp_from_name TEXT, | ||
| 18 | + smtp_from_address TEXT, | ||
| 19 | + -- Limits. Each states its consequence in the UI, not here. | ||
| 20 | + attachment_limit_bytes INTEGER NOT NULL DEFAULT 26214400, | ||
| 21 | + photo_limit_bytes INTEGER NOT NULL DEFAULT 2097152, | ||
| 22 | + -- JSON array of allowed extensions. An empty array means every type. | ||
| 23 | + allowed_file_types TEXT NOT NULL DEFAULT '[]', | ||
| 24 | + -- 'anyone' | 'admin' | ||
| 25 | + who_can_delete_tasks TEXT NOT NULL DEFAULT 'anyone' | ||
| 26 | +); | ||
| 27 | + | ||
| 28 | +CREATE TABLE user ( | ||
| 29 | + id TEXT PRIMARY KEY, | ||
| 30 | + workspace_id TEXT NOT NULL REFERENCES workspace(id), | ||
| 31 | + email TEXT NOT NULL, | ||
| 32 | + display_name TEXT NOT NULL, | ||
| 33 | + -- 'admin' | 'member' | 'viewer' | ||
| 34 | + role TEXT NOT NULL, | ||
| 35 | + -- NULL until the person picks a password on first sign-in. The admin | ||
| 36 | + -- creates the account with a name and an address and nothing else. | ||
| 37 | + password_hash TEXT, | ||
| 38 | + photo_path TEXT, | ||
| 39 | + created_at TEXT NOT NULL, | ||
| 40 | + last_signed_in_at TEXT | ||
| 41 | +); | ||
| 42 | +CREATE UNIQUE INDEX user_email_unique ON user(workspace_id, email); | ||
| 43 | + | ||
| 44 | +-- First sign-in / resend links. Only the hash is stored: the plaintext is shown | ||
| 45 | +-- once when the admin creates or resends it. | ||
| 46 | +CREATE TABLE signin_link ( | ||
| 47 | + id TEXT PRIMARY KEY, | ||
| 48 | + user_id TEXT NOT NULL REFERENCES user(id), | ||
| 49 | + token_hash TEXT NOT NULL, | ||
| 50 | + created_at TEXT NOT NULL, | ||
| 51 | + expires_at TEXT NOT NULL, | ||
| 52 | + used_at TEXT | ||
| 53 | +); | ||
| 54 | +CREATE UNIQUE INDEX signin_link_token ON signin_link(token_hash); | ||
| 55 | + | ||
| 56 | +CREATE TABLE board ( | ||
| 57 | + id TEXT PRIMARY KEY, | ||
| 58 | + workspace_id TEXT NOT NULL REFERENCES workspace(id), | ||
| 59 | + name TEXT NOT NULL, | ||
| 60 | + task_prefix TEXT NOT NULL DEFAULT 'DZ', | ||
| 61 | + next_task_no INTEGER NOT NULL DEFAULT 1, | ||
| 62 | + created_at TEXT NOT NULL | ||
| 63 | +); | ||
| 64 | + | ||
| 65 | +CREATE TABLE board_column ( | ||
| 66 | + id TEXT PRIMARY KEY, | ||
| 67 | + board_id TEXT NOT NULL REFERENCES board(id), | ||
| 68 | + name TEXT NOT NULL, | ||
| 69 | + position INTEGER NOT NULL, | ||
| 70 | + -- The column a finished task lands in; drives the "done Aug 14" card state. | ||
| 71 | + is_done INTEGER NOT NULL DEFAULT 0 | ||
| 72 | +); | ||
| 73 | + | ||
| 74 | +CREATE TABLE task ( | ||
| 75 | + id TEXT PRIMARY KEY, | ||
| 76 | + board_id TEXT NOT NULL REFERENCES board(id), | ||
| 77 | + -- Human key from the mockups, e.g. DZ-14. | ||
| 78 | + task_key TEXT NOT NULL, | ||
| 79 | + title TEXT NOT NULL, | ||
| 80 | + description TEXT NOT NULL DEFAULT '', | ||
| 81 | + column_id TEXT NOT NULL REFERENCES board_column(id), | ||
| 82 | + deadline TEXT, | ||
| 83 | + position REAL NOT NULL DEFAULT 0, | ||
| 84 | + created_by TEXT NOT NULL REFERENCES user(id), | ||
| 85 | + created_at TEXT NOT NULL, | ||
| 86 | + updated_at TEXT NOT NULL, | ||
| 87 | + done_at TEXT, | ||
| 88 | + deleted_at TEXT | ||
| 89 | +); | ||
| 90 | +CREATE UNIQUE INDEX task_key_unique ON task(board_id, task_key); | ||
| 91 | +CREATE INDEX task_by_column ON task(column_id); | ||
| 92 | + | ||
| 93 | +CREATE TABLE task_assignee ( | ||
| 94 | + task_id TEXT NOT NULL REFERENCES task(id), | ||
| 95 | + user_id TEXT NOT NULL REFERENCES user(id), | ||
| 96 | + PRIMARY KEY (task_id, user_id) | ||
| 97 | +); | ||
| 98 | + | ||
| 99 | +CREATE TABLE task_watcher ( | ||
| 100 | + task_id TEXT NOT NULL REFERENCES task(id), | ||
| 101 | + user_id TEXT NOT NULL REFERENCES user(id), | ||
| 102 | + PRIMARY KEY (task_id, user_id) | ||
| 103 | +); | ||
| 104 | + | ||
| 105 | +-- blocked_task_id is blocked by blocking_task_id. cleared_at is set when the | ||
| 106 | +-- blocking task finishes, which is what the "you can start now" rule reads. | ||
| 107 | +CREATE TABLE task_dependency ( | ||
| 108 | + blocked_task_id TEXT NOT NULL REFERENCES task(id), | ||
| 109 | + blocking_task_id TEXT NOT NULL REFERENCES task(id), | ||
| 110 | + created_at TEXT NOT NULL, | ||
| 111 | + cleared_at TEXT, | ||
| 112 | + PRIMARY KEY (blocked_task_id, blocking_task_id) | ||
| 113 | +); | ||
| 114 | + | ||
| 115 | +CREATE TABLE comment ( | ||
| 116 | + id TEXT PRIMARY KEY, | ||
| 117 | + task_id TEXT NOT NULL REFERENCES task(id), | ||
| 118 | + author_id TEXT NOT NULL REFERENCES user(id), | ||
| 119 | + body TEXT NOT NULL, | ||
| 120 | + created_at TEXT NOT NULL | ||
| 121 | +); | ||
| 122 | +CREATE INDEX comment_by_task ON comment(task_id); | ||
| 123 | + | ||
| 124 | +CREATE TABLE attachment ( | ||
| 125 | + id TEXT PRIMARY KEY, | ||
| 126 | + task_id TEXT NOT NULL REFERENCES task(id), | ||
| 127 | + comment_id TEXT REFERENCES comment(id), | ||
| 128 | + file_name TEXT NOT NULL, | ||
| 129 | + mime_type TEXT NOT NULL, | ||
| 130 | + size_bytes INTEGER NOT NULL, | ||
| 131 | + stored_path TEXT NOT NULL, | ||
| 132 | + uploaded_by TEXT NOT NULL REFERENCES user(id), | ||
| 133 | + created_at TEXT NOT NULL | ||
| 134 | +); | ||
| 135 | + | ||
| 136 | +-- The activity strip in the task detail: who did what, and whether it mailed. | ||
| 137 | +CREATE TABLE activity ( | ||
| 138 | + id TEXT PRIMARY KEY, | ||
| 139 | + task_id TEXT NOT NULL REFERENCES task(id), | ||
| 140 | + actor_id TEXT REFERENCES user(id), | ||
| 141 | + kind TEXT NOT NULL, | ||
| 142 | + detail TEXT NOT NULL DEFAULT '', | ||
| 143 | + created_at TEXT NOT NULL | ||
| 144 | +); | ||
| 145 | +CREATE INDEX activity_by_task ON activity(task_id); | ||
| 146 | + | ||
| 147 | +-- Mail rules are written only by the admin and are always on. A rule that | ||
| 148 | +-- addresses an external address stays off until that address confirms. | ||
| 149 | +CREATE TABLE mail_rule ( | ||
| 150 | + id TEXT PRIMARY KEY, | ||
| 151 | + workspace_id TEXT NOT NULL REFERENCES workspace(id), | ||
| 152 | + board_id TEXT REFERENCES board(id), | ||
| 153 | + -- 'status_becomes' | 'deadline_in' | 'unblocked' | ||
| 154 | + trigger_kind TEXT NOT NULL, | ||
| 155 | + trigger_value TEXT NOT NULL, | ||
| 156 | + subject TEXT NOT NULL, | ||
| 157 | + -- 'assignees' | 'assignees_watchers' | 'everyone' | 'external' | ||
| 158 | + audience TEXT NOT NULL, | ||
| 159 | + external_address TEXT, | ||
| 160 | + external_confirmed INTEGER NOT NULL DEFAULT 0, | ||
| 161 | + created_at TEXT NOT NULL, | ||
| 162 | + last_sent_at TEXT | ||
| 163 | +); | ||
| 164 | + | ||
| 165 | +-- One row per (rule, task, transition) actually sent, so a revert-then-redo | ||
| 166 | +-- does not mail twice. | ||
| 167 | +CREATE TABLE mail_send ( | ||
| 168 | + id TEXT PRIMARY KEY, | ||
| 169 | + rule_id TEXT NOT NULL REFERENCES mail_rule(id), | ||
| 170 | + task_id TEXT NOT NULL REFERENCES task(id), | ||
| 171 | + transition TEXT NOT NULL, | ||
| 172 | + sent_at TEXT NOT NULL | ||
| 173 | +); | ||
| 174 | +CREATE UNIQUE INDEX mail_send_once ON mail_send(rule_id, task_id, transition); | ||
| 175 | + | ||
| 176 | +-- Read-only links: dizey.sh/v/<id>. Only the hash of the token is stored, so a | ||
| 177 | +-- database copy does not hand out working links; revoking is server-side and | ||
| 178 | +-- immediate. | ||
| 179 | +CREATE TABLE view_link ( | ||
| 180 | + id TEXT PRIMARY KEY, | ||
| 181 | + workspace_id TEXT NOT NULL REFERENCES workspace(id), | ||
| 182 | + board_id TEXT NOT NULL REFERENCES board(id), | ||
| 183 | + token_hash TEXT NOT NULL, | ||
| 184 | + -- 'whole_board' | 'deadlines' | ||
| 185 | + scope TEXT NOT NULL, | ||
| 186 | + created_by TEXT NOT NULL REFERENCES user(id), | ||
| 187 | + created_at TEXT NOT NULL, | ||
| 188 | + expires_at TEXT, | ||
| 189 | + revoked_at TEXT, | ||
| 190 | + open_count INTEGER NOT NULL DEFAULT 0 | ||
| 191 | +); | ||
| 192 | +CREATE UNIQUE INDEX view_link_token ON view_link(token_hash); | ||
crates/dizey-core/src/lib.rsmodified+2 -0
| @@ -4,5 +4,7 @@ | |||
| 4 | //! `ssr` feature so none of it is compiled into the wasm bundle. | 4 | //! `ssr` feature so none of it is compiled into the wasm bundle. |
| 5 | 5 | ||
| 6 | pub mod role; | 6 | pub mod role; |
| 7 | +pub mod store; | ||
| 7 | 8 | ||
| 8 | pub use role::Role; | 9 | pub use role::Role; |
| 10 | +pub use store::{Store, StoreError, TursoStore}; | ||
crates/dizey-core/src/role.rsmodified+10 -0
| @@ -51,6 +51,16 @@ impl Role { | |||
| 51 | Role::Viewer => "viewer", | 51 | Role::Viewer => "viewer", |
| 52 | } | 52 | } |
| 53 | } | 53 | } |
| 54 | + | ||
| 55 | + /// The inverse of [`Role::as_str`], for values read back out of the store. | ||
| 56 | + pub fn parse(raw: &str) -> Option<Self> { | ||
| 57 | + match raw { | ||
| 58 | + "admin" => Some(Role::Admin), | ||
| 59 | + "member" => Some(Role::Member), | ||
| 60 | + "viewer" => Some(Role::Viewer), | ||
| 61 | + _ => None, | ||
| 62 | + } | ||
| 63 | + } | ||
| 54 | } | 64 | } |
| 55 | 65 | ||
| 56 | #[cfg(test)] | 66 | #[cfg(test)] |
crates/dizey-core/src/store/mod.rsadded+202 -0
| @@ -0,0 +1,202 @@ | |||
| 1 | +//! Storage boundary. | ||
| 2 | +//! | ||
| 3 | +//! Everything the app does to persistent state goes through [`Store`]. The only | ||
| 4 | +//! implementation today is Turso (in-process, SQLite-compatible); a Postgres | ||
| 5 | +//! swap is a new impl of this trait and nothing else. | ||
| 6 | + | ||
| 7 | +use async_trait::async_trait; | ||
| 8 | +use serde::{Deserialize, Serialize}; | ||
| 9 | +use time::OffsetDateTime; | ||
| 10 | + | ||
| 11 | +use crate::Role; | ||
| 12 | + | ||
| 13 | +pub mod turso_store; | ||
| 14 | + | ||
| 15 | +pub use turso_store::TursoStore; | ||
| 16 | + | ||
| 17 | +#[derive(Debug, thiserror::Error)] | ||
| 18 | +pub enum StoreError { | ||
| 19 | + #[error("database: {0}")] | ||
| 20 | + Backend(String), | ||
| 21 | + #[error("not found")] | ||
| 22 | + NotFound, | ||
| 23 | + #[error("{0} already exists")] | ||
| 24 | + Conflict(&'static str), | ||
| 25 | + #[error("stored value is not valid: {0}")] | ||
| 26 | + Corrupt(String), | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +pub type Result<T> = std::result::Result<T, StoreError>; | ||
| 30 | + | ||
| 31 | +/// A workspace and the settings that ride on it. The SMTP password is | ||
| 32 | +/// deliberately absent: it is written through [`Store::set_smtp`] and read only | ||
| 33 | +/// by the mailer, never returned to a page. | ||
| 34 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | ||
| 35 | +pub struct Workspace { | ||
| 36 | + pub id: String, | ||
| 37 | + pub name: String, | ||
| 38 | + pub created_at: OffsetDateTime, | ||
| 39 | + pub smtp_host: Option<String>, | ||
| 40 | + pub smtp_port: Option<u32>, | ||
| 41 | + pub smtp_username: Option<String>, | ||
| 42 | + pub smtp_from_name: Option<String>, | ||
| 43 | + pub smtp_from_address: Option<String>, | ||
| 44 | + pub attachment_limit_bytes: u64, | ||
| 45 | + pub photo_limit_bytes: u64, | ||
| 46 | + pub allowed_file_types: Vec<String>, | ||
| 47 | + pub who_can_delete_tasks: DeletePolicy, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | ||
| 51 | +#[serde(rename_all = "snake_case")] | ||
| 52 | +pub enum DeletePolicy { | ||
| 53 | + /// Anyone who can write tasks may delete one. | ||
| 54 | + Anyone, | ||
| 55 | + /// Only the admin. | ||
| 56 | + Admin, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +impl DeletePolicy { | ||
| 60 | + pub fn as_str(self) -> &'static str { | ||
| 61 | + match self { | ||
| 62 | + DeletePolicy::Anyone => "anyone", | ||
| 63 | + DeletePolicy::Admin => "admin", | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + pub fn parse(raw: &str) -> Result<Self> { | ||
| 68 | + match raw { | ||
| 69 | + "anyone" => Ok(DeletePolicy::Anyone), | ||
| 70 | + "admin" => Ok(DeletePolicy::Admin), | ||
| 71 | + other => Err(StoreError::Corrupt(format!("delete policy {other:?}"))), | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// An account. `password_hash` is `None` for an invited member who has not | ||
| 77 | +/// signed in yet — the admin creates the account with a name and an address and | ||
| 78 | +/// can never read or set the password. | ||
| 79 | +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] | ||
| 80 | +pub struct User { | ||
| 81 | + pub id: String, | ||
| 82 | + pub workspace_id: String, | ||
| 83 | + pub email: String, | ||
| 84 | + pub display_name: String, | ||
| 85 | + pub role: Role, | ||
| 86 | + pub password_hash: Option<String>, | ||
| 87 | + pub photo_path: Option<String>, | ||
| 88 | + pub created_at: OffsetDateTime, | ||
| 89 | + pub last_signed_in_at: Option<OffsetDateTime>, | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +impl User { | ||
| 93 | + /// True once the person has chosen their own password. | ||
| 94 | + pub fn has_signed_in(&self) -> bool { | ||
| 95 | + self.password_hash.is_some() | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +pub struct NewUser { | ||
| 100 | + pub workspace_id: String, | ||
| 101 | + pub email: String, | ||
| 102 | + pub display_name: String, | ||
| 103 | + pub role: Role, | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// A first-sign-in link. Only the hash of the token is ever stored; the | ||
| 107 | +/// plaintext is shown once, when the link is created or resent. | ||
| 108 | +#[derive(Debug, Clone, PartialEq)] | ||
| 109 | +pub struct SigninLink { | ||
| 110 | + pub id: String, | ||
| 111 | + pub user_id: String, | ||
| 112 | + pub created_at: OffsetDateTime, | ||
| 113 | + pub expires_at: OffsetDateTime, | ||
| 114 | + pub used_at: Option<OffsetDateTime>, | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +impl SigninLink { | ||
| 118 | + pub fn is_usable(&self, now: OffsetDateTime) -> bool { | ||
| 119 | + self.used_at.is_none() && now < self.expires_at | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// The storage boundary. Dyn-safe on purpose: handlers hold `Arc<dyn Store>`. | ||
| 124 | +#[async_trait] | ||
| 125 | +pub trait Store: Send + Sync + 'static { | ||
| 126 | + // -- workspace --------------------------------------------------------- | ||
| 127 | + | ||
| 128 | + /// Creates the workspace. Fails with [`StoreError::Conflict`] if one | ||
| 129 | + /// already exists: Dizey hosts a single workspace per database. | ||
| 130 | + async fn create_workspace(&self, name: &str) -> Result<Workspace>; | ||
| 131 | + | ||
| 132 | + async fn workspace(&self) -> Result<Option<Workspace>>; | ||
| 133 | + | ||
| 134 | + async fn set_smtp( | ||
| 135 | + &self, | ||
| 136 | + workspace_id: &str, | ||
| 137 | + host: &str, | ||
| 138 | + port: u32, | ||
| 139 | + username: &str, | ||
| 140 | + password: &str, | ||
| 141 | + from_name: &str, | ||
| 142 | + from_address: &str, | ||
| 143 | + ) -> Result<()>; | ||
| 144 | + | ||
| 145 | + /// Reads the sender password. Only the mailer calls this. | ||
| 146 | + async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>>; | ||
| 147 | + | ||
| 148 | + async fn set_limits( | ||
| 149 | + &self, | ||
| 150 | + workspace_id: &str, | ||
| 151 | + attachment_limit_bytes: u64, | ||
| 152 | + photo_limit_bytes: u64, | ||
| 153 | + allowed_file_types: &[String], | ||
| 154 | + who_can_delete_tasks: DeletePolicy, | ||
| 155 | + ) -> Result<()>; | ||
| 156 | + | ||
| 157 | + // -- users ------------------------------------------------------------- | ||
| 158 | + | ||
| 159 | + async fn create_user(&self, new: NewUser) -> Result<User>; | ||
| 160 | + | ||
| 161 | + async fn user(&self, id: &str) -> Result<Option<User>>; | ||
| 162 | + | ||
| 163 | + /// Lookup by address. Callers must not turn a `None` into a different | ||
| 164 | + /// public response than a `Some`: the sign-in surface never reveals whether | ||
| 165 | + /// an address has an account. | ||
| 166 | + async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result<Option<User>>; | ||
| 167 | + | ||
| 168 | + async fn users(&self, workspace_id: &str) -> Result<Vec<User>>; | ||
| 169 | + | ||
| 170 | + async fn count_users(&self, workspace_id: &str) -> Result<u64>; | ||
| 171 | + | ||
| 172 | + async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()>; | ||
| 173 | + | ||
| 174 | + async fn set_profile( | ||
| 175 | + &self, | ||
| 176 | + user_id: &str, | ||
| 177 | + display_name: &str, | ||
| 178 | + photo_path: Option<&str>, | ||
| 179 | + ) -> Result<()>; | ||
| 180 | + | ||
| 181 | + async fn set_role(&self, user_id: &str, role: Role) -> Result<()>; | ||
| 182 | + | ||
| 183 | + async fn mark_signed_in(&self, user_id: &str, at: OffsetDateTime) -> Result<()>; | ||
| 184 | + | ||
| 185 | + // -- sign-in links ----------------------------------------------------- | ||
| 186 | + | ||
| 187 | + /// Stores the hash of a freshly minted link. The caller keeps the plaintext | ||
| 188 | + /// and shows it once. | ||
| 189 | + async fn create_signin_link( | ||
| 190 | + &self, | ||
| 191 | + user_id: &str, | ||
| 192 | + token_hash: &str, | ||
| 193 | + expires_at: OffsetDateTime, | ||
| 194 | + ) -> Result<SigninLink>; | ||
| 195 | + | ||
| 196 | + /// Looks a link up by the hash of the presented token. Returns the link | ||
| 197 | + /// whether or not it is still usable, so the caller can tell an expired | ||
| 198 | + /// link apart from a wrong one — an expired link is not a dead account. | ||
| 199 | + async fn signin_link_by_hash(&self, token_hash: &str) -> Result<Option<SigninLink>>; | ||
| 200 | + | ||
| 201 | + async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()>; | ||
| 202 | +} | ||
crates/dizey-core/src/store/turso_store.rsadded+628 -0
| @@ -0,0 +1,628 @@ | |||
| 1 | +//! Turso implementation of [`Store`]. | ||
| 2 | +//! | ||
| 3 | +//! Turso is in-process and SQLite-compatible, so the schema is plain SQL and | ||
| 4 | +//! there is no server to run alongside the binary. It ships no migration runner | ||
| 5 | +//! of its own; [`TursoStore::open`] applies the numbered files in | ||
| 6 | +//! `crates/dizey-core/migrations` at boot and records the version. | ||
| 7 | + | ||
| 8 | +use async_trait::async_trait; | ||
| 9 | +use time::OffsetDateTime; | ||
| 10 | +use time::format_description::well_known::Rfc3339; | ||
| 11 | +use turso::{Builder, Connection, Row, Value, params}; | ||
| 12 | +use uuid::Uuid; | ||
| 13 | + | ||
| 14 | +use super::{ | ||
| 15 | + DeletePolicy, NewUser, Result, SigninLink, Store, StoreError, User, Workspace, | ||
| 16 | +}; | ||
| 17 | +use crate::Role; | ||
| 18 | + | ||
| 19 | +/// Every migration, in order. Adding one means appending a file and a line. | ||
| 20 | +const MIGRATIONS: &[(i64, &str)] = &[(1, include_str!("../../migrations/0001_init.sql"))]; | ||
| 21 | + | ||
| 22 | +pub struct TursoStore { | ||
| 23 | + conn: Connection, | ||
| 24 | + // Held so the database outlives its connection. | ||
| 25 | + _db: turso::Database, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl TursoStore { | ||
| 29 | + /// Opens (creating if needed) the database at `path` and brings the schema | ||
| 30 | + /// up to date. `:memory:` gives a throwaway database for tests. | ||
| 31 | + pub async fn open(path: &str) -> Result<Self> { | ||
| 32 | + let db = Builder::new_local(path).build().await.map_err(backend)?; | ||
| 33 | + let conn = db.connect().map_err(backend)?; | ||
| 34 | + // Turso is a single-writer engine. Two connections on one Database | ||
| 35 | + // handle serialise by themselves, but a second handle on the same file | ||
| 36 | + // (a second process, or a careless second open) fails outright with | ||
| 37 | + // "database is locked" and silently drops the write unless a busy | ||
| 38 | + // timeout is set. Both pragmas are set on every connection we hand out. | ||
| 39 | + for pragma in [ | ||
| 40 | + "PRAGMA foreign_keys = ON", | ||
| 41 | + "PRAGMA busy_timeout = 5000", | ||
| 42 | + ] { | ||
| 43 | + conn.execute(pragma, ()).await.map_err(backend)?; | ||
| 44 | + } | ||
| 45 | + let store = Self { conn, _db: db }; | ||
| 46 | + store.migrate().await?; | ||
| 47 | + Ok(store) | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + async fn migrate(&self) -> Result<()> { | ||
| 51 | + self.conn | ||
| 52 | + .execute( | ||
| 53 | + "CREATE TABLE IF NOT EXISTS schema_version ( | ||
| 54 | + version INTEGER PRIMARY KEY, | ||
| 55 | + applied_at TEXT NOT NULL | ||
| 56 | + )", | ||
| 57 | + (), | ||
| 58 | + ) | ||
| 59 | + .await | ||
| 60 | + .map_err(backend)?; | ||
| 61 | + | ||
| 62 | + let applied = self.applied_versions().await?; | ||
| 63 | + for (version, sql) in MIGRATIONS { | ||
| 64 | + if applied.contains(version) { | ||
| 65 | + continue; | ||
| 66 | + } | ||
| 67 | + self.conn.execute_batch(sql).await.map_err(backend)?; | ||
| 68 | + self.conn | ||
| 69 | + .execute( | ||
| 70 | + "INSERT INTO schema_version (version, applied_at) VALUES (?1, ?2)", | ||
| 71 | + params![*version, now_text()?], | ||
| 72 | + ) | ||
| 73 | + .await | ||
| 74 | + .map_err(backend)?; | ||
| 75 | + } | ||
| 76 | + Ok(()) | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + async fn applied_versions(&self) -> Result<Vec<i64>> { | ||
| 80 | + let mut rows = self | ||
| 81 | + .conn | ||
| 82 | + .query("SELECT version FROM schema_version", ()) | ||
| 83 | + .await | ||
| 84 | + .map_err(backend)?; | ||
| 85 | + let mut out = Vec::new(); | ||
| 86 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 87 | + out.push(row.get::<i64>(0).map_err(backend)?); | ||
| 88 | + } | ||
| 89 | + Ok(out) | ||
| 90 | + } | ||
| 91 | + | ||
| 92 | + /// The schema version the database is actually at. | ||
| 93 | + pub async fn schema_version(&self) -> Result<i64> { | ||
| 94 | + Ok(self.applied_versions().await?.into_iter().max().unwrap_or(0)) | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + async fn one_row(&self, sql: &str, args: impl turso::IntoParams) -> Result<Option<Row>> { | ||
| 98 | + let mut rows = self.conn.query(sql, args).await.map_err(backend)?; | ||
| 99 | + rows.next().await.map_err(backend) | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +fn backend<E: std::fmt::Display>(e: E) -> StoreError { | ||
| 104 | + StoreError::Backend(e.to_string()) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +fn now_text() -> Result<String> { | ||
| 108 | + stamp(OffsetDateTime::now_utc()) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +fn stamp(at: OffsetDateTime) -> Result<String> { | ||
| 112 | + at.format(&Rfc3339) | ||
| 113 | + .map_err(|e| StoreError::Corrupt(format!("timestamp: {e}"))) | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +fn parse_stamp(raw: &str) -> Result<OffsetDateTime> { | ||
| 117 | + OffsetDateTime::parse(raw, &Rfc3339) | ||
| 118 | + .map_err(|e| StoreError::Corrupt(format!("timestamp {raw:?}: {e}"))) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +fn opt_stamp(row: &Row, idx: usize) -> Result<Option<OffsetDateTime>> { | ||
| 122 | + match row.get::<Option<String>>(idx).map_err(backend)? { | ||
| 123 | + Some(raw) => Ok(Some(parse_stamp(&raw)?)), | ||
| 124 | + None => Ok(None), | ||
| 125 | + } | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +fn text(row: &Row, idx: usize) -> Result<String> { | ||
| 129 | + row.get::<String>(idx).map_err(backend) | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +fn opt_text(row: &Row, idx: usize) -> Result<Option<String>> { | ||
| 133 | + row.get::<Option<String>>(idx).map_err(backend) | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +fn count_of(row: &Row) -> Result<u64> { | ||
| 137 | + row.get::<i64>(0) | ||
| 138 | + .map_err(backend) | ||
| 139 | + .map(|n| n.max(0) as u64) | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +fn workspace_from(row: &Row) -> Result<Workspace> { | ||
| 143 | + let types_json = text(row, 9)?; | ||
| 144 | + let allowed_file_types: Vec<String> = if types_json.trim().is_empty() { | ||
| 145 | + Vec::new() | ||
| 146 | + } else { | ||
| 147 | + serde_json::from_str(&types_json) | ||
| 148 | + .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))? | ||
| 149 | + }; | ||
| 150 | + Ok(Workspace { | ||
| 151 | + id: text(row, 0)?, | ||
| 152 | + name: text(row, 1)?, | ||
| 153 | + created_at: parse_stamp(&text(row, 2)?)?, | ||
| 154 | + smtp_host: opt_text(row, 3)?, | ||
| 155 | + smtp_port: row.get::<Option<u32>>(4).map_err(backend)?, | ||
| 156 | + smtp_username: opt_text(row, 5)?, | ||
| 157 | + smtp_from_name: opt_text(row, 6)?, | ||
| 158 | + smtp_from_address: opt_text(row, 7)?, | ||
| 159 | + attachment_limit_bytes: row.get::<i64>(8).map_err(backend)?.max(0) as u64, | ||
| 160 | + allowed_file_types, | ||
| 161 | + photo_limit_bytes: row.get::<i64>(10).map_err(backend)?.max(0) as u64, | ||
| 162 | + who_can_delete_tasks: DeletePolicy::parse(&text(row, 11)?)?, | ||
| 163 | + }) | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +const WORKSPACE_COLUMNS: &str = "id, name, created_at, smtp_host, smtp_port, smtp_username, \ | ||
| 167 | + smtp_from_name, smtp_from_address, attachment_limit_bytes, allowed_file_types, \ | ||
| 168 | + photo_limit_bytes, who_can_delete_tasks"; | ||
| 169 | + | ||
| 170 | +fn user_from(row: &Row) -> Result<User> { | ||
| 171 | + Ok(User { | ||
| 172 | + id: text(row, 0)?, | ||
| 173 | + workspace_id: text(row, 1)?, | ||
| 174 | + email: text(row, 2)?, | ||
| 175 | + display_name: text(row, 3)?, | ||
| 176 | + role: Role::parse(&text(row, 4)?) | ||
| 177 | + .ok_or_else(|| StoreError::Corrupt("role".into()))?, | ||
| 178 | + password_hash: opt_text(row, 5)?, | ||
| 179 | + photo_path: opt_text(row, 6)?, | ||
| 180 | + created_at: parse_stamp(&text(row, 7)?)?, | ||
| 181 | + last_signed_in_at: opt_stamp(row, 8)?, | ||
| 182 | + }) | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +const USER_COLUMNS: &str = "id, workspace_id, email, display_name, role, password_hash, \ | ||
| 186 | + photo_path, created_at, last_signed_in_at"; | ||
| 187 | + | ||
| 188 | +fn signin_link_from(row: &Row) -> Result<SigninLink> { | ||
| 189 | + Ok(SigninLink { | ||
| 190 | + id: text(row, 0)?, | ||
| 191 | + user_id: text(row, 1)?, | ||
| 192 | + created_at: parse_stamp(&text(row, 2)?)?, | ||
| 193 | + expires_at: parse_stamp(&text(row, 3)?)?, | ||
| 194 | + used_at: opt_stamp(row, 4)?, | ||
| 195 | + }) | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +/// Addresses are matched case-insensitively; the display form is kept as typed. | ||
| 199 | +fn fold_email(email: &str) -> String { | ||
| 200 | + email.trim().to_lowercase() | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +#[async_trait] | ||
| 204 | +impl Store for TursoStore { | ||
| 205 | + async fn create_workspace(&self, name: &str) -> Result<Workspace> { | ||
| 206 | + if self.workspace().await?.is_some() { | ||
| 207 | + return Err(StoreError::Conflict("workspace")); | ||
| 208 | + } | ||
| 209 | + let id = Uuid::new_v4().to_string(); | ||
| 210 | + self.conn | ||
| 211 | + .execute( | ||
| 212 | + "INSERT INTO workspace (id, name, created_at) VALUES (?1, ?2, ?3)", | ||
| 213 | + params![id.clone(), name, now_text()?], | ||
| 214 | + ) | ||
| 215 | + .await | ||
| 216 | + .map_err(backend)?; | ||
| 217 | + self.workspace().await?.ok_or(StoreError::NotFound) | ||
| 218 | + } | ||
| 219 | + | ||
| 220 | + async fn workspace(&self) -> Result<Option<Workspace>> { | ||
| 221 | + let sql = format!("SELECT {WORKSPACE_COLUMNS} FROM workspace LIMIT 1"); | ||
| 222 | + match self.one_row(&sql, ()).await? { | ||
| 223 | + Some(row) => Ok(Some(workspace_from(&row)?)), | ||
| 224 | + None => Ok(None), | ||
| 225 | + } | ||
| 226 | + } | ||
| 227 | + | ||
| 228 | + async fn set_smtp( | ||
| 229 | + &self, | ||
| 230 | + workspace_id: &str, | ||
| 231 | + host: &str, | ||
| 232 | + port: u32, | ||
| 233 | + username: &str, | ||
| 234 | + password: &str, | ||
| 235 | + from_name: &str, | ||
| 236 | + from_address: &str, | ||
| 237 | + ) -> Result<()> { | ||
| 238 | + self.conn | ||
| 239 | + .execute( | ||
| 240 | + "UPDATE workspace SET smtp_host = ?1, smtp_port = ?2, smtp_username = ?3, \ | ||
| 241 | + smtp_password = ?4, smtp_from_name = ?5, smtp_from_address = ?6 WHERE id = ?7", | ||
| 242 | + params![ | ||
| 243 | + host, | ||
| 244 | + port as i64, | ||
| 245 | + username, | ||
| 246 | + password, | ||
| 247 | + from_name, | ||
| 248 | + from_address, | ||
| 249 | + workspace_id | ||
| 250 | + ], | ||
| 251 | + ) | ||
| 252 | + .await | ||
| 253 | + .map_err(backend)?; | ||
| 254 | + Ok(()) | ||
| 255 | + } | ||
| 256 | + | ||
| 257 | + async fn smtp_password(&self, workspace_id: &str) -> Result<Option<String>> { | ||
| 258 | + match self | ||
| 259 | + .one_row( | ||
| 260 | + "SELECT smtp_password FROM workspace WHERE id = ?1", | ||
| 261 | + params![workspace_id], | ||
| 262 | + ) | ||
| 263 | + .await? | ||
| 264 | + { | ||
| 265 | + Some(row) => opt_text(&row, 0), | ||
| 266 | + None => Err(StoreError::NotFound), | ||
| 267 | + } | ||
| 268 | + } | ||
| 269 | + | ||
| 270 | + async fn set_limits( | ||
| 271 | + &self, | ||
| 272 | + workspace_id: &str, | ||
| 273 | + attachment_limit_bytes: u64, | ||
| 274 | + photo_limit_bytes: u64, | ||
| 275 | + allowed_file_types: &[String], | ||
| 276 | + who_can_delete_tasks: DeletePolicy, | ||
| 277 | + ) -> Result<()> { | ||
| 278 | + let types = serde_json::to_string(allowed_file_types) | ||
| 279 | + .map_err(|e| StoreError::Corrupt(format!("allowed_file_types: {e}")))?; | ||
| 280 | + self.conn | ||
| 281 | + .execute( | ||
| 282 | + "UPDATE workspace SET attachment_limit_bytes = ?1, photo_limit_bytes = ?2, \ | ||
| 283 | + allowed_file_types = ?3, who_can_delete_tasks = ?4 WHERE id = ?5", | ||
| 284 | + params![ | ||
| 285 | + attachment_limit_bytes as i64, | ||
| 286 | + photo_limit_bytes as i64, | ||
| 287 | + types, | ||
| 288 | + who_can_delete_tasks.as_str(), | ||
| 289 | + workspace_id | ||
| 290 | + ], | ||
| 291 | + ) | ||
| 292 | + .await | ||
| 293 | + .map_err(backend)?; | ||
| 294 | + Ok(()) | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + async fn create_user(&self, new: NewUser) -> Result<User> { | ||
| 298 | + let email = fold_email(&new.email); | ||
| 299 | + if self.user_by_email(&new.workspace_id, &email).await?.is_some() { | ||
| 300 | + return Err(StoreError::Conflict("account")); | ||
| 301 | + } | ||
| 302 | + let id = Uuid::new_v4().to_string(); | ||
| 303 | + self.conn | ||
| 304 | + .execute( | ||
| 305 | + "INSERT INTO user (id, workspace_id, email, display_name, role, created_at) \ | ||
| 306 | + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", | ||
| 307 | + params![ | ||
| 308 | + id.clone(), | ||
| 309 | + new.workspace_id, | ||
| 310 | + email, | ||
| 311 | + new.display_name, | ||
| 312 | + new.role.as_str(), | ||
| 313 | + now_text()? | ||
| 314 | + ], | ||
| 315 | + ) | ||
| 316 | + .await | ||
| 317 | + .map_err(backend)?; | ||
| 318 | + self.user(&id).await?.ok_or(StoreError::NotFound) | ||
| 319 | + } | ||
| 320 | + | ||
| 321 | + async fn user(&self, id: &str) -> Result<Option<User>> { | ||
| 322 | + let sql = format!("SELECT {USER_COLUMNS} FROM user WHERE id = ?1"); | ||
| 323 | + match self.one_row(&sql, params![id]).await? { | ||
| 324 | + Some(row) => Ok(Some(user_from(&row)?)), | ||
| 325 | + None => Ok(None), | ||
| 326 | + } | ||
| 327 | + } | ||
| 328 | + | ||
| 329 | + async fn user_by_email(&self, workspace_id: &str, email: &str) -> Result<Option<User>> { | ||
| 330 | + let sql = | ||
| 331 | + format!("SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 AND email = ?2"); | ||
| 332 | + match self | ||
| 333 | + .one_row(&sql, params![workspace_id, fold_email(email)]) | ||
| 334 | + .await? | ||
| 335 | + { | ||
| 336 | + Some(row) => Ok(Some(user_from(&row)?)), | ||
| 337 | + None => Ok(None), | ||
| 338 | + } | ||
| 339 | + } | ||
| 340 | + | ||
| 341 | + async fn users(&self, workspace_id: &str) -> Result<Vec<User>> { | ||
| 342 | + let sql = format!( | ||
| 343 | + "SELECT {USER_COLUMNS} FROM user WHERE workspace_id = ?1 ORDER BY created_at, id" | ||
| 344 | + ); | ||
| 345 | + let mut rows = self.conn.query(&sql, params![workspace_id]).await.map_err(backend)?; | ||
| 346 | + let mut out = Vec::new(); | ||
| 347 | + while let Some(row) = rows.next().await.map_err(backend)? { | ||
| 348 | + out.push(user_from(&row)?); | ||
| 349 | + } | ||
| 350 | + Ok(out) | ||
| 351 | + } | ||
| 352 | + | ||
| 353 | + async fn count_users(&self, workspace_id: &str) -> Result<u64> { | ||
| 354 | + match self | ||
| 355 | + .one_row( | ||
| 356 | + "SELECT COUNT(*) FROM user WHERE workspace_id = ?1", | ||
| 357 | + params![workspace_id], | ||
| 358 | + ) | ||
| 359 | + .await? | ||
| 360 | + { | ||
| 361 | + Some(row) => count_of(&row), | ||
| 362 | + None => Ok(0), | ||
| 363 | + } | ||
| 364 | + } | ||
| 365 | + | ||
| 366 | + async fn set_password_hash(&self, user_id: &str, hash: &str) -> Result<()> { | ||
| 367 | + let n = self | ||
| 368 | + .conn | ||
| 369 | + .execute( | ||
| 370 | + "UPDATE user SET password_hash = ?1 WHERE id = ?2", | ||
| 371 | + params![hash, user_id], | ||
| 372 | + ) | ||
| 373 | + .await | ||
| 374 | + .map_err(backend)?; | ||
| 375 | + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } | ||
| 376 | + } | ||
| 377 | + | ||
| 378 | + async fn set_profile( | ||
| 379 | + &self, | ||
| 380 | + user_id: &str, | ||
| 381 | + display_name: &str, | ||
| 382 | + photo_path: Option<&str>, | ||
| 383 | + ) -> Result<()> { | ||
| 384 | + let photo = match photo_path { | ||
| 385 | + Some(p) => Value::from(p.to_string()), | ||
| 386 | + None => Value::Null, | ||
| 387 | + }; | ||
| 388 | + let n = self | ||
| 389 | + .conn | ||
| 390 | + .execute( | ||
| 391 | + "UPDATE user SET display_name = ?1, photo_path = ?2 WHERE id = ?3", | ||
| 392 | + params![display_name, photo, user_id], | ||
| 393 | + ) | ||
| 394 | + .await | ||
| 395 | + .map_err(backend)?; | ||
| 396 | + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } | ||
| 397 | + } | ||
| 398 | + | ||
| 399 | + async fn set_role(&self, user_id: &str, role: Role) -> Result<()> { | ||
| 400 | + let n = self | ||
| 401 | + .conn | ||
| 402 | + .execute( | ||
| 403 | + "UPDATE user SET role = ?1 WHERE id = ?2", | ||
| 404 | + params![role.as_str(), user_id], | ||
| 405 | + ) | ||
| 406 | + .await | ||
| 407 | + .map_err(backend)?; | ||
| 408 | + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + async fn mark_signed_in(&self, user_id: &str, at: OffsetDateTime) -> Result<()> { | ||
| 412 | + let n = self | ||
| 413 | + .conn | ||
| 414 | + .execute( | ||
| 415 | + "UPDATE user SET last_signed_in_at = ?1 WHERE id = ?2", | ||
| 416 | + params![stamp(at)?, user_id], | ||
| 417 | + ) | ||
| 418 | + .await | ||
| 419 | + .map_err(backend)?; | ||
| 420 | + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } | ||
| 421 | + } | ||
| 422 | + | ||
| 423 | + async fn create_signin_link( | ||
| 424 | + &self, | ||
| 425 | + user_id: &str, | ||
| 426 | + token_hash: &str, | ||
| 427 | + expires_at: OffsetDateTime, | ||
| 428 | + ) -> Result<SigninLink> { | ||
| 429 | + let id = Uuid::new_v4().to_string(); | ||
| 430 | + self.conn | ||
| 431 | + .execute( | ||
| 432 | + "INSERT INTO signin_link (id, user_id, token_hash, created_at, expires_at) \ | ||
| 433 | + VALUES (?1, ?2, ?3, ?4, ?5)", | ||
| 434 | + params![ | ||
| 435 | + id.clone(), | ||
| 436 | + user_id, | ||
| 437 | + token_hash, | ||
| 438 | + now_text()?, | ||
| 439 | + stamp(expires_at)? | ||
| 440 | + ], | ||
| 441 | + ) | ||
| 442 | + .await | ||
| 443 | + .map_err(backend)?; | ||
| 444 | + match self | ||
| 445 | + .one_row( | ||
| 446 | + "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link WHERE id = ?1", | ||
| 447 | + params![id], | ||
| 448 | + ) | ||
| 449 | + .await? | ||
| 450 | + { | ||
| 451 | + Some(row) => signin_link_from(&row), | ||
| 452 | + None => Err(StoreError::NotFound), | ||
| 453 | + } | ||
| 454 | + } | ||
| 455 | + | ||
| 456 | + async fn signin_link_by_hash(&self, token_hash: &str) -> Result<Option<SigninLink>> { | ||
| 457 | + match self | ||
| 458 | + .one_row( | ||
| 459 | + "SELECT id, user_id, created_at, expires_at, used_at FROM signin_link \ | ||
| 460 | + WHERE token_hash = ?1", | ||
| 461 | + params![token_hash], | ||
| 462 | + ) | ||
| 463 | + .await? | ||
| 464 | + { | ||
| 465 | + Some(row) => Ok(Some(signin_link_from(&row)?)), | ||
| 466 | + None => Ok(None), | ||
| 467 | + } | ||
| 468 | + } | ||
| 469 | + | ||
| 470 | + async fn consume_signin_link(&self, id: &str, at: OffsetDateTime) -> Result<()> { | ||
| 471 | + let n = self | ||
| 472 | + .conn | ||
| 473 | + .execute( | ||
| 474 | + "UPDATE signin_link SET used_at = ?1 WHERE id = ?2 AND used_at IS NULL", | ||
| 475 | + params![stamp(at)?, id], | ||
| 476 | + ) | ||
| 477 | + .await | ||
| 478 | + .map_err(backend)?; | ||
| 479 | + if n == 0 { Err(StoreError::NotFound) } else { Ok(()) } | ||
| 480 | + } | ||
| 481 | +} | ||
| 482 | + | ||
| 483 | +#[cfg(test)] | ||
| 484 | +mod probe { | ||
| 485 | + //! What Turso actually does about durability and concurrent writers. | ||
| 486 | + //! | ||
| 487 | + //! These are not assertions about our code; they record engine behaviour we | ||
| 488 | + //! are relying on. They fail loudly if a Turso upgrade changes it. | ||
| 489 | + | ||
| 490 | + use super::*; | ||
| 491 | + | ||
| 492 | + async fn pragma(conn: &Connection, name: &str) -> String { | ||
| 493 | + let mut rows = conn.query(&format!("PRAGMA {name}"), ()).await.unwrap(); | ||
| 494 | + match rows.next().await.unwrap() { | ||
| 495 | + Some(row) => format!("{:?}", row.get_value(0).unwrap()), | ||
| 496 | + None => "<no row>".to_string(), | ||
| 497 | + } | ||
| 498 | + } | ||
| 499 | + | ||
| 500 | + #[tokio::test] | ||
| 501 | + async fn durability_defaults_are_recorded() { | ||
| 502 | + let dir = std::env::temp_dir().join(format!("dizey-probe-{}", Uuid::new_v4())); | ||
| 503 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 504 | + let path = dir.join("probe.db"); | ||
| 505 | + let db = Builder::new_local(path.to_str().unwrap()) | ||
| 506 | + .build() | ||
| 507 | + .await | ||
| 508 | + .unwrap(); | ||
| 509 | + let conn = db.connect().unwrap(); | ||
| 510 | + // WAL journalling with synchronous=FULL: a committed write is fsynced | ||
| 511 | + // before the commit returns. If a Turso upgrade weakens either of | ||
| 512 | + // these, this test is where we find out. | ||
| 513 | + assert_eq!(pragma(&conn, "journal_mode").await, "Text(\"wal\")"); | ||
| 514 | + assert_eq!(pragma(&conn, "synchronous").await, "Integer(2)"); | ||
| 515 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 516 | + } | ||
| 517 | + | ||
| 518 | + #[tokio::test] | ||
| 519 | + async fn concurrent_writers_on_one_database() { | ||
| 520 | + let dir = std::env::temp_dir().join(format!("dizey-probe-{}", Uuid::new_v4())); | ||
| 521 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 522 | + let path = dir.join("probe.db"); | ||
| 523 | + let db = Builder::new_local(path.to_str().unwrap()) | ||
| 524 | + .build() | ||
| 525 | + .await | ||
| 526 | + .unwrap(); | ||
| 527 | + let a = db.connect().unwrap(); | ||
| 528 | + let b = db.connect().unwrap(); | ||
| 529 | + a.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, who TEXT)", ()) | ||
| 530 | + .await | ||
| 531 | + .unwrap(); | ||
| 532 | + | ||
| 533 | + // Interleaved, both connections in flight at once. | ||
| 534 | + let write_a = async { | ||
| 535 | + for i in 0..50i64 { | ||
| 536 | + a.execute("INSERT INTO t (id, who) VALUES (?1, 'a')", params![i]) | ||
| 537 | + .await?; | ||
| 538 | + } | ||
| 539 | + Ok::<_, turso::Error>(()) | ||
| 540 | + }; | ||
| 541 | + let write_b = async { | ||
| 542 | + for i in 100..150i64 { | ||
| 543 | + b.execute("INSERT INTO t (id, who) VALUES (?1, 'b')", params![i]) | ||
| 544 | + .await?; | ||
| 545 | + } | ||
| 546 | + Ok::<_, turso::Error>(()) | ||
| 547 | + }; | ||
| 548 | + // Two connections on ONE handle: the engine serialises them for us. | ||
| 549 | + let (ra, rb) = tokio::join!(write_a, write_b); | ||
| 550 | + ra.expect("writer a"); | ||
| 551 | + rb.expect("writer b"); | ||
| 552 | + | ||
| 553 | + let c = db.connect().unwrap(); | ||
| 554 | + let mut rows = c.query("SELECT COUNT(*) FROM t", ()).await.unwrap(); | ||
| 555 | + let n = rows.next().await.unwrap().unwrap().get::<i64>(0).unwrap(); | ||
| 556 | + assert_eq!(n, 100, "no write lost between two connections"); | ||
| 557 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 558 | + } | ||
| 559 | + | ||
| 560 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 561 | + async fn two_database_handles_on_one_file() { | ||
| 562 | + // Two handles on the same file is the shape a second process takes. | ||
| 563 | + let dir = std::env::temp_dir().join(format!("dizey-probe-{}", Uuid::new_v4())); | ||
| 564 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 565 | + let path = dir.join("probe.db"); | ||
| 566 | + let p = path.to_str().unwrap().to_string(); | ||
| 567 | + | ||
| 568 | + let first = Builder::new_local(&p).build().await.unwrap(); | ||
| 569 | + let setup = first.connect().unwrap(); | ||
| 570 | + setup | ||
| 571 | + .execute("CREATE TABLE t (id INTEGER PRIMARY KEY, who TEXT)", ()) | ||
| 572 | + .await | ||
| 573 | + .unwrap(); | ||
| 574 | + | ||
| 575 | + let second = Builder::new_local(&p).build().await; | ||
| 576 | + let second = match second { | ||
| 577 | + Ok(db) => db, | ||
| 578 | + Err(e) => { | ||
| 579 | + println!("second handle refused: {e}"); | ||
| 580 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 581 | + return; | ||
| 582 | + } | ||
| 583 | + }; | ||
| 584 | + | ||
| 585 | + let a = setup; | ||
| 586 | + let b = second.connect().unwrap(); | ||
| 587 | + for c in [&a, &b] { | ||
| 588 | + c.execute("PRAGMA busy_timeout = 5000", ()).await.unwrap(); | ||
| 589 | + } | ||
| 590 | + let ha = tokio::spawn(async move { | ||
| 591 | + let mut errs = Vec::new(); | ||
| 592 | + for i in 0..100i64 { | ||
| 593 | + if let Err(e) = a | ||
| 594 | + .execute("INSERT INTO t (id, who) VALUES (?1, \'a\')", params![i]) | ||
| 595 | + .await | ||
| 596 | + { | ||
| 597 | + errs.push(e.to_string()); | ||
| 598 | + } | ||
| 599 | + } | ||
| 600 | + errs | ||
| 601 | + }); | ||
| 602 | + let hb = tokio::spawn(async move { | ||
| 603 | + let mut errs = Vec::new(); | ||
| 604 | + for i in 1000..1100i64 { | ||
| 605 | + if let Err(e) = b | ||
| 606 | + .execute("INSERT INTO t (id, who) VALUES (?1, \'b\')", params![i]) | ||
| 607 | + .await | ||
| 608 | + { | ||
| 609 | + errs.push(e.to_string()); | ||
| 610 | + } | ||
| 611 | + } | ||
| 612 | + errs | ||
| 613 | + }); | ||
| 614 | + let (ea, eb) = (ha.await.unwrap(), hb.await.unwrap()); | ||
| 615 | + // With the busy timeout the store sets, a second handle waits its turn | ||
| 616 | + // instead of dropping writes. Without it, roughly 40% of these fail | ||
| 617 | + // with "database is locked". | ||
| 618 | + assert!(ea.is_empty(), "handle a: {ea:?}"); | ||
| 619 | + assert!(eb.is_empty(), "handle b: {eb:?}"); | ||
| 620 | + | ||
| 621 | + let third = Builder::new_local(&p).build().await.unwrap(); | ||
| 622 | + let c = third.connect().unwrap(); | ||
| 623 | + let mut rows = c.query("SELECT COUNT(*) FROM t", ()).await.unwrap(); | ||
| 624 | + let n = rows.next().await.unwrap().unwrap().get::<i64>(0).unwrap(); | ||
| 625 | + assert_eq!(n, 200, "no write lost between two database handles"); | ||
| 626 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 627 | + } | ||
| 628 | +} | ||
crates/dizey-core/tests/store.rsadded+367 -0
| @@ -0,0 +1,367 @@ | |||
| 1 | +//! Behaviour of the storage boundary, driven through the Turso implementation. | ||
| 2 | +//! | ||
| 3 | +//! New storage tests belong in this file rather than a new `tests/*.rs`: one | ||
| 4 | +//! test binary links and runs once. | ||
| 5 | + | ||
| 6 | +use std::path::PathBuf; | ||
| 7 | + | ||
| 8 | +use dizey_core::store::{DeletePolicy, NewUser, Store, StoreError, TursoStore}; | ||
| 9 | +use dizey_core::Role; | ||
| 10 | +use time::{Duration, OffsetDateTime}; | ||
| 11 | +use uuid::Uuid; | ||
| 12 | + | ||
| 13 | +/// A throwaway database on disk. Turso's in-memory mode is not what production | ||
| 14 | +/// runs, so the tests exercise a real file. | ||
| 15 | +struct Scratch { | ||
| 16 | + dir: PathBuf, | ||
| 17 | + store: TursoStore, | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +impl Scratch { | ||
| 21 | + async fn open() -> Self { | ||
| 22 | + let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4())); | ||
| 23 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 24 | + let store = TursoStore::open(dir.join("dizey.db").to_str().unwrap()) | ||
| 25 | + .await | ||
| 26 | + .unwrap(); | ||
| 27 | + Self { dir, store } | ||
| 28 | + } | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +impl Drop for Scratch { | ||
| 32 | + fn drop(&mut self) { | ||
| 33 | + let _ = std::fs::remove_dir_all(&self.dir); | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +async fn workspace_with_admin() -> (Scratch, String, String) { | ||
| 38 | + let scratch = Scratch::open().await; | ||
| 39 | + let ws = scratch.store.create_workspace("Dizey").await.unwrap(); | ||
| 40 | + let admin = scratch | ||
| 41 | + .store | ||
| 42 | + .create_user(NewUser { | ||
| 43 | + workspace_id: ws.id.clone(), | ||
| 44 | + email: "ada@dizey.sh".into(), | ||
| 45 | + display_name: "Ada".into(), | ||
| 46 | + role: Role::Admin, | ||
| 47 | + }) | ||
| 48 | + .await | ||
| 49 | + .unwrap(); | ||
| 50 | + (scratch, ws.id, admin.id) | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +#[tokio::test] | ||
| 54 | +async fn migrations_apply_once_and_survive_reopen() { | ||
| 55 | + let dir = std::env::temp_dir().join(format!("dizey-test-{}", Uuid::new_v4())); | ||
| 56 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 57 | + let path = dir.join("dizey.db").to_string_lossy().into_owned(); | ||
| 58 | + | ||
| 59 | + let first = TursoStore::open(&path).await.unwrap(); | ||
| 60 | + assert_eq!(first.schema_version().await.unwrap(), 1); | ||
| 61 | + first.create_workspace("Dizey").await.unwrap(); | ||
| 62 | + drop(first); | ||
| 63 | + | ||
| 64 | + // Re-opening must not re-run 0001 (which would fail on CREATE TABLE) and | ||
| 65 | + // must not lose what the first open wrote. | ||
| 66 | + let second = TursoStore::open(&path).await.unwrap(); | ||
| 67 | + assert_eq!(second.schema_version().await.unwrap(), 1); | ||
| 68 | + assert_eq!(second.workspace().await.unwrap().unwrap().name, "Dizey"); | ||
| 69 | + drop(second); | ||
| 70 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +#[tokio::test] | ||
| 74 | +async fn a_database_holds_exactly_one_workspace() { | ||
| 75 | + let scratch = Scratch::open().await; | ||
| 76 | + assert!(scratch.store.workspace().await.unwrap().is_none()); | ||
| 77 | + scratch.store.create_workspace("Dizey").await.unwrap(); | ||
| 78 | + let again = scratch.store.create_workspace("Other").await; | ||
| 79 | + assert!(matches!(again, Err(StoreError::Conflict("workspace")))); | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +#[tokio::test] | ||
| 83 | +async fn workspace_defaults_match_the_settings_screen() { | ||
| 84 | + let scratch = Scratch::open().await; | ||
| 85 | + let ws = scratch.store.create_workspace("Dizey").await.unwrap(); | ||
| 86 | + assert_eq!(ws.attachment_limit_bytes, 25 * 1024 * 1024); | ||
| 87 | + assert_eq!(ws.photo_limit_bytes, 2 * 1024 * 1024); | ||
| 88 | + assert!(ws.allowed_file_types.is_empty(), "every type until narrowed"); | ||
| 89 | + assert_eq!(ws.who_can_delete_tasks, DeletePolicy::Anyone); | ||
| 90 | + assert!(ws.smtp_host.is_none()); | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +#[tokio::test] | ||
| 94 | +async fn smtp_password_is_never_part_of_the_workspace_record() { | ||
| 95 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 96 | + scratch | ||
| 97 | + .store | ||
| 98 | + .set_smtp(&ws_id, "smtp.fastmail.com", 465, "dizey", "hunter2", "Dizey", "dizey@dizey.sh") | ||
| 99 | + .await | ||
| 100 | + .unwrap(); | ||
| 101 | + | ||
| 102 | + let ws = scratch.store.workspace().await.unwrap().unwrap(); | ||
| 103 | + assert_eq!(ws.smtp_host.as_deref(), Some("smtp.fastmail.com")); | ||
| 104 | + assert_eq!(ws.smtp_port, Some(465)); | ||
| 105 | + assert_eq!(ws.smtp_from_address.as_deref(), Some("dizey@dizey.sh")); | ||
| 106 | + // The only way to the password is the mailer's own call. | ||
| 107 | + let serialised = serde_json::to_string(&ws).unwrap(); | ||
| 108 | + assert!(!serialised.contains("hunter2"), "{serialised}"); | ||
| 109 | + assert_eq!( | ||
| 110 | + scratch.store.smtp_password(&ws_id).await.unwrap().as_deref(), | ||
| 111 | + Some("hunter2") | ||
| 112 | + ); | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +#[tokio::test] | ||
| 116 | +async fn limits_round_trip_including_the_file_type_list() { | ||
| 117 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 118 | + let types = vec!["png".to_string(), "pdf".to_string()]; | ||
| 119 | + scratch | ||
| 120 | + .store | ||
| 121 | + .set_limits(&ws_id, 10 * 1024 * 1024, 512 * 1024, &types, DeletePolicy::Admin) | ||
| 122 | + .await | ||
| 123 | + .unwrap(); | ||
| 124 | + let ws = scratch.store.workspace().await.unwrap().unwrap(); | ||
| 125 | + assert_eq!(ws.attachment_limit_bytes, 10 * 1024 * 1024); | ||
| 126 | + assert_eq!(ws.photo_limit_bytes, 512 * 1024); | ||
| 127 | + assert_eq!(ws.allowed_file_types, types); | ||
| 128 | + assert_eq!(ws.who_can_delete_tasks, DeletePolicy::Admin); | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +#[tokio::test] | ||
| 132 | +async fn an_invited_member_has_no_password_until_they_choose_one() { | ||
| 133 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 134 | + let member = scratch | ||
| 135 | + .store | ||
| 136 | + .create_user(NewUser { | ||
| 137 | + workspace_id: ws_id.clone(), | ||
| 138 | + email: "grace@dizey.sh".into(), | ||
| 139 | + display_name: "Grace".into(), | ||
| 140 | + role: Role::Member, | ||
| 141 | + }) | ||
| 142 | + .await | ||
| 143 | + .unwrap(); | ||
| 144 | + assert!(member.password_hash.is_none()); | ||
| 145 | + assert!(!member.has_signed_in()); | ||
| 146 | + | ||
| 147 | + scratch | ||
| 148 | + .store | ||
| 149 | + .set_password_hash(&member.id, "$argon2id$fake") | ||
| 150 | + .await | ||
| 151 | + .unwrap(); | ||
| 152 | + let member = scratch.store.user(&member.id).await.unwrap().unwrap(); | ||
| 153 | + assert!(member.has_signed_in()); | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +#[tokio::test] | ||
| 157 | +async fn addresses_are_unique_and_case_insensitive() { | ||
| 158 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 159 | + let dup = scratch | ||
| 160 | + .store | ||
| 161 | + .create_user(NewUser { | ||
| 162 | + workspace_id: ws_id.clone(), | ||
| 163 | + email: " ADA@Dizey.sh ".into(), | ||
| 164 | + display_name: "Ada again".into(), | ||
| 165 | + role: Role::Member, | ||
| 166 | + }) | ||
| 167 | + .await; | ||
| 168 | + assert!(matches!(dup, Err(StoreError::Conflict("account")))); | ||
| 169 | + assert!( | ||
| 170 | + scratch | ||
| 171 | + .store | ||
| 172 | + .user_by_email(&ws_id, "Ada@DIZEY.sh") | ||
| 173 | + .await | ||
| 174 | + .unwrap() | ||
| 175 | + .is_some() | ||
| 176 | + ); | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +#[tokio::test] | ||
| 180 | +async fn an_unknown_address_is_a_plain_none() { | ||
| 181 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 182 | + // The sign-in surface builds its uniform response on this; the store must | ||
| 183 | + // not distinguish "no such account" from anything else by erroring. | ||
| 184 | + assert!( | ||
| 185 | + scratch | ||
| 186 | + .store | ||
| 187 | + .user_by_email(&ws_id, "nobody@dizey.sh") | ||
| 188 | + .await | ||
| 189 | + .unwrap() | ||
| 190 | + .is_none() | ||
| 191 | + ); | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +#[tokio::test] | ||
| 195 | +async fn members_list_and_count_for_the_admin_screen() { | ||
| 196 | + let (scratch, ws_id, admin_id) = workspace_with_admin().await; | ||
| 197 | + for (email, name, role) in [ | ||
| 198 | + ("grace@dizey.sh", "Grace", Role::Member), | ||
| 199 | + ("linus@dizey.sh", "Linus", Role::Viewer), | ||
| 200 | + ] { | ||
| 201 | + scratch | ||
| 202 | + .store | ||
| 203 | + .create_user(NewUser { | ||
| 204 | + workspace_id: ws_id.clone(), | ||
| 205 | + email: email.into(), | ||
| 206 | + display_name: name.into(), | ||
| 207 | + role, | ||
| 208 | + }) | ||
| 209 | + .await | ||
| 210 | + .unwrap(); | ||
| 211 | + } | ||
| 212 | + assert_eq!(scratch.store.count_users(&ws_id).await.unwrap(), 3); | ||
| 213 | + let users = scratch.store.users(&ws_id).await.unwrap(); | ||
| 214 | + assert_eq!(users[0].id, admin_id); | ||
| 215 | + assert_eq!( | ||
| 216 | + users.iter().filter(|u| u.role == Role::Viewer).count(), | ||
| 217 | + 1 | ||
| 218 | + ); | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +#[tokio::test] | ||
| 222 | +async fn profile_and_role_updates_stick() { | ||
| 223 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 224 | + let user = scratch | ||
| 225 | + .store | ||
| 226 | + .create_user(NewUser { | ||
| 227 | + workspace_id: ws_id, | ||
| 228 | + email: "grace@dizey.sh".into(), | ||
| 229 | + display_name: "Grace".into(), | ||
| 230 | + role: Role::Member, | ||
| 231 | + }) | ||
| 232 | + .await | ||
| 233 | + .unwrap(); | ||
| 234 | + | ||
| 235 | + scratch | ||
| 236 | + .store | ||
| 237 | + .set_profile(&user.id, "Grace H.", Some("photos/grace.png")) | ||
| 238 | + .await | ||
| 239 | + .unwrap(); | ||
| 240 | + scratch.store.set_role(&user.id, Role::Viewer).await.unwrap(); | ||
| 241 | + let at = OffsetDateTime::now_utc(); | ||
| 242 | + scratch.store.mark_signed_in(&user.id, at).await.unwrap(); | ||
| 243 | + | ||
| 244 | + let user = scratch.store.user(&user.id).await.unwrap().unwrap(); | ||
| 245 | + assert_eq!(user.display_name, "Grace H."); | ||
| 246 | + assert_eq!(user.photo_path.as_deref(), Some("photos/grace.png")); | ||
| 247 | + assert_eq!(user.role, Role::Viewer); | ||
| 248 | + // Stored as RFC 3339 text, so equality holds to the second. | ||
| 249 | + assert_eq!( | ||
| 250 | + user.last_signed_in_at.unwrap().unix_timestamp(), | ||
| 251 | + at.unix_timestamp() | ||
| 252 | + ); | ||
| 253 | + | ||
| 254 | + // Clearing the photo is a real update, not a no-op. | ||
| 255 | + scratch.store.set_profile(&user.id, "Grace H.", None).await.unwrap(); | ||
| 256 | + assert!(scratch.store.user(&user.id).await.unwrap().unwrap().photo_path.is_none()); | ||
| 257 | +} | ||
| 258 | + | ||
| 259 | +#[tokio::test] | ||
| 260 | +async fn updates_to_a_missing_user_are_not_found() { | ||
| 261 | + let scratch = Scratch::open().await; | ||
| 262 | + let missing = Uuid::new_v4().to_string(); | ||
| 263 | + assert!(matches!( | ||
| 264 | + scratch.store.set_password_hash(&missing, "x").await, | ||
| 265 | + Err(StoreError::NotFound) | ||
| 266 | + )); | ||
| 267 | + assert!(matches!( | ||
| 268 | + scratch.store.set_role(&missing, Role::Member).await, | ||
| 269 | + Err(StoreError::NotFound) | ||
| 270 | + )); | ||
| 271 | +} | ||
| 272 | + | ||
| 273 | +#[tokio::test] | ||
| 274 | +async fn a_signin_link_stores_only_the_hash_and_is_used_once() { | ||
| 275 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 276 | + let user = scratch | ||
| 277 | + .store | ||
| 278 | + .create_user(NewUser { | ||
| 279 | + workspace_id: ws_id, | ||
| 280 | + email: "grace@dizey.sh".into(), | ||
| 281 | + display_name: "Grace".into(), | ||
| 282 | + role: Role::Member, | ||
| 283 | + }) | ||
| 284 | + .await | ||
| 285 | + .unwrap(); | ||
| 286 | + | ||
| 287 | + let now = OffsetDateTime::now_utc(); | ||
| 288 | + let link = scratch | ||
| 289 | + .store | ||
| 290 | + .create_signin_link(&user.id, "hash-of-the-token", now + Duration::days(7)) | ||
| 291 | + .await | ||
| 292 | + .unwrap(); | ||
| 293 | + assert!(link.is_usable(now)); | ||
| 294 | + | ||
| 295 | + // Lookup is by hash: the plaintext never reaches the database. | ||
| 296 | + assert!( | ||
| 297 | + scratch | ||
| 298 | + .store | ||
| 299 | + .signin_link_by_hash("hash-of-the-token") | ||
| 300 | + .await | ||
| 301 | + .unwrap() | ||
| 302 | + .is_some() | ||
| 303 | + ); | ||
| 304 | + assert!( | ||
| 305 | + scratch | ||
| 306 | + .store | ||
| 307 | + .signin_link_by_hash("some-other-hash") | ||
| 308 | + .await | ||
| 309 | + .unwrap() | ||
| 310 | + .is_none() | ||
| 311 | + ); | ||
| 312 | + | ||
| 313 | + scratch.store.consume_signin_link(&link.id, now).await.unwrap(); | ||
| 314 | + let used = scratch | ||
| 315 | + .store | ||
| 316 | + .signin_link_by_hash("hash-of-the-token") | ||
| 317 | + .await | ||
| 318 | + .unwrap() | ||
| 319 | + .unwrap(); | ||
| 320 | + assert!(!used.is_usable(now)); | ||
| 321 | + // A second use finds nothing left to consume. | ||
| 322 | + assert!(matches!( | ||
| 323 | + scratch.store.consume_signin_link(&link.id, now).await, | ||
| 324 | + Err(StoreError::NotFound) | ||
| 325 | + )); | ||
| 326 | +} | ||
| 327 | + | ||
| 328 | +#[tokio::test] | ||
| 329 | +async fn an_expired_link_is_still_a_live_account() { | ||
| 330 | + let (scratch, ws_id, _) = workspace_with_admin().await; | ||
| 331 | + let user = scratch | ||
| 332 | + .store | ||
| 333 | + .create_user(NewUser { | ||
| 334 | + workspace_id: ws_id, | ||
| 335 | + email: "grace@dizey.sh".into(), | ||
| 336 | + display_name: "Grace".into(), | ||
| 337 | + role: Role::Member, | ||
| 338 | + }) | ||
| 339 | + .await | ||
| 340 | + .unwrap(); | ||
| 341 | + | ||
| 342 | + let now = OffsetDateTime::now_utc(); | ||
| 343 | + let stale = scratch | ||
| 344 | + .store | ||
| 345 | + .create_signin_link(&user.id, "stale-hash", now - Duration::hours(1)) | ||
| 346 | + .await | ||
| 347 | + .unwrap(); | ||
| 348 | + assert!(!stale.is_usable(now)); | ||
| 349 | + | ||
| 350 | + // Resending opens the same account rather than making a new one. | ||
| 351 | + let fresh = scratch | ||
| 352 | + .store | ||
| 353 | + .create_signin_link(&user.id, "fresh-hash", now + Duration::days(7)) | ||
| 354 | + .await | ||
| 355 | + .unwrap(); | ||
| 356 | + assert_eq!(fresh.user_id, stale.user_id); | ||
| 357 | + assert!(fresh.is_usable(now)); | ||
| 358 | + assert!(scratch.store.user(&user.id).await.unwrap().is_some()); | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +#[tokio::test] | ||
| 362 | +async fn the_store_is_usable_behind_a_trait_object() { | ||
| 363 | + let scratch = Scratch::open().await; | ||
| 364 | + let store: &dyn Store = &scratch.store; | ||
| 365 | + store.create_workspace("Dizey").await.unwrap(); | ||
| 366 | + assert!(store.workspace().await.unwrap().is_some()); | ||
| 367 | +} | ||