forge
Explore
Log in

Don't you dare go Hollow

Binary leaves the database: attachments and photos live as files

Browse files at this commit

bcf7ceb6eef9145a3eceb9b910f70bb87df36061Ahmet Kaan GümüşParent: 152e905
attachment.bytes and user.photo columns are gone from the declared
schema; bytes live at <storage>/attachments/<id> and
<storage>/photos/<user-id>, 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.

12 changed files +1188 -193

.gitignoremodified+1 -0
@@ -3,6 +3,7 @@
3 /style/main.css3 /style/main.css
4 *.db4 *.db
5 *.db-*5 *.db-*
6+/storage
6 .env7 .env
7 izlek.key8 izlek.key
8 /config/izlek.toml9 /config/izlek.toml
Cargo.lockmodified+1 -0
@@ -1789,6 +1789,7 @@ dependencies = [
1789 "serde_json",1789 "serde_json",
1790 "sha2 0.11.0",1790 "sha2 0.11.0",
1791 "subtle",1791 "subtle",
1792+ "tempfile",
1792 "thiserror",1793 "thiserror",
1793 "time",1794 "time",
1794 "tokio",1795 "tokio",
crates/izlek-core/Cargo.tomlmodified+1 -0
@@ -45,4 +45,5 @@ ulid = { workspace = true, optional = true }
45 async-trait = "0.1.92"45 async-trait = "0.1.92"
46 serde_json.workspace = true46 serde_json.workspace = true
47 tokio = { workspace = true }47 tokio = { workspace = true }
48+tempfile = "3"
48 zip.workspace = true49 zip.workspace = true
crates/izlek-core/migrations/0001_init.sqlmodified+12 -11
@@ -101,9 +101,9 @@ CREATE TABLE user (
101 theme TEXT NOT NULL DEFAULT 'light',101 theme TEXT NOT NULL DEFAULT 'light',
102 language TEXT NOT NULL DEFAULT 'en',102 language TEXT NOT NULL DEFAULT 'en',
103 ui TEXT NOT NULL DEFAULT 'instrument',103 ui TEXT NOT NULL DEFAULT 'instrument',
104- -- The profile picture lives here as bytes, the way an attachment does:104+ -- The profile picture lives as a file under the storage directory, at
105- -- no filesystem path survives a backup or a move.105+ -- `<storage>/photos/<user-id>`, the way an attachment does — this column
106- photo BLOB,106+ -- only marks that one is there.
107 photo_mime TEXT,107 photo_mime TEXT,
108 created_at TEXT NOT NULL,108 created_at TEXT NOT NULL,
109 last_signed_in_at TEXT,109 last_signed_in_at TEXT,
@@ -280,14 +280,16 @@ CREATE TABLE comment (
280 );280 );
281 CREATE INDEX comment_by_task ON comment(task_id);281 CREATE INDEX comment_by_task ON comment(task_id);
282 282
283--- Attachments live in the database file, not on disk beside it.283+-- Attachments live as files under the storage directory, not in this table.
284 --284 --
285--- Izlek is one process over one file, and a second place to keep state is a285+-- One row, one file: the bytes sit at `<storage>/attachments/<id>`, named by
286--- second thing to back up, to lock, and to get out of step with the rows that286+-- the row's own id, and profile photos keep theirs at
287--- name it. And a path is exactly where an uploaded file name must never end287+-- `<storage>/photos/<user-id>` the same way. The directory is state the same
288--- up: `../../etc` is a valid file name and a terrible path. Keeping the bytes288+-- way the database file is — back the two up together, and boot deletes any
289--- here means `file_name` is only ever a label printed on a chip, never289+-- file no row names. And a path is still exactly where an uploaded file name
290--- anything the server resolves.290+-- must never end up: `../../etc` is a valid file name and a terrible path, so
291+-- `file_name` remains a label printed on a chip; the file a row names is
292+-- found by its id alone, never resolved from anything the row was given.
291 CREATE TABLE attachment (293 CREATE TABLE attachment (
292 id TEXT PRIMARY KEY,294 id TEXT PRIMARY KEY,
293 task_id TEXT NOT NULL REFERENCES task(id),295 task_id TEXT NOT NULL REFERENCES task(id),
@@ -295,7 +297,6 @@ CREATE TABLE attachment (
295 file_name TEXT NOT NULL,297 file_name TEXT NOT NULL,
296 mime_type TEXT NOT NULL,298 mime_type TEXT NOT NULL,
297 size_bytes INTEGER NOT NULL,299 size_bytes INTEGER NOT NULL,
298- bytes BLOB NOT NULL,
299 uploaded_by TEXT NOT NULL REFERENCES user(id),300 uploaded_by TEXT NOT NULL REFERENCES user(id),
300 created_at TEXT NOT NULL301 created_at TEXT NOT NULL
301 );302 );
crates/izlek-core/src/config.rsmodified+133 -22
@@ -47,6 +47,8 @@ const FILE_NAME: &str = "config/izlek.toml";
47 /// defaults, so that a plain `izlek` in an empty directory is one command.47 /// defaults, so that a plain `izlek` in an empty directory is one command.
48 const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One process holds it.48 const DEVELOPMENT_DEFAULTS: &str = r#"# Where the one database file lives. One process holds it.
49 database = "izlek.db"49 database = "izlek.db"
50+# Where attachments and profile photos live as files, created on boot.
51+storage = "storage"
50 # The address the server listens on. Environment variables are ignored —52 # The address the server listens on. Environment variables are ignored —
51 # this is the only thing that decides where İzlek binds. It is also the53 # this is the only thing that decides where İzlek binds. It is also the
52 # address mail links fall back to, until an admin sets one in Settings.54 # address mail links fall back to, until an admin sets one in Settings.
@@ -106,6 +108,7 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[
106 #[derive(Deserialize)]108 #[derive(Deserialize)]
107 struct Toml {109 struct Toml {
108 database: Option<String>,110 database: Option<String>,
111+ storage: Option<String>,
109 listen: Option<String>,112 listen: Option<String>,
110 live_seconds: Option<u64>,113 live_seconds: Option<u64>,
111 #[serde(flatten)]114 #[serde(flatten)]
@@ -117,6 +120,10 @@ struct Toml {
117 pub struct Config {120 pub struct Config {
118 /// The database file, absolute. One process holds it.121 /// The database file, absolute. One process holds it.
119 pub database: PathBuf,122 pub database: PathBuf,
123+ /// Where attachments and profile photos live as files, absolute. Binary
124+ /// never sits in the database: this directory and the database file are
125+ /// backed up together, or not at all.
126+ pub storage: PathBuf,
120 /// The address the server binds. The only source for this — `HOST` and127 /// The address the server binds. The only source for this — `HOST` and
121 /// `PORT` environment variables are never read.128 /// `PORT` environment variables are never read.
122 pub listen: SocketAddr,129 pub listen: SocketAddr,
@@ -186,7 +193,7 @@ impl Config {
186 match std::fs::read_to_string(&path) {193 match std::fs::read_to_string(&path) {
187 Ok(text) => {194 Ok(text) => {
188 let config = Config::parse(&text, dir, false)?;195 let config = Config::parse(&text, dir, false)?;
189- complete(&path, &text);196+ complete(&path, &text, dir);
190 Ok(config)197 Ok(config)
191 }198 }
192 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {199 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
@@ -213,12 +220,19 @@ impl Config {
213 /// The reading itself, against a string — which is how it is tested220 /// The reading itself, against a string — which is how it is tested
214 /// without a test being able to disturb another test's filesystem.221 /// without a test being able to disturb another test's filesystem.
215 pub fn parse(text: &str, dir: &Path, defaulted: bool) -> Result<Config, ConfigError> {222 pub fn parse(text: &str, dir: &Path, defaulted: bool) -> Result<Config, ConfigError> {
216- let toml: Toml =223+ let toml: Toml = toml::from_str(text).map_err(|err| ConfigError::Unparseable {
217- toml::from_str(text).map_err(|err| ConfigError::Unparseable { why: err.to_string() })?;224+ why: err.to_string(),
225+ })?;
218 226
219 let value = |raw: Option<String>| raw.filter(|value| !value.trim().is_empty());227 let value = |raw: Option<String>| raw.filter(|value| !value.trim().is_empty());
220 228
221 let database = value(toml.database).ok_or(ConfigError::Missing("database"))?;229 let database = value(toml.database).ok_or(ConfigError::Missing("database"))?;
230+ let database = absolute(dir, Path::new(&database));
231+
232+ let storage = match value(toml.storage) {
233+ Some(raw) => absolute(dir, Path::new(&raw)),
234+ None => default_storage(&database),
235+ };
222 236
223 let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string());237 let listen = value(toml.listen).unwrap_or_else(|| DEFAULT_LISTEN.to_string());
224 let listen: SocketAddr = listen.parse().map_err(|err| ConfigError::Invalid {238 let listen: SocketAddr = listen.parse().map_err(|err| ConfigError::Invalid {
@@ -239,7 +253,8 @@ impl Config {
239 }253 }
240 254
241 Ok(Config {255 Ok(Config {
242- database: absolute(dir, Path::new(&database)),256+ database,
257+ storage,
243 listen,258 listen,
244 live_seconds,259 live_seconds,
245 ignored: toml.other.into_keys().collect(),260 ignored: toml.other.into_keys().collect(),
@@ -274,7 +289,7 @@ impl Config {
274 pub fn report(&self) -> Vec<String> {289 pub fn report(&self) -> Vec<String> {
275 let mut lines = vec![290 let mut lines = vec![
276 format!("database {}", self.database.display()),291 format!("database {}", self.database.display()),
277- format!("listen {}", self.listen),292+ format!("storage {}", self.storage.display()),
278 format!("mail url {} until an admin sets one", self.listen_url()),293 format!("mail url {} until an admin sets one", self.listen_url()),
279 ];294 ];
280 lines.push("mail the sender is in Settings, not here".to_string());295 lines.push("mail the sender is in Settings, not here".to_string());
@@ -302,12 +317,36 @@ impl Config {
302 /// written is not a reason not to start; the defaults it is missing are the317 /// written is not a reason not to start; the defaults it is missing are the
303 /// ones already in force, so the run is correct either way and the note says318 /// ones already in force, so the run is correct either way and the note says
304 /// what could not be done.319 /// what could not be done.
305-fn complete(path: &Path, text: &str) {320+fn complete(path: &Path, text: &str, base: &Path) {
306- let missing: Vec<&str> = OPTIONAL_KEYS321+ let mut missing: Vec<(&str, String)> = OPTIONAL_KEYS
307 .iter()322 .iter()
308 .filter(|(key, _)| !mentions(text, key))323 .filter(|(key, _)| !mentions(text, key))
309- .map(|(_, block)| *block)324+ .map(|(key, block)| (*key, (*block).to_string()))
310 .collect();325 .collect();
326+ // `storage` has no fixed default to print: a file silent about it derives
327+ // the directory from where `database` points, so the completed line says
328+ // the value this boot actually resolved rather than a placeholder.
329+ if !mentions(text, "storage") {
330+ // The same base `parse` resolves against, or the completed line would
331+ // point somewhere this boot never looks (config/ vs the directory
332+ // the app runs from).
333+ let database: Option<String> = toml::from_str::<Toml>(text)
334+ .ok()
335+ .and_then(|t| t.database)
336+ .filter(|value| !value.trim().is_empty());
337+ let storage = database
338+ .as_deref()
339+ .map(|db| default_storage(&absolute(base, Path::new(db))))
340+ .unwrap_or_else(|| PathBuf::from("storage"));
341+ missing.push((
342+ "storage",
343+ format!(
344+ "# Where attachments and profile photos live as files, created on boot.\n\
345+ storage = {:?}\n",
346+ storage.display().to_string()
347+ ),
348+ ));
349+ }
311 if missing.is_empty() {350 if missing.is_empty() {
312 return;351 return;
313 }352 }
@@ -316,13 +355,18 @@ fn complete(path: &Path, text: &str) {
316 completed.push('\n');355 completed.push('\n');
317 }356 }
318 completed.push('\n');357 completed.push('\n');
319- completed.push_str(&missing.join("\n"));358+ completed.push_str(
359+ &missing
360+ .iter()
361+ .map(|(_, block)| block.as_str())
362+ .collect::<Vec<_>>()
363+ .join("\n"),
364+ );
320 match std::fs::write(path, completed) {365 match std::fs::write(path, completed) {
321 Ok(()) => println!(366 Ok(()) => println!(
322 "izlek added {} to {FILE_NAME}, at the default already in use",367 "izlek added {} to {FILE_NAME}, at the default already in use",
323- OPTIONAL_KEYS368+ missing
324 .iter()369 .iter()
325- .filter(|(key, _)| !mentions(text, key))
326 .map(|(key, _)| *key)370 .map(|(key, _)| *key)
327 .collect::<Vec<_>>()371 .collect::<Vec<_>>()
328 .join(", ")372 .join(", ")
@@ -341,6 +385,17 @@ fn mentions(text: &str, key: &str) -> bool {
341 })385 })
342 }386 }
343 387
388+/// Where binary files live when the file is silent about it: beside the
389+/// database file. The two are one backup unit — a backup that takes the
390+/// database but not the files beside it restores a board whose attachments
391+/// and photos are gone — so the default keeps them siblings.
392+fn default_storage(database: &Path) -> PathBuf {
393+ database
394+ .parent()
395+ .map(|parent| parent.join("storage"))
396+ .unwrap_or_else(|| PathBuf::from("storage"))
397+}
398+
344 /// An absolute path for a file that may not exist yet: the directory is399 /// An absolute path for a file that may not exist yet: the directory is
345 /// resolved against `base` (the directory `config/izlek.toml` was read400 /// resolved against `base` (the directory `config/izlek.toml` was read
346 /// from), the file name is kept as written.401 /// from), the file name is kept as written.
@@ -399,7 +454,13 @@ mod tests {
399 // A second load reads the file it just wrote, identically.454 // A second load reads the file it just wrote, identically.
400 let again = Config::load_from(&dir).unwrap();455 let again = Config::load_from(&dir).unwrap();
401 assert!(!again.defaulted);456 assert!(!again.defaulted);
402- assert_eq!(again, Config { defaulted: false, ..config });457+ assert_eq!(
458+ again,
459+ Config {
460+ defaulted: false,
461+ ..config
462+ }
463+ );
403 let _ = std::fs::remove_dir_all(&dir);464 let _ = std::fs::remove_dir_all(&dir);
404 }465 }
405 466
@@ -421,12 +482,23 @@ mod tests {
421 482
422 let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap();483 let written = std::fs::read_to_string(dir.join(FILE_NAME)).unwrap();
423 assert!(written.contains("listen = \"127.0.0.1:7654\""), "{written}");484 assert!(written.contains("listen = \"127.0.0.1:7654\""), "{written}");
485+ // `storage` has no literal default: the completed line is where the
486+ // file's own `database` put it — beside `state/izlek.db` here.
487+ assert!(written.contains("storage = "), "{written}");
424 // What was there is untouched, comment and all.488 // What was there is untouched, comment and all.
425- assert!(written.starts_with("# mine\ndatabase = \"state/izlek.db\"\n"), "{written}");489+ assert!(
490+ written.starts_with("# mine\ndatabase = \"state/izlek.db\"\n"),
491+ "{written}"
492+ );
426 493
427- // Completing is not rewriting: a second load leaves the file alone.494+ // Completing is not rewriting: a second load leaves the file alone,
428- Config::load_from(&dir).unwrap();495+ // and reads the completed key as the default already in use.
429- assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), written);496+ let again = Config::load_from(&dir).unwrap();
497+ assert_eq!(again.storage, config.storage);
498+ assert_eq!(
499+ std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(),
500+ written
501+ );
430 let _ = std::fs::remove_dir_all(&dir);502 let _ = std::fs::remove_dir_all(&dir);
431 }503 }
432 504
@@ -435,16 +507,49 @@ mod tests {
435 fn completion_leaves_a_key_that_is_already_there() {507 fn completion_leaves_a_key_that_is_already_there() {
436 let dir = scratch();508 let dir = scratch();
437 std::fs::create_dir_all(dir.join("config")).unwrap();509 std::fs::create_dir_all(dir.join("config")).unwrap();
438- let mine =510+ let mine = "database = \"izlek.db\"\nstorage = \"files\"\n\
439- "database = \"izlek.db\"\nlisten = \"0.0.0.0:8080\"\nlive_seconds = 30\n";511+ listen = \"0.0.0.0:8080\"\nlive_seconds = 30\n";
440 std::fs::write(dir.join(FILE_NAME), mine).unwrap();512 std::fs::write(dir.join(FILE_NAME), mine).unwrap();
441 let config = Config::load_from(&dir).unwrap();513 let config = Config::load_from(&dir).unwrap();
442 assert_eq!(config.listen, "0.0.0.0:8080".parse().unwrap());514 assert_eq!(config.listen, "0.0.0.0:8080".parse().unwrap());
443 assert_eq!(config.live_seconds, 30);515 assert_eq!(config.live_seconds, 30);
516+ assert!(config.storage.ends_with("files"), "{:?}", config.storage);
444 assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), mine);517 assert_eq!(std::fs::read_to_string(dir.join(FILE_NAME)).unwrap(), mine);
445 let _ = std::fs::remove_dir_all(&dir);518 let _ = std::fs::remove_dir_all(&dir);
446 }519 }
447 520
521+ /// Binary lives where the file says, or — when it says nothing — beside
522+ /// the database, so a backup that takes the database takes the files.
523+ #[test]
524+ fn a_file_without_storage_puts_it_beside_the_database() {
525+ let config = Config::parse(
526+ "database = \"/srv/izlek/izlek.db\"\n",
527+ Path::new("."),
528+ false,
529+ )
530+ .unwrap();
531+ assert_eq!(config.storage, PathBuf::from("/srv/izlek/storage"));
532+ }
533+
534+ /// An explicit storage is taken absolute, the way the database is.
535+ #[test]
536+ fn a_relative_storage_is_reported_absolute() {
537+ let dir = scratch();
538+ let config = Config::parse(
539+ "database = \"izlek.db\"\nstorage = \"state/files\"\n",
540+ &dir,
541+ false,
542+ )
543+ .unwrap();
544+ assert!(config.storage.is_absolute(), "{:?}", config.storage);
545+ assert!(
546+ config.storage.ends_with("state/files"),
547+ "{:?}",
548+ config.storage
549+ );
550+ let _ = std::fs::remove_dir_all(&dir);
551+ }
552+
448 /// A live connection that expires instantly is a reconnect loop, so the553 /// A live connection that expires instantly is a reconnect loop, so the
449 /// key is refused rather than silently corrected.554 /// key is refused rather than silently corrected.
450 #[test]555 #[test]
@@ -456,7 +561,13 @@ mod tests {
456 )561 )
457 .unwrap_err();562 .unwrap_err();
458 assert!(563 assert!(
459- matches!(problem, ConfigError::Invalid { key: "live_seconds", .. }),564+ matches!(
565+ problem,
566+ ConfigError::Invalid {
567+ key: "live_seconds",
568+ ..
569+ }
570+ ),
460 "{problem:?}"571 "{problem:?}"
461 );572 );
462 }573 }
@@ -464,8 +575,7 @@ mod tests {
464 /// A file that never mentions the key still boots, on the default.575 /// A file that never mentions the key still boots, on the default.
465 #[test]576 #[test]
466 fn a_file_without_a_live_window_takes_the_default() {577 fn a_file_without_a_live_window_takes_the_default() {
467- let config =578+ let config = Config::parse("database = \"izlek.db\"\n", Path::new("."), false).unwrap();
468- Config::parse("database = \"izlek.db\"\n", Path::new("."), false).unwrap();
469 assert_eq!(config.live_seconds, 300);579 assert_eq!(config.live_seconds, 300);
470 }580 }
471 581
@@ -514,7 +624,8 @@ mod tests {
514 /// default it is about to be completed with.624 /// default it is about to be completed with.
515 #[test]625 #[test]
516 fn a_file_without_listen_takes_the_default() {626 fn a_file_without_listen_takes_the_default() {
517- let config = Config::parse("database = \"/srv/izlek.db\"\n", Path::new("."), false).unwrap();627+ let config =
628+ Config::parse("database = \"/srv/izlek.db\"\n", Path::new("."), false).unwrap();
518 assert_eq!(config.listen, "127.0.0.1:7654".parse().unwrap());629 assert_eq!(config.listen, "127.0.0.1:7654".parse().unwrap());
519 }630 }
520 631
crates/izlek-core/src/store/mod.rsmodified+7 -4
@@ -115,7 +115,8 @@ pub struct Attachment {
115 pub uploaded_at: OffsetDateTime,115 pub uploaded_at: OffsetDateTime,
116 }116 }
117 117
118-/// A file on its way into the table, bytes and all.118+/// A file on its way into the store, bytes and all: the row goes to the
119+/// database, the bytes to the storage tree beside it.
119 #[derive(Debug, Clone, PartialEq, Eq)]120 #[derive(Debug, Clone, PartialEq, Eq)]
120 pub struct NewAttachment<'a> {121 pub struct NewAttachment<'a> {
121 pub task_id: &'a str,122 pub task_id: &'a str,
@@ -982,9 +983,11 @@ pub trait Store: BoardReads + DetailReads + 'static {
982 at: OffsetDateTime,983 at: OffsetDateTime,
983 ) -> Result<CommentWritten>;984 ) -> Result<CommentWritten>;
984 985
985- /// Hangs a file off a task. The bytes go into the database file with the986+ /// Hangs a file off a task. The bytes go to the storage tree, at
986- /// row: there is no second place for an İzlek deployment to keep, and no987+ /// `<storage>/attachments/<id>`, named by the row's own id — never by
987- /// path for an uploaded name to become.988+ /// anything an upload carried, so an uploaded name cannot become a path.
989+ /// The database keeps the row; the directory keeps the bytes; back the
990+ /// two up together.
988 ///991 ///
989 /// Nothing here decides whether the file was allowed — its size, its type992 /// Nothing here decides whether the file was allowed — its size, its type
990 /// and who may attach it are the handler's questions, answered before the993 /// and who may attach it are the handler's questions, answered before the
crates/izlek-core/src/store/reconcile.rsmodified+278 -7
@@ -4,6 +4,13 @@
4 //! `migrations/0001_init.sql`, the data is copied with an explicit per-table4 //! `migrations/0001_init.sql`, the data is copied with an explicit per-table
5 //! column map, the copy is verified, and only then the files are swapped. The5 //! column map, the copy is verified, and only then the files are swapped. The
6 //! original file is kept as a timestamped backup and is never deleted.6 //! original file is kept as a timestamped backup and is never deleted.
7+//!
8+//! Binary is the one thing that does not travel with the copy. A database of
9+//! an older shape keeps attachment bytes and profile photos inside its
10+//! tables, and the declared schema has no column for them: when such columns
11+//! exist, every blob is written to the storage directory, keyed by its id,
12+//! while the rebuild runs. An extraction failure fails the rebuild, so the
13+//! swap never trades the tables' binary for a directory that is not there.
7 14
8 use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint};15 use super::schema::{SCHEMA, declared_fingerprint, diff_report, fingerprint};
9 use super::{Result, StoreError};16 use super::{Result, StoreError};
@@ -25,9 +32,17 @@ pub struct ReconcileOptions {
25 /// - Empty or already-current databases are a no-op.32 /// - Empty or already-current databases are a no-op.
26 /// - A differing database is backed up, rebuilt, verified and swapped into33 /// - A differing database is backed up, rebuilt, verified and swapped into
27 /// place.34 /// place.
35+/// - A database that still keeps binary in its tables has it extracted to
36+/// `storage`'s `attachments` and `photos` subdirectories during the
37+/// rebuild. `None` is accepted only when there is nothing to extract: a
38+/// caller with nowhere to put files must not quietly drop them.
28 /// - A rebuild that fails verification deletes the `.rebuilt` file and leaves39 /// - A rebuild that fails verification deletes the `.rebuilt` file and leaves
29 /// the original untouched.40 /// the original untouched.
30-pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> {41+pub async fn reconcile(
42+ path: &str,
43+ storage: Option<&std::path::Path>,
44+ opts: ReconcileOptions,
45+) -> Result<()> {
31 if path == ":memory:" {46 if path == ":memory:" {
32 return Err(StoreError::Backend(47 return Err(StoreError::Backend(
33 "reconcile is not meaningful on an in-memory database".into(),48 "reconcile is not meaningful on an in-memory database".into(),
@@ -87,7 +102,7 @@ pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> {
87 let rebuilt_path = format!("{}.rebuilt", path);102 let rebuilt_path = format!("{}.rebuilt", path);
88 cleanup_rebuilt(&rebuilt_path);103 cleanup_rebuilt(&rebuilt_path);
89 104
90- let result = rebuild(path, &rebuilt_path, &old_conn).await;105+ let result = rebuild(path, &rebuilt_path, &old_conn, storage).await;
91 106
92 // Close the read-only connection before any file moves; this also107 // Close the read-only connection before any file moves; this also
93 // releases the WAL locks on the original file.108 // releases the WAL locks on the original file.
@@ -147,7 +162,12 @@ pub async fn reconcile(path: &str, opts: ReconcileOptions) -> Result<()> {
147 /// a default tag for any board that comes across with none), and verifies162 /// a default tag for any board that comes across with none), and verifies
148 /// the result. On success the rebuilt file is complete and checkpointed; on163 /// the result. On success the rebuilt file is complete and checkpointed; on
149 /// failure the caller deletes it.164 /// failure the caller deletes it.
150-async fn rebuild(path: &str, rebuilt_path: &str, old_conn: &Connection) -> Result<()> {165+async fn rebuild(
166+ path: &str,
167+ rebuilt_path: &str,
168+ old_conn: &Connection,
169+ storage: Option<&std::path::Path>,
170+) -> Result<()> {
151 // The copy runs as `INSERT ... SELECT FROM old.<table>`, which needs171 // The copy runs as `INSERT ... SELECT FROM old.<table>`, which needs
152 // ATTACH — still gated in this engine, and switched on only here, for the172 // ATTACH — still gated in this engine, and switched on only here, for the
153 // one connection that does the rebuild. The verification afterwards is173 // 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
169 .execute_batch(SCHEMA)189 .execute_batch(SCHEMA)
170 .await190 .await
171 .map_err(|e| StoreError::Backend(e.to_string()))?;191 .map_err(|e| StoreError::Backend(e.to_string()))?;
192+ // The blobs leave the old database before any row is copied: the copy's
193+ // maps have no column to carry them, so this is the one moment to secure
194+ // them. A failure here fails the whole rebuild, and the original file
195+ // stays exactly as it was.
196+ extract_blobs(old_conn, storage).await?;
172 197
173 copy_data(old_conn, &new_conn, path).await?;198 copy_data(old_conn, &new_conn, path).await?;
174 verify(old_conn, &new_conn).await?;199 verify(old_conn, &new_conn).await?;
@@ -337,7 +362,10 @@ fn build_maps(
337 "theme",362 "theme",
338 "language",363 "language",
339 "ui",364 "ui",
340- "photo",365+ // `photo` is deliberately unmapped: the bytes do not travel
366+ // with the copy. `extract_blobs` wrote each one to the
367+ // storage directory under the user's id; the mime type is
368+ // metadata and stays with the row.
341 "photo_mime",369 "photo_mime",
342 "created_at",370 "created_at",
343 "last_signed_in_at",371 "last_signed_in_at",
@@ -482,6 +510,9 @@ fn build_maps(
482 });510 });
483 maps.push(TableMap {511 maps.push(TableMap {
484 name: "attachment",512 name: "attachment",
513+ // `bytes` is deliberately unmapped: the file's contents live under
514+ // the storage directory now, and `extract_blobs` wrote each one
515+ // there before this copy ran. The row keeps only the metadata.
485 columns: old_cols(&[516 columns: old_cols(&[
486 "id",517 "id",
487 "task_id",518 "task_id",
@@ -489,7 +520,6 @@ fn build_maps(
489 "file_name",520 "file_name",
490 "mime_type",521 "mime_type",
491 "size_bytes",522 "size_bytes",
492- "bytes",
493 "uploaded_by",523 "uploaded_by",
494 "created_at",524 "created_at",
495 ]),525 ]),
@@ -581,6 +611,81 @@ fn old_cols(cols: &[&'static str]) -> Vec<(&'static str, String)> {
581 cols.iter().map(|c| (*c, format!("old.{}", c))).collect()611 cols.iter().map(|c| (*c, format!("old.{}", c))).collect()
582 }612 }
583 613
614+/// Writes every blob the old schema still carried to the storage directory,
615+/// before any row is copied: attachments under `<storage>/attachments/<id>`,
616+/// profile photos under `<storage>/photos/<user id>`. Each file goes down
617+/// through a temp name in its own directory and a rename, so a crash
618+/// mid-write never leaves a half file wearing a real name, and a name an
619+/// earlier failed attempt left behind is simply overwritten.
620+async fn extract_blobs(old_conn: &Connection, storage: Option<&std::path::Path>) -> Result<()> {
621+ let has_bytes = old_has_column(old_conn, "attachment", "bytes").await?;
622+ let has_photo = old_has_column(old_conn, "user", "photo").await?;
623+ if (has_bytes || has_photo) && storage.is_none() {
624+ return Err(StoreError::Backend(
625+ "the old schema keeps binary in its tables but no storage directory \
626+ was given; the rebuild would drop it"
627+ .into(),
628+ ));
629+ }
630+ let Some(storage) = storage else {
631+ return Ok(());
632+ };
633+ if has_bytes {
634+ extract_column(old_conn, &storage.join("attachments"), "attachment", "bytes").await?;
635+ }
636+ if has_photo {
637+ extract_column(old_conn, &storage.join("photos"), "user", "photo").await?;
638+ }
639+ Ok(())
640+}
641+
642+/// Reads `<table>.<column>` row by row and writes each value to `<dir>/<row
643+/// id>`. NULLs are skipped — a photo that was cleared carried no bytes and
644+/// leaves no file. The directory is made if missing, so a storage root that
645+/// predates the boot's own creation still holds together. Any failure stops
646+/// the rebuild.
647+async fn extract_column(
648+ old_conn: &Connection,
649+ dir: &std::path::Path,
650+ table: &str,
651+ column: &str,
652+) -> Result<()> {
653+ std::fs::create_dir_all(dir)
654+ .map_err(|e| StoreError::Backend(format!("could not create {}: {e}", dir.display())))?;
655+ let sql = format!("SELECT id, {column} FROM {table} WHERE {column} IS NOT NULL");
656+ let mut rows = old_conn
657+ .query(&sql, ())
658+ .await
659+ .map_err(|e| StoreError::Backend(e.to_string()))?;
660+ while let Some(row) = rows
661+ .next()
662+ .await
663+ .map_err(|e| StoreError::Backend(e.to_string()))?
664+ {
665+ let id: String = row.get(0).map_err(|e| StoreError::Backend(e.to_string()))?;
666+ let bytes: Vec<u8> = row.get(1).map_err(|e| StoreError::Backend(e.to_string()))?;
667+ write_blob(dir, &id, &bytes).map_err(|e| {
668+ StoreError::Backend(format!("extracting {table}.{column} for {id}: {e}"))
669+ })?;
670+ }
671+ Ok(())
672+}
673+
674+/// One blob, one file: written to a temp name in the target directory and
675+/// renamed onto the final name, so a reader of the final name never sees a
676+/// partial file.
677+fn write_blob(dir: &std::path::Path, id: &str, bytes: &[u8]) -> std::io::Result<()> {
678+ let temp = dir.join(format!(".{}.tmp-{}", id, Ulid::new()));
679+ std::fs::write(&temp, bytes)?;
680+ match std::fs::rename(&temp, dir.join(id)) {
681+ Ok(()) => Ok(()),
682+ Err(err) => {
683+ let _ = std::fs::remove_file(&temp);
684+ Err(err)
685+ }
686+ }
687+}
688+
584 /// Returns true if the attached old `workspace` table already carries the689 /// Returns true if the attached old `workspace` table already carries the
585 /// sender-check columns added by the old 0002 migration.690 /// sender-check columns added by the old 0002 migration.
586 async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {691 async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result<bool> {
@@ -962,8 +1067,11 @@ fn backup_name(path: &str) -> Result<String> {
962 1067
963 #[cfg(test)]1068 #[cfg(test)]
964 mod tests {1069 mod tests {
965- use super::{TableMap, backup_name, build_maps, validate_maps};1070+ use super::{
966- use turso::Builder;1071+ ReconcileOptions, TableMap, backup_name, build_maps, old_has_column, reconcile,
1072+ validate_maps,
1073+ };
1074+ use turso::{Builder, params};
967 use ulid::Ulid;1075 use ulid::Ulid;
968 use crate::store::schema::SCHEMA;1076 use crate::store::schema::SCHEMA;
969 1077
@@ -1015,4 +1123,167 @@ mod tests {
1015 let _ = std::fs::remove_dir_all(&dir);1123 let _ = std::fs::remove_dir_all(&dir);
1016 }1124 }
1017 1125
1126+ /// Writes an old-shape database at `path`: the declared schema, plus the
1127+ /// two blob columns the swap removed, holding one attachment and two
1128+ /// users — one photographed, one not. Returns the bytes it planted.
1129+ async fn old_shape_database(path: &str) -> (Vec<u8>, Vec<u8>) {
1130+ let attachment_bytes = b"file-bytes".to_vec();
1131+ let photo_bytes = b"face-bytes".to_vec();
1132+ let db = Builder::new_local(path).build().await.unwrap();
1133+ let conn = db.connect().unwrap();
1134+ conn.execute_batch(SCHEMA).await.unwrap();
1135+ // ALTER keeps the tables' own constraints intact, so this is the
1136+ // shape a live database of the previous generation has.
1137+ conn.execute(
1138+ "ALTER TABLE attachment ADD COLUMN bytes BLOB NOT NULL DEFAULT x''",
1139+ (),
1140+ )
1141+ .await
1142+ .unwrap();
1143+ conn.execute("ALTER TABLE user ADD COLUMN photo BLOB", ())
1144+ .await
1145+ .unwrap();
1146+ let now = "2026-01-01T00:00:00Z";
1147+ conn.execute(
1148+ "INSERT INTO user (id, workspace_id, email, display_name, role, photo_mime, photo, \
1149+ created_at) \
1150+ VALUES ('U1', 'W1', 'one@izlek.sh', 'One', 'admin', 'image/png', ?1, ?2)",
1151+ params![&photo_bytes[..], now],
1152+ )
1153+ .await
1154+ .unwrap();
1155+ conn.execute(
1156+ "INSERT INTO user (id, workspace_id, email, display_name, role, created_at) \
1157+ VALUES ('U2', 'W1', 'two@izlek.sh', 'Two', 'member', ?1)",
1158+ params![now],
1159+ )
1160+ .await
1161+ .unwrap();
1162+ conn.execute(
1163+ "INSERT INTO workspace (id, name, created_at) VALUES ('W1', 'Dizey', ?1)",
1164+ params![now],
1165+ )
1166+ .await
1167+ .unwrap();
1168+ conn.execute(
1169+ "INSERT INTO board (id, workspace_id, name, created_at) \
1170+ VALUES ('B1', 'W1', 'Board', ?1)",
1171+ params![now],
1172+ )
1173+ .await
1174+ .unwrap();
1175+ conn.execute(
1176+ "INSERT INTO tag (id, board_id, name, position, is_default, created_at) \
1177+ VALUES ('TG1', 'B1', 'General', 0, 1, ?1)",
1178+ params![now],
1179+ )
1180+ .await
1181+ .unwrap();
1182+ conn.execute(
1183+ "INSERT INTO board_column (id, board_id, name, position) \
1184+ VALUES ('C1', 'B1', 'Backlog', 0)",
1185+ (),
1186+ )
1187+ .await
1188+ .unwrap();
1189+ conn.execute(
1190+ "INSERT INTO task (id, board_id, task_key, title, column_id, tag_id, created_by, \
1191+ created_at, updated_at) \
1192+ VALUES ('T1', 'B1', 'DZ-1', 'a task', 'C1', 'TG1', 'U1', ?1, ?1)",
1193+ params![now],
1194+ )
1195+ .await
1196+ .unwrap();
1197+ conn.execute(
1198+ "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, bytes, \
1199+ uploaded_by, created_at) \
1200+ VALUES ('F1', 'T1', 'a.bin', 'application/octet-stream', ?1, ?2, 'U1', ?3)",
1201+ params![attachment_bytes.len() as i64, &attachment_bytes[..], now],
1202+ )
1203+ .await
1204+ .unwrap();
1205+ (attachment_bytes, photo_bytes)
1206+ }
1207+
1208+ /// An old-shape database rebuilds with its binary outside the tables: one
1209+ /// file per attachment under `attachments/`, one per photographed user
1210+ /// under `photos/`, byte-identical, and the rebuilt tables carry neither
1211+ /// column any more.
1212+ #[tokio::test]
1213+ async fn an_old_shaped_database_extracts_its_blobs_to_the_storage_dir() {
1214+ let dir = std::env::temp_dir().join(format!("izlek-reconcile-{}", Ulid::new()));
1215+ std::fs::create_dir_all(&dir).unwrap();
1216+ let path = dir.join("izlek.db").to_str().unwrap().to_string();
1217+ let (attachment_bytes, photo_bytes) = old_shape_database(&path).await;
1218+
1219+ let storage = dir.join("storage");
1220+ reconcile(
1221+ &path,
1222+ Some(storage.as_path()),
1223+ ReconcileOptions {
1224+ dry_run: false,
1225+ yes: true,
1226+ auto: true,
1227+ },
1228+ )
1229+ .await
1230+ .expect("the rebuild with extraction failed");
1231+
1232+ assert_eq!(
1233+ std::fs::read(storage.join("attachments").join("F1")).unwrap(),
1234+ attachment_bytes
1235+ );
1236+ assert_eq!(
1237+ std::fs::read(storage.join("photos").join("U1")).unwrap(),
1238+ photo_bytes
1239+ );
1240+ // A photo that was never set carried no bytes and leaves no file.
1241+ assert!(!storage.join("photos").join("U2").exists());
1242+
1243+ let db = Builder::new_local(&path).build().await.unwrap();
1244+ let conn = db.connect().unwrap();
1245+ assert!(
1246+ !old_has_column(&conn, "attachment", "bytes").await.unwrap(),
1247+ "the rebuilt attachment table still carries bytes"
1248+ );
1249+ assert!(
1250+ !old_has_column(&conn, "user", "photo").await.unwrap(),
1251+ "the rebuilt user table still carries photo"
1252+ );
1253+ drop(conn);
1254+ drop(db);
1255+ let _ = std::fs::remove_dir_all(&dir);
1256+ }
1257+
1258+ /// Rebuilding an old-shape database with nowhere to put the binary is
1259+ /// refused rather than dropping every blob on the floor, and the refusal
1260+ /// leaves the original file in place with nothing staged beside it.
1261+ #[tokio::test]
1262+ async fn a_rebuild_without_storage_refuses_to_drop_blobs() {
1263+ let dir = std::env::temp_dir().join(format!("izlek-reconcile-{}", Ulid::new()));
1264+ std::fs::create_dir_all(&dir).unwrap();
1265+ let path = dir.join("izlek.db").to_str().unwrap().to_string();
1266+ old_shape_database(&path).await;
1267+
1268+ let err = reconcile(
1269+ &path,
1270+ None,
1271+ ReconcileOptions {
1272+ dry_run: false,
1273+ yes: true,
1274+ auto: true,
1275+ },
1276+ )
1277+ .await
1278+ .expect_err("a rebuild that would drop binary passed");
1279+ assert!(err.to_string().contains("storage"), "{err}");
1280+ assert!(std::path::Path::new(&path).exists());
1281+ let leftovers: Vec<String> = std::fs::read_dir(&dir)
1282+ .unwrap()
1283+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
1284+ .filter(|name| name.contains(".backup-") || name.ends_with(".rebuilt"))
1285+ .collect();
1286+ assert!(leftovers.is_empty(), "{leftovers:?}");
1287+ let _ = std::fs::remove_dir_all(&dir);
1288+ }
1018 }1289 }
crates/izlek-core/src/store/turso_store.rsmodified+603 -84
@@ -7,8 +7,8 @@
7 7
8 use async_trait::async_trait;8 use async_trait::async_trait;
9 use rand::Rng;9 use rand::Rng;
10-use time::{Duration, OffsetDateTime};
11 use time::format_description::well_known::Rfc3339;10 use time::format_description::well_known::Rfc3339;
11+use time::{Duration, OffsetDateTime};
12 use turso::transaction::{Transaction, TransactionBehavior};12 use turso::transaction::{Transaction, TransactionBehavior};
13 use turso::{Builder, Connection, Row, Value, params, params_from_iter};13 use turso::{Builder, Connection, Row, Value, params, params_from_iter};
14 use ulid::Ulid;14 use ulid::Ulid;
@@ -16,12 +16,12 @@ use ulid::Ulid;
16 use super::secret;16 use super::secret;
17 use super::{17 use super::{
18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten,18 ActivityEvent, ActivityFilter, ActivityLine, Attachment, Audience, ClaimedSend, CommentWritten,
19- Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, MailDecision, MailOutcome, MailRule,19+ Deletion, Dir, Event, FeedCursor, FeedPage, Freeing, LinkKind, MailDecision, MailOutcome,
20- MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, SendState,20+ MailRule, MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind,
21- SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated, Trigger,21+ SendState, SenderCheck, SenderTest, Session, SigninLink, Store, StoreError, Tag, TaskCreated,
22- User, UserStats, Workspace, LinkKind,22+ Trigger, User, UserStats, Workspace,
23 };23 };
24-use super::{reconcile, ReconcileOptions, schema, sniff};24+use super::{ReconcileOptions, reconcile, schema, sniff};
25 use crate::Role;25 use crate::Role;
26 use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition};26 use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TagChip, TaskRow, Transition};
27 use crate::detail::{27 use crate::detail::{
@@ -57,6 +57,12 @@ pub struct TursoStore {
57 /// can hand out a receiver per subscriber; nothing is ever read from here57 /// can hand out a receiver per subscriber; nothing is ever read from here
58 /// by the store itself.58 /// by the store itself.
59 live: tokio::sync::broadcast::Sender<Change>,59 live: tokio::sync::broadcast::Sender<Change>,
60+ /// Root of the file tree the binary payloads live under: `attachments/`
61+ /// for task files, `photos/` for profile pictures, one raw file per row,
62+ /// named by the row's own id. The database keeps the facts and this tree
63+ /// keeps the bytes; a boot sweep deletes whichever half outlives the
64+ /// other.
65+ storage: std::path::PathBuf,
60 }66 }
61 67
62 impl TursoStore {68 impl TursoStore {
@@ -79,13 +85,20 @@ impl TursoStore {
79 }85 }
80 86
81 /// Opens (creating if needed) the database at `path` and brings the schema87 /// Opens (creating if needed) the database at `path` and brings the schema
82- /// up to date. `:memory:` gives a throwaway database for tests.88+ /// up to date. `storage` is the root of the file tree the binary payloads
83- pub async fn open(path: &str) -> Result<Self> {89+ /// (attachment bytes, profile photos) live under — created here if
90+ /// missing. `:memory:` gives a throwaway database for tests, which still
91+ /// hand in a storage directory, usually a tempdir, for the files.
92+ pub async fn open(path: &str, storage: &std::path::Path) -> Result<Self> {
93+ // Before anything else, including the reconcile below that extracts
94+ // old blobs into this tree: a fresh storage path is a normal first
95+ // boot, and every writer past this point assumes the tree is there.
96+ ensure_storage_dirs(storage)?;
84 let existed = path != ":memory:" && std::path::Path::new(path).exists();97 let existed = path != ":memory:" && std::path::Path::new(path).exists();
85 // Before anything holds this file open: a database of an older shape is98 // Before anything holds this file open: a database of an older shape is
86 // rebuilt now, while no handle of ours points at the file that the99 // rebuilt now, while no handle of ours points at the file that the
87 // rebuild is about to replace.100 // rebuild is about to replace.
88- Self::repair_if_stale(path).await?;101+ Self::repair_if_stale(path, storage).await?;
89 let db = Builder::new_local(path).build().await.map_err(backend)?;102 let db = Builder::new_local(path).build().await.map_err(backend)?;
90 let conn = db.connect().map_err(backend)?;103 let conn = db.connect().map_err(backend)?;
91 // Turso is a single-writer engine. Two connections on one Database104 // Turso is a single-writer engine. Two connections on one Database
@@ -121,10 +134,12 @@ impl TursoStore {
121 db,134 db,
122 key,135 key,
123 live,136 live,
137+ storage: storage.to_path_buf(),
124 };138 };
125 store.migrate(path).await?;139 store.migrate(path).await?;
126 store.encrypt_plaintext_passwords().await?;140 store.encrypt_plaintext_passwords().await?;
127 store.resniff_generic_attachments().await?;141 store.resniff_generic_attachments().await?;
142+ store.sweep_orphan_files().await?;
128 // The file may have been rebuilt from a backup; its permissions and143 // The file may have been rebuilt from a backup; its permissions and
129 // any transient WAL/SHM siblings should still be private.144 // any transient WAL/SHM siblings should still be private.
130 if path != ":memory:" {145 if path != ":memory:" {
@@ -187,7 +202,7 @@ impl TursoStore {
187 ///202 ///
188 /// Cheap by design. The pass opens with a count of generic rows and, when203 /// Cheap by design. The pass opens with a count of generic rows and, when
189 /// there are none — every database after one pass, and every database204 /// there are none — every database after one pass, and every database
190- /// whose uploads all postdate the sniffer — reads no blob bytes at all.205+ /// whose uploads all postdate the sniffer — reads no file bytes at all.
191 /// Otherwise each such row donates two windows, the first206 /// Otherwise each such row donates two windows, the first
192 /// [`sniff::HEAD_WINDOW`] and last [`sniff::TAIL_WINDOW`] bytes, and only207 /// [`sniff::HEAD_WINDOW`] and last [`sniff::TAIL_WINDOW`] bytes, and only
193 /// when the windows find a zip with no office marker in them does the row208 /// when the windows find a zip with no office marker in them does the row
@@ -207,7 +222,7 @@ impl TursoStore {
207 let conn = self.conn.lock().await;222 let conn = self.conn.lock().await;
208 223
209 // The existence probe the whole pass hangs off: one count of a short224 // The existence probe the whole pass hangs off: one count of a short
210- // text column, no blob reads, and the common case is done here.225+ // text column, no file reads, and the common case is done here.
211 let mut rows = conn226 let mut rows = conn
212 .query(227 .query(
213 &format!("SELECT COUNT(*) FROM attachment WHERE mime_type IN ({marks})"),228 &format!("SELECT COUNT(*) FROM attachment WHERE mime_type IN ({marks})"),
@@ -226,10 +241,7 @@ impl TursoStore {
226 let mut rows = conn241 let mut rows = conn
227 .query(242 .query(
228 &format!(243 &format!(
229- "SELECT id, mime_type, substr(bytes, 1, {head}), substr(bytes, -{tail}) \244+ "SELECT id, mime_type FROM attachment WHERE mime_type IN ({marks})",
230- FROM attachment WHERE mime_type IN ({marks})",
231- head = sniff::HEAD_WINDOW,
232- tail = sniff::TAIL_WINDOW,
233 marks = marks,245 marks = marks,
234 ),246 ),
235 params_from_iter(buckets.iter().copied()),247 params_from_iter(buckets.iter().copied()),
@@ -240,22 +252,26 @@ impl TursoStore {
240 while let Some(row) = rows.next().await.map_err(backend)? {252 while let Some(row) = rows.next().await.map_err(backend)? {
241 let id = text(&row, 0)?;253 let id = text(&row, 0)?;
242 let stored = text(&row, 1)?;254 let stored = text(&row, 1)?;
243- let head: Vec<u8> = row.get(2).map_err(backend)?;255+ let path = attachment_file(&self.storage, &id);
244- let tail: Vec<u8> = row.get(3).map_err(backend)?;256+ let (head, tail) = match read_windows(&path, sniff::HEAD_WINDOW, sniff::TAIL_WINDOW) {
257+ Ok(windows) => windows,
258+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
259+ eprintln!(
260+ "attachment {id} wears a generic mime but its file is missing; \
261+ leaving it as stored"
262+ );
263+ continue;
264+ }
265+ Err(e) => return Err(backend(e)),
266+ };
245 let candidate = match sniff::refine(&stored, &head, &tail) {267 let candidate = match sniff::refine(&stored, &head, &tail) {
246 sniff::Verdict::Settle(candidate) => candidate,268 sniff::Verdict::Settle(candidate) => candidate,
247 sniff::Verdict::ReadDirectory { offset, size } => {269 sniff::Verdict::ReadDirectory { offset, size } => {
248 let len = size.min(sniff::DIRECTORY_CAP as u64) as i64;270 let len = size.min(sniff::DIRECTORY_CAP as u64) as i64;
249- let mut directory = conn271+ match read_window_at(&path, offset, len) {
250- .query(272+ Ok(directory) => sniff::office_entry_mime(&directory),
251- "SELECT substr(bytes, ?1, ?2) FROM attachment WHERE id = ?3",273+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
252- params![offset as i64 + 1, len, id.clone()],274+ Err(e) => return Err(backend(e)),
253- )
254- .await
255- .map_err(backend)?;
256- match directory.next().await.map_err(backend)? {
257- Some(row) => sniff::office_entry_mime(&row.get::<Vec<u8>>(0).map_err(backend)?),
258- None => None,
259 }275 }
260 }276 }
261 };277 };
@@ -274,6 +290,58 @@ impl TursoStore {
274 Ok(())290 Ok(())
275 }291 }
276 292
293+ /// Sets the storage tree against the database, once per boot, after the
294+ /// resniff. The database and the tree are two halves of one state, and a
295+ /// crash between a row write and its file write — either order — leaves
296+ /// exactly one half behind. A file no row names goes, including a `.tmp`
297+ /// a crash abandoned mid-write; a row whose file is gone is only said
298+ /// out loud and otherwise kept, because deleting the row would turn a
299+ /// lost file into a lost fact — the row is still what screens list, and
300+ /// a re-upload replaces it cleanly.
301+ async fn sweep_orphan_files(&self) -> Result<()> {
302+ let conn = self.conn.lock().await;
303+ let attachments = known_ids(&conn, "SELECT id FROM attachment").await?;
304+ let photos = known_ids(&conn, "SELECT id FROM user WHERE photo_mime IS NOT NULL").await?;
305+ drop(conn);
306+ for (dir, known, kind) in [
307+ (
308+ self.storage.join(ATTACHMENTS_DIR),
309+ &attachments,
310+ "attachment",
311+ ),
312+ (self.storage.join(PHOTOS_DIR), &photos, "photo"),
313+ ] {
314+ for id in known.iter() {
315+ if !dir.join(id).is_file() {
316+ eprintln!("{kind} {id} names a file that is not there");
317+ }
318+ }
319+ let entries = match std::fs::read_dir(&dir) {
320+ Ok(entries) => entries,
321+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
322+ Err(e) => return Err(backend(e)),
323+ };
324+ for entry in entries {
325+ let entry = entry.map_err(backend)?;
326+ let path = entry.path();
327+ if !path.is_file() {
328+ continue;
329+ }
330+ let named = entry
331+ .file_name()
332+ .to_str()
333+ .is_some_and(|n| known.contains(n));
334+ if !named && let Err(e) = std::fs::remove_file(&path) {
335+ eprintln!(
336+ "could not delete orphaned storage file {}: {e}",
337+ path.display()
338+ );
339+ }
340+ }
341+ }
342+ Ok(())
343+ }
344+
277 /// Brings the database to the declared schema.345 /// Brings the database to the declared schema.
278 ///346 ///
279 /// - An empty database is created from `migrations/0001_init.sql`.347 /// - An empty database is created from `migrations/0001_init.sql`.
@@ -295,6 +363,7 @@ impl TursoStore {
295 )363 )
296 .await364 .await
297 .map_err(backend)?;365 .map_err(backend)?;
366+
298 let empty = match rows.next().await.map_err(backend)? {367 let empty = match rows.next().await.map_err(backend)? {
299 Some(row) => row.get::<i64>(0).map_err(backend)? == 0,368 Some(row) => row.get::<i64>(0).map_err(backend)? == 0,
300 None => true,369 None => true,
@@ -307,7 +376,11 @@ impl TursoStore {
307 let _ = conn.execute("ROLLBACK", ()).await;376 let _ = conn.execute("ROLLBACK", ()).await;
308 return Err(backend(e));377 return Err(backend(e));
309 }378 }
310- return conn.execute("COMMIT", ()).await.map_err(backend).map(|_| ());379+ return conn
380+ .execute("COMMIT", ())
381+ .await
382+ .map_err(backend)
383+ .map(|_| ());
311 }384 }
312 385
313 if path == ":memory:" {386 if path == ":memory:" {
@@ -340,7 +413,7 @@ impl TursoStore {
340 /// `turso::Database` opened beforehand still refers to the file that is413 /// `turso::Database` opened beforehand still refers to the file that is
341 /// now the backup. Reconnecting such a handle reads the old database and414 /// now the backup. Reconnecting such a handle reads the old database and
342 /// makes a successful rebuild look like a failed one.415 /// makes a successful rebuild look like a failed one.
343- async fn repair_if_stale(path: &str) -> Result<()> {416+ async fn repair_if_stale(path: &str, storage: &std::path::Path) -> Result<()> {
344 if path == ":memory:" || !std::path::Path::new(path).exists() {417 if path == ":memory:" || !std::path::Path::new(path).exists() {
345 return Ok(());418 return Ok(());
346 }419 }
@@ -381,6 +454,7 @@ impl TursoStore {
381 );454 );
382 reconcile(455 reconcile(
383 path,456 path,
457+ Some(storage),
384 ReconcileOptions {458 ReconcileOptions {
385 dry_run: false,459 dry_run: false,
386 yes: false,460 yes: false,
@@ -745,6 +819,120 @@ fn restrict_if_present(path: &std::path::Path) -> Result<()> {
745 Ok(())819 Ok(())
746 }820 }
747 821
822+/// The storage tree's two subdirectories. One file per row under each, the
823+/// file named by the row's own id — an id the store minted, never anything
824+/// an upload carried, so a path here is always exactly one store-named file
825+/// deep and `file_name` stays a label.
826+const ATTACHMENTS_DIR: &str = "attachments";
827+const PHOTOS_DIR: &str = "photos";
828+
829+/// Where attachment `id`'s bytes live.
830+fn attachment_file(storage: &std::path::Path, id: &str) -> std::path::PathBuf {
831+ storage.join(ATTACHMENTS_DIR).join(id)
832+}
833+
834+/// Where `user_id`'s photo lives.
835+fn photo_file(storage: &std::path::Path, user_id: &str) -> std::path::PathBuf {
836+ storage.join(PHOTOS_DIR).join(user_id)
837+}
838+
839+/// Creates the storage tree — the root and its two subdirectories — when it
840+/// is missing, private to the process owner. A fresh storage path is a
841+/// normal first boot, not a failure, and everything below this point
842+/// assumes the directories are there to write into.
843+fn ensure_storage_dirs(storage: &std::path::Path) -> Result<()> {
844+ for dir in [
845+ storage.to_path_buf(),
846+ storage.join(ATTACHMENTS_DIR),
847+ storage.join(PHOTOS_DIR),
848+ ] {
849+ std::fs::create_dir_all(&dir).map_err(|e| {
850+ StoreError::Backend(format!("creating storage directory {}: {e}", dir.display()))
851+ })?;
852+ #[cfg(unix)]
853+ {
854+ use std::os::unix::fs::PermissionsExt;
855+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))
856+ .map_err(|e| StoreError::Backend(format!("restricting {}: {e}", dir.display())))?;
857+ }
858+ }
859+ Ok(())
860+}
861+
862+/// Writes `bytes` to `path` through a temporary file in the same directory
863+/// and a rename: a crash or a full disk mid-write leaves whatever file was
864+/// there before intact, never a truncated one under the real name. The
865+/// temporary carries a name no row will ever wear, so one a crash abandoned
866+/// is exactly what the boot sweep deletes.
867+fn write_file_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
868+ use std::io::Write as _;
869+ let tmp = path.with_extension(format!("{}.tmp", Ulid::new()));
870+ let mut file = std::fs::File::create(&tmp)?;
871+ file.write_all(bytes)?;
872+ file.sync_all()?;
873+ std::fs::rename(&tmp, path)
874+}
875+
876+/// Whatever of `buf.len()` bytes the file holds from here — a file that ends
877+/// (or shrinks) under a read hands over the short read, the same answer
878+/// `substr` gave, and the sniffer decides from what it gets or declines.
879+fn read_up_to(file: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result<usize> {
880+ use std::io::Read as _;
881+ let mut filled = 0;
882+ while filled < buf.len() {
883+ match file.read(&mut buf[filled..])? {
884+ 0 => break,
885+ n => filled += n,
886+ }
887+ }
888+ Ok(filled)
889+}
890+
891+/// `path`'s first `head` and last `tail` bytes — the windows the sniffer
892+/// decides from, the same shape `substr(bytes, ...)` used to hand over. A
893+/// file shorter than a window gives that window its whole self.
894+fn read_windows(
895+ path: &std::path::Path,
896+ head: i64,
897+ tail: i64,
898+) -> std::io::Result<(Vec<u8>, Vec<u8>)> {
899+ use std::io::Seek as _;
900+ let mut file = std::fs::File::open(path)?;
901+ let len = file.metadata()?.len();
902+ let mut head_buf = vec![0u8; len.min(head.max(0) as u64) as usize];
903+ let got = read_up_to(&mut file, &mut head_buf)?;
904+ head_buf.truncate(got);
905+ file.seek(std::io::SeekFrom::Start(len - len.min(tail.max(0) as u64)))?;
906+ let mut tail_buf = vec![0u8; len.min(tail.max(0) as u64) as usize];
907+ let got = read_up_to(&mut file, &mut tail_buf)?;
908+ tail_buf.truncate(got);
909+ Ok((head_buf, tail_buf))
910+}
911+
912+/// `len` bytes of `path` starting at `offset` — the central-directory read
913+/// `substr(bytes, offset + 1, len)` used to do. A directory the file does
914+/// not actually hold comes back short; the caller treats that as no
915+/// verdict, exactly as it treated `substr`'s empty answer.
916+fn read_window_at(path: &std::path::Path, offset: u64, len: i64) -> std::io::Result<Vec<u8>> {
917+ use std::io::Seek as _;
918+ let mut file = std::fs::File::open(path)?;
919+ file.seek(std::io::SeekFrom::Start(offset))?;
920+ let mut buf = vec![0u8; len.max(0) as usize];
921+ let got = read_up_to(&mut file, &mut buf)?;
922+ buf.truncate(got);
923+ Ok(buf)
924+}
925+
926+/// Every id `sql` hands back — the set of files the sweep must keep.
927+async fn known_ids(conn: &Connection, sql: &str) -> Result<std::collections::HashSet<String>> {
928+ let mut rows = conn.query(sql, ()).await.map_err(backend)?;
929+ let mut out = std::collections::HashSet::new();
930+ while let Some(row) = rows.next().await.map_err(backend)? {
931+ out.insert(text(&row, 0)?);
932+ }
933+ Ok(out)
934+}
935+
748 /// The key for `path`'s database. `:memory:` has no directory to anchor a936 /// The key for `path`'s database. `:memory:` has no directory to anchor a
749 /// sibling file to and does not survive the process anyway, so it gets a937 /// sibling file to and does not survive the process anyway, so it gets a
750 /// key generated fresh in memory — every in-memory store in the test suite938 /// key generated fresh in memory — every in-memory store in the test suite
@@ -956,7 +1144,7 @@ fn user_from(row: &Row) -> Result<User> {
956 }1144 }
957 1145
958 const USER_COLUMNS: &str = "id, workspace_id, email, display_name, role, password_hash, \1146 const USER_COLUMNS: &str = "id, workspace_id, email, display_name, role, password_hash, \
959- (photo IS NOT NULL), created_at, last_signed_in_at, invited_by, timezone, theme, language, ui";1147+ (photo_mime IS NOT NULL), created_at, last_signed_in_at, invited_by, timezone, theme, language, ui";
960 1148
961 fn signin_link_from(row: &Row) -> Result<SigninLink> {1149 fn signin_link_from(row: &Row) -> Result<SigninLink> {
962 Ok(SigninLink {1150 Ok(SigninLink {
@@ -1434,28 +1622,50 @@ impl Store for TursoStore {
1434 }1622 }
1435 1623
1436 async fn set_photo(&self, user_id: &str, bytes: &[u8], mime: &str) -> Result<()> {1624 async fn set_photo(&self, user_id: &str, bytes: &[u8], mime: &str) -> Result<()> {
1625+ // The new bytes stage under a name no row wears, the row commits,
1626+ // and only then does the rename put them over the old photo: a failed
1627+ // update leaves the committed photo exactly as it was, and a crash
1628+ // between commit and rename serves the old bytes next to a staged
1629+ // file the boot sweep collects — stale, never destroyed.
1630+ let path = photo_file(&self.storage, user_id);
1631+ let staged = path.with_extension(format!("incoming-{}", Ulid::new()));
1632+ write_file_atomic(&staged, bytes).map_err(|e| StoreError::Backend(e.to_string()))?;
1437 let conn = self.conn.lock().await;1633 let conn = self.conn.lock().await;
1438- let n = conn1634+ let written = conn
1439 .execute(1635 .execute(
1440- "UPDATE user SET photo = ?1, photo_mime = ?2 WHERE id = ?3",1636+ "UPDATE user SET photo_mime = ?1 WHERE id = ?2",
1441- params![bytes, mime, user_id],1637+ params![mime, user_id],
1442 )1638 )
1443- .await1639+ .await;
1444- .map_err(backend)?;1640+ let n = match written {
1641+ Ok(n) => n,
1642+ Err(e) => {
1643+ drop(conn);
1644+ let _ = std::fs::remove_file(&staged);
1645+ return Err(backend(e));
1646+ }
1647+ };
1445 if n == 0 {1648 if n == 0 {
1649+ drop(conn);
1650+ let _ = std::fs::remove_file(&staged);
1446 Err(StoreError::NotFound)1651 Err(StoreError::NotFound)
1447 } else {1652 } else {
1448 drop(conn);1653 drop(conn);
1654+ std::fs::rename(&staged, &path).map_err(|e| StoreError::Backend(e.to_string()))?;
1449 self.announce([Topic::Members]);1655 self.announce([Topic::Members]);
1450 Ok(())1656 Ok(())
1451 }1657 }
1452 }1658 }
1453 1659
1454 async fn clear_photo(&self, user_id: &str) -> Result<()> {1660 async fn clear_photo(&self, user_id: &str) -> Result<()> {
1661+ // The row goes first: the file may only follow a delete that
1662+ // committed, or a crash in between would leave a row whose photo is
1663+ // gone. The unlink is best-effort — a file that survives it is
1664+ // orphaned bytes the boot sweep collects.
1455 let conn = self.conn.lock().await;1665 let conn = self.conn.lock().await;
1456 let n = conn1666 let n = conn
1457 .execute(1667 .execute(
1458- "UPDATE user SET photo = NULL, photo_mime = NULL WHERE id = ?1",1668+ "UPDATE user SET photo_mime = NULL WHERE id = ?1",
1459 params![user_id],1669 params![user_id],
1460 )1670 )
1461 .await1671 .await
@@ -1464,6 +1674,7 @@ impl Store for TursoStore {
1464 Err(StoreError::NotFound)1674 Err(StoreError::NotFound)
1465 } else {1675 } else {
1466 drop(conn);1676 drop(conn);
1677+ let _ = std::fs::remove_file(photo_file(&self.storage, user_id));
1467 self.announce([Topic::Members]);1678 self.announce([Topic::Members]);
1468 Ok(())1679 Ok(())
1469 }1680 }
@@ -1473,17 +1684,25 @@ impl Store for TursoStore {
1473 let conn = self.conn.lock().await;1684 let conn = self.conn.lock().await;
1474 let mut rows = conn1685 let mut rows = conn
1475 .query(1686 .query(
1476- "SELECT photo, photo_mime FROM user WHERE id = ?1",1687+ "SELECT photo_mime FROM user WHERE id = ?1",
1477 params![user_id],1688 params![user_id],
1478 )1689 )
1479 .await1690 .await
1480 .map_err(backend)?;1691 .map_err(backend)?;
1481- match rows.next().await.map_err(backend)? {1692+ let mime = match rows.next().await.map_err(backend)? {
1482- Some(row) => match row.get::<Option<Vec<u8>>>(0).map_err(backend)? {1693+ Some(row) => opt_text(&row, 0)?,
1483- Some(bytes) => Ok(Some((bytes, text(&row, 1)?))),1694+ None => return Ok(None),
1484- None => Ok(None),1695+ };
1485- },1696+ drop(conn);
1486- None => Ok(None),1697+ let Some(mime) = mime else {
1698+ return Ok(None);
1699+ };
1700+ match std::fs::read(photo_file(&self.storage, user_id)) {
1701+ Ok(bytes) => Ok(Some((bytes, mime))),
1702+ // A row whose file went missing is reported at boot; the photo
1703+ // read answers "nothing to serve" rather than failing the page.
1704+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1705+ Err(e) => Err(StoreError::Backend(e.to_string())),
1487 }1706 }
1488 }1707 }
1489 1708
@@ -1991,11 +2210,7 @@ impl Store for TursoStore {
1991 tx.commit().await.map_err(backend)?;2210 tx.commit().await.map_err(backend)?;
1992 2211
1993 // Task birth touches the board and the task page at once.2212 // Task birth touches the board and the task page at once.
1994- let mut topics = vec![2213+ let mut topics = vec![Topic::Board, Topic::Task(id.clone()), Topic::Activity];
1995- Topic::Board,
1996- Topic::Task(id.clone()),
1997- Topic::Activity,
1998- ];
1999 if reminded {2214 if reminded {
2000 topics.push(Topic::Queue);2215 topics.push(Topic::Queue);
2001 }2216 }
@@ -2162,7 +2377,10 @@ impl Store for TursoStore {
2162 // A no-change assign changes no facts, so the reminders stand as2377 // A no-change assign changes no facts, so the reminders stand as
2163 // they are.2378 // they are.
2164 let reminded = if n > 0 {2379 let reminded = if n > 0 {
2165- match self.sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc()).await {2380+ match self
2381+ .sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc())
2382+ .await
2383+ {
2166 Ok(reminded) => reminded,2384 Ok(reminded) => reminded,
2167 Err(e) => {2385 Err(e) => {
2168 let _ = tx.rollback().await;2386 let _ = tx.rollback().await;
@@ -2199,7 +2417,10 @@ impl Store for TursoStore {
2199 .await2417 .await
2200 .map_err(backend)?;2418 .map_err(backend)?;
2201 let reminded = if n > 0 {2419 let reminded = if n > 0 {
2202- match self.sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc()).await {2420+ match self
2421+ .sync_task_reminders(&tx, task_id, OffsetDateTime::now_utc())
2422+ .await
2423+ {
2203 Ok(reminded) => reminded,2424 Ok(reminded) => reminded,
2204 Err(e) => {2425 Err(e) => {
2205 let _ = tx.rollback().await;2426 let _ = tx.rollback().await;
@@ -2419,27 +2640,38 @@ impl Store for TursoStore {
2419 }2640 }
2420 2641
2421 async fn add_attachment(&self, new: NewAttachment<'_>) -> Result<String> {2642 async fn add_attachment(&self, new: NewAttachment<'_>) -> Result<String> {
2422- let conn = self.conn.lock().await;2643+ // The file lands first, temp-plus-rename, then the row says it is
2644+ // there: a crash in between leaves an orphan file the boot sweep
2645+ // deletes, never a row pointing at nothing. If the row write fails,
2646+ // the file is unlinked best-effort — the row was never born, so the
2647+ // bytes must not outlive it under a name nothing points at.
2423 let id = Ulid::new().to_string();2648 let id = Ulid::new().to_string();
2424 let size = new.bytes.len() as i64;2649 let size = new.bytes.len() as i64;
2425- conn.execute(2650+ let path = attachment_file(&self.storage, &id);
2426- "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \2651+ write_file_atomic(&path, &new.bytes).map_err(|e| StoreError::Backend(e.to_string()))?;
2427- size_bytes, bytes, uploaded_by, created_at) \2652+ let conn = self.conn.lock().await;
2428- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",2653+ let written = conn
2429- params![2654+ .execute(
2430- id.clone(),2655+ "INSERT INTO attachment (id, task_id, comment_id, file_name, mime_type, \
2431- new.task_id,2656+ size_bytes, uploaded_by, created_at) \
2432- new.comment_id,2657+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
2433- new.file_name,2658+ params![
2434- new.mime_type,2659+ id.clone(),
2435- size,2660+ new.task_id,
2436- new.bytes,2661+ new.comment_id,
2437- new.uploaded_by,2662+ new.file_name,
2438- stamp(new.at)?2663+ new.mime_type,
2439- ],2664+ size,
2440- )2665+ new.uploaded_by,
2441- .await2666+ stamp(new.at)?
2442- .map_err(backend)?;2667+ ],
2668+ )
2669+ .await;
2670+ if let Err(e) = written {
2671+ drop(conn);
2672+ let _ = std::fs::remove_file(&path);
2673+ return Err(backend(e));
2674+ }
2443 drop(conn);2675 drop(conn);
2444 self.announce([Topic::Task(new.task_id.to_string())]);2676 self.announce([Topic::Task(new.task_id.to_string())]);
2445 Ok(id)2677 Ok(id)
@@ -2482,12 +2714,20 @@ impl Store for TursoStore {
2482 async fn attachment_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {2714 async fn attachment_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {
2483 let conn = self.conn.lock().await;2715 let conn = self.conn.lock().await;
2484 let mut rows = conn2716 let mut rows = conn
2485- .query("SELECT bytes FROM attachment WHERE id = ?1", params![id])2717+ .query("SELECT 1 FROM attachment WHERE id = ?1", params![id])
2486 .await2718 .await
2487 .map_err(backend)?;2719 .map_err(backend)?;
2488- match rows.next().await.map_err(backend)? {2720+ let known = rows.next().await.map_err(backend)?.is_some();
2489- Some(row) => Ok(Some(row.get::<Vec<u8>>(0).map_err(backend)?)),2721+ drop(conn);
2490- None => Ok(None),2722+ if !known {
2723+ return Ok(None);
2724+ }
2725+ match std::fs::read(attachment_file(&self.storage, id)) {
2726+ Ok(bytes) => Ok(Some(bytes)),
2727+ // A row whose file went missing is reported at boot; the read
2728+ // answers "nothing to serve" rather than failing the panel.
2729+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
2730+ Err(e) => Err(StoreError::Backend(e.to_string())),
2491 }2731 }
2492 }2732 }
2493 2733
@@ -2506,10 +2746,15 @@ impl Store for TursoStore {
2506 .await2746 .await
2507 .map_err(backend)?;2747 .map_err(backend)?;
2508 drop(conn);2748 drop(conn);
2509- if gone > 02749+ if gone > 0 {
2510- && let Some(task_id) = owner2750+ // After the delete: the file may only follow a delete that
2511- {2751+ // committed, or a crash in between would leave a row whose file
2512- self.announce([Topic::Task(task_id)]);2752+ // is gone. Best-effort — a file that survives is orphaned bytes
2753+ // the boot sweep collects.
2754+ let _ = std::fs::remove_file(attachment_file(&self.storage, id));
2755+ if let Some(task_id) = owner {
2756+ self.announce([Topic::Task(task_id)]);
2757+ }
2513 }2758 }
2514 Ok(gone > 0)2759 Ok(gone > 0)
2515 }2760 }
@@ -4543,7 +4788,7 @@ impl DetailReads for TursoStore {
4543 let conn = self.conn.lock().await;4788 let conn = self.conn.lock().await;
4544 let mut rows = conn4789 let mut rows = conn
4545 .query(4790 .query(
4546- "SELECT u.id, u.display_name, (u.photo IS NOT NULL) FROM task_assignee a \4791+ "SELECT u.id, u.display_name, (u.photo_mime IS NOT NULL) FROM task_assignee a \
4547 JOIN user u ON u.id = a.user_id \4792 JOIN user u ON u.id = a.user_id \
4548 WHERE a.task_id = ?1 ORDER BY u.display_name",4793 WHERE a.task_id = ?1 ORDER BY u.display_name",
4549 params![task_id],4794 params![task_id],
@@ -4567,7 +4812,7 @@ impl DetailReads for TursoStore {
4567 // so neither leaves the server for this screen.4812 // so neither leaves the server for this screen.
4568 let mut rows = conn4813 let mut rows = conn
4569 .query(4814 .query(
4570- "SELECT id, display_name, (photo IS NOT NULL) FROM user \4815+ "SELECT id, display_name, (photo_mime IS NOT NULL) FROM user \
4571 WHERE workspace_id = ?1 AND role <> ?2 ORDER BY display_name",4816 WHERE workspace_id = ?1 AND role <> ?2 ORDER BY display_name",
4572 params![workspace_id, Role::Viewer.as_str()],4817 params![workspace_id, Role::Viewer.as_str()],
4573 )4818 )
@@ -4626,7 +4871,7 @@ impl DetailReads for TursoStore {
4626 let conn = self.conn.lock().await;4871 let conn = self.conn.lock().await;
4627 let mut rows = conn4872 let mut rows = conn
4628 .query(4873 .query(
4629- "SELECT c.id, c.body, c.created_at, u.id, u.display_name, (u.photo IS NOT NULL) \4874+ "SELECT c.id, c.body, c.created_at, u.id, u.display_name, (u.photo_mime IS NOT NULL) \
4630 FROM comment c JOIN user u ON u.id = c.author_id \4875 FROM comment c JOIN user u ON u.id = c.author_id \
4631 WHERE c.task_id = ?1 ORDER BY c.created_at, c.rowid",4876 WHERE c.task_id = ?1 ORDER BY c.created_at, c.rowid",
4632 params![task_id],4877 params![task_id],
@@ -4682,7 +4927,7 @@ impl DetailReads for TursoStore {
4682 let mut rows = conn4927 let mut rows = conn
4683 .query(4928 .query(
4684 "SELECT a.id, a.kind, a.detail, a.created_at, u.id, u.display_name, \4929 "SELECT a.id, a.kind, a.detail, a.created_at, u.id, u.display_name, \
4685- (u.photo IS NOT NULL) \4930+ (u.photo_mime IS NOT NULL) \
4686 FROM activity a LEFT JOIN user u ON u.id = a.actor_id \4931 FROM activity a LEFT JOIN user u ON u.id = a.actor_id \
4687 WHERE a.task_id = ?1 ORDER BY a.created_at DESC, a.rowid DESC",4932 WHERE a.task_id = ?1 ORDER BY a.created_at DESC, a.rowid DESC",
4688 params![task_id],4933 params![task_id],
@@ -4719,7 +4964,7 @@ impl DetailReads for TursoStore {
4719 let mut rows = conn4964 let mut rows = conn
4720 .query(4965 .query(
4721 "SELECT t.id, t.task_key, t.title, t.column_id, t.done_at, t.parent_id, \4966 "SELECT t.id, t.task_key, t.title, t.column_id, t.done_at, t.parent_id, \
4722- u.id, u.display_name, (u.photo IS NOT NULL) \4967+ u.id, u.display_name, (u.photo_mime IS NOT NULL) \
4723 FROM task t \4968 FROM task t \
4724 LEFT JOIN task_assignee a ON a.task_id = t.id \4969 LEFT JOIN task_assignee a ON a.task_id = t.id \
4725 LEFT JOIN user u ON u.id = a.user_id \4970 LEFT JOIN user u ON u.id = a.user_id \
@@ -4852,7 +5097,7 @@ impl BoardReads for TursoStore {
4852 let conn = self.conn.lock().await;5097 let conn = self.conn.lock().await;
4853 let mut rows = conn5098 let mut rows = conn
4854 .query(5099 .query(
4855- "SELECT a.task_id, u.id, u.display_name, (u.photo IS NOT NULL) \5100+ "SELECT a.task_id, u.id, u.display_name, (u.photo_mime IS NOT NULL) \
4856 FROM task_assignee a \5101 FROM task_assignee a \
4857 JOIN task t ON t.id = a.task_id \5102 JOIN task t ON t.id = a.task_id \
4858 JOIN user u ON u.id = a.user_id \5103 JOIN user u ON u.id = a.user_id \
@@ -5070,7 +5315,7 @@ mod probe {
5070 async fn the_workspace_read_path_cannot_carry_the_password() {5315 async fn the_workspace_read_path_cannot_carry_the_password() {
5071 let dir = std::env::temp_dir().join(format!("izlek-sender-{}", Ulid::new()));5316 let dir = std::env::temp_dir().join(format!("izlek-sender-{}", Ulid::new()));
5072 std::fs::create_dir_all(&dir).unwrap();5317 std::fs::create_dir_all(&dir).unwrap();
5073- let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap())5318+ let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage"))
5074 .await5319 .await
5075 .unwrap();5320 .unwrap();
5076 use crate::store::Store as _;5321 use crate::store::Store as _;
@@ -5113,3 +5358,277 @@ mod probe {
5113 let _ = std::fs::remove_dir_all(&dir);5358 let _ = std::fs::remove_dir_all(&dir);
5114 }5359 }
5115 }5360 }
5361+
5362+/// The storage tree is the other half of the state the rows describe. These
5363+/// drive the file half through the same [`Store`] API the handlers use: a
5364+/// row's bytes live at exactly one path named by the row's id, a delete
5365+/// takes the file with it, and a boot sweep collects what the rows stopped
5366+/// naming. Nothing binary is in the database any more — the premise a
5367+/// missing file is recoverable-by-reread no longer holds, and these are
5368+/// where that shows up if it breaks.
5369+#[cfg(test)]
5370+mod storage_fs {
5371+ use super::*;
5372+
5373+ /// A file-backed store and its storage tree, both under one tempdir the
5374+ /// fixture keeps alive. File-backed because the boot passes (reconcile,
5375+ /// resniff, sweep) only run for a database that survives its handle.
5376+ struct Fixture {
5377+ store: TursoStore,
5378+ dir: tempfile::TempDir,
5379+ }
5380+
5381+ impl Fixture {
5382+ async fn open() -> Self {
5383+ let dir = tempfile::tempdir().unwrap();
5384+ let store = TursoStore::open(
5385+ dir.path().join("izlek.db").to_str().unwrap(),
5386+ &dir.path().join("storage"),
5387+ )
5388+ .await
5389+ .unwrap();
5390+ Self { store, dir }
5391+ }
5392+
5393+ fn storage(&self) -> std::path::PathBuf {
5394+ self.dir.path().join("storage")
5395+ }
5396+
5397+ /// A workspace with its admin, and one task on the default board.
5398+ async fn with_task(&self) -> (String, String, String) {
5399+ let (ws, admin) = self
5400+ .store
5401+ .claim_workspace("İzlek", "ada@izlek.sh", "Ada", "hash")
5402+ .await
5403+ .unwrap();
5404+ let admin = admin.id;
5405+ let board = self.store.board(&ws.id).await.unwrap().unwrap();
5406+ let column = self
5407+ .store
5408+ .columns(&board.id)
5409+ .await
5410+ .unwrap()
5411+ .into_iter()
5412+ .find(|c| !c.is_done)
5413+ .unwrap_or_else(|| panic!("no open column"))
5414+ .id;
5415+ let task = self
5416+ .store
5417+ .create_task(NewTask {
5418+ clock_at: None,
5419+ board_id: &board.id,
5420+ column_id: &column,
5421+ parent_id: None,
5422+ title: "a task",
5423+ description: "",
5424+ deadline: None,
5425+ created_by: &admin,
5426+ })
5427+ .await
5428+ .unwrap()
5429+ .row
5430+ .id;
5431+ (ws.id, admin, task)
5432+ }
5433+ }
5434+
5435+ #[tokio::test]
5436+ async fn an_attachment_round_trips_through_its_file() {
5437+ let fx = Fixture::open().await;
5438+ let (_ws, admin, task) = fx.with_task().await;
5439+ let bytes: Vec<u8> = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0xff, 0x00];
5440+ let id = fx
5441+ .store
5442+ .add_attachment(NewAttachment {
5443+ task_id: &task,
5444+ comment_id: None,
5445+ file_name: "shot.png",
5446+ mime_type: "image/png",
5447+ bytes: bytes.clone(),
5448+ uploaded_by: &admin,
5449+ at: OffsetDateTime::now_utc(),
5450+ })
5451+ .await
5452+ .unwrap();
5453+
5454+ assert_eq!(
5455+ fx.store.attachment_bytes(&id).await.unwrap().unwrap(),
5456+ bytes
5457+ );
5458+ // The bytes are a file the row's id names, under attachments/, and
5459+ // nothing binary went into the database: the temp file the write
5460+ // passed through is gone, and the tree holds exactly one file.
5461+ let file = attachment_file(&fx.storage(), &id);
5462+ assert!(file.is_file(), "the attachment file exists");
5463+ assert_eq!(std::fs::read(&file).unwrap(), bytes);
5464+ let dir = fx.storage().join(ATTACHMENTS_DIR);
5465+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
5466+ }
5467+
5468+ #[tokio::test]
5469+ async fn a_photo_round_trips_through_its_file() {
5470+ let fx = Fixture::open().await;
5471+ let (_ws, admin, _task) = fx.with_task().await;
5472+ fx.store
5473+ .set_photo(&admin, b"grace-bytes", "image/png")
5474+ .await
5475+ .unwrap();
5476+
5477+ let photo = fx.store.photo(&admin).await.unwrap().unwrap();
5478+ assert_eq!(photo.0, b"grace-bytes".to_vec());
5479+ assert_eq!(photo.1, "image/png");
5480+ let file = photo_file(&fx.storage(), &admin);
5481+ assert!(file.is_file(), "the photo file exists");
5482+ assert_eq!(std::fs::read(&file).unwrap(), b"grace-bytes");
5483+ }
5484+
5485+ #[tokio::test]
5486+ async fn deleting_an_attachment_takes_its_file_with_it() {
5487+ let fx = Fixture::open().await;
5488+ let (_ws, admin, task) = fx.with_task().await;
5489+ let id = fx
5490+ .store
5491+ .add_attachment(NewAttachment {
5492+ task_id: &task,
5493+ comment_id: None,
5494+ file_name: "note.txt",
5495+ mime_type: "text/plain",
5496+ bytes: b"hello".to_vec(),
5497+ uploaded_by: &admin,
5498+ at: OffsetDateTime::now_utc(),
5499+ })
5500+ .await
5501+ .unwrap();
5502+ let file = attachment_file(&fx.storage(), &id);
5503+
5504+ assert!(fx.store.delete_attachment(&id).await.unwrap());
5505+ assert!(!file.exists(), "the file went with the row");
5506+ assert!(fx.store.attachment(&id).await.unwrap().is_none());
5507+ assert!(fx.store.attachment_bytes(&id).await.unwrap().is_none());
5508+ // A second delete is still a no-op, file and all.
5509+ assert!(!fx.store.delete_attachment(&id).await.unwrap());
5510+ }
5511+
5512+ #[tokio::test]
5513+ async fn clearing_a_photo_takes_its_file_with_it() {
5514+ let fx = Fixture::open().await;
5515+ let (_ws, admin, _task) = fx.with_task().await;
5516+ fx.store
5517+ .set_photo(&admin, b"grace-bytes", "image/png")
5518+ .await
5519+ .unwrap();
5520+ let file = photo_file(&fx.storage(), &admin);
5521+
5522+ fx.store.clear_photo(&admin).await.unwrap();
5523+ assert!(!file.exists(), "the file went with the marker");
5524+ assert!(fx.store.photo(&admin).await.unwrap().is_none());
5525+ assert!(!fx.store.user(&admin).await.unwrap().unwrap().has_photo);
5526+ }
5527+
5528+ #[tokio::test]
5529+ async fn the_boot_sweep_deletes_files_no_row_names() {
5530+ let fx = Fixture::open().await;
5531+ let attachments = fx.storage().join(ATTACHMENTS_DIR);
5532+ let photos = fx.storage().join(PHOTOS_DIR);
5533+ // Strays in both subdirs: a file under a made-up id, and the temp
5534+ // file a crash abandoned mid-write.
5535+ std::fs::write(attachments.join("01AAAAAAAAAAAAAAAAAAAAAAAA"), b"x").unwrap();
5536+ std::fs::write(attachments.join("02BBBBBBBBBBBBBBBBBBBBBBBB.tmp"), b"x").unwrap();
5537+ std::fs::write(photos.join("03CCCCCCCCCCCCCCCCCCCCCCCC"), b"x").unwrap();
5538+
5539+ // A reopen is a boot; the sweep runs inside it.
5540+ let Fixture { store, dir } = fx;
5541+ drop(store);
5542+ let db_path = dir.path().join("izlek.db").to_str().unwrap().to_string();
5543+ let storage = dir.path().join("storage");
5544+ let store = TursoStore::open(&db_path, &storage).await.unwrap();
5545+ assert_eq!(std::fs::read_dir(&attachments).unwrap().count(), 0);
5546+ assert_eq!(std::fs::read_dir(&photos).unwrap().count(), 0);
5547+ drop(store);
5548+ }
5549+
5550+ #[tokio::test]
5551+ async fn a_row_whose_file_is_missing_is_kept_and_said_out_loud() {
5552+ let fx = Fixture::open().await;
5553+ let (_ws, admin, task) = fx.with_task().await;
5554+ let id = fx
5555+ .store
5556+ .add_attachment(NewAttachment {
5557+ task_id: &task,
5558+ comment_id: None,
5559+ file_name: "shot.png",
5560+ mime_type: "image/png",
5561+ bytes: b"payload".to_vec(),
5562+ uploaded_by: &admin,
5563+ at: OffsetDateTime::now_utc(),
5564+ })
5565+ .await
5566+ .unwrap();
5567+ fx.store
5568+ .set_photo(&admin, b"grace-bytes", "image/png")
5569+ .await
5570+ .unwrap();
5571+ // The files are lost the way a botched restore loses them: rows on
5572+ // disk, files gone.
5573+ std::fs::remove_file(attachment_file(&fx.storage(), &id)).unwrap();
5574+ std::fs::remove_file(photo_file(&fx.storage(), &admin)).unwrap();
5575+
5576+ let Fixture { store, dir } = fx;
5577+ drop(store);
5578+ let db_path = dir.path().join("izlek.db").to_str().unwrap().to_string();
5579+ let storage = dir.path().join("storage");
5580+ let store = TursoStore::open(&db_path, &storage).await.unwrap();
5581+ // Both rows survive the sweep; the reads answer "nothing to serve".
5582+ assert!(store.attachment(&id).await.unwrap().is_some());
5583+ assert!(store.attachment_bytes(&id).await.unwrap().is_none());
5584+ let admin_row = store.user(&admin).await.unwrap().unwrap();
5585+ assert!(admin_row.has_photo, "the row still says a photo is there");
5586+ assert!(store.photo(&admin).await.unwrap().is_none());
5587+ }
5588+
5589+ #[tokio::test]
5590+ async fn the_boot_resniff_reads_its_windows_from_the_file() {
5591+ let fx = Fixture::open().await;
5592+ let (_ws, admin, task) = fx.with_task().await;
5593+ // A zip whose entry names name a presentation. Uploaded with the
5594+ // generic bucket a pre-sniffer write froze on — the store does not
5595+ // sniff on the way in, so the row wears it until a boot pass runs.
5596+ let bytes = zip_with(&["ppt/presentation.xml", "ppt/slides/slide1.xml"]);
5597+ let id = fx
5598+ .store
5599+ .add_attachment(NewAttachment {
5600+ task_id: &task,
5601+ comment_id: None,
5602+ file_name: "old.pptx",
5603+ mime_type: "application/zip",
5604+ bytes,
5605+ uploaded_by: &admin,
5606+ at: OffsetDateTime::now_utc(),
5607+ })
5608+ .await
5609+ .unwrap();
5610+ let Fixture { store, dir } = fx;
5611+ drop(store);
5612+ let db_path = dir.path().join("izlek.db").to_str().unwrap().to_string();
5613+ let storage = dir.path().join("storage");
5614+ let store = TursoStore::open(&db_path, &storage).await.unwrap();
5615+ assert_eq!(
5616+ store.attachment(&id).await.unwrap().unwrap().mime_type,
5617+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
5618+ "the windows came off the file, and they settled the type"
5619+ );
5620+ }
5621+
5622+ /// A zip of the named entries, contents irrelevant: the sniffer reads
5623+ /// the entry names a zip stores uncompressed.
5624+ fn zip_with(names: &[&str]) -> Vec<u8> {
5625+ use std::io::Write as _;
5626+ let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
5627+ for name in names {
5628+ zip.start_file(*name, zip::write::SimpleFileOptions::default())
5629+ .unwrap();
5630+ zip.write_all(b"<xml/>").unwrap();
5631+ }
5632+ zip.finish().unwrap().into_inner()
5633+ }
5634+}
crates/izlek-core/tests/store.rsmodified+103 -48
@@ -19,6 +19,7 @@ use ulid::Ulid;
19 /// runs, so the tests exercise a real file.19 /// runs, so the tests exercise a real file.
20 struct Scratch {20 struct Scratch {
21 dir: PathBuf,21 dir: PathBuf,
22+ storage: PathBuf,
22 store: TursoStore,23 store: TursoStore,
23 }24 }
24 25
@@ -26,10 +27,11 @@ impl Scratch {
26 async fn open() -> Self {27 async fn open() -> Self {
27 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));28 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
28 std::fs::create_dir_all(&dir).unwrap();29 std::fs::create_dir_all(&dir).unwrap();
29- let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap())30+ let storage = dir.join("storage");
31+ let store = TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &storage)
30 .await32 .await
31 .unwrap();33 .unwrap();
32- Self { dir, store }34+ Self { dir, storage, store }
33 }35 }
34 }36 }
35 37
@@ -100,14 +102,14 @@ async fn the_schema_is_created_once_and_survives_reopen() {
100 std::fs::create_dir_all(&dir).unwrap();102 std::fs::create_dir_all(&dir).unwrap();
101 let path = dir.join("izlek.db").to_string_lossy().into_owned();103 let path = dir.join("izlek.db").to_string_lossy().into_owned();
102 104
103- let first = TursoStore::open(&path).await.unwrap();105+ let first = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
104 claim(&first).await;106 claim(&first).await;
105 drop(first);107 drop(first);
106 108
107 // Re-opening a database that already has tables must not re-run the109 // Re-opening a database that already has tables must not re-run the
108 // schema (its CREATE TABLE would fail on the first one) and must not110 // schema (its CREATE TABLE would fail on the first one) and must not
109 // lose what the first open wrote.111 // lose what the first open wrote.
110- let second = TursoStore::open(&path).await.unwrap();112+ let second = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
111 assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek");113 assert_eq!(second.workspace().await.unwrap().unwrap().name, "İzlek");
112 drop(second);114 drop(second);
113 let _ = std::fs::remove_dir_all(&dir);115 let _ = std::fs::remove_dir_all(&dir);
@@ -699,7 +701,7 @@ async fn concurrent_claims_produce_exactly_one_admin() {
699 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));701 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
700 std::fs::create_dir_all(&dir).unwrap();702 std::fs::create_dir_all(&dir).unwrap();
701 let path = dir.join("izlek.db").to_string_lossy().into_owned();703 let path = dir.join("izlek.db").to_string_lossy().into_owned();
702- let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap());704+ let store = std::sync::Arc::new(TursoStore::open(&path, &dir.join("storage")).await.unwrap());
703 705
704 let hash = hash_password("tide-tables-1892").unwrap();706 let hash = hash_password("tide-tables-1892").unwrap();
705 let mut claims = Vec::new();707 let mut claims = Vec::new();
@@ -752,7 +754,7 @@ async fn many_concurrent_callers_never_see_concurrent_use_forbidden() {
752 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));754 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
753 std::fs::create_dir_all(&dir).unwrap();755 std::fs::create_dir_all(&dir).unwrap();
754 let path = dir.join("izlek.db").to_string_lossy().into_owned();756 let path = dir.join("izlek.db").to_string_lossy().into_owned();
755- let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap());757+ let store = std::sync::Arc::new(TursoStore::open(&path, &dir.join("storage")).await.unwrap());
756 let (workspace_id, _) = claim(&store).await;758 let (workspace_id, _) = claim(&store).await;
757 759
758 let mut tasks = Vec::new();760 let mut tasks = Vec::new();
@@ -1211,6 +1213,10 @@ async fn profile_and_role_updates_stick() {
1211 let photo = scratch.store.photo(&user.id).await.unwrap().unwrap();1213 let photo = scratch.store.photo(&user.id).await.unwrap().unwrap();
1212 assert_eq!(photo.0, b"grace-bytes".to_vec());1214 assert_eq!(photo.0, b"grace-bytes".to_vec());
1213 assert_eq!(photo.1, "image/png");1215 assert_eq!(photo.1, "image/png");
1216+ // The bytes are the file the row's id names, not anything in the
1217+ // database.
1218+ let photo_file = scratch.storage.join("photos").join(&user.id);
1219+ assert_eq!(std::fs::read(&photo_file).unwrap(), b"grace-bytes");
1214 let user = scratch.store.user(&user.id).await.unwrap().unwrap();1220 let user = scratch.store.user(&user.id).await.unwrap().unwrap();
1215 assert_eq!(user.display_name, "Grace H.");1221 assert_eq!(user.display_name, "Grace H.");
1216 assert!(user.has_photo);1222 assert!(user.has_photo);
@@ -1221,11 +1227,13 @@ async fn profile_and_role_updates_stick() {
1221 at.unix_timestamp()1227 at.unix_timestamp()
1222 );1228 );
1223 1229
1224- // Clearing the photo is a real update, not a no-op.1230+ // Clearing the photo is a real update, not a no-op — the file goes
1231+ // with the marker.
1225 scratch.store.clear_photo(&user.id).await.unwrap();1232 scratch.store.clear_photo(&user.id).await.unwrap();
1226 let user = scratch.store.user(&user.id).await.unwrap().unwrap();1233 let user = scratch.store.user(&user.id).await.unwrap().unwrap();
1227 assert!(!user.has_photo);1234 assert!(!user.has_photo);
1228 assert!(scratch.store.photo(&user.id).await.unwrap().is_none());1235 assert!(scratch.store.photo(&user.id).await.unwrap().is_none());
1236+ assert!(!photo_file.exists());
1229 }1237 }
1230 1238
1231 #[tokio::test]1239 #[tokio::test]
@@ -1235,7 +1243,7 @@ async fn email_change_persists_and_refuses_a_taken_address() {
1235 let path = dir.join("izlek.db").to_str().unwrap().to_string();1243 let path = dir.join("izlek.db").to_str().unwrap().to_string();
1236 1244
1237 let user_id = {1245 let user_id = {
1238- let store = TursoStore::open(&path).await.unwrap();1246+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
1239 let (ws_id, _admin_id) = claim(&store).await;1247 let (ws_id, _admin_id) = claim(&store).await;
1240 let user_id = member(&store, &ws_id, "grace@izlek.sh", "Grace").await;1248 let user_id = member(&store, &ws_id, "grace@izlek.sh", "Grace").await;
1241 store1249 store
@@ -1268,7 +1276,7 @@ async fn email_change_persists_and_refuses_a_taken_address() {
1268 };1276 };
1269 1277
1270 // Persists across a reopen, and the refused attempt did not stick.1278 // Persists across a reopen, and the refused attempt did not stick.
1271- let store = TursoStore::open(&path).await.unwrap();1279+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
1272 let user = store.user(&user_id).await.unwrap().unwrap();1280 let user = store.user(&user_id).await.unwrap().unwrap();
1273 assert_eq!(user.email, "grace.new@izlek.sh");1281 assert_eq!(user.email, "grace.new@izlek.sh");
1274 1282
@@ -1281,7 +1289,7 @@ async fn display_preferences_default_and_persist_across_reopen() {
1281 std::fs::create_dir_all(&dir).unwrap();1289 std::fs::create_dir_all(&dir).unwrap();
1282 let path = dir.join("izlek.db").to_string_lossy().into_owned();1290 let path = dir.join("izlek.db").to_string_lossy().into_owned();
1283 1291
1284- let store = TursoStore::open(&path).await.unwrap();1292+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
1285 let (_, admin_id) = claim(&store).await;1293 let (_, admin_id) = claim(&store).await;
1286 1294
1287 let admin = store.user(&admin_id).await.unwrap().unwrap();1295 let admin = store.user(&admin_id).await.unwrap().unwrap();
@@ -1296,7 +1304,7 @@ async fn display_preferences_default_and_persist_across_reopen() {
1296 .unwrap();1304 .unwrap();
1297 drop(store);1305 drop(store);
1298 1306
1299- let reopened = TursoStore::open(&path).await.unwrap();1307+ let reopened = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
1300 let admin = reopened.user(&admin_id).await.unwrap().unwrap();1308 let admin = reopened.user(&admin_id).await.unwrap().unwrap();
1301 assert_eq!(admin.timezone, "Europe/Istanbul");1309 assert_eq!(admin.timezone, "Europe/Istanbul");
1302 assert_eq!(admin.theme, "dark");1310 assert_eq!(admin.theme, "dark");
@@ -1451,7 +1459,7 @@ async fn a_prefetched_link_is_consumed_exactly_once() {
1451 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));1459 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
1452 std::fs::create_dir_all(&dir).unwrap();1460 std::fs::create_dir_all(&dir).unwrap();
1453 let path = dir.join("izlek.db").to_string_lossy().into_owned();1461 let path = dir.join("izlek.db").to_string_lossy().into_owned();
1454- let store = std::sync::Arc::new(TursoStore::open(&path).await.unwrap());1462+ let store = std::sync::Arc::new(TursoStore::open(&path, &dir.join("storage")).await.unwrap());
1455 let (ws_id, _) = claim(&store).await;1463 let (ws_id, _) = claim(&store).await;
1456 let user_id = member(&store, &ws_id, "grace@izlek.sh", "Grace").await;1464 let user_id = member(&store, &ws_id, "grace@izlek.sh", "Grace").await;
1457 1465
@@ -1694,9 +1702,12 @@ use std::sync::Arc;
1694 /// by the returned guard.1702 /// by the returned guard.
1695 async fn accounts() -> (Scratch, Accounts) {1703 async fn accounts() -> (Scratch, Accounts) {
1696 let scratch = Scratch::open().await;1704 let scratch = Scratch::open().await;
1697- let store = TursoStore::open(scratch.dir.join("izlek.db").to_str().unwrap())1705+ let store = TursoStore::open(
1698- .await1706+ scratch.dir.join("izlek.db").to_str().unwrap(),
1699- .unwrap();1707+ &scratch.dir.join("storage"),
1708+ )
1709+ .await
1710+ .unwrap();
1700 let accounts = Accounts::new(Arc::new(store) as Arc<dyn Store>, "https://izlek.sh");1711 let accounts = Accounts::new(Arc::new(store) as Arc<dyn Store>, "https://izlek.sh");
1701 (scratch, accounts)1712 (scratch, accounts)
1702 }1713 }
@@ -3988,7 +3999,7 @@ async fn an_orphan_row_is_refused() {
3988 std::fs::create_dir_all(&dir).unwrap();3999 std::fs::create_dir_all(&dir).unwrap();
3989 let path = dir.join("izlek.db").to_str().unwrap().to_owned();4000 let path = dir.join("izlek.db").to_str().unwrap().to_owned();
3990 {4001 {
3991- TursoStore::open(&path).await.unwrap();4002+ TursoStore::open(&path, &dir.join("storage")).await.unwrap();
3992 }4003 }
3993 4004
3994 let db = turso::Builder::new_local(&path).build().await.unwrap();4005 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() {
4065 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));4076 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
4066 std::fs::create_dir_all(&dir).unwrap();4077 std::fs::create_dir_all(&dir).unwrap();
4067 let path = dir.join("izlek.db").to_string_lossy().into_owned();4078 let path = dir.join("izlek.db").to_string_lossy().into_owned();
4068- let store = TursoStore::open(&path).await.unwrap();4079+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
4069 let (workspace, _admin) = claim(&store).await;4080 let (workspace, _admin) = claim(&store).await;
4070 let board = store.board(&workspace).await.unwrap().unwrap();4081 let board = store.board(&workspace).await.unwrap().unwrap();
4071 drop(store);4082 drop(store);
@@ -4550,7 +4561,7 @@ async fn waiting(minutes: u32) -> (PathBuf, Arc<TursoStore>, String, String) {
4550 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));4561 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
4551 std::fs::create_dir_all(&dir).unwrap();4562 std::fs::create_dir_all(&dir).unwrap();
4552 let store = Arc::new(4563 let store = Arc::new(
4553- TursoStore::open(dir.join("izlek.db").to_str().unwrap())4564+ TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage"))
4554 .await4565 .await
4555 .unwrap(),4566 .unwrap(),
4556 );4567 );
@@ -5439,14 +5450,14 @@ async fn an_account_records_the_admin_who_made_it() {
5439 }5450 }
5440 5451
5441 #[tokio::test]5452 #[tokio::test]
5442-async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() {5453+async fn a_file_lands_in_the_storage_tree_and_comes_back_byte_for_byte() {
5443 let (scratch, workspace, admin) = workspace_with_admin().await;5454 let (scratch, workspace, admin) = workspace_with_admin().await;
5444 let store = &scratch.store;5455 let store = &scratch.store;
5445 let now = OffsetDateTime::now_utc();5456 let now = OffsetDateTime::now_utc();
5446 let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await;5457 let task = add_task(store, &workspace, "Backlog", "a task", None, &admin).await;
5447 5458
5448 // Bytes that are not text and are not valid UTF-8, because an attachment5459 // Bytes that are not text and are not valid UTF-8, because an attachment
5449- // is not a string and the column it lives in must not treat it as one.5460+ // is not a string and must not be treated as one, wherever it sits.
5450 let bytes: Vec<u8> = vec![5461 let bytes: Vec<u8> = vec![
5451 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe,5462 0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0x00, 0xfe,
5452 ];5463 ];
@@ -5470,6 +5481,17 @@ async fn a_file_goes_into_the_database_file_and_comes_back_byte_for_byte() {
5470 assert_eq!(row.size_bytes, bytes.len() as u64);5481 assert_eq!(row.size_bytes, bytes.len() as u64);
5471 assert_eq!(row.uploaded_by, admin);5482 assert_eq!(row.uploaded_by, admin);
5472 assert_eq!(store.attachment_bytes(&id).await.unwrap().unwrap(), bytes);5483 assert_eq!(store.attachment_bytes(&id).await.unwrap().unwrap(), bytes);
5484+
5485+ // The bytes are the file the row's id names, under the storage tree —
5486+ // not a second copy anywhere else. The temp file the write passed
5487+ // through is gone, and the directory holds exactly one file.
5488+ let file = scratch.storage.join("attachments").join(&id);
5489+ assert_eq!(std::fs::read(&file).unwrap(), bytes);
5490+ let files: Vec<String> = std::fs::read_dir(scratch.storage.join("attachments"))
5491+ .unwrap()
5492+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
5493+ .collect();
5494+ assert_eq!(files, vec![id], "the tree holds exactly the row's file");
5473 }5495 }
5474 5496
5475 #[tokio::test]5497 #[tokio::test]
@@ -5495,12 +5517,24 @@ async fn a_file_name_that_is_a_path_is_stored_as_the_label_it_is() {
5495 .unwrap();5517 .unwrap();
5496 let row = store.attachment(&id).await.unwrap().unwrap();5518 let row = store.attachment(&id).await.unwrap().unwrap();
5497 assert_eq!(row.file_name, "../../etc/passwd");5519 assert_eq!(row.file_name, "../../etc/passwd");
5498- // And nothing was written anywhere but the database file and its key5520+
5499- // (see `store::secret`) — never a file named after the attachment.5521+ // The label never became a path: the bytes sit at the one place the
5522+ // row's own id names, under the storage tree, and nothing was written
5523+ // outside it beside the database file and its key (see `store::secret`).
5524+ let attachments = scratch.storage.join("attachments");
5525+ let files: Vec<String> = std::fs::read_dir(&attachments)
5526+ .unwrap()
5527+ .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
5528+ .collect();
5529+ assert_eq!(files, vec![id.clone()], "the tree holds exactly the row's file");
5530+ assert_eq!(
5531+ std::fs::read(attachments.join(&id)).unwrap(),
5532+ b"root:x:0:0"
5533+ );
5500 let written: Vec<String> = std::fs::read_dir(&scratch.dir)5534 let written: Vec<String> = std::fs::read_dir(&scratch.dir)
5501 .unwrap()5535 .unwrap()
5502 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())5536 .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
5503- .filter(|name| !name.starts_with("izlek.db") && name != "izlek.key")5537+ .filter(|name| !name.starts_with("izlek.db") && name != "izlek.key" && name != "storage")
5504 .collect();5538 .collect();
5505 assert!(written.is_empty(), "{written:?}");5539 assert!(written.is_empty(), "{written:?}");
5506 }5540 }
@@ -5555,7 +5589,11 @@ async fn a_file_can_be_taken_away_and_saying_so_twice_is_answered_honestly() {
5555 .await5589 .await
5556 .unwrap();5590 .unwrap();
5557 5591
5592+ let file = scratch.storage.join("attachments").join(&id);
5593+ assert!(file.is_file(), "the file is there before the delete");
5594+
5558 assert!(store.delete_attachment(&id).await.unwrap());5595 assert!(store.delete_attachment(&id).await.unwrap());
5596+ assert!(!file.exists(), "the file went with the row");
5559 assert!(!store.delete_attachment(&id).await.unwrap());5597 assert!(!store.delete_attachment(&id).await.unwrap());
5560 assert!(store.attachment(&id).await.unwrap().is_none());5598 assert!(store.attachment(&id).await.unwrap().is_none());
5561 assert!(store.attachment_bytes(&id).await.unwrap().is_none());5599 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() {
7187 7225
7188 izlek_core::store::reconcile(7226 izlek_core::store::reconcile(
7189 &path,7227 &path,
7228+ Some(&dir.join("storage")),
7190 izlek_core::store::ReconcileOptions {7229 izlek_core::store::ReconcileOptions {
7191 dry_run: false,7230 dry_run: false,
7192 yes: true,7231 yes: true,
@@ -7239,23 +7278,30 @@ async fn reconcile_carries_a_live_shaped_database_onto_the_declared_schema() {
7239 "each board owes exactly one default tag"7278 "each board owes exactly one default tag"
7240 );7279 );
7241 7280
7242- // The blob survived byte for byte.7281+ // The blob survived byte for byte — as the file the row's id names,
7282+ // under the storage tree the rebuild was handed, with the row still
7283+ // agreeing with it. (The database has no bytes column any more; the
7284+ // fingerprint check above already fails if one came back.)
7285+ let stored = std::fs::read(
7286+ dir.join("storage")
7287+ .join("attachments")
7288+ .join("F1"),
7289+ )
7290+ .expect("the attachment's file did not survive the rebuild");
7291+ assert_eq!(stored.len(), 5000);
7243 assert_eq!(7292 assert_eq!(
7244- scalar(7293+ &stored[..4],
7245- &path,7294+ &[0, 1, 2, 3],
7246- "SELECT length(bytes) FROM attachment WHERE id = 'F1'"7295+ "the attachment's bytes changed in the rebuild"
7247- )
7248- .await,
7249- 5000
7250 );7296 );
7251 assert_eq!(7297 assert_eq!(
7252 scalar(7298 scalar(
7253 &path,7299 &path,
7254- "SELECT COUNT(*) FROM attachment WHERE id = 'F1' AND hex(substr(bytes, 1, 4)) = '00010203'",7300+ "SELECT size_bytes FROM attachment WHERE id = 'F1'"
7255 )7301 )
7256 .await,7302 .await,
7257- 1,7303+ 5000,
7258- "the attachment's bytes changed in the rebuild"7304+ "the row no longer agrees with its file"
7259 );7305 );
7260 7306
7261 // The quiet window is a column the old shape never had: a workspace that7307 // 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() {
7331 7377
7332 izlek_core::store::reconcile(7378 izlek_core::store::reconcile(
7333 &path,7379 &path,
7380+ Some(&dir.join("storage")),
7334 izlek_core::store::ReconcileOptions {7381 izlek_core::store::ReconcileOptions {
7335 dry_run: false,7382 dry_run: false,
7336 yes: true,7383 yes: true,
@@ -7416,6 +7463,7 @@ async fn reconcile_seeds_a_default_only_for_a_board_without_one() {
7416 7463
7417 izlek_core::store::reconcile(7464 izlek_core::store::reconcile(
7418 &path,7465 &path,
7466+ Some(&dir.join("storage")),
7419 izlek_core::store::ReconcileOptions {7467 izlek_core::store::ReconcileOptions {
7420 dry_run: false,7468 dry_run: false,
7421 yes: true,7469 yes: true,
@@ -7484,6 +7532,7 @@ async fn reconciling_a_database_that_already_matches_changes_nothing() {
7484 7532
7485 izlek_core::store::reconcile(7533 izlek_core::store::reconcile(
7486 &path,7534 &path,
7535+ Some(&scratch.dir.join("storage")),
7487 izlek_core::store::ReconcileOptions {7536 izlek_core::store::ReconcileOptions {
7488 dry_run: false,7537 dry_run: false,
7489 yes: true,7538 yes: true,
@@ -7505,7 +7554,7 @@ async fn opening_a_stale_database_repairs_it() {
7505 7554
7506 // The boot path: no flag, no prompt — the store comes up on a database of7555 // The boot path: no flag, no prompt — the store comes up on a database of
7507 // the old shape, having repaired it on the way.7556 // the old shape, having repaired it on the way.
7508- let store = TursoStore::open(&path)7557+ let store = TursoStore::open(&path, &dir.join("storage"))
7509 .await7558 .await
7510 .expect("the store would not open a database it was supposed to repair");7559 .expect("the store would not open a database it was supposed to repair");
7511 drop(store);7560 drop(store);
@@ -7522,7 +7571,7 @@ async fn opening_a_stale_database_repairs_it() {
7522 assert_eq!(backups_beside(&dir).len(), 1);7571 assert_eq!(backups_beside(&dir).len(), 1);
7523 7572
7524 // Opening it again finds it current and leaves it alone.7573 // Opening it again finds it current and leaves it alone.
7525- let store = TursoStore::open(&path).await.unwrap();7574+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
7526 drop(store);7575 drop(store);
7527 assert_eq!(7576 assert_eq!(
7528 backups_beside(&dir).len(),7577 backups_beside(&dir).len(),
@@ -7542,7 +7591,7 @@ async fn two_repairs_leave_two_backups() {
7542 auto: true,7591 auto: true,
7543 };7592 };
7544 7593
7545- izlek_core::store::reconcile(&path, opts()).await.unwrap();7594+ izlek_core::store::reconcile(&path, Some(&dir.join("storage")), opts()).await.unwrap();
7546 assert_eq!(backups_beside(&dir).len(), 1);7595 assert_eq!(backups_beside(&dir).len(), 1);
7547 7596
7548 // Put the database back to the old shape and repair it again: the first7597 // 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() {
7556 drop(conn);7605 drop(conn);
7557 drop(db);7606 drop(db);
7558 7607
7559- izlek_core::store::reconcile(&path, opts()).await.unwrap();7608+ izlek_core::store::reconcile(&path, Some(&dir.join("storage")), opts()).await.unwrap();
7560 let backups = backups_beside(&dir);7609 let backups = backups_beside(&dir);
7561 assert_eq!(7610 assert_eq!(
7562 backups.len(),7611 backups.len(),
@@ -7600,6 +7649,7 @@ async fn a_rebuild_keeps_a_window_the_admin_already_set() {
7600 7649
7601 izlek_core::store::reconcile(7650 izlek_core::store::reconcile(
7602 &path,7651 &path,
7652+ Some(&scratch.dir.join("storage")),
7603 izlek_core::store::ReconcileOptions {7653 izlek_core::store::ReconcileOptions {
7604 dry_run: false,7654 dry_run: false,
7605 yes: true,7655 yes: true,
@@ -8675,7 +8725,7 @@ async fn reminder_rows_survive_a_reopen() {
8675 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));8725 let dir = std::env::temp_dir().join(format!("izlek-test-{}", Ulid::new()));
8676 std::fs::create_dir_all(&dir).unwrap();8726 std::fs::create_dir_all(&dir).unwrap();
8677 let path = dir.join("izlek.db").to_string_lossy().into_owned();8727 let path = dir.join("izlek.db").to_string_lossy().into_owned();
8678- let store = TursoStore::open(&path).await.unwrap();8728+ let store = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
8679 let (workspace, admin) = claim(&store).await;8729 let (workspace, admin) = claim(&store).await;
8680 let mate = member(&store, &workspace, "grace@izlek.sh", "Grace").await;8730 let mate = member(&store, &workspace, "grace@izlek.sh", "Grace").await;
8681 let clock = OffsetDateTime::now_utc() + Duration::hours(2);8731 let clock = OffsetDateTime::now_utc() + Duration::hours(2);
@@ -8686,7 +8736,7 @@ async fn reminder_rows_survive_a_reopen() {
8686 let before = before;8736 let before = before;
8687 drop(store);8737 drop(store);
8688 8738
8689- let reopened = TursoStore::open(&path).await.unwrap();8739+ let reopened = TursoStore::open(&path, &dir.join("storage")).await.unwrap();
8690 let after = reminders(&reopened, &task).await;8740 let after = reminders(&reopened, &task).await;
8691 assert_eq!(after.len(), before.len());8741 assert_eq!(after.len(), before.len());
8692 assert_eq!(8742 assert_eq!(
@@ -9423,10 +9473,12 @@ fn ole_bytes(with_workbook: bool) -> Vec<u8> {
9423 bytes9473 bytes
9424 }9474 }
9425 9475
9426-/// A scratch database carrying old-style attachment rows: real bytes under9476+/// A scratch database carrying pre-fs attachment rows: generic mimes under
9427-/// the generic mime a pre-sniffer upload froze on. The first open creates9477+/// which the boot pass may refine, with the bytes where the pass reads them
9428-/// the schema and finds nothing to do; the rows go in through a raw9478+/// now — a file per row, named by the row's id. The first open creates the
9429-/// connection; the caller then opens the store again, which runs the pass.9479+/// schema and finds nothing to do; the rows go in through a raw connection
9480+/// and their bytes land in the storage tree by hand; the caller then opens
9481+/// the store again, which runs the pass.
9430 struct Planted {9482 struct Planted {
9431 dir: PathBuf,9483 dir: PathBuf,
9432 path: String,9484 path: String,
@@ -9437,18 +9489,19 @@ impl Planted {
9437 let dir = std::env::temp_dir().join(format!("izlek-resniff-{}", Ulid::new()));9489 let dir = std::env::temp_dir().join(format!("izlek-resniff-{}", Ulid::new()));
9438 std::fs::create_dir_all(&dir).unwrap();9490 std::fs::create_dir_all(&dir).unwrap();
9439 let path = dir.join("izlek.db").to_str().unwrap().to_string();9491 let path = dir.join("izlek.db").to_str().unwrap().to_string();
9440- drop(TursoStore::open(&path).await.unwrap());9492+ drop(TursoStore::open(&path, &dir.join("storage")).await.unwrap());
9441 let db = turso::Builder::new_local(&path).build().await.unwrap();9493 let db = turso::Builder::new_local(&path).build().await.unwrap();
9442 let conn = db.connect().unwrap();9494 let conn = db.connect().unwrap();
9443 for (id, mime, bytes) in rows {9495 for (id, mime, bytes) in rows {
9444 conn.execute(9496 conn.execute(
9445 "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, \9497 "INSERT INTO attachment (id, task_id, file_name, mime_type, size_bytes, \
9446- bytes, uploaded_by, created_at) \9498+ uploaded_by, created_at) \
9447- VALUES (?1, 'T1', 'old.bin', ?2, ?3, ?4, 'U1', '2026-08-01T00:00:00Z')",9499+ VALUES (?1, 'T1', 'old.bin', ?2, ?3, 'U1', '2026-08-01T00:00:00Z')",
9448- turso::params![id, mime, bytes.len() as i64, bytes.clone()],9500+ turso::params![id, mime, bytes.len() as i64],
9449 )9501 )
9450 .await9502 .await
9451 .unwrap();9503 .unwrap();
9504+ std::fs::write(dir.join("storage").join("attachments").join(id), bytes).unwrap();
9452 }9505 }
9453 drop(conn);9506 drop(conn);
9454 drop(db);9507 drop(db);
@@ -9460,7 +9513,9 @@ impl Planted {
9460 }9513 }
9461 9514
9462 async fn open(&self) -> TursoStore {9515 async fn open(&self) -> TursoStore {
9463- TursoStore::open(self.path()).await.unwrap()9516+ TursoStore::open(self.path(), &self.dir.join("storage"))
9517+ .await
9518+ .unwrap()
9464 }9519 }
9465 }9520 }
9466 9521
crates/izlek-web/src/detail.rsmodified+11 -14
@@ -547,9 +547,7 @@ pub(crate) fn combine_clock(
547 match (hour, minute) {547 match (hour, minute) {
548 (None, None) => Ok(None),548 (None, None) => Ok(None),
549 (Some(""), Some("")) => Ok(Some(String::new())),549 (Some(""), Some("")) => Ok(Some(String::new())),
550- (Some(hour), Some(minute)) => {550+ (Some(hour), Some(minute)) => Ok(Some(format!("{}:{}", hour.trim(), minute.trim()))),
551- Ok(Some(format!("{}:{}", hour.trim(), minute.trim())))
552- }
553 _ => Err(Refusal::BadClock),551 _ => Err(Refusal::BadClock),
554 }552 }
555 }553 }
@@ -968,9 +966,10 @@ async fn delete_task(cx: &Cx, Form(input): Form<TaskIdForm>) -> Redirect {
968 ))966 ))
969 }967 }
970 968
971-/// Deletes an attachment's row and its bytes. A hard delete, unlike969+/// Deletes an attachment's row and its file. A hard delete, unlike
972-/// [`delete_task`]'s soft one — a file is a blob in the database, not a fact970+/// [`delete_task`]'s soft one — an upload is not a fact worth an audit
973-/// worth an audit trail. Only the person who put it there, or an admin, may971+/// trail.
972+/// Only the person who put it there, or an admin, may
974 /// take it away.973 /// take it away.
975 #[route(POST "/api/delete_file")]974 #[route(POST "/api/delete_file")]
976 async fn delete_file(cx: &Cx, Form(input): Form<FileIdForm>) -> Redirect {975 async fn delete_file(cx: &Cx, Form(input): Form<FileIdForm>) -> Redirect {
@@ -1298,8 +1297,6 @@ async fn deadline_control(
1298 may_write: bool,1297 may_write: bool,
1299 lang: Lang,1298 lang: Lang,
1300 ) -> Result {1299 ) -> Result {
1301-
1302-
1303 let overdue = task.is_overdue(today);1300 let overdue = task.is_overdue(today);
1304 let local = task.clock_at.map(|at| at.to_offset(zone));1301 let local = task.clock_at.map(|at| at.to_offset(zone));
1305 let label = match (&local, task.deadline_parts(today)) {1302 let label = match (&local, task.deadline_parts(today)) {
@@ -2459,12 +2456,12 @@ pub async fn file_viewer_modal(
2459 // board and passed down.2456 // board and passed down.
2460 let deck = if kind == crate::files::ViewerKind::Slides {2457 let deck = if kind == crate::files::ViewerKind::Slides {
2461 match store.attachment_bytes(file_id).await {2458 match store.attachment_bytes(file_id).await {
2462- Ok(Some(bytes)) => tokio::task::spawn_blocking(move || {2459+ Ok(Some(bytes)) => {
2463- crate::slides::read(bytes, sheet_index)2460+ tokio::task::spawn_blocking(move || crate::slides::read(bytes, sheet_index))
2464- })2461+ .await
2465- .await2462+ .ok()
2466- .ok()2463+ .flatten()
2467- .flatten(),2464+ }
2468 _ => None,2465 _ => None,
2469 }2466 }
2470 } else {2467 } else {
crates/izlek-web/src/main.rsmodified+36 -1
@@ -36,6 +36,7 @@ async fn main() {
36 };36 };
37 if let Err(problem) = izlek_core::store::reconcile(37 if let Err(problem) = izlek_core::store::reconcile(
38 &config.database.to_string_lossy(),38 &config.database.to_string_lossy(),
39+ Some(config.storage.as_path()),
39 izlek_core::store::ReconcileOptions {40 izlek_core::store::ReconcileOptions {
40 dry_run,41 dry_run,
41 yes,42 yes,
@@ -88,11 +89,17 @@ async fn main() {
88 };89 };
89 println!("izlek {stylesheet}");90 println!("izlek {stylesheet}");
90 91
92+ // Attachments and profile photos are files beside the database now, not
93+ // bytes in a table. The tree is made before the store opens, because the
94+ // reconcile an old database triggers on the way extracts every blob into
95+ // it.
96+ ensure_storage_tree(&config.storage);
97+
91 // One process per database file: Turso is a single-writer engine and a98 // One process per database file: Turso is a single-writer engine and a
92 // second process on the same file loses writes rather than queueing.99 // second process on the same file loses writes rather than queueing.
93 //100 //
94 // `open` applies any unapplied migration before it returns.101 // `open` applies any unapplied migration before it returns.
95- let store = TursoStore::open(&config.database.to_string_lossy())102+ let store = TursoStore::open(&config.database.to_string_lossy(), &config.storage)
96 .await103 .await
97 .expect("failed to open the database");104 .expect("failed to open the database");
98 let store: Arc<dyn izlek_core::store::Store> = Arc::new(store);105 let store: Arc<dyn izlek_core::store::Store> = Arc::new(store);
@@ -154,6 +161,34 @@ async fn main() {
154 .expect("server error");161 .expect("server error");
155 }162 }
156 163
164+/// Makes the storage tree the store keeps binary files in, if it is not
165+/// there: `<storage>/attachments` and `<storage>/photos`, private to the user
166+/// the process runs as. A directory that exists is left exactly as it is; one
167+/// that cannot be made stops the boot — the failure this prevents is a
168+/// rebuild extracting blobs into a tree that is not there, and it is better
169+/// met before anything is opened.
170+fn ensure_storage_tree(storage: &std::path::Path) {
171+ let make = |dir: &std::path::Path| {
172+ if let Err(err) = std::fs::create_dir_all(dir) {
173+ eprintln!("izlek: could not create {}: {err}", dir.display());
174+ std::process::exit(2);
175+ }
176+ #[cfg(unix)]
177+ {
178+ use std::os::unix::fs::PermissionsExt;
179+ if let Err(err) = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
180+ {
181+ eprintln!("izlek: could not restrict {}: {err}", dir.display());
182+ std::process::exit(2);
183+ }
184+ }
185+ };
186+ make(storage);
187+ for name in ["attachments", "photos"] {
188+ make(&storage.join(name));
189+ }
190+}
191+
157 /// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a192 /// Resolves when the process is asked to stop: Ctrl+C, or `SIGTERM` from a
158 /// service manager.193 /// service manager.
159 async fn shutdown_signal() {194 async fn shutdown_signal() {
crates/izlek-web/tests/http.rsmodified+2 -2
@@ -67,7 +67,7 @@ impl App {
67 let dir = std::env::temp_dir().join(format!("izlek-http-{}", Ulid::new()));67 let dir = std::env::temp_dir().join(format!("izlek-http-{}", Ulid::new()));
68 std::fs::create_dir_all(&dir).unwrap();68 std::fs::create_dir_all(&dir).unwrap();
69 let store: Arc<dyn Store> = Arc::new(69 let store: Arc<dyn Store> = Arc::new(
70- TursoStore::open(dir.join("izlek.db").to_str().unwrap())70+ TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage"))
71 .await71 .await
72 .unwrap(),72 .unwrap(),
73 );73 );
@@ -109,7 +109,7 @@ impl App {
109 let dir = std::env::temp_dir().join(format!("izlek-http-{}", Ulid::new()));109 let dir = std::env::temp_dir().join(format!("izlek-http-{}", Ulid::new()));
110 std::fs::create_dir_all(&dir).unwrap();110 std::fs::create_dir_all(&dir).unwrap();
111 let store: Arc<dyn Store> = Arc::new(111 let store: Arc<dyn Store> = Arc::new(
112- TursoStore::open(dir.join("izlek.db").to_str().unwrap())112+ TursoStore::open(dir.join("izlek.db").to_str().unwrap(), &dir.join("storage"))
113 .await113 .await
114 .unwrap(),114 .unwrap(),
115 );115 );