diff --git a/Cargo.lock b/Cargo.lock index ca0fa35..c18f2a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1931,6 +1931,7 @@ dependencies = [ "lettre", "parking_lot", "quick-xml", + "reqwest", "serde", "serde_json", "sha2 0.10.9", @@ -2273,6 +2274,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3008,6 +3019,7 @@ dependencies = [ "base64 0.22.1", "bytes", "futures-core", + "futures-util", "http", "http-body", "http-body-util", @@ -3016,6 +3028,7 @@ dependencies = [ "hyper-util", "js-sys", "log", + "mime_guess", "percent-encoding", "pin-project-lite", "quinn", @@ -4756,6 +4769,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/crates/iz-core/migrations/0007_attachment_remote.sql b/crates/iz-core/migrations/0007_attachment_remote.sql new file mode 100644 index 0000000..8307206 --- /dev/null +++ b/crates/iz-core/migrations/0007_attachment_remote.sql @@ -0,0 +1,8 @@ +-- An attachment row learns where its bytes live. +-- +-- `local`: under `/attachments/`, as every row before this +-- column kept them. `stored`: through the family's Files service, keyed by +-- the row's own id — in's service routes are keyed by external id, which is +-- this id, so no second id column is added. Rows from before the column are +-- local by definition and start there; nothing is backfilled. +ALTER TABLE attachment ADD COLUMN remote_state TEXT NOT NULL DEFAULT 'local'; diff --git a/crates/iz-core/src/config.rs b/crates/iz-core/src/config.rs index 0458db9..1bc02c4 100644 --- a/crates/iz-core/src/config.rs +++ b/crates/iz-core/src/config.rs @@ -49,6 +49,13 @@ const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One p database = "iz.db" # Where attachments live as files, created on boot. storage = "storage" +# Attachments can live with the family's Files service instead of this +# disk. Uncomment, fill in the service key minted for iz, and remove the +# `storage` line above in the same breath — one key cannot be both a +# path and a table, and a file that tries both is refused at boot. +#[storage.in] +#token = "" + # The address the server listens on. Environment variables are ignored — # this is the only thing that decides where iz binds. It is also the # address mail links fall back to, until an admin sets one in Settings. @@ -151,10 +158,15 @@ struct OidcToml { /// The shape of `config/iz.toml`, before the values are checked. Anything /// else the file says lands in `other`, which is read for its key names only /// — enough for the report to say a key was seen and not obeyed. +/// +/// `storage` is read as a raw value on purpose: it has been a string (the +/// attachments directory) since the first file, and the Files service turns +/// it into a table — `[storage.in]`, whose `token` is the service key. +/// One field, both shapes, and neither shape a surprise to the reader. #[derive(Deserialize)] struct Toml { database: Option, - storage: Option, + storage: Option, listen: Option, live_seconds: Option, base_url: Option, @@ -203,11 +215,24 @@ pub struct Config { pub base_url: String, /// The OIDC provider iz trusts. pub oidc: OidcConfig, + /// The family's Files service, when `[storage.in]` names a token. + /// Absent — or an empty token — means "not configured": the feature + /// cannot be switched on and never auto-appears. The token is a secret + /// minted once in in's panel; it is never printed and never rendered. + pub storage_in: Option, /// Whether `config/iz.toml` did not exist and was just written with the /// development defaults this boot. pub defaulted: bool, } +/// The family's Files service, as the file states it: the service key minted +/// for iz, shown once and kept here. `config/iz.toml` is created 0600, and +/// nothing reads this token back out — not the report, not a page. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct InStorage { + pub token: String, +} + /// Why the process is not starting. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ConfigError { @@ -301,9 +326,39 @@ impl Config { let database = value(toml.database).ok_or(ConfigError::Missing("database"))?; let database = absolute(dir, Path::new(&database)); - let storage = match value(toml.storage) { - Some(raw) => absolute(dir, Path::new(&raw)), - None => default_storage(&database), + // Two shapes share the one key. A string is where binary files live, + // as in every file so far — empty means the default beside the + // database, the same as no line at all. A table is the Files + // service: `[storage.in]`, whose `token` is the key minted for iz, + // and the file no longer names a local tree, so the default stands + // in for the directory the photos (always local) still need. Any + // other shape is a file that does not know what it is saying. + let (storage, storage_in) = match toml.storage { + Some(toml::Value::String(raw)) => { + let path = value(Some(raw)); + let storage = match path { + Some(raw) => absolute(dir, Path::new(&raw)), + None => default_storage(&database), + }; + (storage, None) + } + Some(toml::Value::Table(table)) => { + let token = table + .get("in") + .and_then(|in_table| in_table.get("token")) + .and_then(|token| token.as_str()) + .map(str::to_string) + .and_then(|token| value(Some(token))); + let storage_in = token.map(|token| InStorage { token }); + (default_storage(&database), storage_in) + } + Some(_) => { + return Err(ConfigError::Invalid { + key: "storage", + why: "a directory path or a [storage.in] table, not this".to_string(), + }) + } + None => (default_storage(&database), None), }; let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string()); @@ -355,6 +410,7 @@ impl Config { redirect_uri, }, ignored, + storage_in, defaulted, }) } @@ -443,8 +499,15 @@ fn complete(path: &Path, text: &str, base: &Path) { .collect(); // `storage` has no fixed default to print: a file silent about it derives // the directory from where `database` points, so the completed line says - // the value this boot actually resolved rather than a placeholder. - if !mentions(text, "storage") { + // the value this boot actually resolved rather than a placeholder. A + // file that already speaks of the Files service (`[storage.in]`) is + // left alone — appending a `storage` line would turn the key into two + // shapes at once, and TOML refuses that file at the next boot. + let speaks_of_in = toml::from_str::(text) + .ok() + .and_then(|t| t.storage) + .is_some_and(|storage| storage.is_table()); + if !speaks_of_in && !mentions(text, "storage") { // The same base `parse` resolves against, or the completed line would // point somewhere this boot never looks (config/ vs the directory // the app runs from). @@ -456,11 +519,22 @@ fn complete(path: &Path, text: &str, base: &Path) { .as_deref() .map(|db| default_storage(&absolute(base, Path::new(db)))) .unwrap_or_else(|| PathBuf::from("storage")); + // The Files service block rides along commented: the token is a + // secret minted once, and a file is never auto-completed into + // holding one (in's r2-config rule). Reading the file is still how + // a reader learns the feature exists. missing.push(( "storage", format!( "# Where attachments live as files, created on boot.\n\ - storage = {:?}\n", + storage = {:?}\n\ + \n\ + # Attachments can live with the family's Files service instead\n\ + # of this disk. Uncomment, fill in the service key minted for\n\ + # iz, and remove the `storage` line above in the same breath —\n\ + # one key cannot be both a path and a table.\n\ + #[storage.in]\n\ + #token = \"\"\n", storage.display().to_string() ), )); @@ -683,6 +757,60 @@ mod tests { ); let _ = std::fs::remove_dir_all(&dir); } + /// The Files service block: present, it names a token and the local + /// attachments tree falls back beside the database — the file that + /// carries the table cannot also carry the `storage` path. + #[test] + fn a_storage_in_table_names_the_service_key() { + let config = Config::parse( + &format!("database = \"iz.db\"\n[storage.in]\ntoken = \"tok-123\"\n{OIDC}"), + Path::new("."), + false, + ) + .unwrap(); + assert_eq!( + config.storage_in, + Some(InStorage { + token: "tok-123".to_string() + }) + ); + assert!(config.storage.ends_with("storage"), "{:?}", config.storage); + } + + /// Absent, the feature does not exist: no default is invented, and the + /// mode form will never offer it. + #[test] + fn a_file_without_storage_in_configures_nothing() { + let config = Config::parse( + &format!("database = \"iz.db\"\nstorage = \"files\"\n{OIDC}"), + Path::new("."), + false, + ) + .unwrap(); + assert_eq!(config.storage_in, None); + assert!(config.storage.ends_with("files")); + } + + /// An empty token is no token: the table alone does not half-configure + /// the feature. + #[test] + fn an_empty_storage_in_token_configures_nothing() { + let config = Config::parse( + &format!("database = \"iz.db\"\n[storage.in]\ntoken = \"\"\n{OIDC}"), + Path::new("."), + false, + ) + .unwrap(); + assert_eq!(config.storage_in, None); + } + + /// The written file teaches the feature by carrying the block, but only + /// as a comment: a file is never auto-completed into holding a secret. + #[test] + fn the_written_template_carries_the_files_service_block_commented() { + assert!(DEVELOPMENT_DEFAULTS.contains("#[storage.in]")); + assert!(DEVELOPMENT_DEFAULTS.contains("#token = \"\"")); + } /// A live connection that expires instantly is a reconnect loop, so the /// key is refused rather than silently corrected. diff --git a/crates/iz-core/src/store/mod.rs b/crates/iz-core/src/store/mod.rs index 8d8e338..ca64424 100644 --- a/crates/iz-core/src/store/mod.rs +++ b/crates/iz-core/src/store/mod.rs @@ -112,6 +112,80 @@ pub struct Attachment { pub size_bytes: u64, pub uploaded_by: String, pub uploaded_at: OffsetDateTime, + /// Where the bytes live. `Stored` rows name no file on this machine: the + /// bytes sit with the family's Files service, under this very id. + pub remote: AttachmentWhere, +} + +/// Where one attachment's bytes are. Serialized lowercase, so a page that +/// carries the list sees the same words the column stores. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AttachmentWhere { + /// Under `/attachments/` on this machine. + Local, + /// With the Files service, under this row's own id. + Stored, +} + +impl AttachmentWhere { + pub fn as_str(&self) -> &'static str { + match self { + AttachmentWhere::Local => "local", + AttachmentWhere::Stored => "stored", + } + } + + pub fn parse(raw: &str) -> Option { + match raw { + "local" => Some(AttachmentWhere::Local), + "stored" => Some(AttachmentWhere::Stored), + _ => None, + } + } +} + +/// Which surface keeps the workspace's attachment bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum StorageBackend { + /// This machine's own storage tree, as it has always been. + Local, + /// The family's Files service, through the service key iz was minted. + In, +} + +impl StorageBackend { + pub fn as_str(&self) -> &'static str { + match self { + StorageBackend::Local => "local", + StorageBackend::In => "in", + } + } + + pub fn parse(raw: &str) -> Option { + match raw { + "local" => Some(StorageBackend::Local), + "in" => Some(StorageBackend::In), + _ => None, + } + } +} + +/// A file already on the Files service, waiting for its row: the bytes went +/// out under `id` before this was written, so the id is passed in rather +/// than minted here — a row born pointing at bytes that were never pushed +/// would serve nothing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NewRemoteAttachment<'a> { + pub id: String, + pub task_id: &'a str, + pub comment_id: Option<&'a str>, + pub file_name: &'a str, + pub mime_type: &'a str, + pub size_bytes: u64, + pub uploaded_by: &'a str, + pub at: OffsetDateTime, } /// A file on its way into the store, bytes and all: the row goes to the @@ -931,6 +1005,42 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Takes a file away for good. `false` when there was no such row. async fn delete_attachment(&self, id: &str) -> Result; + // -- attachment storage backend ----------------------------------------- + + /// Writes which surface keeps the attachment bytes: this machine's own + /// tree, or the family's Files service. One save, one announcement — + /// the settings surfaces that show the choice re-read when it changes. + async fn set_storage_backend(&self, backend: StorageBackend) -> Result<()>; + + /// The surface currently keeping the bytes. `Local` when the key was + /// never written — the default is the caller's, and the caller's + /// default is the machine, exactly as before this existed. + async fn storage_backend(&self) -> Result; + + /// Writes the row for a file whose bytes were already pushed to the + /// Files service under `new.id`. No local file is touched: the row is + /// born stored, and nothing here can fail the bytes that are already + /// out. + async fn add_remote_attachment(&self, new: NewRemoteAttachment<'_>) -> Result; + + /// The rows still keeping their bytes on this machine, oldest first — + /// the migration drain's pick, and its progress meter. + async fn local_attachments(&self, limit: u64) -> Result>; + + /// Marks a row stored and takes its local file with it — one call, so a + /// row can never be seen stored beside a file that is still there. + /// `false` when there was no such row. + async fn mark_attachment_stored(&self, id: &str) -> Result; + + /// How many rows still keep their bytes on this machine. + async fn local_attachment_count(&self) -> Result; + + /// Says, on the live channel, that the storage surface moved, without a + /// row changing. The migration's "nothing left to move" moment is not a + /// write — the last row's own write announced itself — but the card + /// watching the drain owes its reader one more refresh when the counter + /// it shows is gone. + async fn announce_storage(&self) -> Result<()>; /// Writes the title, description, deadline and clock the detail screen /// saved, and records one activity line per field that actually changed. diff --git a/crates/iz-core/src/store/reconcile.rs b/crates/iz-core/src/store/reconcile.rs index f1053f1..22bd751 100644 --- a/crates/iz-core/src/store/reconcile.rs +++ b/crates/iz-core/src/store/reconcile.rs @@ -476,16 +476,24 @@ fn build_maps( // `bytes` is deliberately unmapped: the file's contents live under // the storage directory now, and `extract_blobs` wrote each one // there before this copy ran. The row keeps only the metadata. - columns: old_cols(&[ - "id", - "task_id", - "comment_id", - "file_name", - "mime_type", - "size_bytes", - "uploaded_by", - "created_at", - ]), + columns: vec![ + ("id", "old.id".into()), + ("task_id", "old.task_id".into()), + ("comment_id", "old.comment_id".into()), + ("file_name", "old.file_name".into()), + ("mime_type", "old.mime_type".into()), + ("size_bytes", "old.size_bytes".into()), + ("uploaded_by", "old.uploaded_by".into()), + ("created_at", "old.created_at".into()), + ( + // Remote storage is new with this schema: every carried row + // kept its bytes on this machine, so every row arrives local + // — the schema's own default, said out loud here because the + // map is explicit on purpose. + "remote_state", + "'local'".to_string(), + ), + ], }); maps.push(TableMap { name: "transition", diff --git a/crates/iz-core/src/store/schema.rs b/crates/iz-core/src/store/schema.rs index 00c2f9f..9c5eb16 100644 --- a/crates/iz-core/src/store/schema.rs +++ b/crates/iz-core/src/store/schema.rs @@ -20,6 +20,7 @@ pub(crate) const MIGRATIONS: &[&str] = &[ include_str!("../../migrations/0004_no_photo_limit.sql"), include_str!("../../migrations/0005_settings.sql"), include_str!("../../migrations/0006_photo_version.sql"), + include_str!("../../migrations/0007_attachment_remote.sql"), ]; /// The whole declared schema — every migration applied in order — as one diff --git a/crates/iz-core/src/store/turso_store.rs b/crates/iz-core/src/store/turso_store.rs index 72bcb52..a76cdca 100644 --- a/crates/iz-core/src/store/turso_store.rs +++ b/crates/iz-core/src/store/turso_store.rs @@ -15,11 +15,11 @@ use ulid::Ulid; use super::secret; use super::{ - ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten, - Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule, - MailSend, MemberSync, NewAttachment, NewSender, NewTask, Recipient, Result, SendKind, - SendState, SenderCheck, SenderTest, Store, StoreError, Tag, TaskCreated, Trigger, User, - UserStats, Workspace, + ActivityEvent, ActivityFilter, ActivityLine, Attachment, AttachmentWhere, Audience, + ClaimedSend, CommentWritten, Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, + MailOutcome, MailRule, MailSend, MemberSync, NewAttachment, NewRemoteAttachment, NewSender, + NewTask, Recipient, Result, SendKind, SendState, SenderCheck, SenderTest, StorageBackend, + Store, StoreError, Tag, TaskCreated, Trigger, User, UserStats, Workspace, }; use super::{ReconcileOptions, reconcile, schema, sniff}; use crate::Role; @@ -392,7 +392,10 @@ impl TursoStore { // text column, no file reads, and the common case is done here. let mut rows = conn .query( - &format!("SELECT COUNT(*) FROM attachment WHERE mime_type IN ({marks})"), + &format!( + "SELECT COUNT(*) FROM attachment \ + WHERE mime_type IN ({marks}) AND remote_state = 'local'" + ), params_from_iter(buckets.iter().copied()), ) .await @@ -408,7 +411,8 @@ impl TursoStore { let mut rows = conn .query( &format!( - "SELECT id, mime_type FROM attachment WHERE mime_type IN ({marks})", + "SELECT id, mime_type FROM attachment \ + WHERE mime_type IN ({marks}) AND remote_state = 'local'", marks = marks, ), params_from_iter(buckets.iter().copied()), @@ -1232,6 +1236,7 @@ fn opt_stamp(row: &Row, idx: usize) -> Result> { /// One attachment row, in the column order every query above selects. fn attachment_row(row: &Row) -> Result { + let remote = text(row, 8)?; Ok(Attachment { id: text(row, 0)?, task_id: text(row, 1)?, @@ -1241,9 +1246,13 @@ fn attachment_row(row: &Row) -> Result { size_bytes: row.get::(5).map_err(backend)?.max(0) as u64, uploaded_by: text(row, 6)?, uploaded_at: parse_stamp(&text(row, 7)?)?, + remote: AttachmentWhere::parse(&remote).ok_or_else(|| { + StoreError::Corrupt(format!( + "attachment wears an unknown remote state {remote:?}" + )) + })?, }) } - fn text(row: &Row, idx: usize) -> Result { row.get::(idx).map_err(backend) } @@ -2848,7 +2857,7 @@ impl Store for TursoStore { let mut rows = conn .query( "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \ - uploaded_by, created_at FROM attachment \ + uploaded_by, created_at, remote_state FROM attachment \ WHERE task_id = ?1 ORDER BY created_at, rowid", params![task_id], ) @@ -2866,7 +2875,7 @@ impl Store for TursoStore { let mut rows = conn .query( "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \ - uploaded_by, created_at FROM attachment WHERE id = ?1", + uploaded_by, created_at, remote_state FROM attachment WHERE id = ?1", params![id], ) .await @@ -2925,6 +2934,127 @@ impl Store for TursoStore { Ok(gone > 0) } + async fn set_storage_backend(&self, which: StorageBackend) -> Result<()> { + // The key is also named by `iz-web` (`STORAGE_BACKEND_KEY`), which + // reads the row directly only in tests; the trait is the real door. + const KEY: &str = "storage_backend"; + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO setting (key, value) VALUES (?1, ?2) \ + ON CONFLICT (key) DO UPDATE SET value = excluded.value", + params![KEY, which.as_str()], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Settings]); + Ok(()) + } + + async fn storage_backend(&self) -> Result { + Ok(self + .get_setting("storage_backend") + .await? + .and_then(|raw| StorageBackend::parse(&raw)) + .unwrap_or(StorageBackend::Local)) + } + + async fn add_remote_attachment(&self, new: NewRemoteAttachment<'_>) -> Result { + // The bytes are already on the Files service under `new.id`; the row + // is the only fact to write, born stored. No file lands here, so a + // failure here costs a row, never bytes. + let conn = self.conn.lock().await; + conn.execute( + "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \ + size_bytes, uploaded_by, created_at, remote_state) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'stored')", + params![ + new.id.clone(), + new.task_id, + new.comment_id, + new.file_name, + new.mime_type, + new.size_bytes as i64, + new.uploaded_by, + stamp(new.at)? + ], + ) + .await + .map_err(backend)?; + drop(conn); + self.announce([Topic::Task(new.task_id.to_string())]); + Ok(new.id) + } + + async fn local_attachments(&self, limit: u64) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT id, task_id, comment_id, file_name, mime_type, size_bytes, \ + uploaded_by, created_at, remote_state FROM attachment \ + WHERE remote_state = 'local' ORDER BY created_at, rowid LIMIT ?1", + params![limit as i64], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(attachment_row(&row)?); + } + Ok(out) + } + + async fn mark_attachment_stored(&self, id: &str) -> Result { + // Which task gained a stored file has to be read before the row + // moves, the way `delete_attachment` reads its owner: after the + // write there is nothing left to ask. + let owner = self + .one_row("SELECT task_id FROM attachment WHERE id = ?1", params![id]) + .await? + .map(|row| row.get::(0).map_err(backend)) + .transpose()?; + let conn = self.conn.lock().await; + let moved = conn + .execute( + "UPDATE attachment SET remote_state = 'stored' WHERE id = ?1", + params![id], + ) + .await + .map_err(backend)?; + drop(conn); + if moved > 0 { + // The row says stored, so the file must go — one call, so no + // reader between the two ever sees stored beside a file that is + // still there. Best-effort: a file that survives the unlink is + // orphaned bytes the boot sweep collects. + let _ = std::fs::remove_file(attachment_file(&self.storage, id)); + if let Some(task_id) = owner { + self.announce([Topic::Task(task_id)]); + } + } + Ok(moved > 0) + } + + async fn local_attachment_count(&self) -> Result { + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT COUNT(*) FROM attachment WHERE remote_state = 'local'", + (), + ) + .await + .map_err(backend)?; + match rows.next().await.map_err(backend)? { + Some(row) => count_of(&row), + None => Ok(0), + } + } + + async fn announce_storage(&self) -> Result<()> { + self.announce([Topic::Settings]); + Ok(()) + } + async fn save_task( &self, task_id: &str, diff --git a/crates/iz-core/tests/store.rs b/crates/iz-core/tests/store.rs index e4595b8..94f38c9 100644 --- a/crates/iz-core/tests/store.rs +++ b/crates/iz-core/tests/store.rs @@ -8,8 +8,8 @@ use std::path::PathBuf; use iz_core::Role; use iz_core::store::{ - Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, SendKind, SendState, Store, - StoreError, Trigger, TursoStore, User, + Audience, Event, MailOutcome, MailRule, NewAttachment, NewRemoteAttachment, NewSender, + SendKind, SendState, StorageBackend, Store, StoreError, Trigger, TursoStore, User, }; use time::{Duration, OffsetDateTime}; use ulid::Ulid; @@ -8856,3 +8856,247 @@ async fn app_settings_round_trip_through_one_row_per_key() { Some("https://iz.example".to_string()) ); } + +// -- attachment storage backend ---------------------------------------------- + +/// An attachment pushed to the Files service before its row exists: the row +/// is born stored, names no file on this machine, and answers the screen's +/// reads like any other attachment. +#[tokio::test] +async fn a_remote_attachment_is_born_stored_without_a_local_file() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let task = add_task(&scratch.store, &workspace, "Backlog", "Ship it", None, &admin).await; + let id = Ulid::new().to_string(); + let stored = scratch + .store + .add_remote_attachment(NewRemoteAttachment { + id: id.clone(), + task_id: &task, + comment_id: None, + file_name: "remote.png", + mime_type: "image/png", + size_bytes: 7, + uploaded_by: &admin, + at: OffsetDateTime::now_utc(), + }) + .await + .unwrap(); + assert_eq!(stored, id, "the row carries the id the push used"); + + let row = scratch.store.attachment(&id).await.unwrap().unwrap(); + assert_eq!(row.remote, iz_core::store::AttachmentWhere::Stored); + assert_eq!(row.file_name, "remote.png"); + assert_eq!(row.size_bytes, 7); + assert!( + !scratch + .storage + .join("attachments") + .join(&id) + .exists(), + "a stored row names no file on this machine" + ); + assert_eq!( + scratch.store.attachments(&task).await.unwrap()[0].id, + id, + "the screen lists a stored row like any other" + ); + assert_eq!(scratch.store.local_attachment_count().await.unwrap(), 0); + let _ = std::fs::remove_dir_all(&scratch.dir); +} + +/// The mode is an app-level fact with a default the caller owns: reads +/// before any write answer Local, and the write is visible to the next read. +#[tokio::test] +async fn the_storage_backend_reads_back_what_was_written() { + let (scratch, _workspace, _admin) = workspace_with_admin().await; + assert_eq!( + scratch.store.storage_backend().await.unwrap(), + StorageBackend::Local, + "a store never told answers Local, as it always has" + ); + scratch + .store + .set_storage_backend(StorageBackend::In) + .await + .unwrap(); + assert_eq!( + scratch.store.storage_backend().await.unwrap(), + StorageBackend::In + ); + scratch + .store + .set_storage_backend(StorageBackend::Local) + .await + .unwrap(); + assert_eq!( + scratch.store.storage_backend().await.unwrap(), + StorageBackend::Local + ); + let _ = std::fs::remove_dir_all(&scratch.dir); +} + +/// Switching the backend is a settings save: every surface showing it is +/// woken, exactly like `set_limits`. +#[tokio::test] +async fn setting_the_storage_backend_announces_settings() { + let (scratch, _workspace, _admin) = workspace_with_admin().await; + let mut rx = scratch.store.subscribe(); + scratch + .store + .set_storage_backend(StorageBackend::In) + .await + .unwrap(); + let seen: Vec = { + let mut out = Vec::new(); + while let Ok(change) = rx.try_recv() { + out.push(change.topic.kind().to_string()); + } + out + }; + assert!( + seen.iter().any(|kind| kind == "settings"), + "the switch did not announce Settings; heard {seen:?}" + ); + let _ = std::fs::remove_dir_all(&scratch.dir); +} + +/// The drain's pick: only local rows, oldest first, and no more than asked. +#[tokio::test] +async fn local_attachments_are_the_oldest_local_rows_up_to_the_limit() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let task = add_task(&scratch.store, &workspace, "Backlog", "Ship it", None, &admin).await; + let now = OffsetDateTime::now_utc(); + let mut ids = Vec::new(); + for (n, name) in ["a.png", "b.png", "c.png"].iter().enumerate() { + ids.push( + scratch + .store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: name, + mime_type: "image/png", + bytes: vec![0x89, b'0' + n as u8, 0x50, 0x4E, 0x47], + uploaded_by: &admin, + at: now + Duration::minutes(n as i64), + }) + .await + .unwrap(), + ); + } + // The middle one already moved; it must not appear in the drain's pick. + scratch + .store + .mark_attachment_stored(&ids[1]) + .await + .unwrap() + ; + + let picked = scratch.store.local_attachments(10).await.unwrap(); + assert_eq!( + picked.iter().map(|a| a.id.clone()).collect::>(), + vec![ids[0].clone(), ids[2].clone()], + "only local rows, in upload order" + ); + assert_eq!( + scratch + .store + .local_attachments(1) + .await + .unwrap() + .iter() + .map(|a| a.id.clone()) + .collect::>(), + vec![ids[0].clone()], + "the limit is the drain's batch size" + ); + assert_eq!(scratch.store.local_attachment_count().await.unwrap(), 2); + let _ = std::fs::remove_dir_all(&scratch.dir); +} + +/// Marking stored flips the row and takes the file with it in the same +/// call, and answers false for a row that is not there. +#[tokio::test] +async fn marking_stored_moves_the_row_and_unlinks_the_file() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let task = add_task(&scratch.store, &workspace, "Backlog", "Ship it", None, &admin).await; + let id = scratch + .store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "gone.png", + mime_type: "image/png", + bytes: vec![0x89, 0x50, 0x4E, 0x47], + uploaded_by: &admin, + at: OffsetDateTime::now_utc(), + }) + .await + .unwrap(); + let file = scratch.storage.join("attachments").join(&id); + assert!(file.is_file()); + + assert!(scratch.store.mark_attachment_stored(&id).await.unwrap()); + assert_eq!( + scratch + .store + .attachment(&id) + .await + .unwrap() + .unwrap() + .remote, + iz_core::store::AttachmentWhere::Stored + ); + assert!(!file.exists(), "the local bytes left with the row's state"); + assert_eq!(scratch.store.local_attachment_count().await.unwrap(), 0); + + let missing = Ulid::new().to_string(); + assert!( + !scratch + .store + .mark_attachment_stored(&missing) + .await + .unwrap(), + "a row that is not there was never marked" + ); + let _ = std::fs::remove_dir_all(&scratch.dir); +} + +/// A row the boot sniffer must leave alone: a stored row wears bytes on the +/// Files service, not under `attachments/`, so the pass that refines generic +/// mimes by reading those files must not even look at it — a zip-pptx +/// planted stored keeps its generic mime across the boot. +#[tokio::test] +async fn the_boot_resniff_leaves_stored_rows_alone() { + let dir = std::env::temp_dir().join(format!("iz-resniff-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("iz.db").to_str().unwrap().to_string(); + drop(TursoStore::open(&path, &dir.join("storage")).await.unwrap()); + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute( + "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, \ + uploaded_by, created_at, remote_state) \ + VALUES ('FR', 'T1', 'deck.bin', 'application/zip', 4, 'U1', \ + '2026-08-01T00:00:00Z', 'stored')", + turso::params![], + ) + .await + .unwrap(); + // The very bytes a local row would be refined on. + std::fs::write( + dir.join("storage").join("attachments").join("FR"), + zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]), + ) + .unwrap(); + drop(conn); + drop(db); + + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); + assert_eq!( + store.attachment("FR").await.unwrap().unwrap().mime_type, + "application/zip", + "a stored row's mime is the push's own fact, not this disk's guess" + ); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/iz-web/Cargo.toml b/crates/iz-web/Cargo.toml index 189a235..2e6c823 100644 --- a/crates/iz-web/Cargo.toml +++ b/crates/iz-web/Cargo.toml @@ -25,6 +25,18 @@ iz-core = { workspace = true, features = ["server"] } serde.workspace = true serde_json.workspace = true time.workspace = true +# Talks to the family's Files service for attachment storage: the machine +# API (multipart push, raw fetch, hard delete) behind iz's `[storage.in]` +# token. rustls, not OpenSSL, for the same reason the mailer is. +reqwest = { version = "0.13.4", default-features = false, features = [ + "rustls", + "json", + "multipart", +] } +# Mints the external id every pushed attachment carries: in's service +# routes are keyed by it, so it is minted here, before the push, not by +# the store. +ulid = { workspace = true } thiserror.workspace = true tokio = { workspace = true } async-trait = "0.1.92" diff --git a/crates/iz-web/src/detail.rs b/crates/iz-web/src/detail.rs index 3d5adb3..6f88270 100644 --- a/crates/iz-web/src/detail.rs +++ b/crates/iz-web/src/detail.rs @@ -21,7 +21,7 @@ use iz_core::detail::{ Comment, DeletionCost, DependencyEdge, TaskDetail, TaskFacts, moment_label_in, moment_label_with_seconds_in, parse_zone, }; -use iz_core::store::{Store, StoreError, User}; +use iz_core::store::{AttachmentWhere, Store, StoreError, User}; use serde::{Deserialize, Serialize}; use time::{Date, UtcOffset}; use topcoat::Result; @@ -974,7 +974,10 @@ async fn delete_task(cx: &Cx, Form(input): Form) -> Redirect { /// [`delete_task`]'s soft one — an upload is not a fact worth an audit /// trail. /// Only the person who put it there, or an admin, may -/// take it away. +/// take it away. A row stored on the Files service takes its bytes from +/// in first: the remote copy only goes when in says it went, so an +/// unreachable service refuses the delete and the row stays, serviceable +/// again the moment in returns. #[route(POST "/api/delete_file")] async fn delete_file(cx: &Cx, Form(input): Form) -> Redirect { let user = match require_user(cx).await { @@ -992,6 +995,16 @@ async fn delete_file(cx: &Cx, Form(input): Form) -> Redirect { return redirect(cx, Some(Refusal::Forbidden)); } + if attachment.remote == AttachmentWhere::Stored { + let Some((_, url)) = crate::storage::in_of(store.as_ref()).await else { + return redirect(cx, Some(Refusal::StorageUnavailable)); + }; + if let Err(problem) = crate::storage::client(cx).delete(&url, &attachment.id).await { + eprintln!("storage delete: {problem:?}"); + return redirect(cx, Some(Refusal::StorageUnavailable)); + } + } + store.delete_attachment(&input.file_id).await?; let _ = store .record_activity( diff --git a/crates/iz-web/src/files.rs b/crates/iz-web/src/files.rs index f74889d..10a92a6 100644 --- a/crates/iz-web/src/files.rs +++ b/crates/iz-web/src/files.rs @@ -15,9 +15,12 @@ use topcoat::router::{ }; use iz_core::store::sniff::sniff; -use iz_core::store::{NewAttachment, Store, User}; +use iz_core::store::{ + NewAttachment, NewRemoteAttachment, AttachmentWhere, StorageBackend, Store, User, +}; use crate::server::{Refusal, store, require_user}; +use ulid::Ulid; path_param!(id); @@ -218,6 +221,16 @@ fn not_found() -> (StatusCode, HeaderMap, Vec) { (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) } +/// The 503 a stored attachment serves when the Files service cannot be +/// reached — one plain line, and never the 404, because the row exists. +fn service_unavailable() -> (StatusCode, HeaderMap, Vec) { + ( + StatusCode::SERVICE_UNAVAILABLE, + HeaderMap::new(), + b"the Files service is unreachable\n".to_vec(), + ) +} + /// A single-range `Range: bytes=...` request resolved against `total` bytes, /// as `(start, end)` inclusive. `None` for anything this does not parse as /// exactly one `bytes=` range (a multi-range header included) — the caller @@ -376,23 +389,47 @@ async fn upload( None => None, }; - let mut added: Result<(), iz_core::store::StoreError> = Ok(()); + // Which surface keeps the bytes is decided per request, after the + // validation chain above — that chain (role, task, extension, streamed + // size, sniff, label) is identical in both modes, because a file iz + // would refuse on its own disk it refuses in the family's storage too. + let backend = match store.storage_backend().await { + Ok(backend) => backend, + Err(_) => return Ok(back_to(&task_id, Some(Refusal::Unavailable))), + }; + let mut added: Result<(), Refusal> = Ok(()); for (file_name, bytes) in files { let label = label_of(&file_name); let mime_type = sniff(&bytes); - added = store - .add_attachment(NewAttachment { - task_id: &task_id, - comment_id: comment_id.as_deref(), - file_name: &label, - mime_type, - bytes, - uploaded_by: &user.id, - at: OffsetDateTime::now_utc(), - }) - .await - .map(|_| ()); + added = match backend { + StorageBackend::Local => store + .add_attachment(NewAttachment { + task_id: &task_id, + comment_id: comment_id.as_deref(), + file_name: &label, + mime_type, + bytes, + uploaded_by: &user.id, + at: OffsetDateTime::now_utc(), + }) + .await + .map(|_| ()) + .map_err(|_| Refusal::NotFound), + StorageBackend::In => { + push_to_in( + cx, + store.as_ref(), + &task_id, + comment_id.as_deref(), + &label, + mime_type, + bytes, + &user.id, + ) + .await + } + }; if added.is_ok() && comment_id.is_none() { let _ = store @@ -410,10 +447,63 @@ async fn upload( Ok(match added { Ok(_) => back_to(&task_id, None), - Err(_) => back_to(&task_id, Some(Refusal::NotFound)), + Err(refusal) => back_to(&task_id, Some(refusal)), }) } +/// The In-mode half of the upload: the bytes go out under an id minted +/// here, and only when in says they landed does the row exist. Synchronous +/// passthrough on purpose — no upload queue — so a service that is not +/// there is a refusal the uploader can act on now. On the rare failure +/// after the push landed (the task gone mid-request, say) the push is +/// taken back best-effort; a leaked remote file is the accepted residual +/// if that take-back also fails. +async fn push_to_in( + cx: &Cx, + store: &dyn Store, + task_id: &str, + comment_id: Option<&str>, + label: &str, + mime_type: &str, + bytes: Vec, + uploader: &str, +) -> Result<(), Refusal> { + let Some((_, url)) = crate::storage::in_of(store).await else { + return Err(Refusal::StorageNotListed); + }; + let external_id = Ulid::new().to_string(); + let size = bytes.len() as u64; + let client = crate::storage::client(cx); + if let Err(problem) = client + .put(&url, &external_id, label, bytes, mime_type) + .await + { + eprintln!("storage push: {problem:?}"); + return Err(match problem { + crate::storage::StorageProblem::Quota => Refusal::StorageQuota, + _ => Refusal::StorageUnavailable, + }); + } + if let Err(problem) = store + .add_remote_attachment(NewRemoteAttachment { + id: external_id.clone(), + task_id, + comment_id, + file_name: label, + mime_type, + size_bytes: size, + uploaded_by: uploader, + at: OffsetDateTime::now_utc(), + }) + .await + { + eprintln!("storage row after push: {problem}"); + let _ = client.delete(&url, &external_id).await; + return Err(Refusal::NotFound); + } + Ok(()) +} + /// Serves one attachment's bytes, or the same not-found a stranger to the /// task would see for a task that does not exist — never a `403`, which would /// confirm the id belongs to someone else's workspace. @@ -433,8 +523,27 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> if task_of(store.as_ref(), &user, &row.task_id).await.is_err() { return Ok(not_found()); } - let Ok(Some(bytes)) = store.attachment_bytes(id).await else { - return Ok(not_found()); + // A stored row's bytes are not on this disk: they come back through + // the Files service, and an unreachable service is a 503 — never the + // not-found a stranger sees, because the row exists and this caller + // has already cleared its task. A local row reads exactly as before. + let bytes = match row.remote { + AttachmentWhere::Local => match store.attachment_bytes(id).await { + Ok(Some(bytes)) => bytes, + _ => return Ok(not_found()), + }, + AttachmentWhere::Stored => { + let Some((_, url)) = crate::storage::in_of(store.as_ref()).await else { + return Ok(service_unavailable()); + }; + match crate::storage::client(cx).fetch(&url, id).await { + Ok(bytes) => bytes, + Err(problem) => { + eprintln!("storage fetch: {problem:?}"); + return Ok(service_unavailable()); + } + } + } }; let forced_download = query_params::(cx)?.dl.is_some(); diff --git a/crates/iz-web/src/i18n.rs b/crates/iz-web/src/i18n.rs index d06a183..7497d7c 100644 --- a/crates/iz-web/src/i18n.rs +++ b/crates/iz-web/src/i18n.rs @@ -131,6 +131,17 @@ pub enum Key { ConnectionLastEvent, ConnectionLastPass, ConnectionNever, + StorageTitle, + StorageService, + StorageMode, + StorageModeLocal, + StorageModeIn, + StorageConnection, + StorageUnreachable, + StorageLimit, + StorageMigration, + StorageLastProblem, + StorageAbsent, EmailLabel, ThemeLabel, LightOption, @@ -565,6 +576,28 @@ pub fn t(lang: Lang, key: Key) -> &'static str { (ConnectionLastPass, Tr) => "Son tam geçiş", (ConnectionNever, En) => "never", (ConnectionNever, Tr) => "hiç", + (StorageTitle, En) => "Storage", + (StorageTitle, Tr) => "Depolama", + (StorageService, En) => "Service", + (StorageService, Tr) => "Hizmet", + (StorageMode, En) => "Mode", + (StorageMode, Tr) => "Mod", + (StorageModeLocal, En) => "Local disk", + (StorageModeLocal, Tr) => "Yerel disk", + (StorageModeIn, En) => "Files (in)", + (StorageModeIn, Tr) => "Dosyalar (in)", + (StorageConnection, En) => "Connection", + (StorageConnection, Tr) => "Bağlantı", + (StorageUnreachable, En) => "Unreachable", + (StorageUnreachable, Tr) => "Erişilemiyor", + (StorageLimit, En) => "Limit", + (StorageLimit, Tr) => "Limit", + (StorageMigration, En) => "Migration", + (StorageMigration, Tr) => "Aktarım", + (StorageLastProblem, En) => "Last problem", + (StorageLastProblem, Tr) => "Son sorun", + (StorageAbsent, En) => "Not in the family", + (StorageAbsent, Tr) => "Ailede değil", (EmailLabel, En) => "EMAIL", (EmailLabel, Tr) => "E-POSTA", (ThemeLabel, En) => "THEME", diff --git a/crates/iz-web/src/layout.rs b/crates/iz-web/src/layout.rs index 2b6e70a..6f604f3 100644 --- a/crates/iz-web/src/layout.rs +++ b/crates/iz-web/src/layout.rs @@ -239,7 +239,7 @@ pub async fn topbar_nav(cx: &Cx, active: NavPage, role: iz_core::Role, lang: Lan /// background beat in `main.rs`. Absent, empty, unparseable or a store /// that will not answer all read the same: an empty list, which renders /// no switcher. A page must not fail for the want of a wordmark. -async fn family_of(cx: &Cx) -> Vec { +pub(crate) async fn family_of(cx: &Cx) -> Vec { match store(cx).get_setting(FAMILY_KEY).await { Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(), _ => Vec::new(), diff --git a/crates/iz-web/src/lib.rs b/crates/iz-web/src/lib.rs index 3e08e1a..f32acd7 100644 --- a/crates/iz-web/src/lib.rs +++ b/crates/iz-web/src/lib.rs @@ -18,6 +18,7 @@ pub mod people; pub mod rules; pub mod server; pub mod settings; +pub mod storage; pub mod sheet; pub mod slides; pub mod smtp; diff --git a/crates/iz-web/src/main.rs b/crates/iz-web/src/main.rs index 89d1e86..ac9da5f 100644 --- a/crates/iz-web/src/main.rs +++ b/crates/iz-web/src/main.rs @@ -143,6 +143,16 @@ async fn main() { config.oidc.client_id.clone(), config.oidc.client_secret.clone(), ); + // The family's Files service as a storage peer, beside the identity + // peer above: the client carries the key `[storage.in]` named (and + // when the deployment never configured one, the client still exists — + // every call then refuses before the wire), and the health beside it + // is what the Settings Storage card renders. The beat below keeps + // both current. + let storage_client = iz_web::storage::StorageClient::new( + config.storage_in.as_ref().map(|storage| storage.token.clone()), + ); + let storage_health = iz_web::storage::StorageHealth::new(); // The engine is always built, because a sender can appear at any moment: // an admin fills the panel in and the next sweep sends what was held. It // holds one connection pool, rebuilt only when the settings behind it @@ -173,6 +183,16 @@ async fn main() { health.clone(), )); tokio::spawn(directory_stream(store.clone(), directory.clone(), health.clone())); + // The storage mirror's watchdog: follows the family to wherever in + // lives now, keeps the card's facts current, and — while the + // workspace's attachments live on in — drains the rows still on this + // disk. First pass runs right away, so a fresh enablement starts + // moving rows within the beat. + tokio::spawn(storage_beat( + store.clone(), + storage_client.clone(), + storage_health.clone(), + )); // Told when the process is stopping, so the live streams end instead of // being waited out. See `iz_web::live::Shutdown`. let (stop, stopping) = tokio::sync::watch::channel(false); @@ -190,7 +210,9 @@ async fn main() { ) .app_context(store.clone()) .app_context(directory) - .app_context(health) + .app_context(health.clone()) + .app_context(storage_client.clone()) + .app_context(storage_health.clone()) .app_context(iz_client::LogoutBack(Arc::new(iz_web::server::logout_back))) .app_context(config.clone()) .app_context(iz_web::live::LiveWindow(std::time::Duration::from_secs( @@ -505,6 +527,24 @@ async fn directory_stream( } } +/// The storage beat: [`iz_web::storage::storage_cycle`] over and over, +/// [`iz_web::storage::STORAGE_SECONDS`] apart. The cycle body is extracted +/// the way `mirror_directory` is, so a test can run one beat by hand; this +/// loop is only the alarm clock. +async fn storage_beat( + store: Arc, + client: iz_web::storage::StorageClient, + health: iz_web::storage::StorageHealth, +) { + loop { + iz_web::storage::storage_cycle(&store, &client, &health).await; + tokio::time::sleep(std::time::Duration::from_secs( + iz_web::storage::STORAGE_SECONDS, + )) + .await; + } +} + /// Waits for something to happen to the mail queue specifically. /// /// The channel carries every topic, and the sweep cares about one. Filtering diff --git a/crates/iz-web/src/server.rs b/crates/iz-web/src/server.rs index c0ed1e2..1415c72 100644 --- a/crates/iz-web/src/server.rs +++ b/crates/iz-web/src/server.rs @@ -37,6 +37,11 @@ pub fn config(cx: &Cx) -> iz_core::Config { /// value is a JSON array of `{key, name, url}` — exactly what im's /// `/family` served. pub const FAMILY_KEY: &str = "family"; +/// The app-level `setting` key the storage mode form writes: which surface +/// keeps the attachment bytes, `"local"` or `"in"`. The store's +/// `set_storage_backend` owns the write and the announcement; the constant +/// is named here beside `FAMILY_KEY` because tests read the row directly. +pub const STORAGE_BACKEND_KEY: &str = "storage_backend"; /// The app-level `setting` key the public-address field on Settings /// writes: where a sign-out that started here sends the browser. Saving @@ -410,6 +415,17 @@ pub enum Refusal { NoSuchMember, /// The address typed into the add-member form already has a row here. AlreadyMember, + /// in refused the push: the bytes iz holds have spent the limit im set. + StorageQuota, + /// Storage through the Files service was asked for while `[storage.in]` + /// holds no token — there is no key to speak with. + StorageNotConfigured, + /// The Files service is not in the family mirror, so there is no URL to + /// push to. im's panel puts it there; iz does not guess. + StorageNotListed, + /// The Files service did not answer — down, mid-deploy, or the wire + /// between. An upload is not queued for later; it is refused now. + StorageUnavailable, Unavailable, } @@ -454,6 +470,10 @@ impl Refusal { Refusal::NotFound => "No such task.".to_string(), Refusal::NoSuchMember => "No such member.".to_string(), Refusal::AlreadyMember => "Already a member.".to_string(), + Refusal::StorageNotConfigured => "The Files service has no key.".to_string(), + Refusal::StorageNotListed => "The Files service is not in the family.".to_string(), + Refusal::StorageUnavailable => "The Files service is unreachable.".to_string(), + Refusal::StorageQuota => "The Files service is full.".to_string(), Refusal::Unavailable => "Something went wrong.".to_string(), } } @@ -487,6 +507,10 @@ impl Refusal { Refusal::NotFound => "Böyle bir görev yok.".to_string(), Refusal::NoSuchMember => "Böyle bir üye yok.".to_string(), Refusal::AlreadyMember => "Zaten üye.".to_string(), + Refusal::StorageNotConfigured => "Dosyalar hizmetinin anahtarı yok.".to_string(), + Refusal::StorageNotListed => "Dosyalar hizmeti ailede değil.".to_string(), + Refusal::StorageUnavailable => "Dosyalar hizmetine erişilemiyor.".to_string(), + Refusal::StorageQuota => "Dosyalar hizmeti dolu.".to_string(), Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(), Refusal::BadLimit => { "Limit en az 1 MB, dosya başına en çok 500 MB olabilir.".to_string() @@ -552,6 +576,10 @@ impl Refusal { "not-found" => Refusal::NotFound, "no-such-member" => Refusal::NoSuchMember, "already-member" => Refusal::AlreadyMember, + "storage-quota" => Refusal::StorageQuota, + "storage-not-configured" => Refusal::StorageNotConfigured, + "storage-not-listed" => Refusal::StorageNotListed, + "storage-unavailable" => Refusal::StorageUnavailable, "unavailable" => Refusal::Unavailable, _ => return None, }) @@ -596,6 +624,10 @@ impl Refusal { Refusal::NotFound => "not-found", Refusal::NoSuchMember => "no-such-member", Refusal::AlreadyMember => "already-member", + Refusal::StorageNotConfigured => "storage-not-configured", + Refusal::StorageNotListed => "storage-not-listed", + Refusal::StorageUnavailable => "storage-unavailable", + Refusal::StorageQuota => "storage-quota", Refusal::Unavailable => "unavailable", } } diff --git a/crates/iz-web/src/settings.rs b/crates/iz-web/src/settings.rs index c0014f8..421b37c 100644 --- a/crates/iz-web/src/settings.rs +++ b/crates/iz-web/src/settings.rs @@ -21,7 +21,7 @@ use topcoat::router::{HeaderMap, HeaderValue, StatusCode, header, page, route}; use topcoat::view::view; use iz_core::detail::ActivityKind; -use iz_core::store::{NewSender, SenderCheck, SenderTest, Store, StoreError, User}; +use iz_core::store::{NewSender, SenderCheck, SenderTest, StorageBackend, Store, StoreError, User}; use crate::i18n::{Key, Lang, t}; use crate::server::{PUBLIC_URL_KEY, Refusal, config, mail, require_admin, require_user, store}; @@ -142,7 +142,7 @@ fn redirect_to(query: &str) -> (StatusCode, HeaderMap, Vec) { fn section_of_call(call: &str) -> &'static str { match call { "save_sender" | "send_test_mail" | "check_sender" => "outgoing", - "save_limits" => "limits", + "save_limits" | "save_storage" => "limits", "save_public_url" => "server", "set_role" | "set_disabled" | "add_member" => "members", "send_message" => "message", @@ -305,6 +305,58 @@ async fn save_limits( Ok(saved_or_refused("save_limits", refusal)) } +#[derive(serde::Deserialize)] +struct SaveStorageForm { + backend: String, +} + +/// Switches which surface keeps attachment bytes. Admin-only, checked here +/// — the Limits panel is an admin's, but the route is the gate. +/// +/// `in` is refused unless the whole road is there: a key named by +/// `[storage.in]`, and a family row pointing at the service. Anything +/// less would strand new uploads at a service this workspace cannot +/// reach; `local` always stands, because this disk is always here. +#[route(POST "/api/save_storage")] +async fn save_storage( + cx: &Cx, + Form(input): Form, +) -> Result<(StatusCode, HeaderMap, Vec)> { + if let Err(refusal) = require_admin(cx).await { + return Ok(saved_or_refused("save_storage", Some(refusal))); + } + let backend = match input.backend.as_str() { + "local" => StorageBackend::Local, + "in" => { + if config(cx).storage_in.is_none() { + return Ok(saved_or_refused( + "save_storage", + Some(Refusal::StorageNotConfigured), + )); + } + let listed = crate::layout::family_of(cx) + .await + .iter() + .any(|service| service.key == "in"); + if !listed { + return Ok(saved_or_refused( + "save_storage", + Some(Refusal::StorageNotListed), + )); + } + StorageBackend::In + } + _ => return Ok(saved_or_refused("save_storage", Some(Refusal::NotFound))), + }; + match store(cx).set_storage_backend(backend).await { + Ok(()) => Ok(saved_or_refused("save_storage", None)), + Err(problem) => { + eprintln!("store error: {problem}"); + Ok(saved_or_refused("save_storage", Some(Refusal::Unavailable))) + } + } +} + #[derive(serde::Deserialize)] struct SaveSenderForm { host: String, @@ -942,6 +994,65 @@ async fn connection_card(cx: &Cx, lang: Lang) -> Result { } } +/// The Storage card's body: where the family says the Files service is, +/// whether it answered the last beat, how full the account im limits +/// stands, and — while rows still move — how far the drain has come. +/// Read from the mirror and the beat's health only; the key +/// `[storage.in]` holds is not read here, so no render path can carry it. +async fn storage_card( + cx: &Cx, + lang: Lang, + listed: Option<(String, String)>, + snap: &crate::storage::StorageSnapshot, + backend: StorageBackend, +) -> Result { + let service_line = match &listed { + Some((name, url)) => format!("{name} · {url}"), + None => t(lang, Key::StorageAbsent).to_string(), + }; + let (state_word, state_class) = if snap.connected { + (t(lang, Key::ConnectionConnected), "connection-on") + } else { + (t(lang, Key::StorageUnreachable), "connection-wait") + }; + let limit_line = match (snap.used, snap.quota) { + (Some(used), Some(quota)) => format!( + "{} of {}", + crate::storage::human_bytes(used), + crate::storage::human_bytes(quota) + ), + _ => "—".to_string(), + }; + let problem_line = match &snap.problem_word { + Some(word) => format!( + "{} ago · {}", + crate::directory::age_text(snap.problem_age), + word + ), + None => t(lang, Key::ConnectionNever).to_string(), + }; + view! { + cx => +
+
(t(lang, Key::StorageService))
+
(service_line)
+
(t(lang, Key::StorageConnection))
+
+ + (state_word) +
+
(t(lang, Key::StorageLimit))
+
(limit_line)
+ if backend == StorageBackend::In && let Some((moved, total)) = snap.migrating { +
(t(lang, Key::StorageMigration))
+
(format!("{moved} of {total}"))
+ } +
(t(lang, Key::StorageLastProblem))
+
(problem_line)
+
+ } +} + /// One row of the member list, as an admin may see it. Identity is im's to /// vouch — the row carries no password and no link token, only what the /// workspace itself decides: the role and whether the account is disabled. @@ -1253,13 +1364,33 @@ async fn settings_page(cx: &Cx) -> Result { let (profile_refusal, profile_saved) = call_state(query, "save_profile"); let (sender_refusal, sender_saved) = call_state(query, "save_sender"); let (test_refusal, _) = call_state(query, "send_test_mail"); - let (limits_refusal, limits_saved) = call_state(query, "save_limits"); - let (server_refusal, server_saved) = call_state(query, "save_public_url"); - let (role_refusal, _) = call_state(query, "set_role"); - let (disabled_refusal, _) = call_state(query, "set_disabled"); - let (add_refusal, add_saved) = call_state(query, "add_member"); - let member_refusal = role_refusal.or(disabled_refusal).or(add_refusal); - let (message_refusal, message_saved) = call_state(query, "send_message"); + let (limits_refusal, limits_saved) = call_state(query, "save_limits"); + let (storage_refusal, storage_saved) = call_state(query, "save_storage"); + let (server_refusal, server_saved) = call_state(query, "save_public_url"); + let (role_refusal, _) = call_state(query, "set_role"); + let (disabled_refusal, _) = call_state(query, "set_disabled"); + let (add_refusal, add_saved) = call_state(query, "add_member"); + let member_refusal = role_refusal.or(disabled_refusal).or(add_refusal); + let (message_refusal, message_saved) = call_state(query, "send_message"); + + // What the Storage panel renders: the surface the workspace currently + // keeps its bytes on, where the family mirror says the Files service + // is, and the storage beat's latest stand. The key `[storage.in]` + // holds is only asked about (`is_some`), never read into the page. + let storage = if administers && section == Section::Limits { + let backend = store(cx) + .storage_backend() + .await + .unwrap_or(StorageBackend::Local); + let listed = crate::layout::family_of(cx) + .await + .into_iter() + .find(|service| service.key == "in") + .map(|service| (service.name, service.url)); + Some((backend, listed, crate::storage::health(cx).snapshot())) + } else { + None + }; view! { cx => @@ -1558,6 +1689,44 @@ async fn settings_page(cx: &Cx) -> Result { } + // The storage toggle and its card, beside the limits it + // answers to: which surface keeps the bytes, and how the + // Files service stands this beat. The `in` option only + // exists when `[storage.in]` named a key — a deployment + // without one is offered no road it cannot take. + if section == Section::Limits && let Some((backend, listed, snap)) = storage { + let local = backend == StorageBackend::Local; +
+
+

(t(lang, Key::StorageTitle))

+ (t(lang, Key::AdminOnly)) +
+
+ +
+ if let Some(refusal) = &storage_refusal { + (refusal.message_in(lang)) + } + if storage_saved { + (t(lang, Key::Saved)) + } + +
+
+
+ (storage_card(cx, lang, listed, &snap, backend).await?) +
+
+ } + if section == Section::Server {
diff --git a/crates/iz-web/src/storage.rs b/crates/iz-web/src/storage.rs new file mode 100644 index 0000000..9cd34a8 --- /dev/null +++ b/crates/iz-web/src/storage.rs @@ -0,0 +1,479 @@ +//! How attachments reach the family's Files service, and how the Settings +//! card sees that service: the storage client and its health, one file. +//! +//! The client is stateless by design — the base URL is a per-call argument, +//! because the family can move between beats and a URL captured at boot is +//! a URL that goes stale. The token is the one thing held: it comes from +//! `config/iz.toml` at boot and never leaves this struct except onto the +//! wire, as a Bearer header. It is never logged and never rendered. +//! +//! Every call carries a ceiling so a stalled service cannot park a request +//! or the drain forever: a connect ceiling on the client, a read ceiling +//! between body bytes, and a total ceiling on the small calls. A large push +//! or fetch takes as long as the bytes take — the ceilings bite silence, +//! not size. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use iz_core::store::Store; +use parking_lot::Mutex; +use topcoat::context::{Cx, try_app_context}; + +// --------------------------------------------------------------------------- +// Client +// --------------------------------------------------------------------------- + +/// Why a storage call did not do what it was asked. `Quota` is in's own word +/// for "the limit im set is spent"; everything else is either the wire or a +/// refusal whose words only a log can use. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StorageProblem { + /// The service did not answer at all — down, mid-deploy, unreachable. + Unreachable, + /// in refused the push because the account's bytes are spent. + Quota, + /// The service answered with something unusable. The words are for the + /// log and the card's "last problem", never for a page. + Other(String), +} + +/// What in reports about iz's service account: the limit im set, and how +/// much of it the stored attachments hold. +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +pub struct Status { + #[serde(default)] + pub quota_bytes: u64, + #[serde(default)] + pub used_bytes: u64, +} + +#[derive(Clone)] +pub struct StorageClient { + http: reqwest::Client, + token: Option, +} + +impl StorageClient { + /// One client per process: it holds a connection pool. A `None` token is + /// a deployment with no `[storage.in]` — the client exists (the handlers + /// keep one shape) and every call refuses before touching the wire. + pub fn new(token: Option) -> Self { + let http = reqwest::Client::builder() + // A stalled connect is the one hang a total ceiling on the small + // calls cannot cover; five seconds is generous for a LAN peer. + .connect_timeout(Duration::from_secs(5)) + // Silence between body bytes, not total time: a half-sent 400 MB + // attachment is a transfer, a half-sent nothing is a stall. + .read_timeout(Duration::from_secs(10)) + .build() + .unwrap_or_default(); + Self { http, token } + } + + fn bearer(&self) -> Option<&str> { + self.token.as_deref() + } + + /// Is the service standing? `GET /healthz` is open — no key, no body to + /// read — because a probe that needed the account could not tell "in is + /// down" from "the key was rotated" without a second call. + pub async fn probe(&self, url: &str) -> bool { + let Ok(reply) = self + .http + .get(format!("{url}/healthz")) + .timeout(Duration::from_secs(10)) + .send() + .await + else { + return false; + }; + reply.status().is_success() + } + + /// The account's bytes: the limit im set and what is held. `None` on a + /// refused key, a service too old to know the route, or a dead wire — + /// the card reads it as "no facts yet", the same quiet it starts with. + pub async fn status(&self, url: &str) -> Option { + let reply = self + .http + .get(format!("{url}/api/service/status")) + .bearer_auth(self.bearer()?) + .timeout(Duration::from_secs(10)) + .send() + .await + .ok()?; + if !reply.status().is_success() { + return None; + } + reply.json::().await.ok() + } + + /// Pushes one attachment. Idempotent by construction: in keys its rows + /// by `external_id`, which is iz's own attachment id, so a retry after + /// an unclear answer replaces the same bytes rather than doubling them. + /// Answers in's file id — the same `external_id` it was handed. + pub async fn put( + &self, + url: &str, + external_id: &str, + name: &str, + bytes: Vec, + mime: &str, + ) -> Result { + let token = self.bearer().ok_or(StorageProblem::Other("no key".into()))?; + let part = reqwest::multipart::Part::bytes(bytes) + .file_name(name.to_string()) + .mime_str(mime) + .map_err(|_| StorageProblem::Other(format!("mime {mime:?}")))?; + let form = reqwest::multipart::Form::new() + .text("external_id", external_id.to_string()) + .text("name", name.to_string()) + .part("file", part); + // No total ceiling on purpose: the widest attachment iz allows is + // the widest push this makes, and the read ceiling above is what + // stops a stalled body. + let reply = self + .http + .post(format!("{url}/api/service/files")) + .bearer_auth(token) + .multipart(form) + .send() + .await + .map_err(|_| StorageProblem::Unreachable)?; + let body: serde_json::Value = reply + .json() + .await + .map_err(|problem| StorageProblem::Other(problem.to_string()))?; + if let Some(id) = body.get("ok").and_then(|id| id.as_str()) { + return Ok(id.to_string()); + } + match body.get("err").and_then(|err| err.as_str()) { + Some("QuotaExceeded") => Err(StorageProblem::Quota), + Some(other) => Err(StorageProblem::Other(other.to_string())), + None => Err(StorageProblem::Other("unusable answer".into())), + } + } + + /// Fetches one attachment's bytes back. The row exists in iz — an + /// unreachable service is a problem to say so, never a not-found. + pub async fn fetch(&self, url: &str, external_id: &str) -> Result, StorageProblem> { + let token = self.bearer().ok_or(StorageProblem::Other("no key".into()))?; + let reply = self + .http + .get(format!("{url}/api/service/file/{external_id}")) + .bearer_auth(token) + .send() + .await + .map_err(|_| StorageProblem::Unreachable)?; + if !reply.status().is_success() { + return Err(StorageProblem::Other(format!( + "fetch answered {}", + reply.status() + ))); + } + let bytes = reply + .bytes() + .await + .map_err(|_| StorageProblem::Unreachable)?; + Ok(bytes.to_vec()) + } + + /// Takes one attachment away from in — a hard delete, no trash, the + /// same hard delete iz's own store does. + pub async fn delete(&self, url: &str, external_id: &str) -> Result<(), StorageProblem> { + let token = self.bearer().ok_or(StorageProblem::Other("no key".into()))?; + let reply = self + .http + .delete(format!("{url}/api/service/file/{external_id}")) + .bearer_auth(token) + .timeout(Duration::from_secs(10)) + .send() + .await + .map_err(|_| StorageProblem::Unreachable)?; + if reply.status().is_success() { + Ok(()) + } else { + Err(StorageProblem::Other(format!( + "delete answered {}", + reply.status() + ))) + } + } +} + +/// The client `main.rs` registers beside the store; every handler that +/// branches on the backend reaches it through here. +pub fn client(cx: &Cx) -> &StorageClient { + try_app_context::(cx) + .expect("the storage client was registered on the router") +} + +// --------------------------------------------------------------------------- +// Health +// --------------------------------------------------------------------------- + +/// The Files service's stand, as the Settings card renders it. The storage +/// beat writes; the page reads. +/// +/// Deliberately dumb, like [`crate::directory::DirectoryHealth`] beside +/// which it lives: one mutex over plain fields, written a few times a +/// minute, read once a view. The token never comes near this struct, so the +/// render path cannot leak what it was never given. +#[derive(Clone, Default)] +pub struct StorageHealth(Arc>); + +#[derive(Default)] +struct Inner { + /// Where the family says in lives, and what im named it — refreshed + /// every beat, so a moved service is followed, not remembered. + url: Option, + name: Option, + /// The last probe found a standing service. + connected: bool, + used: Option, + quota: Option, + /// The drain's counter: `(moved so far, total there were to move)`. + /// `None` whenever no drain is running — before the first, and the + /// moment the last row moved. + migrating: Option<(u64, u64)>, + last_ok: Option, + /// What went wrong, as a short machine word, and when. + last_problem: Option<(Instant, String)>, +} + +/// One rendered view of [`StorageHealth`]. +#[derive(Clone)] +pub struct StorageSnapshot { + pub has_service: bool, + pub connected: bool, + pub used: Option, + pub quota: Option, + pub migrating: Option<(u64, u64)>, + pub ok_age: Option, + pub problem_age: Option, + pub problem_word: Option, +} + +impl StorageHealth { + pub fn new() -> Self { + Self::default() + } + + /// The family mirror named the service this beat. + pub fn seen(&self, url: &str, name: &str) { + let mut inner = self.0.lock(); + inner.url = Some(url.to_string()); + inner.name = Some(name.to_string()); + } + + /// The family mirror has no row for in. + pub fn unlisted(&self) { + let mut inner = self.0.lock(); + inner.url = None; + inner.name = None; + inner.connected = false; + } + + /// The probe and the status both landed: the facts are current. + pub fn reachable(&self, used: Option, quota: Option) { + let mut inner = self.0.lock(); + inner.connected = true; + inner.used = used; + inner.quota = quota; + inner.last_ok = Some(Instant::now()); + } + + /// The probe or the status did not land. The word is the fact in + /// shorthand — `unreachable`, `quota` — for the card's one line. + pub fn problem(&self, word: &str) { + let mut inner = self.0.lock(); + inner.connected = false; + inner.last_problem = Some((Instant::now(), word.to_string())); + } + + /// A drain is running and moved one more row. + pub fn migrating(&self, moved: u64, total: u64) { + self.0.lock().migrating = Some((moved, total)); + } + + /// The drain finished: the counter goes, and does not come back until a + /// new batch of local rows earns a new total. + pub fn drained(&self) { + self.0.lock().migrating = None; + } + + pub fn snapshot(&self) -> StorageSnapshot { + let inner = self.0.lock(); + let now = Instant::now(); + StorageSnapshot { + has_service: inner.url.is_some(), + connected: inner.connected, + used: inner.used, + quota: inner.quota, + migrating: inner.migrating, + ok_age: inner.last_ok.map(|at| now.saturating_duration_since(at)), + problem_age: inner + .last_problem + .as_ref() + .map(|(at, _)| now.saturating_duration_since(*at)), + problem_word: inner.last_problem.as_ref().map(|(_, word)| word.clone()), + } + } +} + +/// The health `main.rs` registers on the router beside the client it +/// describes. +pub fn health(cx: &Cx) -> &StorageHealth { + try_app_context::(cx).expect("the storage health was registered on the router") +} + +// --------------------------------------------------------------------------- +// The cycle +// --------------------------------------------------------------------------- + +/// How often the storage beat runs. Short enough that an enablement starts +/// moving rows within half a minute, long enough that the probe is a +/// glance, not a conversation. +pub const STORAGE_SECONDS: u64 = 30; + +/// How many rows one drain cycle pushes. The push is the expensive half, so +/// the batch is small: the beat is the retry, and four rows a beat drains a +/// real backlog quietly instead of monopolising the store. +const DRAIN_BATCH: u64 = 4; + +/// Where in sits in the family mirror: its human name and its URL, or +/// nothing when the mirror has no row for it. Read per use — the family can +/// move between beats. +pub async fn in_of(store: &dyn Store) -> Option<(String, String)> { + let raw = store.get_setting(crate::server::FAMILY_KEY).await.ok()??; + let family: Vec = serde_json::from_str(&raw).ok()?; + let row = family.into_iter().find(|service| service.key == "in")?; + Some((row.name, row.url)) +} + +/// One pass of the storage beat: follow the family mirror, ask the service +/// how it stands, and — while the workspace's attachments live on in — +/// drain the rows still on this disk. The body is extracted from the loop +/// in `main.rs` the way `mirror_directory` is, so a test can run one beat +/// by hand. +pub async fn storage_cycle( + store: &std::sync::Arc, + client: &StorageClient, + health: &StorageHealth, +) { + // 1. Where does the family say in is, this beat? + let service = in_of(store.as_ref()).await; + match &service { + Some((name, url)) => health.seen(url, name), + None => health.unlisted(), + } + let Some((_, url)) = service else { + return; + }; + + // 2. How does the service stand? + if !client.probe(&url).await { + health.problem("unreachable"); + return; + } + match client.status(&url).await { + Some(status) => health.reachable(Some(status.used_bytes), Some(status.quota_bytes)), + None => { + health.problem("status"); + return; + } + } + + // 3. Only a workspace switched to in drains; local mode leaves the + // local rows exactly where they are. + if store + .storage_backend() + .await + .unwrap_or(iz_core::store::StorageBackend::Local) + != iz_core::store::StorageBackend::In + { + return; + } + let count = store.local_attachment_count().await.unwrap_or(0); + if count == 0 { + return; + } + + // The total is captured when a drain starts and never re-captured + // while one runs, so the counter only ever climbs to its end. A beat + // that finds the counter standing picks up where it left off. + let total = match health.snapshot().migrating { + Some((_, total)) => total, + None => count, + }; + + let Ok(rows) = store.local_attachments(DRAIN_BATCH).await else { + health.problem("store"); + return; + }; + for row in rows { + let Ok(Some(bytes)) = store.attachment_bytes(&row.id).await else { + health.problem("store"); + return; + }; + match client + .put(&url, &row.id, &row.file_name, bytes, &row.mime_type) + .await + { + Ok(_) => {} + Err(StorageProblem::Quota) => { + health.problem("quota"); + return; + } + Err(problem) => { + health.problem(&problem_word(&problem)); + return; + } + } + // The row flips and the file leaves this disk in one call; a push + // that landed but a row that refuses is retried whole next beat — + // in's push is idempotent by external id, so the replace is free. + if store.mark_attachment_stored(&row.id).await.ok() != Some(true) { + health.problem("store"); + return; + } + let remaining = store.local_attachment_count().await.unwrap_or(0); + health.migrating(total.saturating_sub(remaining), total); + } + + // 4. The last row of the batch gone and nothing left: the counter the + // card shows is gone with it, and every open admin page hears once. + if store.local_attachment_count().await.unwrap_or(0) == 0 { + health.drained(); + let _ = store.announce_storage().await; + } +} + +/// A storage problem as the card's one word for it. +fn problem_word(problem: &StorageProblem) -> String { + match problem { + StorageProblem::Unreachable => "unreachable".to_string(), + StorageProblem::Quota => "quota".to_string(), + StorageProblem::Other(other) => other.chars().take(40).collect(), + } +} + +/// Bytes in human units: `512 B`, `1.5 KiB`, `2.0 GiB`. One decimal past +/// bytes so a quota line reads at a glance. Ported from in's settings panel, +/// whose usage lines this card's Limit row mirrors — the family renders +/// bytes one way. +pub fn human_bytes(bytes: u64) -> String { + const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"]; + let mut value = bytes as f64; + let mut unit = 0; + while value >= 1024.0 && unit + 1 < UNITS.len() { + value /= 1024.0; + unit += 1; + } + if unit == 0 { + format!("{bytes} {}", UNITS[unit]) + } else { + format!("{value:.1} {}", UNITS[unit]) + } +} diff --git a/crates/iz-web/tests/http.rs b/crates/iz-web/tests/http.rs index e387860..dc7b81f 100644 --- a/crates/iz-web/tests/http.rs +++ b/crates/iz-web/tests/http.rs @@ -273,6 +273,11 @@ struct App { store: Arc, client: iz_client::Config, fake: FakeIm, + /// The storage peer's client and health, registered exactly as + /// `main.rs` registers them; `storage_cycle` tests run the beat by + /// hand over these. + storage_client: iz_web::storage::StorageClient, + storage_health: iz_web::storage::StorageHealth, /// What the Settings Connection card renders: poked by hand in tests /// the way the mirror task pokes it in the process. health: iz_web::directory::DirectoryHealth, @@ -283,15 +288,23 @@ struct App { impl App { async fn build(mail: Mail) -> Self { - Self::build_with(mail, None, "").await + Self::build_with(mail, None, "", None).await } - + /// Like `build`, but with the knobs a configured deployment has: the - /// family list mirrored from im — passed as the raw JSON the `setting` - /// row holds, so a test can also feed it a body that will not parse — - /// and the configured `base_url`. Building them in is what lets the - /// switcher and the sign-out handoff be asserted over real HTTP. - async fn build_with(mail: Mail, family: Option, base_url: &str) -> Self { + /// family list mirrored from im — passed as the raw JSON the `setting` + /// row holds, so a test can also feed it a body that will not parse — + /// and the configured `base_url`. Building them in is what lets the + /// switcher and the sign-out handoff be asserted over real HTTP. + /// + /// `storage_in` is the `[storage.in]` token, when the deployment + /// under test has one. + async fn build_with( + mail: Mail, + family: Option, + base_url: &str, + storage_in: Option, + ) -> Self { let dir = std::env::temp_dir().join(format!("iz-http-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let db = dir.join("iz.db"); @@ -309,6 +322,8 @@ impl App { .await .unwrap(); } + let storage_client = iz_web::storage::StorageClient::new(storage_in.clone()); + let storage_health = iz_web::storage::StorageHealth::new(); let fake = FakeIm::spawn().await; let config = iz_core::Config { database: db, @@ -323,6 +338,8 @@ impl App { redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), }, ignored: Vec::new(), + storage_in: storage_in + .map(|token| iz_core::config::InStorage { token }), defaulted: false, }; // The fallback half of the chain, built exactly as `main.rs` builds @@ -358,7 +375,9 @@ impl App { "iz-test", "s3cr3t", )) - .app_context(health.clone()) + .app_context(health.clone()) + .app_context(storage_client.clone()) + .app_context(storage_health.clone()) .app_context(iz_client::LogoutBack(Arc::new( iz_web::server::logout_back, ))) @@ -367,15 +386,17 @@ impl App { .app_context(iz_web::live::Shutdown(stopping)) .app_context(mail) .build(); - Self { - dir, - router, - store, - client, - fake, - health, - stop, - } + Self { + dir, + router, + store, + client, + fake, + storage_client, + storage_health, + health, + stop, + } } async fn open() -> Self { @@ -414,6 +435,7 @@ impl App { redirect_uri: "http://127.0.0.1:7655/auth/callback".to_string(), }, ignored: Vec::new(), + storage_in: None, defaulted: false, }; // The fallback half of the chain, built exactly as `main.rs` builds @@ -428,6 +450,8 @@ impl App { cookie_key: [7u8; 32], }; let health = iz_web::directory::DirectoryHealth::new(); + let storage_client = iz_web::storage::StorageClient::new(None); + let storage_health = iz_web::storage::StorageHealth::new(); let (stop, stopping) = tokio::sync::watch::channel(false); let router = iz_client::mount( Router::builder() @@ -449,7 +473,9 @@ impl App { "iz-test", "s3cr3t", )) - .app_context(health.clone()) + .app_context(health.clone()) + .app_context(storage_client.clone()) + .app_context(storage_health.clone()) .app_context(iz_client::LogoutBack(Arc::new( iz_web::server::logout_back, ))) @@ -458,17 +484,18 @@ impl App { .app_context(iz_web::live::Shutdown(stopping)) .app_context(Mail::sending(engine)) .build(); - Self { - dir, - router, - store, - client, - fake, - health, - stop, - } + Self { + dir, + router, + store, + client, + fake, + storage_client, + storage_health, + health, + stop, + } } - /// Mints a session cookie for an im identity, registering its claims on /// the fake — exactly what `/auth/callback` seals, without the browser /// dance. The local row is provisioned on the next request, the way a @@ -9723,7 +9750,8 @@ async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() { // A configured `base_url` is what the fallback says when nothing is // stored — a deployment behind a proxy says its name once, in the file. - let configured = App::build_with(Mail::silent(), None, "https://board.example").await; + let configured = + App::build_with(Mail::silent(), None, "https://board.example", None).await; let raw = configured.get("/auth/logout", None).await; let expected = format!( "{}/logout?back={}", @@ -9734,7 +9762,7 @@ async fn a_sign_out_hands_the_browser_to_the_providers_logout_pointed_home() { // A stored public address wins over the configured chain, and it reads // per request: no restart between the save and the next sign-out. - let stored = App::build_with(Mail::silent(), None, "https://stale.example").await; + let stored = App::build_with(Mail::silent(), None, "https://stale.example", None).await; stored .store .set_setting(iz_web::server::PUBLIC_URL_KEY, "https://stored.example") @@ -9760,7 +9788,7 @@ async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_confi {\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:7654\"},\ {\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}]" .to_string(); - let app = App::build_with(Mail::silent(), Some(family), "").await; + let app = App::build_with(Mail::silent(), Some(family), "", None).await; let board_admin = admin(&app).await; let html = String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string(); assert!(html.contains("wordmark-family"), "{html}"); @@ -9777,7 +9805,7 @@ async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_confi // and a mirror that never arrived. let alone = "[{\"key\":\"iz\",\"name\":\"Board\",\"url\":\"http://127.0.0.1:7654\"}]"; for broken in ["[".to_string(), "[]".to_string(), alone.to_string()] { - let app = App::build_with(Mail::silent(), Some(broken), "").await; + let app = App::build_with(Mail::silent(), Some(broken), "", None).await; let board_admin = admin(&app).await; let html = String::from_utf8_lossy(&app.get("/", Some(&board_admin)).await.bytes).to_string(); @@ -9792,3 +9820,827 @@ async fn the_topbar_shows_the_family_switcher_and_marks_this_app_only_when_confi "no mirror, no switcher: {plain}" ); } + +// -- the Files service ------------------------------------------------------ + +/// The Bearer key the storage tests name in `[storage.in]`: the fake in +/// answers it and nothing else, so a call that arrives without it is a +/// 401 the same way the real service answers an unknown key. +const STORAGE_TOKEN: &str = "iz-storage-key"; + +/// A fake in: the Files service's machine side over bare TCP, canned the +/// way `iz_web::storage::StorageClient` speaks. Every `/api/service/*` +/// call is recorded as `" "` so a test can assert on the +/// wire, not only on the rows; a push's file part is kept and served +/// back by `GET /api/service/file/{id}`, so the fetch path reads the +/// same bytes the push path wrote. +struct FakeIn { + addr: std::net::SocketAddr, + calls: Arc>>, + files: Arc>>>, + refuse_quota: Arc, + down: Arc, +} + +impl FakeIn { + async fn spawn() -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let calls: Arc>> = Arc::new(Mutex::new(Vec::new())); + let files: Arc>>> = Arc::new(Mutex::new(HashMap::new())); + let refuse_quota = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let log = calls.clone(); + let store = files.clone(); + let quota_flag = refuse_quota.clone(); + let down_flag = down.clone(); + tokio::spawn(async move { + loop { + let Ok((socket, _)) = listener.accept().await else { + return; + }; + if down_flag.load(std::sync::atomic::Ordering::SeqCst) { + continue; + } + let log = log.clone(); + let store = store.clone(); + let quota_flag = quota_flag.clone(); + let socket_down = down_flag.clone(); + tokio::spawn(async move { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut socket = socket; + let mut buf = vec![0u8; 8192]; + let mut req = Vec::new(); + // Same keep-alive loop as the fake im: closing after + // every answer races the client's pool. + loop { + let body_start = loop { + let Ok(n) = socket.read(&mut buf).await else { + return; + }; + if n == 0 { + return; + } + req.extend_from_slice(&buf[..n]); + if let Some(end) = headers_end(&req) { + let head = String::from_utf8_lossy(&req[..end]).to_string(); + let len = content_length(&head); + if req.len() >= end + len { + break end; + } + } + if req.len() > 2_000_000 { + return; + } + }; + let head = String::from_utf8_lossy(&req[..body_start]).to_string(); + // Down is per request, not per socket: a pooled + // connection that was alive when the service went + // down must stop answering too, the way the real + // service's sockets die mid-conversation. + if socket_down.load(std::sync::atomic::Ordering::SeqCst) { + return; + } + let first = head.lines().next().unwrap_or("").to_string(); + let len = content_length(&head); + let body: Vec = req[body_start..body_start + len].to_vec(); + req.drain(..body_start + len); + let (status, content_type, payload) = + storage_answer(&log, &store, "a_flag, &head, &first, &body); + let response = format!( + "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\n\r\n", + payload.len() + ); + if socket.write_all(response.as_bytes()).await.is_err() { + return; + } + if socket.write_all(&payload).await.is_err() { + return; + } + } + }); + } + }); + Self { + addr, + calls, + files, + refuse_quota, + down, + } + } + + fn url(&self) -> String { + format!("http://{}", self.addr) + } + + /// The wire, in order: one `" "` per service call. + fn calls(&self) -> Vec { + self.calls.lock().clone() + } + + /// Whether a push under this id is being held by the service. + fn holds(&self, id: &str) -> bool { + self.files.lock().contains_key(id) + } + + fn refuse_quota(&self) { + self.refuse_quota + .store(true, std::sync::atomic::Ordering::SeqCst); + } + + /// Stops answering — accepts and drops, which reads to the client as + /// the connection the storage ceilings are for. + fn set_down(&self) { + self.down + .store(true, std::sync::atomic::Ordering::SeqCst); + } +} + +/// The fake in's one router: the probe is open, the machine side wants +/// the Bearer key, and the four service routes answer the JSON shape the +/// client parses. A push is kept under its `external_id` — pulled out of +/// the multipart body by boundary, the way the real service's form +/// parser would — so the fetch and delete routes have something real to +/// work on. +fn storage_answer( + log: &Arc>>, + files: &Arc>>>, + refuse_quota: &Arc, + head: &str, + request_line: &str, + body: &[u8], +) -> (&'static str, String, Vec) { + let mut parts = request_line.split_whitespace(); + let method = parts.next().unwrap_or(""); + let target = parts.next().unwrap_or(""); + let path = target + .split_once('?') + .map(|(path, _)| path) + .unwrap_or(target); + if method == "GET" && path == "/healthz" { + return ("200 OK", "text/plain".to_string(), b"ok".to_vec()); + } + let authed = head + .lines() + .filter_map(|line| line.split_once(':')) + .any(|(name, value)| { + name.trim().eq_ignore_ascii_case("authorization") + && value.trim() == format!("Bearer {STORAGE_TOKEN}") + }); + if !authed { + return ( + "401 Unauthorized", + "application/json".to_string(), + br#"{"err":"Unauthorized"}"#.to_vec(), + ); + } + log.lock().push(format!("{method} {path}")); + match (method, path) { + ("GET", "/api/service/status") => ( + "200 OK", + "application/json".to_string(), + br#"{"ok":true,"quota_bytes":10737418240,"used_bytes":1073741824}"#.to_vec(), + ), + ("POST", "/api/service/files") => { + if refuse_quota.load(std::sync::atomic::Ordering::SeqCst) { + return ( + "200 OK", + "application/json".to_string(), + br#"{"err":"QuotaExceeded"}"#.to_vec(), + ); + } + let Some(id) = multipart_field(body, head, "external_id") else { + return ( + "400 Bad Request", + "application/json".to_string(), + br#"{"err":"NoExternalId"}"#.to_vec(), + ); + }; + let bytes = multipart_file(body, head); + files.lock().insert(id.clone(), bytes); + let answer = format!("{{\"ok\":\"{id}\"}}"); + ("200 OK", "application/json".to_string(), answer.into_bytes()) + } + ("GET", path) => match path.strip_prefix("/api/service/file/") { + Some(id) if !id.is_empty() => match files.lock().get(id) { + Some(bytes) => ( + "200 OK", + "application/octet-stream".to_string(), + bytes.clone(), + ), + None => ( + "404 Not Found", + "application/json".to_string(), + br#"{"err":"NotFound"}"#.to_vec(), + ), + }, + _ => ( + "404 Not Found", + "application/json".to_string(), + br#"{"err":"NotFound"}"#.to_vec(), + ), + }, + ("DELETE", path) => { + if let Some(id) = path.strip_prefix("/api/service/file/") { + files.lock().remove(id); + } + ( + "200 OK", + "application/json".to_string(), + br#"{"ok":true}"#.to_vec(), + ) + } + _ => ( + "404 Not Found", + "text/plain".to_string(), + Vec::new(), + ), + } +} +/// One text field out of a multipart body, by `name`. The parts are read +/// line-wise — a part's headers carry `name="..."`, its value rides the +/// lines after them — which is enough for the two fields the client +/// writes; the content-type check is the proof this is a multipart body +/// at all. +fn multipart_field(body: &[u8], head: &str, name: &str) -> Option { + let multipart = head.lines().any(|line| { + line.to_ascii_lowercase() + .starts_with("content-type: multipart/form-data") + }); + if !multipart { + return None; + } + let marker = format!("name=\"{name}\""); + let mut in_part = false; + for part in body.split(|&b| b == b'\n') { + let text = String::from_utf8_lossy(part); + let line = text.trim_end_matches('\r'); + if line.starts_with("--") { + in_part = false; + continue; + } + // The header line names the part; the value is the first line + // after the blank one that follows it. + if in_part { + if !line.is_empty() { + return Some(line.to_string()); + } + } else if line.contains(&marker) && line.contains(':') { + in_part = true; + } + } + None +} + +/// The file part's bytes out of a multipart body: everything between the +/// `name="file"` part's blank line and the boundary that closes it. +fn multipart_file(body: &[u8], head: &str) -> Vec { + let Some(boundary) = head + .lines() + .filter_map(|line| line.split_once(':')) + .find(|(field, _)| field.trim().eq_ignore_ascii_case("content-type")) + .and_then(|(_, value)| value.split("boundary=").nth(1).map(str::trim)) + else { + return Vec::new(); + }; + let marker = format!("--{boundary}"); + let needle = b"name=\"file\""; + let Some(at) = body.windows(needle.len()).position(|w| w == needle) else { + return Vec::new(); + }; + let after = &body[at..]; + let Some(start) = after.windows(4).position(|w| w == b"\r\n\r\n") else { + return Vec::new(); + }; + let bytes = &after[start + 4..]; + let end = bytes + .windows(marker.len()) + .position(|w| w == marker.as_bytes()) + .unwrap_or(bytes.len()); + bytes[..end] + .strip_suffix(b"\r\n") + .unwrap_or(&bytes[..end]) + .to_vec() +} + +/// The family mirror holding a Files row at `url`: the JSON the `setting` +/// row keeps, exactly the shape the beat stores. +fn family_with_in(url: &str) -> String { + format!( + "[{{\"key\":\"in\",\"name\":\"Files\",\"url\":\"{url}\"}},\ + {{\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}}]" + ) +} + +/// An app whose deployment named a storage key, with a Files service in +/// the family mirror to point at. +async fn storage_app(fake: &FakeIn) -> App { + App::build_with( + Mail::silent(), + Some(family_with_in(&fake.url())), + "", + Some(STORAGE_TOKEN.to_string()), + ) + .await +} + +/// How many files sit in the storage tree's attachment directory: the +/// honest count of what is still on this disk. +fn local_file_count(app: &App) -> usize { + std::fs::read_dir(app.dir.join("storage").join("attachments")) + .map(|entries| entries.count()) + .unwrap_or(0) +} + +#[tokio::test] +async fn an_upload_in_in_mode_lands_on_the_service_and_serves_from_it() { + let fake = FakeIn::spawn().await; + let app = storage_app(&fake).await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Stored upload").await; + + let saved = app + .post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "in")], + ) + .await; + assert_eq!(saved.status, StatusCode::SEE_OTHER, "{}", saved.body); + assert!( + saved + .location + .as_deref() + .unwrap_or_default() + .contains("saved=save_storage§ion=limits"), + "{:?}", + saved.location + ); + + let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4]; + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("spec.png", "image/png", &png)), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + answer.location.as_deref(), + Some(format!("/?task={task}&tab=files").as_str()) + ); + assert!( + fake.calls().iter().any(|call| call == "POST /api/service/files"), + "the push never happened: {:?}", + fake.calls() + ); + + let rows = app.store.attachments(&task).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].remote, iz_core::store::AttachmentWhere::Stored); + assert_eq!(local_file_count(&app), 0, "a local file was written anyway"); + assert!(fake.holds(&rows[0].id)); + + let download = app + .get(&format!("/files/{}", rows[0].id), Some(&admin_cookie)) + .await; + assert_eq!(download.status, StatusCode::OK); + assert_eq!(download.bytes, png); + assert_eq!(download.content_type.as_deref(), Some("image/png")); + assert!( + download + .disposition + .as_deref() + .unwrap_or_default() + .starts_with("inline;"), + "{:?}", + download.disposition + ); + assert_eq!( + download.cache_control.as_deref(), + Some("private, max-age=31536000, immutable") + ); + assert!( + fake.calls() + .iter() + .any(|call| call.starts_with("GET /api/service/file/")), + "the fetch never happened: {:?}", + fake.calls() + ); +} + +/// A Files service that is not there is refused in the moment, on every +/// leg: the upload says so, the download is a 503 rather than a +/// not-found, and the delete leaves the row exactly where it was. +#[tokio::test] +async fn a_down_files_service_refuses_uploads_downloads_and_deletes() { + let fake = FakeIn::spawn().await; + let app = storage_app(&fake).await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Down service").await; + app.post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "in")], + ) + .await; + + let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4]; + app.post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("up.png", "image/png", &png)), + ) + .await; + let rows = app.store.attachments(&task).await.unwrap(); + assert_eq!(rows.len(), 1); + let stored = rows[0].id.clone(); + + fake.set_down(); + + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("down.png", "image/png", &png)), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=storage-unavailable&on=upload_file"), + "{:?}", + answer.location + ); + assert_eq!(app.store.attachments(&task).await.unwrap().len(), 1); + + let download = app.get(&format!("/files/{stored}"), Some(&admin_cookie)).await; + assert_eq!(download.status, StatusCode::SERVICE_UNAVAILABLE); + + let delete = app + .post( + "/api/delete_file", + Some(&admin_cookie), + &[("file_id", &stored)], + ) + .await; + assert_eq!(delete.status, StatusCode::SEE_OTHER); + assert!( + delete.body.contains("StorageUnavailable"), + "the delete did not refuse: {}", + delete.body + ); + assert!( + app.store.attachment(&stored).await.unwrap().is_some(), + "the row went while the service was down" + ); +} + +/// Deleting a stored row takes the remote copy first and only then the +/// row: the service sees the DELETE, its copy is gone, and the task's +/// file list is empty. +#[tokio::test] +async fn deleting_a_stored_row_takes_the_remote_copy_first() { + let fake = FakeIn::spawn().await; + let app = storage_app(&fake).await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Remote delete").await; + app.post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "in")], + ) + .await; + + let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4]; + app.post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("gone.png", "image/png", &png)), + ) + .await; + let rows = app.store.attachments(&task).await.unwrap(); + assert_eq!(rows.len(), 1); + let stored = rows[0].id.clone(); + assert!(fake.holds(&stored)); + + let answer = app + .post( + "/api/delete_file", + Some(&admin_cookie), + &[("file_id", &stored)], + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER, "{}", answer.body); + assert!( + !answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal="), + "{:?}", + answer.location + ); + assert!( + fake.calls() + .iter() + .any(|call| call == &format!("DELETE /api/service/file/{stored}")), + "the remote copy was never taken: {:?}", + fake.calls() + ); + assert!(!fake.holds(&stored)); + assert!( + app.store.attachment(&stored).await.unwrap().is_none(), + "the row survived the delete" + ); + assert!(app.store.attachments(&task).await.unwrap().is_empty()); +} + +/// The mode switch is an admin's, and `in` is only offered when the whole +/// road is there: a key in the config and a family row naming the +/// service. A member is refused; a keyless deployment is refused; a +/// family without the service is refused; with both, the save lands. +#[tokio::test] +async fn save_storage_is_admin_only_and_refuses_a_road_that_is_not_there() { + // A member cannot switch the surface, on either value. + let fake = FakeIn::spawn().await; + let app = storage_app(&fake).await; + let admin_cookie = admin(&app).await; + let plain = member(&app, "memre@iz.sh", "Memre").await; + let answer = app + .post("/api/save_storage", Some(&plain), &[("backend", "local")]) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + // Settings routes carry the refusal on the redirect's query, not the + // body — the route has no hydrated caller to answer with a value. + assert_eq!(answer.body, ""); + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=forbidden&on=save_storage§ion=limits"), + "{:?}", + answer.location + ); + + // No `[storage.in]` token: `in` is not a road this deployment can + // take, no matter what the family says. + let keyless = App::build_with( + Mail::silent(), + Some(family_with_in(&fake.url())), + "", + None, + ) + .await; + let keyless_admin = admin(&keyless).await; + let answer = keyless + .post( + "/api/save_storage", + Some(&keyless_admin), + &[("backend", "in")], + ) + .await; + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=storage-not-configured&on=save_storage"), + "{:?}", + answer.location + ); + // The form never offered it either. + let html = String::from_utf8_lossy( + &keyless + .get("/settings?section=limits", Some(&keyless_admin)) + .await + .bytes, + ) + .to_string(); + assert!(!html.contains("value=\"in\""), "{html}"); + + // A family with no Files row: there is no URL to push to. + let unlisted = App::build_with( + Mail::silent(), + Some( + "[{\"key\":\"im\",\"name\":\"Account\",\"url\":\"http://127.0.0.1:7650\"}]" + .to_string(), + ), + "", + Some(STORAGE_TOKEN.to_string()), + ) + .await; + let unlisted_admin = admin(&unlisted).await; + let answer = unlisted + .post( + "/api/save_storage", + Some(&unlisted_admin), + &[("backend", "in")], + ) + .await; + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=storage-not-listed&on=save_storage"), + "{:?}", + answer.location + ); + + // Both in place: the save lands, the store says so, and local stands + // as the way back. + let answer = app + .post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "in")], + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("saved=save_storage§ion=limits"), + "{:?}", + answer.location + ); + assert_eq!( + app.store.storage_backend().await.unwrap(), + iz_core::store::StorageBackend::In + ); + let answer = app + .post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "local")], + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert_eq!( + app.store.storage_backend().await.unwrap(), + iz_core::store::StorageBackend::Local + ); +} + +/// The Storage card carries the beat's facts — the family's name for the +/// service, the connection's stand, the limit im set, the drain's count, +/// the last problem — and never the key the calls speak with. +#[tokio::test] +async fn the_storage_card_shows_the_beats_facts_without_the_key() { + let fake = FakeIn::spawn().await; + let app = storage_app(&fake).await; + let admin_cookie = admin(&app).await; + + app.storage_health.seen(&fake.url(), "Files"); + app.storage_health + .reachable(Some(1024 * 1024 * 1024), Some(10 * 1024 * 1024 * 1024)); + let html = String::from_utf8_lossy( + &app + .get("/settings?section=limits", Some(&admin_cookie)) + .await + .bytes, + ) + .to_string(); + assert!(html.contains("id=\"storage\""), "{html}"); + assert!(html.contains(&format!("Files · {}", fake.url())), "{html}"); + assert!(html.contains("connection-on"), "{html}"); + assert!(html.contains("Connected"), "{html}"); + assert!(html.contains("1.0 GiB of 10.0 GiB"), "{html}"); + assert!(html.contains("never"), "{html}"); + assert!(!html.contains(STORAGE_TOKEN), "the key leaked: {html}"); + + // The drain's count and the last problem, once the beat has both. + app.post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "in")], + ) + .await; + app.storage_health.problem("quota"); + app.storage_health.migrating(2, 5); + let html = String::from_utf8_lossy( + &app + .get("/settings?section=limits", Some(&admin_cookie)) + .await + .bytes, + ) + .to_string(); + assert!(html.contains("2 of 5"), "{html}"); + assert!(html.contains("quota"), "{html}"); + assert!(html.contains("connection-wait"), "{html}"); + assert!(html.contains("Unreachable"), "{html}"); + assert!(!html.contains(STORAGE_TOKEN), "the key leaked: {html}"); +} + +/// One beat of the storage cycle, by hand: a workspace switched to in +/// with rows still on this disk has them pushed, flipped to stored, and +/// unlinked, and a service that has gone down since is a problem on the +/// card rather than a stuck drain. +#[tokio::test] +async fn the_storage_beat_drains_local_rows_into_the_service() { + let fake = FakeIn::spawn().await; + let app = storage_app(&fake).await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Drained rows").await; + + // Two rows on local disk, the way every row was before the switch. + let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4]; + for name in ["one.png", "two.png"] { + app.post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some((name, "image/png", &png)), + ) + .await; + } + assert_eq!(local_file_count(&app), 2); + assert!(fake.calls().is_empty()); + + app.post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "in")], + ) + .await; + iz_web::storage::storage_cycle(&app.store, &app.storage_client, &app.storage_health).await; + + let rows = app.store.attachments(&task).await.unwrap(); + assert_eq!(rows.len(), 2); + assert!( + rows.iter() + .all(|row| row.remote == iz_core::store::AttachmentWhere::Stored), + "not every row drained" + ); + assert_eq!(local_file_count(&app), 0, "the local files survived the drain"); + assert!(rows.iter().all(|row| fake.holds(&row.id))); + let snap = app.storage_health.snapshot(); + assert!(snap.connected); + assert_eq!(snap.migrating, None); + + // The service gone: the beat says so on the card and nothing moves — + // there is nothing left to move — while the rows stay serviceable + // from wherever the service comes back. + fake.set_down(); + iz_web::storage::storage_cycle(&app.store, &app.storage_client, &app.storage_health).await; + let snap = app.storage_health.snapshot(); + assert!(!snap.connected); + assert_eq!(snap.problem_word.as_deref(), Some("unreachable")); +} + +/// A full service refuses the push with its own word, and the upload +/// carries it: nothing is stored, on either side. +#[tokio::test] +async fn a_full_service_refuses_the_upload_with_its_own_word() { + let fake = FakeIn::spawn().await; + let app = storage_app(&fake).await; + let admin_cookie = admin(&app).await; + let column = first_column(&app).await; + let task = a_task(&app, &admin_cookie, &column, "Full service").await; + app.post( + "/api/save_storage", + Some(&admin_cookie), + &[("backend", "in")], + ) + .await; + fake.refuse_quota(); + + let png = [0x89u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4]; + let answer = app + .post_multipart( + "/files", + Some(&admin_cookie), + &[("task_id", &task)], + Some(("full.png", "image/png", &png)), + ) + .await; + assert_eq!(answer.status, StatusCode::SEE_OTHER); + assert!( + answer + .location + .as_deref() + .unwrap_or_default() + .contains("refusal=storage-quota&on=upload_file"), + "{:?}", + answer.location + ); + assert!(app.store.attachments(&task).await.unwrap().is_empty()); + assert_eq!(local_file_count(&app), 0); +}