From bcf7ceb6eef9145a3eceb9b910f70bb87df36061 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 3 Sep 2026 01:38:48 +0300 Subject: [PATCH] Binary leaves the database: attachments and photos live as files attachment.bytes and user.photo columns are gone from the declared schema; bytes live at /attachments/ and /photos/, named by the row's own id, written temp-plus-rename. The store trait keeps its shape, so handlers and routes are untouched. - config: new storage key, defaulting beside the database file so a backup that takes one takes the other; missing keys are completed with the resolved default, resolved against the same base parse uses - reconcile: a database of the old shape rebuilds with every blob extracted to its file before the swap, byte for byte; without a storage dir it refuses loudly rather than dropping binary - store: add/set stage the file before the row commits (a photo being replaced keeps its committed bytes until the new row is in), deletes take the file with the row, boot sweeps files no row names and says out loud when a row's file is missing - resniff reads its head/tail windows from the file instead of substr - has_photo derives from photo_mime everywhere the dropped column was the marker Verified against a copy of the production database: 14 attachments and 3 photos extracted sha256-identical, 58 MB database rebuilt to 450 KB, original kept as a timestamped backup, server serves and the files route stays gated. --- .gitignore | 1 + Cargo.lock | 1 + crates/izlek-core/Cargo.toml | 1 + crates/izlek-core/migrations/0001_init.sql | 23 +- crates/izlek-core/src/config.rs | 155 ++++- crates/izlek-core/src/store/mod.rs | 11 +- crates/izlek-core/src/store/reconcile.rs | 285 ++++++++- crates/izlek-core/src/store/turso_store.rs | 687 ++++++++++++++++++--- crates/izlek-core/tests/store.rs | 151 +++-- crates/izlek-web/src/detail.rs | 25 +- crates/izlek-web/src/main.rs | 37 +- crates/izlek-web/tests/http.rs | 4 +- 12 files changed, 1188 insertions(+), 193 deletions(-) diff --git a/.gitignore b/.gitignore index d2bb8ac..9394917 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ /style/main.css *.db *.db-* +/storage .env izlek.key /config/izlek.toml diff --git a/Cargo.lock b/Cargo.lock index 8b4e509..64602da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1789,6 +1789,7 @@ dependencies = [ "serde_json", "sha2 0.11.0", "subtle", + "tempfile", "thiserror", "time", "tokio", diff --git a/crates/izlek-core/Cargo.toml b/crates/izlek-core/Cargo.toml index a7bc960..081581d 100644 --- a/crates/izlek-core/Cargo.toml +++ b/crates/izlek-core/Cargo.toml @@ -45,4 +45,5 @@ ulid = { workspace = true, optional = true } async-trait = "0.1.92" serde_json.workspace = true tokio = { workspace = true } +tempfile = "3" zip.workspace = true diff --git a/crates/izlek-core/migrations/0001_init.sql b/crates/izlek-core/migrations/0001_init.sql index 3fd06b4..6e05fa3 100644 --- a/crates/izlek-core/migrations/0001_init.sql +++ b/crates/izlek-core/migrations/0001_init.sql @@ -101,9 +101,9 @@ CREATE TABLE user ( theme TEXT NOT NULL DEFAULT 'light', language TEXT NOT NULL DEFAULT 'en', ui TEXT NOT NULL DEFAULT 'instrument', - -- The profile picture lives here as bytes, the way an attachment does: - -- no filesystem path survives a backup or a move. - photo BLOB, + -- The profile picture lives as a file under the storage directory, at + -- `/photos/`, the way an attachment does — this column + -- only marks that one is there. photo_mime TEXT, created_at TEXT NOT NULL, last_signed_in_at TEXT, @@ -280,14 +280,16 @@ CREATE TABLE comment ( ); CREATE INDEX comment_by_task ON comment(task_id); --- Attachments live in the database file, not on disk beside it. +-- Attachments live as files under the storage directory, not in this table. -- --- Izlek is one process over one file, and a second place to keep state is a --- second thing to back up, to lock, and to get out of step with the rows that --- name it. And a path is exactly where an uploaded file name must never end --- up: `../../etc` is a valid file name and a terrible path. Keeping the bytes --- here means `file_name` is only ever a label printed on a chip, never --- anything the server resolves. +-- One row, one file: the bytes sit at `/attachments/`, named by +-- the row's own id, and profile photos keep theirs at +-- `/photos/` the same way. The directory is state the same +-- way the database file is — back the two up together, and boot deletes any +-- file no row names. And a path is still exactly where an uploaded file name +-- must never end up: `../../etc` is a valid file name and a terrible path, so +-- `file_name` remains a label printed on a chip; the file a row names is +-- found by its id alone, never resolved from anything the row was given. CREATE TABLE attachment ( id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES task(id), @@ -295,7 +297,6 @@ CREATE TABLE attachment ( file_name TEXT NOT NULL, mime_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, - bytes BLOB NOT NULL, uploaded_by TEXT NOT NULL REFERENCES user(id), created_at TEXT NOT NULL ); diff --git a/crates/izlek-core/src/config.rs b/crates/izlek-core/src/config.rs index 3807d70..75d0d2b 100644 --- a/crates/izlek-core/src/config.rs +++ b/crates/izlek-core/src/config.rs @@ -47,6 +47,8 @@ const FILE_NAME: &str = "config/izlek.toml"; /// defaults, so that a plain `izlek` in an empty directory is one command. const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One process holds it. database = "izlek.db" +# Where attachments and profile photos live as files, created on boot. +storage = "storage" # The address the server listens on. Environment variables are ignored — # this is the only thing that decides where İzlek binds. It is also the # address mail links fall back to, until an admin sets one in Settings. @@ -106,6 +108,7 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[ #[derive(Deserialize)] struct Toml { database: Option, + storage: Option, listen: Option, live_seconds: Option, #[serde(flatten)] @@ -117,6 +120,10 @@ struct Toml { pub struct Config { /// The database file, absolute. One process holds it. pub database: PathBuf, + /// Where attachments and profile photos live as files, absolute. Binary + /// never sits in the database: this directory and the database file are + /// backed up together, or not at all. + pub storage: PathBuf, /// The address the server binds. The only source for this — `HOST` and /// `PORT` environment variables are never read. pub listen: SocketAddr, @@ -186,7 +193,7 @@ impl Config { match std::fs::read_to_string(&path) { Ok(text) => { let config = Config::parse(&text, dir, false)?; - complete(&path, &text); + complete(&path, &text, dir); Ok(config) } Err(err) if err.kind() == std::io::ErrorKind::NotFound => { @@ -213,12 +220,19 @@ impl Config { /// The reading itself, against a string — which is how it is tested /// without a test being able to disturb another test's filesystem. pub fn parse(text: &str, dir: &Path, defaulted: bool) -> Result { - let toml: Toml = - toml::from_str(text).map_err(|err| ConfigError::Unparseable { why: err.to_string() })?; + let toml: Toml = toml::from_str(text).map_err(|err| ConfigError::Unparseable { + why: err.to_string(), + })?; let value = |raw: Option| raw.filter(|value| !value.trim().is_empty()); 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), + }; let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string()); let listen: SocketAddr = listen.parse().map_err(|err| ConfigError::Invalid { @@ -239,7 +253,8 @@ impl Config { } Ok(Config { - database: absolute(dir, Path::new(&database)), + database, + storage, listen, live_seconds, ignored: toml.other.into_keys().collect(), @@ -274,7 +289,7 @@ impl Config { pub fn report(&self) -> Vec { let mut lines = vec![ format!("database {}", self.database.display()), - format!("listen {}", self.listen), + format!("storage {}", self.storage.display()), format!("mail url {} until an admin sets one", self.listen_url()), ]; lines.push("mail the sender is in Settings, not here".to_string()); @@ -302,12 +317,36 @@ impl Config { /// written is not a reason not to start; the defaults it is missing are the /// ones already in force, so the run is correct either way and the note says /// what could not be done. -fn complete(path: &Path, text: &str) { - let missing: Vec<&str> = OPTIONAL_KEYS +fn complete(path: &Path, text: &str, base: &Path) { + let mut missing: Vec<(&str, String)> = OPTIONAL_KEYS .iter() .filter(|(key, _)| !mentions(text, key)) - .map(|(_, block)| *block) + .map(|(key, block)| (*key, (*block).to_string())) .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 same base `parse` resolves against, or the completed line would + // point somewhere this boot never looks (config/ vs the directory + // the app runs from). + let database: Option = toml::from_str::(text) + .ok() + .and_then(|t| t.database) + .filter(|value| !value.trim().is_empty()); + let storage = database + .as_deref() + .map(|db| default_storage(&absolute(base, Path::new(db)))) + .unwrap_or_else(|| PathBuf::from("storage")); + missing.push(( + "storage", + format!( + "# Where attachments and profile photos live as files, created on boot.\n\ + storage = {:?}\n", + storage.display().to_string() + ), + )); + } if missing.is_empty() { return; } @@ -316,13 +355,18 @@ fn complete(path: &Path, text: &str) { completed.push('\n'); } completed.push('\n'); - completed.push_str(&missing.join("\n")); + completed.push_str( + &missing + .iter() + .map(|(_, block)| block.as_str()) + .collect::>() + .join("\n"), + ); match std::fs::write(path, completed) { Ok(()) => println!( "izlek added {} to {FILE_NAME}, at the default already in use", - OPTIONAL_KEYS + missing .iter() - .filter(|(key, _)| !mentions(text, key)) .map(|(key, _)| *key) .collect::>() .join(", ") @@ -341,6 +385,17 @@ fn mentions(text: &str, key: &str) -> bool { }) } +/// Where binary files live when the file is silent about it: beside the +/// database file. The two are one backup unit — a backup that takes the +/// database but not the files beside it restores a board whose attachments +/// and photos are gone — so the default keeps them siblings. +fn default_storage(database: &Path) -> PathBuf { + database + .parent() + .map(|parent| parent.join("storage")) + .unwrap_or_else(|| PathBuf::from("storage")) +} + /// An absolute path for a file that may not exist yet: the directory is /// resolved against `base` (the directory `config/izlek.toml` was read /// from), the file name is kept as written. @@ -399,7 +454,13 @@ mod tests { // A second load reads the file it just wrote, identically. let again = Config::load_from(&dir).unwrap(); assert!(!again.defaulted); - assert_eq!(again, Config { defaulted: false, ..config }); + assert_eq!( + again, + Config { + defaulted: false, + ..config + } + ); let _ = std::fs::remove_dir_all(&dir); } @@ -421,12 +482,23 @@ mod tests { let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(); assert!(written.contains("listen = \"127.0.0.1:7654\""), "{written}"); + // `storage` has no literal default: the completed line is where the + // file's own `database` put it — beside `state/izlek.db` here. + assert!(written.contains("storage = "), "{written}"); // What was there is untouched, comment and all. - assert!(written.starts_with("# mine\ndatabase = \"state/izlek.db\"\n"), "{written}"); + assert!( + written.starts_with("# mine\ndatabase = \"state/izlek.db\"\n"), + "{written}" + ); - // Completing is not rewriting: a second load leaves the file alone. - Config::load_from(&dir).unwrap(); - assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), written); + // Completing is not rewriting: a second load leaves the file alone, + // and reads the completed key as the default already in use. + let again = Config::load_from(&dir).unwrap(); + assert_eq!(again.storage, config.storage); + assert_eq!( + std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), + written + ); let _ = std::fs::remove_dir_all(&dir); } @@ -435,16 +507,49 @@ mod tests { fn completion_leaves_a_key_that_is_already_there() { let dir = scratch(); std::fs::create_dir_all(dir.join("config")).unwrap(); - let mine = - "database = \"izlek.db\"\nlisten = \"0.0.0.0:8080\"\nlive_seconds = 30\n"; + let mine = "database = \"izlek.db\"\nstorage = \"files\"\n\ + listen = \"0.0.0.0:8080\"\nlive_seconds = 30\n"; std::fs::write(dir.join(FILE_NAME), mine).unwrap(); let config = Config::load_from(&dir).unwrap(); assert_eq!(config.listen, "0.0.0.0:8080".parse().unwrap()); assert_eq!(config.live_seconds, 30); + assert!(config.storage.ends_with("files"), "{:?}", config.storage); assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), mine); let _ = std::fs::remove_dir_all(&dir); } + /// Binary lives where the file says, or — when it says nothing — beside + /// the database, so a backup that takes the database takes the files. + #[test] + fn a_file_without_storage_puts_it_beside_the_database() { + let config = Config::parse( + "database = \"/srv/izlek/izlek.db\"\n", + Path::new("."), + false, + ) + .unwrap(); + assert_eq!(config.storage, PathBuf::from("/srv/izlek/storage")); + } + + /// An explicit storage is taken absolute, the way the database is. + #[test] + fn a_relative_storage_is_reported_absolute() { + let dir = scratch(); + let config = Config::parse( + "database = \"izlek.db\"\nstorage = \"state/files\"\n", + &dir, + false, + ) + .unwrap(); + assert!(config.storage.is_absolute(), "{:?}", config.storage); + assert!( + config.storage.ends_with("state/files"), + "{:?}", + config.storage + ); + let _ = std::fs::remove_dir_all(&dir); + } + /// A live connection that expires instantly is a reconnect loop, so the /// key is refused rather than silently corrected. #[test] @@ -456,7 +561,13 @@ mod tests { ) .unwrap_err(); assert!( - matches!(problem, ConfigError::Invalid { key: "live_seconds", .. }), + matches!( + problem, + ConfigError::Invalid { + key: "live_seconds", + .. + } + ), "{problem:?}" ); } @@ -464,8 +575,7 @@ mod tests { /// A file that never mentions the key still boots, on the default. #[test] fn a_file_without_a_live_window_takes_the_default() { - let config = - Config::parse("database = \"izlek.db\"\n", Path::new("."), false).unwrap(); + let config = Config::parse("database = \"izlek.db\"\n", Path::new("."), false).unwrap(); assert_eq!(config.live_seconds, 300); } @@ -514,7 +624,8 @@ mod tests { /// default it is about to be completed with. #[test] fn a_file_without_listen_takes_the_default() { - let config = Config::parse("database = \"/srv/izlek.db\"\n", Path::new("."), false).unwrap(); + let config = + Config::parse("database = \"/srv/izlek.db\"\n", Path::new("."), false).unwrap(); assert_eq!(config.listen, "127.0.0.1:7654".parse().unwrap()); } diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 7bb70b2..3eacf8f 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -115,7 +115,8 @@ pub struct Attachment { pub uploaded_at: OffsetDateTime, } -/// A file on its way into the table, bytes and all. +/// A file on its way into the store, bytes and all: the row goes to the +/// database, the bytes to the storage tree beside it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct NewAttachment<'a> { pub task_id: &'a str, @@ -982,9 +983,11 @@ pub trait Store: BoardReads + DetailReads + 'static { at: OffsetDateTime, ) -> Result; - /// Hangs a file off a task. The bytes go into the database file with the - /// row: there is no second place for an İzlek deployment to keep, and no - /// path for an uploaded name to become. + /// Hangs a file off a task. The bytes go to the storage tree, at + /// `/attachments/`, named by the row's own id — never by + /// anything an upload carried, so an uploaded name cannot become a path. + /// The database keeps the row; the directory keeps the bytes; back the + /// two up together. /// /// Nothing here decides whether the file was allowed — its size, its type /// and who may attach it are the handler's questions, answered before the diff --git a/crates/izlek-core/src/store/reconcile.rs b/crates/izlek-core/src/store/reconcile.rs index 0808487..4ef2830 100644 --- a/crates/izlek-core/src/store/reconcile.rs +++ b/crates/izlek-core/src/store/reconcile.rs @@ -4,6 +4,13 @@ //! `migrations/0001_init.sql`, the data is copied with an explicit per-table //! column map, the copy is verified, and only then the files are swapped. The //! original file is kept as a timestamped backup and is never deleted. +//! +//! Binary is the one thing that does not travel with the copy. A database of +//! an older shape keeps attachment bytes and profile photos inside its +//! tables, and the declared schema has no column for them: when such columns +//! exist, every blob is written to the storage directory, keyed by its id, +//! while the rebuild runs. An extraction failure fails the rebuild, so the +//! swap never trades the tables' binary for a directory that is not there. use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint}; use super::{Result, StoreError}; @@ -25,9 +32,17 @@ pub struct ReconcileOptions { /// - Empty or already-current databases are a no-op. /// - A differing database is backed up, rebuilt, verified and swapped into /// place. +/// - A database that still keeps binary in its tables has it extracted to +/// `storage`'s `attachments` and `photos` subdirectories during the +/// rebuild. `None` is accepted only when there is nothing to extract: a +/// caller with nowhere to put files must not quietly drop them. /// - A rebuild that fails verification deletes the `.rebuilt` file and leaves /// the original untouched. -pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> { +pub async fn reconcile( + path: &str, + storage: Option<&std::path::Path>, + opts: ReconcileOptions, +) -> Result<()> { if path == ":memory:" { return Err(StoreError::Backend( "reconcile is not meaningful on an in-memory database".into(), @@ -87,7 +102,7 @@ pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> { let rebuilt_path = format!("{}.rebuilt", path); cleanup_rebuilt(&rebuilt_path); - let result = rebuild(path, &rebuilt_path, &old_conn).await; + let result = rebuild(path, &rebuilt_path, &old_conn, storage).await; // Close the read-only connection before any file moves; this also // releases the WAL locks on the original file. @@ -147,7 +162,12 @@ pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> { /// a default tag for any board that comes across with none), and verifies /// the result. On success the rebuilt file is complete and checkpointed; on /// failure the caller deletes it. -async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Result<()> { +async fn rebuild( + path: &str, + rebuilt_path: &str, + old_conn: &Connection, + storage: Option<&std::path::Path>, +) -> Result<()> { // The copy runs as `INSERT ... SELECT FROM old.`, which needs // ATTACH — still gated in this engine, and switched on only here, for the // one connection that does the rebuild. The verification afterwards is @@ -169,6 +189,11 @@ async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Resul .execute_batch(SCHEMA) .await .map_err(|e| StoreError::Backend(e.to_string()))?; + // The blobs leave the old database before any row is copied: the copy's + // maps have no column to carry them, so this is the one moment to secure + // them. A failure here fails the whole rebuild, and the original file + // stays exactly as it was. + extract_blobs(old_conn, storage).await?; copy_data(old_conn, &new_conn, path).await?; verify(old_conn, &new_conn).await?; @@ -337,7 +362,10 @@ fn build_maps( "theme", "language", "ui", - "photo", + // `photo` is deliberately unmapped: the bytes do not travel + // with the copy. `extract_blobs` wrote each one to the + // storage directory under the user's id; the mime type is + // metadata and stays with the row. "photo_mime", "created_at", "last_signed_in_at", @@ -482,6 +510,9 @@ fn build_maps( }); maps.push(TableMap { name: "attachment", + // `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", @@ -489,7 +520,6 @@ fn build_maps( "file_name", "mime_type", "size_bytes", - "bytes", "uploaded_by", "created_at", ]), @@ -581,6 +611,81 @@ fn old_cols(cols: &[&'static str]) -> Vec<(&'static str, String)> { cols.iter().map(|c| (*c, format!("old.{}", c))).collect() } +/// Writes every blob the old schema still carried to the storage directory, +/// before any row is copied: attachments under `/attachments/`, +/// profile photos under `/photos/`. Each file goes down +/// through a temp name in its own directory and a rename, so a crash +/// mid-write never leaves a half file wearing a real name, and a name an +/// earlier failed attempt left behind is simply overwritten. +async fn extract_blobs(old_conn: &Connection, storage: Option<&std::path::Path>) -> Result<()> { + let has_bytes = old_has_column(old_conn, "attachment", "bytes").await?; + let has_photo = old_has_column(old_conn, "user", "photo").await?; + if (has_bytes || has_photo) && storage.is_none() { + return Err(StoreError::Backend( + "the old schema keeps binary in its tables but no storage directory \ + was given; the rebuild would drop it" + .into(), + )); + } + let Some(storage) = storage else { + return Ok(()); + }; + if has_bytes { + extract_column(old_conn, &storage.join("attachments"), "attachment", "bytes").await?; + } + if has_photo { + extract_column(old_conn, &storage.join("photos"), "user", "photo").await?; + } + Ok(()) +} + +/// Reads `
.` row by row and writes each value to `/`. NULLs are skipped — a photo that was cleared carried no bytes and +/// leaves no file. The directory is made if missing, so a storage root that +/// predates the boot's own creation still holds together. Any failure stops +/// the rebuild. +async fn extract_column( + old_conn: &Connection, + dir: &std::path::Path, + table: &str, + column: &str, +) -> Result<()> { + std::fs::create_dir_all(dir) + .map_err(|e| StoreError::Backend(format!("could not create {}: {e}", dir.display())))?; + let sql = format!("SELECT id, {column} FROM {table} WHERE {column} IS NOT NULL"); + let mut rows = old_conn + .query(&sql, ()) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + while let Some(row) = rows + .next() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + { + let id: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?; + let bytes: Vec = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?; + write_blob(dir, &id, &bytes).map_err(|e| { + StoreError::Backend(format!("extracting {table}.{column} for {id}: {e}")) + })?; + } + Ok(()) +} + +/// One blob, one file: written to a temp name in the target directory and +/// renamed onto the final name, so a reader of the final name never sees a +/// partial file. +fn write_blob(dir: &std::path::Path, id: &str, bytes: &[u8]) -> std::io::Result<()> { + let temp = dir.join(format!(".{}.tmp-{}", id, Ulid::new())); + std::fs::write(&temp, bytes)?; + match std::fs::rename(&temp, dir.join(id)) { + Ok(()) => Ok(()), + Err(err) => { + let _ = std::fs::remove_file(&temp); + Err(err) + } + } +} + /// Returns true if the attached old `workspace` table already carries the /// sender-check columns added by the old 0002 migration. async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result { @@ -962,8 +1067,11 @@ fn backup_name(path: &str) -> Result { #[cfg(test)] mod tests { - use super::{TableMap, backup_name, build_maps, validate_maps}; - use turso::Builder; + use super::{ + ReconcileOptions, TableMap, backup_name, build_maps, old_has_column, reconcile, + validate_maps, + }; + use turso::{Builder, params}; use ulid::Ulid; use crate::store::schema::SCHEMA; @@ -1015,4 +1123,167 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Writes an old-shape database at `path`: the declared schema, plus the + /// two blob columns the swap removed, holding one attachment and two + /// users — one photographed, one not. Returns the bytes it planted. + async fn old_shape_database(path: &str) -> (Vec, Vec) { + let attachment_bytes = b"file-bytes".to_vec(); + let photo_bytes = b"face-bytes".to_vec(); + let db = Builder::new_local(path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute_batch(SCHEMA).await.unwrap(); + // ALTER keeps the tables' own constraints intact, so this is the + // shape a live database of the previous generation has. + conn.execute( + "ALTER TABLE attachment ADD COLUMN bytes BLOB NOT NULL DEFAULT x''", + (), + ) + .await + .unwrap(); + conn.execute("ALTER TABLE user ADD COLUMN photo BLOB", ()) + .await + .unwrap(); + let now = "2026-01-01T00:00:00Z"; + conn.execute( + "INSERT INTO user (id, workspace_id, email, display_name, role, photo_mime, photo, \ + created_at) \ + VALUES ('U1', 'W1', 'one@izlek.sh', 'One', 'admin', 'image/png', ?1, ?2)", + params![&photo_bytes[..], now], + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO user (id, workspace_id, email, display_name, role, created_at) \ + VALUES ('U2', 'W1', 'two@izlek.sh', 'Two', 'member', ?1)", + params![now], + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO workspace (id, name, created_at) VALUES ('W1', 'Dizey', ?1)", + params![now], + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO board (id, workspace_id, name, created_at) \ + VALUES ('B1', 'W1', 'Board', ?1)", + params![now], + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \ + VALUES ('TG1', 'B1', 'General', 0, 1, ?1)", + params![now], + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO board_column (id, board_id, name, position) \ + VALUES ('C1', 'B1', 'Backlog', 0)", + (), + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO task (id, board_id, task_key, title, column_id, tag_id, created_by, \ + created_at, updated_at) \ + VALUES ('T1', 'B1', 'DZ-1', 'a task', 'C1', 'TG1', 'U1', ?1, ?1)", + params![now], + ) + .await + .unwrap(); + conn.execute( + "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, bytes, \ + uploaded_by, created_at) \ + VALUES ('F1', 'T1', 'a.bin', 'application/octet-stream', ?1, ?2, 'U1', ?3)", + params![attachment_bytes.len() as i64, &attachment_bytes[..], now], + ) + .await + .unwrap(); + (attachment_bytes, photo_bytes) + } + + /// An old-shape database rebuilds with its binary outside the tables: one + /// file per attachment under `attachments/`, one per photographed user + /// under `photos/`, byte-identical, and the rebuilt tables carry neither + /// column any more. + #[tokio::test] + async fn an_old_shaped_database_extracts_its_blobs_to_the_storage_dir() { + let dir = std::env::temp_dir().join(format!("izlek-reconcile-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("izlek.db").to_str().unwrap().to_string(); + let (attachment_bytes, photo_bytes) = old_shape_database(&path).await; + + let storage = dir.join("storage"); + reconcile( + &path, + Some(storage.as_path()), + ReconcileOptions { + dry_run: false, + yes: true, + auto: true, + }, + ) + .await + .expect("the rebuild with extraction failed"); + + assert_eq!( + std::fs::read(storage.join("attachments").join("F1")).unwrap(), + attachment_bytes + ); + assert_eq!( + std::fs::read(storage.join("photos").join("U1")).unwrap(), + photo_bytes + ); + // A photo that was never set carried no bytes and leaves no file. + assert!(!storage.join("photos").join("U2").exists()); + + let db = Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + assert!( + !old_has_column(&conn, "attachment", "bytes").await.unwrap(), + "the rebuilt attachment table still carries bytes" + ); + assert!( + !old_has_column(&conn, "user", "photo").await.unwrap(), + "the rebuilt user table still carries photo" + ); + drop(conn); + drop(db); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Rebuilding an old-shape database with nowhere to put the binary is + /// refused rather than dropping every blob on the floor, and the refusal + /// leaves the original file in place with nothing staged beside it. + #[tokio::test] + async fn a_rebuild_without_storage_refuses_to_drop_blobs() { + let dir = std::env::temp_dir().join(format!("izlek-reconcile-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("izlek.db").to_str().unwrap().to_string(); + old_shape_database(&path).await; + + let err = reconcile( + &path, + None, + ReconcileOptions { + dry_run: false, + yes: true, + auto: true, + }, + ) + .await + .expect_err("a rebuild that would drop binary passed"); + assert!(err.to_string().contains("storage"), "{err}"); + assert!(std::path::Path::new(&path).exists()); + let leftovers: Vec = std::fs::read_dir(&dir) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .filter(|name| name.contains(".backup-") || name.ends_with(".rebuilt")) + .collect(); + assert!(leftovers.is_empty(), "{leftovers:?}"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 1aacf06..1860816 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -7,8 +7,8 @@ use async_trait::async_trait; use rand::Rng; -use time::{Duration, OffsetDateTime}; use time::format_description::well_known::Rfc3339; +use time::{Duration, OffsetDateTime}; use turso::transaction::{Transaction, TransactionBehavior}; use turso::{Builder, Connection, Row, Value, params, params_from_iter}; use ulid::Ulid; @@ -16,12 +16,12 @@ 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, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState, - SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger, - User, UserStats, Workspace, LinkKind, + Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, LinkKind, MailDecision, MailOutcome, + MailRule, MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, + SendState, SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, + Trigger, User, UserStats, Workspace, }; -use super::{reconcile, ReconcileOptions, schema, sniff}; +use super::{ReconcileOptions, reconcile, schema, sniff}; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition}; use crate::detail::{ @@ -57,6 +57,12 @@ pub struct TursoStore { /// can hand out a receiver per subscriber; nothing is ever read from here /// by the store itself. live: tokio::sync::broadcast::Sender, + /// Root of the file tree the binary payloads live under: `attachments/` + /// for task files, `photos/` for profile pictures, one raw file per row, + /// named by the row's own id. The database keeps the facts and this tree + /// keeps the bytes; a boot sweep deletes whichever half outlives the + /// other. + storage: std::path::PathBuf, } impl TursoStore { @@ -79,13 +85,20 @@ impl TursoStore { } /// Opens (creating if needed) the database at `path` and brings the schema - /// up to date. `:memory:` gives a throwaway database for tests. - pub async fn open(path: &str) -> Result { + /// up to date. `storage` is the root of the file tree the binary payloads + /// (attachment bytes, profile photos) live under — created here if + /// missing. `:memory:` gives a throwaway database for tests, which still + /// hand in a storage directory, usually a tempdir, for the files. + pub async fn open(path: &str, storage: &std::path::Path) -> Result { + // Before anything else, including the reconcile below that extracts + // old blobs into this tree: a fresh storage path is a normal first + // boot, and every writer past this point assumes the tree is there. + ensure_storage_dirs(storage)?; let existed = path != ":memory:" && std::path::Path::new(path).exists(); // Before anything holds this file open: a database of an older shape is // rebuilt now, while no handle of ours points at the file that the // rebuild is about to replace. - Self::repair_if_stale(path).await?; + Self::repair_if_stale(path, storage).await?; let db = Builder::new_local(path).build().await.map_err(backend)?; let conn = db.connect().map_err(backend)?; // Turso is a single-writer engine. Two connections on one Database @@ -121,10 +134,12 @@ impl TursoStore { db, key, live, + storage: storage.to_path_buf(), }; store.migrate(path).await?; store.encrypt_plaintext_passwords().await?; store.resniff_generic_attachments().await?; + store.sweep_orphan_files().await?; // The file may have been rebuilt from a backup; its permissions and // any transient WAL/SHM siblings should still be private. if path != ":memory:" { @@ -187,7 +202,7 @@ impl TursoStore { /// /// Cheap by design. The pass opens with a count of generic rows and, when /// there are none — every database after one pass, and every database - /// whose uploads all postdate the sniffer — reads no blob bytes at all. + /// whose uploads all postdate the sniffer — reads no file bytes at all. /// Otherwise each such row donates two windows, the first /// [`sniff::HEAD_WINDOW`] and last [`sniff::TAIL_WINDOW`] bytes, and only /// when the windows find a zip with no office marker in them does the row @@ -207,7 +222,7 @@ impl TursoStore { let conn = self.conn.lock().await; // The existence probe the whole pass hangs off: one count of a short - // text column, no blob reads, and the common case is done here. + // 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})"), @@ -226,10 +241,7 @@ impl TursoStore { let mut rows = conn .query( &format!( - "SELECT id, mime_type, substr(bytes, 1, {head}), substr(bytes, -{tail}) \ - FROM attachment WHERE mime_type IN ({marks})", - head = sniff::HEAD_WINDOW, - tail = sniff::TAIL_WINDOW, + "SELECT id, mime_type FROM attachment WHERE mime_type IN ({marks})", marks = marks, ), params_from_iter(buckets.iter().copied()), @@ -240,22 +252,26 @@ impl TursoStore { while let Some(row) = rows.next().await.map_err(backend)? { let id = text(&row, 0)?; let stored = text(&row, 1)?; - let head: Vec = row.get(2).map_err(backend)?; - let tail: Vec = row.get(3).map_err(backend)?; + let path = attachment_file(&self.storage, &id); + let (head, tail) = match read_windows(&path, sniff::HEAD_WINDOW, sniff::TAIL_WINDOW) { + Ok(windows) => windows, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + eprintln!( + "attachment {id} wears a generic mime but its file is missing; \ + leaving it as stored" + ); + continue; + } + Err(e) => return Err(backend(e)), + }; let candidate = match sniff::refine(&stored, &head, &tail) { sniff::Verdict::Settle(candidate) => candidate, sniff::Verdict::ReadDirectory { offset, size } => { let len = size.min(sniff::DIRECTORY_CAP as u64) as i64; - let mut directory = conn - .query( - "SELECT substr(bytes, ?1, ?2) FROM attachment WHERE id = ?3", - params![offset as i64 + 1, len, id.clone()], - ) - .await - .map_err(backend)?; - match directory.next().await.map_err(backend)? { - Some(row) => sniff::office_entry_mime(&row.get::>(0).map_err(backend)?), - None => None, + match read_window_at(&path, offset, len) { + Ok(directory) => sniff::office_entry_mime(&directory), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(backend(e)), } } }; @@ -274,6 +290,58 @@ impl TursoStore { Ok(()) } + /// Sets the storage tree against the database, once per boot, after the + /// resniff. The database and the tree are two halves of one state, and a + /// crash between a row write and its file write — either order — leaves + /// exactly one half behind. A file no row names goes, including a `.tmp` + /// a crash abandoned mid-write; a row whose file is gone is only said + /// out loud and otherwise kept, because deleting the row would turn a + /// lost file into a lost fact — the row is still what screens list, and + /// a re-upload replaces it cleanly. + async fn sweep_orphan_files(&self) -> Result<()> { + let conn = self.conn.lock().await; + let attachments = known_ids(&conn, "SELECT id FROM attachment").await?; + let photos = known_ids(&conn, "SELECT id FROM user WHERE photo_mime IS NOT NULL").await?; + drop(conn); + for (dir, known, kind) in [ + ( + self.storage.join(ATTACHMENTS_DIR), + &attachments, + "attachment", + ), + (self.storage.join(PHOTOS_DIR), &photos, "photo"), + ] { + for id in known.iter() { + if !dir.join(id).is_file() { + eprintln!("{kind} {id} names a file that is not there"); + } + } + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(backend(e)), + }; + for entry in entries { + let entry = entry.map_err(backend)?; + let path = entry.path(); + if !path.is_file() { + continue; + } + let named = entry + .file_name() + .to_str() + .is_some_and(|n| known.contains(n)); + if !named && let Err(e) = std::fs::remove_file(&path) { + eprintln!( + "could not delete orphaned storage file {}: {e}", + path.display() + ); + } + } + } + Ok(()) + } + /// Brings the database to the declared schema. /// /// - An empty database is created from `migrations/0001_init.sql`. @@ -295,6 +363,7 @@ impl TursoStore { ) .await .map_err(backend)?; + let empty = match rows.next().await.map_err(backend)? { Some(row) => row.get::(0).map_err(backend)? == 0, None => true, @@ -307,7 +376,11 @@ impl TursoStore { let _ = conn.execute("ROLLBACK", ()).await; return Err(backend(e)); } - return conn.execute("COMMIT", ()).await.map_err(backend).map(|_| ()); + return conn + .execute("COMMIT", ()) + .await + .map_err(backend) + .map(|_| ()); } if path == ":memory:" { @@ -340,7 +413,7 @@ impl TursoStore { /// `turso::Database` opened beforehand still refers to the file that is /// now the backup. Reconnecting such a handle reads the old database and /// makes a successful rebuild look like a failed one. - async fn repair_if_stale(path: &str) -> Result<()> { + async fn repair_if_stale(path: &str, storage: &std::path::Path) -> Result<()> { if path == ":memory:" || !std::path::Path::new(path).exists() { return Ok(()); } @@ -381,6 +454,7 @@ impl TursoStore { ); reconcile( path, + Some(storage), ReconcileOptions { dry_run: false, yes: false, @@ -745,6 +819,120 @@ fn restrict_if_present(path: &std::path::Path) -> Result<()> { Ok(()) } +/// The storage tree's two subdirectories. One file per row under each, the +/// file named by the row's own id — an id the store minted, never anything +/// an upload carried, so a path here is always exactly one store-named file +/// deep and `file_name` stays a label. +const ATTACHMENTS_DIR: &str = "attachments"; +const PHOTOS_DIR: &str = "photos"; + +/// Where attachment `id`'s bytes live. +fn attachment_file(storage: &std::path::Path, id: &str) -> std::path::PathBuf { + storage.join(ATTACHMENTS_DIR).join(id) +} + +/// Where `user_id`'s photo lives. +fn photo_file(storage: &std::path::Path, user_id: &str) -> std::path::PathBuf { + storage.join(PHOTOS_DIR).join(user_id) +} + +/// Creates the storage tree — the root and its two subdirectories — when it +/// is missing, private to the process owner. A fresh storage path is a +/// normal first boot, not a failure, and everything below this point +/// assumes the directories are there to write into. +fn ensure_storage_dirs(storage: &std::path::Path) -> Result<()> { + for dir in [ + storage.to_path_buf(), + storage.join(ATTACHMENTS_DIR), + storage.join(PHOTOS_DIR), + ] { + std::fs::create_dir_all(&dir).map_err(|e| { + StoreError::Backend(format!("creating storage directory {}: {e}", dir.display())) + })?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)) + .map_err(|e| StoreError::Backend(format!("restricting {}: {e}", dir.display())))?; + } + } + Ok(()) +} + +/// Writes `bytes` to `path` through a temporary file in the same directory +/// and a rename: a crash or a full disk mid-write leaves whatever file was +/// there before intact, never a truncated one under the real name. The +/// temporary carries a name no row will ever wear, so one a crash abandoned +/// is exactly what the boot sweep deletes. +fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + let tmp = path.with_extension(format!("{}.tmp", Ulid::new())); + let mut file = std::fs::File::create(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; + std::fs::rename(&tmp, path) +} + +/// Whatever of `buf.len()` bytes the file holds from here — a file that ends +/// (or shrinks) under a read hands over the short read, the same answer +/// `substr` gave, and the sniffer decides from what it gets or declines. +fn read_up_to(file: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result { + use std::io::Read as _; + let mut filled = 0; + while filled < buf.len() { + match file.read(&mut buf[filled..])? { + 0 => break, + n => filled += n, + } + } + Ok(filled) +} + +/// `path`'s first `head` and last `tail` bytes — the windows the sniffer +/// decides from, the same shape `substr(bytes, ...)` used to hand over. A +/// file shorter than a window gives that window its whole self. +fn read_windows( + path: &std::path::Path, + head: i64, + tail: i64, +) -> std::io::Result<(Vec, Vec)> { + use std::io::Seek as _; + let mut file = std::fs::File::open(path)?; + let len = file.metadata()?.len(); + let mut head_buf = vec![0u8; len.min(head.max(0) as u64) as usize]; + let got = read_up_to(&mut file, &mut head_buf)?; + head_buf.truncate(got); + file.seek(std::io::SeekFrom::Start(len - len.min(tail.max(0) as u64)))?; + let mut tail_buf = vec![0u8; len.min(tail.max(0) as u64) as usize]; + let got = read_up_to(&mut file, &mut tail_buf)?; + tail_buf.truncate(got); + Ok((head_buf, tail_buf)) +} + +/// `len` bytes of `path` starting at `offset` — the central-directory read +/// `substr(bytes, offset + 1, len)` used to do. A directory the file does +/// not actually hold comes back short; the caller treats that as no +/// verdict, exactly as it treated `substr`'s empty answer. +fn read_window_at(path: &std::path::Path, offset: u64, len: i64) -> std::io::Result> { + use std::io::Seek as _; + let mut file = std::fs::File::open(path)?; + file.seek(std::io::SeekFrom::Start(offset))?; + let mut buf = vec![0u8; len.max(0) as usize]; + let got = read_up_to(&mut file, &mut buf)?; + buf.truncate(got); + Ok(buf) +} + +/// Every id `sql` hands back — the set of files the sweep must keep. +async fn known_ids(conn: &Connection, sql: &str) -> Result> { + let mut rows = conn.query(sql, ()).await.map_err(backend)?; + let mut out = std::collections::HashSet::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.insert(text(&row, 0)?); + } + Ok(out) +} + /// The key for `path`'s database. `:memory:` has no directory to anchor a /// sibling file to and does not survive the process anyway, so it gets a /// key generated fresh in memory — every in-memory store in the test suite @@ -956,7 +1144,7 @@ fn user_from(row: &Row) -> Result { } const USER_COLUMNS: &str = "id, workspace_id, email, display_name, role, password_hash, \ - (photo IS NOT NULL), created_at, last_signed_in_at, invited_by, timezone, theme, language, ui"; + (photo_mime IS NOT NULL), created_at, last_signed_in_at, invited_by, timezone, theme, language, ui"; fn signin_link_from(row: &Row) -> Result { Ok(SigninLink { @@ -1434,28 +1622,50 @@ impl Store for TursoStore { } async fn set_photo(&self, user_id: &str, bytes: &[u8], mime: &str) -> Result<()> { + // The new bytes stage under a name no row wears, the row commits, + // and only then does the rename put them over the old photo: a failed + // update leaves the committed photo exactly as it was, and a crash + // between commit and rename serves the old bytes next to a staged + // file the boot sweep collects — stale, never destroyed. + let path = photo_file(&self.storage, user_id); + let staged = path.with_extension(format!("incoming-{}", Ulid::new())); + write_file_atomic(&staged, bytes).map_err(|e| StoreError::Backend(e.to_string()))?; let conn = self.conn.lock().await; - let n = conn + let written = conn .execute( - "UPDATE user SET photo = ?1, photo_mime = ?2 WHERE id = ?3", - params![bytes, mime, user_id], + "UPDATE user SET photo_mime = ?1 WHERE id = ?2", + params![mime, user_id], ) - .await - .map_err(backend)?; + .await; + let n = match written { + Ok(n) => n, + Err(e) => { + drop(conn); + let _ = std::fs::remove_file(&staged); + return Err(backend(e)); + } + }; if n == 0 { + drop(conn); + let _ = std::fs::remove_file(&staged); Err(StoreError::NotFound) } else { drop(conn); + std::fs::rename(&staged, &path).map_err(|e| StoreError::Backend(e.to_string()))?; self.announce([Topic::Members]); Ok(()) } } async fn clear_photo(&self, user_id: &str) -> Result<()> { + // The row goes first: the file may only follow a delete that + // committed, or a crash in between would leave a row whose photo is + // gone. The unlink is best-effort — a file that survives it is + // orphaned bytes the boot sweep collects. let conn = self.conn.lock().await; let n = conn .execute( - "UPDATE user SET photo = NULL, photo_mime = NULL WHERE id = ?1", + "UPDATE user SET photo_mime = NULL WHERE id = ?1", params![user_id], ) .await @@ -1464,6 +1674,7 @@ impl Store for TursoStore { Err(StoreError::NotFound) } else { drop(conn); + let _ = std::fs::remove_file(photo_file(&self.storage, user_id)); self.announce([Topic::Members]); Ok(()) } @@ -1473,17 +1684,25 @@ impl Store for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT photo, photo_mime FROM user WHERE id = ?1", + "SELECT photo_mime FROM user WHERE id = ?1", params![user_id], ) .await .map_err(backend)?; - match rows.next().await.map_err(backend)? { - Some(row) => match row.get::>>(0).map_err(backend)? { - Some(bytes) => Ok(Some((bytes, text(&row, 1)?))), - None => Ok(None), - }, - None => Ok(None), + let mime = match rows.next().await.map_err(backend)? { + Some(row) => opt_text(&row, 0)?, + None => return Ok(None), + }; + drop(conn); + let Some(mime) = mime else { + return Ok(None); + }; + match std::fs::read(photo_file(&self.storage, user_id)) { + Ok(bytes) => Ok(Some((bytes, mime))), + // A row whose file went missing is reported at boot; the photo + // read answers "nothing to serve" rather than failing the page. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(StoreError::Backend(e.to_string())), } } @@ -1991,11 +2210,7 @@ impl Store for TursoStore { tx.commit().await.map_err(backend)?; // Task birth touches the board and the task page at once. - let mut topics = vec![ - Topic::Board, - Topic::Task(id.clone()), - Topic::Activity, - ]; + let mut topics = vec![Topic::Board, Topic::Task(id.clone()), Topic::Activity]; if reminded { topics.push(Topic::Queue); } @@ -2162,7 +2377,10 @@ impl Store for TursoStore { // A no-change assign changes no facts, so the reminders stand as // they are. let reminded = if n > 0 { - match self.sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc()).await { + match self + .sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc()) + .await + { Ok(reminded) => reminded, Err(e) => { let _ = tx.rollback().await; @@ -2199,7 +2417,10 @@ impl Store for TursoStore { .await .map_err(backend)?; let reminded = if n > 0 { - match self.sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc()).await { + match self + .sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc()) + .await + { Ok(reminded) => reminded, Err(e) => { let _ = tx.rollback().await; @@ -2419,27 +2640,38 @@ impl Store for TursoStore { } async fn add_attachment(&self, new: NewAttachment<'_>) -> Result { - let conn = self.conn.lock().await; + // The file lands first, temp-plus-rename, then the row says it is + // there: a crash in between leaves an orphan file the boot sweep + // deletes, never a row pointing at nothing. If the row write fails, + // the file is unlinked best-effort — the row was never born, so the + // bytes must not outlive it under a name nothing points at. let id = Ulid::new().to_string(); let size = new.bytes.len() as i64; - conn.execute( - "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \ - size_bytes, bytes, uploaded_by, created_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", - params![ - id.clone(), - new.task_id, - new.comment_id, - new.file_name, - new.mime_type, - size, - new.bytes, - new.uploaded_by, - stamp(new.at)? - ], - ) - .await - .map_err(backend)?; + let path = attachment_file(&self.storage, &id); + write_file_atomic(&path, &new.bytes).map_err(|e| StoreError::Backend(e.to_string()))?; + let conn = self.conn.lock().await; + let written = conn + .execute( + "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \ + size_bytes, uploaded_by, created_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params![ + id.clone(), + new.task_id, + new.comment_id, + new.file_name, + new.mime_type, + size, + new.uploaded_by, + stamp(new.at)? + ], + ) + .await; + if let Err(e) = written { + drop(conn); + let _ = std::fs::remove_file(&path); + return Err(backend(e)); + } drop(conn); self.announce([Topic::Task(new.task_id.to_string())]); Ok(id) @@ -2482,12 +2714,20 @@ impl Store for TursoStore { async fn attachment_bytes(&self, id: &str) -> Result>> { let conn = self.conn.lock().await; let mut rows = conn - .query("SELECT bytes FROM attachment WHERE id = ?1", params![id]) + .query("SELECT 1 FROM attachment WHERE id = ?1", params![id]) .await .map_err(backend)?; - match rows.next().await.map_err(backend)? { - Some(row) => Ok(Some(row.get::>(0).map_err(backend)?)), - None => Ok(None), + let known = rows.next().await.map_err(backend)?.is_some(); + drop(conn); + if !known { + return Ok(None); + } + match std::fs::read(attachment_file(&self.storage, id)) { + Ok(bytes) => Ok(Some(bytes)), + // A row whose file went missing is reported at boot; the read + // answers "nothing to serve" rather than failing the panel. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(StoreError::Backend(e.to_string())), } } @@ -2506,10 +2746,15 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - if gone > 0 - && let Some(task_id) = owner - { - self.announce([Topic::Task(task_id)]); + if gone > 0 { + // After the delete: the file may only follow a delete that + // committed, or a crash in between would leave a row whose file + // is gone. Best-effort — a file that survives 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(gone > 0) } @@ -4543,7 +4788,7 @@ impl DetailReads for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT u.id, u.display_name, (u.photo IS NOT NULL) FROM task_assignee a \ + "SELECT u.id, u.display_name, (u.photo_mime IS NOT NULL) FROM task_assignee a \ JOIN user u ON u.id = a.user_id \ WHERE a.task_id = ?1 ORDER BY u.display_name", params![task_id], @@ -4567,7 +4812,7 @@ impl DetailReads for TursoStore { // so neither leaves the server for this screen. let mut rows = conn .query( - "SELECT id, display_name, (photo IS NOT NULL) FROM user \ + "SELECT id, display_name, (photo_mime IS NOT NULL) FROM user \ WHERE workspace_id = ?1 AND role <> ?2 ORDER BY display_name", params![workspace_id, Role::Viewer.as_str()], ) @@ -4626,7 +4871,7 @@ impl DetailReads for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT c.id, c.body, c.created_at, u.id, u.display_name, (u.photo IS NOT NULL) \ + "SELECT c.id, c.body, c.created_at, u.id, u.display_name, (u.photo_mime IS NOT NULL) \ FROM comment c JOIN user u ON u.id = c.author_id \ WHERE c.task_id = ?1 ORDER BY c.created_at, c.rowid", params![task_id], @@ -4682,7 +4927,7 @@ impl DetailReads for TursoStore { let mut rows = conn .query( "SELECT a.id, a.kind, a.detail, a.created_at, u.id, u.display_name, \ - (u.photo IS NOT NULL) \ + (u.photo_mime IS NOT NULL) \ FROM activity a LEFT JOIN user u ON u.id = a.actor_id \ WHERE a.task_id = ?1 ORDER BY a.created_at DESC, a.rowid DESC", params![task_id], @@ -4719,7 +4964,7 @@ impl DetailReads for TursoStore { let mut rows = conn .query( "SELECT t.id, t.task_key, t.title, t.column_id, t.done_at, t.parent_id, \ - u.id, u.display_name, (u.photo IS NOT NULL) \ + u.id, u.display_name, (u.photo_mime IS NOT NULL) \ FROM task t \ LEFT JOIN task_assignee a ON a.task_id = t.id \ LEFT JOIN user u ON u.id = a.user_id \ @@ -4852,7 +5097,7 @@ impl BoardReads for TursoStore { let conn = self.conn.lock().await; let mut rows = conn .query( - "SELECT a.task_id, u.id, u.display_name, (u.photo IS NOT NULL) \ + "SELECT a.task_id, u.id, u.display_name, (u.photo_mime IS NOT NULL) \ FROM task_assignee a \ JOIN task t ON t.id = a.task_id \ JOIN user u ON u.id = a.user_id \ @@ -5070,7 +5315,7 @@ mod probe { async fn the_workspace_read_path_cannot_carry_the_password() { let dir = std::env::temp_dir().join(format!("izlek-sender-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); - let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap()) + let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage")) .await .unwrap(); use crate::store::Store as _; @@ -5113,3 +5358,277 @@ mod probe { let _ = std::fs::remove_dir_all(&dir); } } + +/// The storage tree is the other half of the state the rows describe. These +/// drive the file half through the same [`Store`] API the handlers use: a +/// row's bytes live at exactly one path named by the row's id, a delete +/// takes the file with it, and a boot sweep collects what the rows stopped +/// naming. Nothing binary is in the database any more — the premise a +/// missing file is recoverable-by-reread no longer holds, and these are +/// where that shows up if it breaks. +#[cfg(test)] +mod storage_fs { + use super::*; + + /// A file-backed store and its storage tree, both under one tempdir the + /// fixture keeps alive. File-backed because the boot passes (reconcile, + /// resniff, sweep) only run for a database that survives its handle. + struct Fixture { + store: TursoStore, + dir: tempfile::TempDir, + } + + impl Fixture { + async fn open() -> Self { + let dir = tempfile::tempdir().unwrap(); + let store = TursoStore::open( + dir.path().join("izlek.db").to_str().unwrap(), + &dir.path().join("storage"), + ) + .await + .unwrap(); + Self { store, dir } + } + + fn storage(&self) -> std::path::PathBuf { + self.dir.path().join("storage") + } + + /// A workspace with its admin, and one task on the default board. + async fn with_task(&self) -> (String, String, String) { + let (ws, admin) = self + .store + .claim_workspace("İzlek", "ada@izlek.sh", "Ada", "hash") + .await + .unwrap(); + let admin = admin.id; + let board = self.store.board(&ws.id).await.unwrap().unwrap(); + let column = self + .store + .columns(&board.id) + .await + .unwrap() + .into_iter() + .find(|c| !c.is_done) + .unwrap_or_else(|| panic!("no open column")) + .id; + let task = self + .store + .create_task(NewTask { + clock_at: None, + board_id: &board.id, + column_id: &column, + parent_id: None, + title: "a task", + description: "", + deadline: None, + created_by: &admin, + }) + .await + .unwrap() + .row + .id; + (ws.id, admin, task) + } + } + + #[tokio::test] + async fn an_attachment_round_trips_through_its_file() { + let fx = Fixture::open().await; + let (_ws, admin, task) = fx.with_task().await; + let bytes: Vec = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0xff, 0x00]; + let id = fx + .store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "shot.png", + mime_type: "image/png", + bytes: bytes.clone(), + uploaded_by: &admin, + at: OffsetDateTime::now_utc(), + }) + .await + .unwrap(); + + assert_eq!( + fx.store.attachment_bytes(&id).await.unwrap().unwrap(), + bytes + ); + // The bytes are a file the row's id names, under attachments/, and + // nothing binary went into the database: the temp file the write + // passed through is gone, and the tree holds exactly one file. + let file = attachment_file(&fx.storage(), &id); + assert!(file.is_file(), "the attachment file exists"); + assert_eq!(std::fs::read(&file).unwrap(), bytes); + let dir = fx.storage().join(ATTACHMENTS_DIR); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + } + + #[tokio::test] + async fn a_photo_round_trips_through_its_file() { + let fx = Fixture::open().await; + let (_ws, admin, _task) = fx.with_task().await; + fx.store + .set_photo(&admin, b"grace-bytes", "image/png") + .await + .unwrap(); + + let photo = fx.store.photo(&admin).await.unwrap().unwrap(); + assert_eq!(photo.0, b"grace-bytes".to_vec()); + assert_eq!(photo.1, "image/png"); + let file = photo_file(&fx.storage(), &admin); + assert!(file.is_file(), "the photo file exists"); + assert_eq!(std::fs::read(&file).unwrap(), b"grace-bytes"); + } + + #[tokio::test] + async fn deleting_an_attachment_takes_its_file_with_it() { + let fx = Fixture::open().await; + let (_ws, admin, task) = fx.with_task().await; + let id = fx + .store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "note.txt", + mime_type: "text/plain", + bytes: b"hello".to_vec(), + uploaded_by: &admin, + at: OffsetDateTime::now_utc(), + }) + .await + .unwrap(); + let file = attachment_file(&fx.storage(), &id); + + assert!(fx.store.delete_attachment(&id).await.unwrap()); + assert!(!file.exists(), "the file went with the row"); + assert!(fx.store.attachment(&id).await.unwrap().is_none()); + assert!(fx.store.attachment_bytes(&id).await.unwrap().is_none()); + // A second delete is still a no-op, file and all. + assert!(!fx.store.delete_attachment(&id).await.unwrap()); + } + + #[tokio::test] + async fn clearing_a_photo_takes_its_file_with_it() { + let fx = Fixture::open().await; + let (_ws, admin, _task) = fx.with_task().await; + fx.store + .set_photo(&admin, b"grace-bytes", "image/png") + .await + .unwrap(); + let file = photo_file(&fx.storage(), &admin); + + fx.store.clear_photo(&admin).await.unwrap(); + assert!(!file.exists(), "the file went with the marker"); + assert!(fx.store.photo(&admin).await.unwrap().is_none()); + assert!(!fx.store.user(&admin).await.unwrap().unwrap().has_photo); + } + + #[tokio::test] + async fn the_boot_sweep_deletes_files_no_row_names() { + let fx = Fixture::open().await; + let attachments = fx.storage().join(ATTACHMENTS_DIR); + let photos = fx.storage().join(PHOTOS_DIR); + // Strays in both subdirs: a file under a made-up id, and the temp + // file a crash abandoned mid-write. + std::fs::write(attachments.join("01AAAAAAAAAAAAAAAAAAAAAAAA"), b"x").unwrap(); + std::fs::write(attachments.join("02BBBBBBBBBBBBBBBBBBBBBBBB.tmp"), b"x").unwrap(); + std::fs::write(photos.join("03CCCCCCCCCCCCCCCCCCCCCCCC"), b"x").unwrap(); + + // A reopen is a boot; the sweep runs inside it. + let Fixture { store, dir } = fx; + drop(store); + let db_path = dir.path().join("izlek.db").to_str().unwrap().to_string(); + let storage = dir.path().join("storage"); + let store = TursoStore::open(&db_path, &storage).await.unwrap(); + assert_eq!(std::fs::read_dir(&attachments).unwrap().count(), 0); + assert_eq!(std::fs::read_dir(&photos).unwrap().count(), 0); + drop(store); + } + + #[tokio::test] + async fn a_row_whose_file_is_missing_is_kept_and_said_out_loud() { + let fx = Fixture::open().await; + let (_ws, admin, task) = fx.with_task().await; + let id = fx + .store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "shot.png", + mime_type: "image/png", + bytes: b"payload".to_vec(), + uploaded_by: &admin, + at: OffsetDateTime::now_utc(), + }) + .await + .unwrap(); + fx.store + .set_photo(&admin, b"grace-bytes", "image/png") + .await + .unwrap(); + // The files are lost the way a botched restore loses them: rows on + // disk, files gone. + std::fs::remove_file(attachment_file(&fx.storage(), &id)).unwrap(); + std::fs::remove_file(photo_file(&fx.storage(), &admin)).unwrap(); + + let Fixture { store, dir } = fx; + drop(store); + let db_path = dir.path().join("izlek.db").to_str().unwrap().to_string(); + let storage = dir.path().join("storage"); + let store = TursoStore::open(&db_path, &storage).await.unwrap(); + // Both rows survive the sweep; the reads answer "nothing to serve". + assert!(store.attachment(&id).await.unwrap().is_some()); + assert!(store.attachment_bytes(&id).await.unwrap().is_none()); + let admin_row = store.user(&admin).await.unwrap().unwrap(); + assert!(admin_row.has_photo, "the row still says a photo is there"); + assert!(store.photo(&admin).await.unwrap().is_none()); + } + + #[tokio::test] + async fn the_boot_resniff_reads_its_windows_from_the_file() { + let fx = Fixture::open().await; + let (_ws, admin, task) = fx.with_task().await; + // A zip whose entry names name a presentation. Uploaded with the + // generic bucket a pre-sniffer write froze on — the store does not + // sniff on the way in, so the row wears it until a boot pass runs. + let bytes = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]); + let id = fx + .store + .add_attachment(NewAttachment { + task_id: &task, + comment_id: None, + file_name: "old.pptx", + mime_type: "application/zip", + bytes, + uploaded_by: &admin, + at: OffsetDateTime::now_utc(), + }) + .await + .unwrap(); + let Fixture { store, dir } = fx; + drop(store); + let db_path = dir.path().join("izlek.db").to_str().unwrap().to_string(); + let storage = dir.path().join("storage"); + let store = TursoStore::open(&db_path, &storage).await.unwrap(); + assert_eq!( + store.attachment(&id).await.unwrap().unwrap().mime_type, + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "the windows came off the file, and they settled the type" + ); + } + + /// A zip of the named entries, contents irrelevant: the sniffer reads + /// the entry names a zip stores uncompressed. + fn zip_with(names: &[&str]) -> Vec { + use std::io::Write as _; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for name in names { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"").unwrap(); + } + zip.finish().unwrap().into_inner() + } +} diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 197a2b7..7be840f 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -19,6 +19,7 @@ use ulid::Ulid; /// runs, so the tests exercise a real file. struct Scratch { dir: PathBuf, + storage: PathBuf, store: TursoStore, } @@ -26,10 +27,11 @@ impl Scratch { async fn open() -> Self { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); - let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap()) + let storage = dir.join("storage"); + let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &storage) .await .unwrap(); - Self { dir, store } + Self { dir, storage, store } } } @@ -100,14 +102,14 @@ async fn the_schema_is_created_once_and_survives_reopen() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); - let first = TursoStore::open(&path).await.unwrap(); + let first = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); claim(&first).await; drop(first); // Re-opening a database that already has tables must not re-run the // schema (its CREATE TABLE would fail on the first one) and must not // lose what the first open wrote. - let second = TursoStore::open(&path).await.unwrap(); + let second = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek"); drop(second); let _ = std::fs::remove_dir_all(&dir); @@ -699,7 +701,7 @@ async fn concurrent_claims_produce_exactly_one_admin() { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); - let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap()); + let store = std::sync::Arc::new(TursoStore::open(&path, &dir.join("storage")).await.unwrap()); let hash = hash_password("tide-tables-1892").unwrap(); let mut claims = Vec::new(); @@ -752,7 +754,7 @@ async fn many_concurrent_callers_never_see_concurrent_use_forbidden() { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); - let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap()); + let store = std::sync::Arc::new(TursoStore::open(&path, &dir.join("storage")).await.unwrap()); let (workspace_id, _) = claim(&store).await; let mut tasks = Vec::new(); @@ -1211,6 +1213,10 @@ async fn profile_and_role_updates_stick() { let photo = scratch.store.photo(&user.id).await.unwrap().unwrap(); assert_eq!(photo.0, b"grace-bytes".to_vec()); assert_eq!(photo.1, "image/png"); + // The bytes are the file the row's id names, not anything in the + // database. + let photo_file = scratch.storage.join("photos").join(&user.id); + assert_eq!(std::fs::read(&photo_file).unwrap(), b"grace-bytes"); let user = scratch.store.user(&user.id).await.unwrap().unwrap(); assert_eq!(user.display_name, "Grace H."); assert!(user.has_photo); @@ -1221,11 +1227,13 @@ async fn profile_and_role_updates_stick() { at.unix_timestamp() ); - // Clearing the photo is a real update, not a no-op. + // Clearing the photo is a real update, not a no-op — the file goes + // with the marker. scratch.store.clear_photo(&user.id).await.unwrap(); let user = scratch.store.user(&user.id).await.unwrap().unwrap(); assert!(!user.has_photo); assert!(scratch.store.photo(&user.id).await.unwrap().is_none()); + assert!(!photo_file.exists()); } #[tokio::test] @@ -1235,7 +1243,7 @@ async fn email_change_persists_and_refuses_a_taken_address() { let path = dir.join("izlek.db").to_str().unwrap().to_string(); let user_id = { - let store = TursoStore::open(&path).await.unwrap(); + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); let (ws_id, _admin_id) = claim(&store).await; let user_id = member(&store, &ws_id, "grace@izlek.sh", "Grace").await; store @@ -1268,7 +1276,7 @@ async fn email_change_persists_and_refuses_a_taken_address() { }; // Persists across a reopen, and the refused attempt did not stick. - let store = TursoStore::open(&path).await.unwrap(); + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); let user = store.user(&user_id).await.unwrap().unwrap(); assert_eq!(user.email, "grace.new@izlek.sh"); @@ -1281,7 +1289,7 @@ async fn display_preferences_default_and_persist_across_reopen() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); - let store = TursoStore::open(&path).await.unwrap(); + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); let (_, admin_id) = claim(&store).await; let admin = store.user(&admin_id).await.unwrap().unwrap(); @@ -1296,7 +1304,7 @@ async fn display_preferences_default_and_persist_across_reopen() { .unwrap(); drop(store); - let reopened = TursoStore::open(&path).await.unwrap(); + let reopened = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); let admin = reopened.user(&admin_id).await.unwrap().unwrap(); assert_eq!(admin.timezone, "Europe/Istanbul"); assert_eq!(admin.theme, "dark"); @@ -1451,7 +1459,7 @@ async fn a_prefetched_link_is_consumed_exactly_once() { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); - let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap()); + let store = std::sync::Arc::new(TursoStore::open(&path, &dir.join("storage")).await.unwrap()); let (ws_id, _) = claim(&store).await; let user_id = member(&store, &ws_id, "grace@izlek.sh", "Grace").await; @@ -1694,9 +1702,12 @@ use std::sync::Arc; /// by the returned guard. async fn accounts() -> (Scratch, Accounts) { let scratch = Scratch::open().await; - let store = TursoStore::open(scratch.dir.join("izlek.db").to_str().unwrap()) - .await - .unwrap(); + let store = TursoStore::open( + scratch.dir.join("izlek.db").to_str().unwrap(), + &scratch.dir.join("storage"), + ) + .await + .unwrap(); let accounts = Accounts::new(Arc::new(store) as Arc, "https://izlek.sh"); (scratch, accounts) } @@ -3988,7 +3999,7 @@ async fn an_orphan_row_is_refused() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_str().unwrap().to_owned(); { - TursoStore::open(&path).await.unwrap(); + TursoStore::open(&path, &dir.join("storage")).await.unwrap(); } let db = turso::Builder::new_local(&path).build().await.unwrap(); @@ -4065,7 +4076,7 @@ async fn a_rule_naming_a_column_it_cannot_act_on_is_refused_by_the_schema() { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); - let store = TursoStore::open(&path).await.unwrap(); + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); let (workspace, _admin) = claim(&store).await; let board = store.board(&workspace).await.unwrap().unwrap(); drop(store); @@ -4550,7 +4561,7 @@ async fn waiting(minutes: u32) -> (PathBuf, Arc, String, String) { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let store = Arc::new( - TursoStore::open(dir.join("izlek.db").to_str().unwrap()) + TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage")) .await .unwrap(), ); @@ -5439,14 +5450,14 @@ async fn an_account_records_the_admin_who_made_it() { } #[tokio::test] -async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() { +async fn a_file_lands_in_the_storage_tree_and_comes_back_byte_for_byte() { let (scratch, workspace, admin) = workspace_with_admin().await; let store = &scratch.store; let now = OffsetDateTime::now_utc(); let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await; // Bytes that are not text and are not valid UTF-8, because an attachment - // is not a string and the column it lives in must not treat it as one. + // is not a string and must not be treated as one, wherever it sits. let bytes: Vec = vec![ 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe, ]; @@ -5470,6 +5481,17 @@ async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() { assert_eq!(row.size_bytes, bytes.len() as u64); assert_eq!(row.uploaded_by, admin); assert_eq!(store.attachment_bytes(&id).await.unwrap().unwrap(), bytes); + + // The bytes are the file the row's id names, under the storage tree — + // not a second copy anywhere else. The temp file the write passed + // through is gone, and the directory holds exactly one file. + let file = scratch.storage.join("attachments").join(&id); + assert_eq!(std::fs::read(&file).unwrap(), bytes); + let files: Vec = std::fs::read_dir(scratch.storage.join("attachments")) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(files, vec![id], "the tree holds exactly the row's file"); } #[tokio::test] @@ -5495,12 +5517,24 @@ async fn a_file_name_that_is_a_path_is_stored_as_the_label_it_is() { .unwrap(); let row = store.attachment(&id).await.unwrap().unwrap(); assert_eq!(row.file_name, "../../etc/passwd"); - // And nothing was written anywhere but the database file and its key - // (see `store::secret`) — never a file named after the attachment. + + // The label never became a path: the bytes sit at the one place the + // row's own id names, under the storage tree, and nothing was written + // outside it beside the database file and its key (see `store::secret`). + let attachments = scratch.storage.join("attachments"); + let files: Vec = std::fs::read_dir(&attachments) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(files, vec![id.clone()], "the tree holds exactly the row's file"); + assert_eq!( + std::fs::read(attachments.join(&id)).unwrap(), + b"root:x:0:0" + ); let written: Vec = std::fs::read_dir(&scratch.dir) .unwrap() .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) - .filter(|name| !name.starts_with("izlek.db") && name != "izlek.key") + .filter(|name| !name.starts_with("izlek.db") && name != "izlek.key" && name != "storage") .collect(); assert!(written.is_empty(), "{written:?}"); } @@ -5555,7 +5589,11 @@ async fn a_file_can_be_taken_away_and_saying_so_twice_is_answered_honestly() { .await .unwrap(); + let file = scratch.storage.join("attachments").join(&id); + assert!(file.is_file(), "the file is there before the delete"); + assert!(store.delete_attachment(&id).await.unwrap()); + assert!(!file.exists(), "the file went with the row"); assert!(!store.delete_attachment(&id).await.unwrap()); assert!(store.attachment(&id).await.unwrap().is_none()); assert!(store.attachment_bytes(&id).await.unwrap().is_none()); @@ -7187,6 +7225,7 @@ async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() { izlek_core::store::reconcile( &path, + Some(&dir.join("storage")), izlek_core::store::ReconcileOptions { dry_run: false, yes: true, @@ -7239,23 +7278,30 @@ async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() { "each board owes exactly one default tag" ); - // The blob survived byte for byte. + // The blob survived byte for byte — as the file the row's id names, + // under the storage tree the rebuild was handed, with the row still + // agreeing with it. (The database has no bytes column any more; the + // fingerprint check above already fails if one came back.) + let stored = std::fs::read( + dir.join("storage") + .join("attachments") + .join("F1"), + ) + .expect("the attachment's file did not survive the rebuild"); + assert_eq!(stored.len(), 5000); assert_eq!( - scalar( - &path, - "SELECT length(bytes) FROM attachment WHERE id = 'F1'" - ) - .await, - 5000 + &stored[..4], + &[0, 1, 2, 3], + "the attachment's bytes changed in the rebuild" ); assert_eq!( scalar( &path, - "SELECT COUNT(*) FROM attachment WHERE id = 'F1' AND hex(substr(bytes, 1, 4)) = '00010203'", + "SELECT size_bytes FROM attachment WHERE id = 'F1'" ) .await, - 1, - "the attachment's bytes changed in the rebuild" + 5000, + "the row no longer agrees with its file" ); // The quiet window is a column the old shape never had: a workspace that @@ -7331,6 +7377,7 @@ async fn reconcile_preserves_user_tags_and_the_tasks_that_wear_them() { izlek_core::store::reconcile( &path, + Some(&dir.join("storage")), izlek_core::store::ReconcileOptions { dry_run: false, yes: true, @@ -7416,6 +7463,7 @@ async fn reconcile_seeds_a_default_only_for_a_board_without_one() { izlek_core::store::reconcile( &path, + Some(&dir.join("storage")), izlek_core::store::ReconcileOptions { dry_run: false, yes: true, @@ -7484,6 +7532,7 @@ async fn reconciling_a_database_that_already_matches_changes_nothing() { izlek_core::store::reconcile( &path, + Some(&scratch.dir.join("storage")), izlek_core::store::ReconcileOptions { dry_run: false, yes: true, @@ -7505,7 +7554,7 @@ async fn opening_a_stale_database_repairs_it() { // The boot path: no flag, no prompt — the store comes up on a database of // the old shape, having repaired it on the way. - let store = TursoStore::open(&path) + let store = TursoStore::open(&path, &dir.join("storage")) .await .expect("the store would not open a database it was supposed to repair"); drop(store); @@ -7522,7 +7571,7 @@ async fn opening_a_stale_database_repairs_it() { assert_eq!(backups_beside(&dir).len(), 1); // Opening it again finds it current and leaves it alone. - let store = TursoStore::open(&path).await.unwrap(); + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); drop(store); assert_eq!( backups_beside(&dir).len(), @@ -7542,7 +7591,7 @@ async fn two_repairs_leave_two_backups() { auto: true, }; - izlek_core::store::reconcile(&path, opts()).await.unwrap(); + izlek_core::store::reconcile(&path, Some(&dir.join("storage")), opts()).await.unwrap(); assert_eq!(backups_beside(&dir).len(), 1); // Put the database back to the old shape and repair it again: the first @@ -7556,7 +7605,7 @@ async fn two_repairs_leave_two_backups() { drop(conn); drop(db); - izlek_core::store::reconcile(&path, opts()).await.unwrap(); + izlek_core::store::reconcile(&path, Some(&dir.join("storage")), opts()).await.unwrap(); let backups = backups_beside(&dir); assert_eq!( backups.len(), @@ -7600,6 +7649,7 @@ async fn a_rebuild_keeps_a_window_the_admin_already_set() { izlek_core::store::reconcile( &path, + Some(&scratch.dir.join("storage")), izlek_core::store::ReconcileOptions { dry_run: false, yes: true, @@ -8675,7 +8725,7 @@ async fn reminder_rows_survive_a_reopen() { let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_string_lossy().into_owned(); - let store = TursoStore::open(&path).await.unwrap(); + let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); let (workspace, admin) = claim(&store).await; let mate = member(&store, &workspace, "grace@izlek.sh", "Grace").await; let clock = OffsetDateTime::now_utc() + Duration::hours(2); @@ -8686,7 +8736,7 @@ async fn reminder_rows_survive_a_reopen() { let before = before; drop(store); - let reopened = TursoStore::open(&path).await.unwrap(); + let reopened = TursoStore::open(&path, &dir.join("storage")).await.unwrap(); let after = reminders(&reopened, &task).await; assert_eq!(after.len(), before.len()); assert_eq!( @@ -9423,10 +9473,12 @@ fn ole_bytes(with_workbook: bool) -> Vec { bytes } -/// A scratch database carrying old-style attachment rows: real bytes under -/// the generic mime a pre-sniffer upload froze on. The first open creates -/// the schema and finds nothing to do; the rows go in through a raw -/// connection; the caller then opens the store again, which runs the pass. +/// A scratch database carrying pre-fs attachment rows: generic mimes under +/// which the boot pass may refine, with the bytes where the pass reads them +/// now — a file per row, named by the row's id. The first open creates the +/// schema and finds nothing to do; the rows go in through a raw connection +/// and their bytes land in the storage tree by hand; the caller then opens +/// the store again, which runs the pass. struct Planted { dir: PathBuf, path: String, @@ -9437,18 +9489,19 @@ impl Planted { let dir = std::env::temp_dir().join(format!("izlek-resniff-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("izlek.db").to_str().unwrap().to_string(); - drop(TursoStore::open(&path).await.unwrap()); + drop(TursoStore::open(&path, &dir.join("storage")).await.unwrap()); let db = turso::Builder::new_local(&path).build().await.unwrap(); let conn = db.connect().unwrap(); for (id, mime, bytes) in rows { conn.execute( "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, \ - bytes, uploaded_by, created_at) \ - VALUES (?1, 'T1', 'old.bin', ?2, ?3, ?4, 'U1', '2026-08-01T00:00:00Z')", - turso::params![id, mime, bytes.len() as i64, bytes.clone()], + uploaded_by, created_at) \ + VALUES (?1, 'T1', 'old.bin', ?2, ?3, 'U1', '2026-08-01T00:00:00Z')", + turso::params![id, mime, bytes.len() as i64], ) .await .unwrap(); + std::fs::write(dir.join("storage").join("attachments").join(id), bytes).unwrap(); } drop(conn); drop(db); @@ -9460,7 +9513,9 @@ impl Planted { } async fn open(&self) -> TursoStore { - TursoStore::open(self.path()).await.unwrap() + TursoStore::open(self.path(), &self.dir.join("storage")) + .await + .unwrap() } } diff --git a/crates/izlek-web/src/detail.rs b/crates/izlek-web/src/detail.rs index bbc7d6a..f47d70e 100644 --- a/crates/izlek-web/src/detail.rs +++ b/crates/izlek-web/src/detail.rs @@ -547,9 +547,7 @@ pub(crate) fn combine_clock( match (hour, minute) { (None, None) => Ok(None), (Some(""), Some("")) => Ok(Some(String::new())), - (Some(hour), Some(minute)) => { - Ok(Some(format!("{}:{}", hour.trim(), minute.trim()))) - } + (Some(hour), Some(minute)) => Ok(Some(format!("{}:{}", hour.trim(), minute.trim()))), _ => Err(Refusal::BadClock), } } @@ -968,9 +966,10 @@ async fn delete_task(cx: &Cx, Form(input): Form) -> Redirect { )) } -/// Deletes an attachment's row and its bytes. A hard delete, unlike -/// [`delete_task`]'s soft one — a file is a blob in the database, not a fact -/// worth an audit trail. Only the person who put it there, or an admin, may +/// Deletes an attachment's row and its file. A hard delete, unlike +/// [`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. #[route(POST "/api/delete_file")] async fn delete_file(cx: &Cx, Form(input): Form) -> Redirect { @@ -1298,8 +1297,6 @@ async fn deadline_control( may_write: bool, lang: Lang, ) -> Result { - - let overdue = task.is_overdue(today); let local = task.clock_at.map(|at| at.to_offset(zone)); let label = match (&local, task.deadline_parts(today)) { @@ -2459,12 +2456,12 @@ pub async fn file_viewer_modal( // board and passed down. let deck = if kind == crate::files::ViewerKind::Slides { match store.attachment_bytes(file_id).await { - Ok(Some(bytes)) => tokio::task::spawn_blocking(move || { - crate::slides::read(bytes, sheet_index) - }) - .await - .ok() - .flatten(), + Ok(Some(bytes)) => { + tokio::task::spawn_blocking(move || crate::slides::read(bytes, sheet_index)) + .await + .ok() + .flatten() + } _ => None, } } else { diff --git a/crates/izlek-web/src/main.rs b/crates/izlek-web/src/main.rs index 745932b..ddf5403 100644 --- a/crates/izlek-web/src/main.rs +++ b/crates/izlek-web/src/main.rs @@ -36,6 +36,7 @@ async fn main() { }; if let Err(problem) = izlek_core::store::reconcile( &config.database.to_string_lossy(), + Some(config.storage.as_path()), izlek_core::store::ReconcileOptions { dry_run, yes, @@ -88,11 +89,17 @@ async fn main() { }; println!("izlek {stylesheet}"); + // Attachments and profile photos are files beside the database now, not + // bytes in a table. The tree is made before the store opens, because the + // reconcile an old database triggers on the way extracts every blob into + // it. + ensure_storage_tree(&config.storage); + // One process per database file: Turso is a single-writer engine and a // second process on the same file loses writes rather than queueing. // // `open` applies any unapplied migration before it returns. - let store = TursoStore::open(&config.database.to_string_lossy()) + let store = TursoStore::open(&config.database.to_string_lossy(), &config.storage) .await .expect("failed to open the database"); let store: Arc = Arc::new(store); @@ -154,6 +161,34 @@ async fn main() { .expect("server error"); } +/// Makes the storage tree the store keeps binary files in, if it is not +/// there: `/attachments` and `/photos`, private to the user +/// the process runs as. A directory that exists is left exactly as it is; one +/// that cannot be made stops the boot — the failure this prevents is a +/// rebuild extracting blobs into a tree that is not there, and it is better +/// met before anything is opened. +fn ensure_storage_tree(storage: &std::path::Path) { + let make = |dir: &std::path::Path| { + if let Err(err) = std::fs::create_dir_all(dir) { + eprintln!("izlek: could not create {}: {err}", dir.display()); + std::process::exit(2); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if let Err(err) = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)) + { + eprintln!("izlek: could not restrict {}: {err}", dir.display()); + std::process::exit(2); + } + } + }; + make(storage); + for name in ["attachments", "photos"] { + make(&storage.join(name)); + } +} + /// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a /// service manager. async fn shutdown_signal() { diff --git a/crates/izlek-web/tests/http.rs b/crates/izlek-web/tests/http.rs index d8bba0f..7089d31 100644 --- a/crates/izlek-web/tests/http.rs +++ b/crates/izlek-web/tests/http.rs @@ -67,7 +67,7 @@ impl App { let dir = std::env::temp_dir().join(format!("izlek-http-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let store: Arc = Arc::new( - TursoStore::open(dir.join("izlek.db").to_str().unwrap()) + TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage")) .await .unwrap(), ); @@ -109,7 +109,7 @@ impl App { let dir = std::env::temp_dir().join(format!("izlek-http-{}", Ulid::new())); std::fs::create_dir_all(&dir).unwrap(); let store: Arc = Arc::new( - TursoStore::open(dir.join("izlek.db").to_str().unwrap()) + TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage")) .await .unwrap(), );