From e284c5a6cb3d555c9da07b57a8bc448f07b6ca89 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:07:24 -0600 Subject: [PATCH 1/8] Refuse a catalog with an unknown layout before anything is written Journal::open checks, after the format and version stamps and before the snapshot is parsed or anything is written, for two signs of a layout this version does not know: a top-level key in catalog.snap outside the known set (the error names the key), and a segments/ folder next to the snapshot, including when there is no snapshot at all. Both refuse with CatalogError::Newer. The Store trait gains one defaulted method, has_folder, since folder existence is not expressible through its flat namespace. Fixes #3962 (points 1 and 3; point 2 is #2867). --- crates/catalog/src/journal.rs | 40 ++++++++- crates/catalog/src/store.rs | 22 +++++ crates/catalog/src/tests_format_version.rs | 97 ++++++++++++++++++++++ 3 files changed, 158 insertions(+), 1 deletion(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 75ec07e59f1..6ac1fc26587 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -79,6 +79,10 @@ //! parse, fails [`Journal::open`] with [`CatalogError::Newer`] before any file is modified — it //! is never mistaken for a torn tail or damage. (Builds up to v0.2.0 refuse a v2 snapshot with //! "unsupported format".) +//! - **An unknown layout is refused, untouched** (#3962): a snapshot at a readable version with a +//! top-level key other than `format`, `version`, `seq` and `catalog`, or a `segments` folder +//! next to it, fails [`Journal::open`] with [`CatalogError::Newer`] the same way — the photos may +//! live where this version doesn't look, and the upgrade rewrite would save an empty catalog. use crate::store::Store; use crate::{Catalog, CatalogError, Op, Result}; @@ -418,6 +422,34 @@ struct SnapHeader { version: u32, } +/// The top-level keys a `catalog.snap` of this format may have. Anything else means the library is +/// laid out in a way this version doesn't read (#3962): ignoring the key would load part of it and +/// the upgrade-on-open rewrite would then save that part over the whole. +const SNAP_KEYS: [&str; 4] = ["format", "version", "seq", "catalog"]; +/// A folder next to `catalog.snap` that this format never writes (a segment-file layout keeps the +/// photos there). Its presence means the snapshot alone isn't the library (#3962). +const SEGMENTS: &str = "segments"; + +/// Refuse a library whose layout this version doesn't read, before anything reads it into the +/// catalog or writes to it: a top-level key in `catalog.snap` outside [`SNAP_KEYS`] (`snap`), or a +/// [`SEGMENTS`] folder next to it. Without this guard such a library loads as an empty catalog and +/// the first snapshot overwrites it (#3962). +fn refuse_unknown_layout(store: &mut dyn Store, snap: Option<&[u8]>) -> Result<()> { + let layout = "this library's layout isn't one this version reads"; + if let Some(bytes) = snap { + // (values are skipped, not built: the catalog itself is parsed once, by `Journal::open`) + type Keys = std::collections::BTreeMap; + let keys: Keys = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + if let Some(key) = keys.keys().find(|k| !SNAP_KEYS.contains(&k.as_str())) { + return Err(newer(format!("{SNAPSHOT} has a top-level {key:?} this version doesn't know: {layout}"))); + } + } + if store.has_folder(SEGMENTS).map_err(io)? { + return Err(newer(format!("the library has a {SEGMENTS:?} folder next to {SNAPSHOT}: {layout}"))); + } + Ok(()) +} + /// The whole `catalog.snap` (after [`SnapHeader`] was checked; `format` and `version` are ignored). #[derive(serde::Deserialize)] struct SnapFile { @@ -443,6 +475,8 @@ impl Journal { if h.version > VERSION { return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version))); } + // a readable stamp, but a layout this version doesn't read: refused untouched (#3962) + refuse_unknown_layout(store.as_mut(), Some(bytes.as_slice()))?; let s: SnapFile = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; // a seq this high can't come from real use; the next record's seq would wrap if s.seq > MAX_SEQ { @@ -455,7 +489,11 @@ impl Journal { } (catalog, s.seq, Some(h.version)) } - None => (Catalog::new(), 0, None), + None => { + // no snapshot: a fresh one would otherwise be written beside the segments + refuse_unknown_layout(store.as_mut(), None)?; + (Catalog::new(), 0, None) + } }; report.snapshot_seq = snapshot_seq; let mut j = Journal { diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index 3345ef884f1..58c977f4495 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -56,6 +56,13 @@ pub trait Store: Send { fn unwritten(&self) -> Option<(usize, String)> { None } + /// Is there a folder called `name` among the files? The journal refuses a library laid out + /// with a folder this version doesn't read (#3962) rather than load part of it and overwrite + /// the rest. The default: a flat store (no folders), so `false`. + fn has_folder(&mut self, name: &str) -> io::Result { + let _ = name; + Ok(false) + } } /// Appends and truncates open the name's own file, so anything else at the name is the library's @@ -285,6 +292,16 @@ impl Store for FsStore { fn unwritten(&self) -> Option<(usize, String)> { self.log.as_ref().and_then(|w| w.unwritten()) } + + fn has_folder(&mut self, name: &str) -> io::Result { + // (a link to a folder counts: what it points at is what another build would read) + match std::fs::metadata(self.path(name)) { + Ok(md) => Ok(md.is_dir()), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false), + // can't tell: an error, not a guess that would let the open go on to write + Err(e) => Err(e), + } + } } /// Counts the bytes written through it. @@ -345,6 +362,11 @@ impl Store for MemStore { fn describe(&self) -> String { "memory".into() } + /// A file named `/…` stands for a file inside folder `name`. + fn has_folder(&mut self, name: &str) -> io::Result { + let prefix = format!("{name}/"); + Ok(self.files.lock().unwrap_or_else(|e| e.into_inner()).keys().any(|k| k.starts_with(&prefix))) + } fn background_writer(&self) -> Option> { self.background.then(|| Box::new(self.clone()) as Box) } diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 612ee4586bc..ee70db46e52 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -151,6 +151,103 @@ fn newer_snapshot_is_refused_untouched() { assert!(e.contains(&format!("v{}", VERSION + 1)), "{e}"); } +/// Issue #3962: `catalog.snap` at stamp `version` holding `base`, with `extra` spliced in as more +/// top-level members (empty: an ordinary snapshot). +fn snap_at(version: u32, base: &Catalog, extra: &str) -> Vec { + format!("{{\"format\":\"lightcraft-catalog\",\"version\":{version},{extra}\"seq\":2,\"catalog\":{}}}\n", base.to_snapshot()).into_bytes() +} + +/// The readable stamps the layout tests run at: this build's and an older one. +const READABLE: [u32; 2] = [VERSION, VERSION - 1]; + +/// A snapshot at a readable stamp with a top-level key this format never writes (a fork that kept +/// its photos elsewhere) is refused untouched, not loaded as a catalog without them and then saved +/// over by the upgrade or the next snapshot (#3962). Before the fix the open succeeded. +#[test] +fn unknown_top_level_key_is_refused_untouched() { + let (base, log, _) = legacy_parts(); + for version in READABLE { + for (key, extra) in [("segments", r#""segments":["0001.seg","0002.seg"],"#), ("photoIndex", r#""photoIndex":{"count":2},"#)] { + let m = MemStore::new(); + m.set(SNAPSHOT, snap_at(version, &base, extra)); + m.set(LOG, log.clone().into_bytes()); + assert_refused_untouched(&m); + let e = Journal::open(Box::new(m)).err().unwrap().to_string(); + assert!(e.contains(&format!("{key:?}")) && e.contains("layout isn't one this version reads"), "v{version}: {e}"); + } + } +} + +/// A `segments` folder next to an otherwise ordinary snapshot: the snapshot isn't the whole +/// library, so it is refused untouched (#3962). Also with no snapshot at all, where a new empty +/// one would otherwise be written beside the folder. Before the fix the open succeeded. +#[test] +fn segments_folder_is_refused_untouched() { + let (base, log, _) = legacy_parts(); + for version in READABLE { + let m = MemStore::new(); + m.set(SNAPSHOT, snap_at(version, &base, "")); + m.set(LOG, log.clone().into_bytes()); + m.set("segments/0001.seg", b"photos live here".to_vec()); + assert_refused_untouched(&m); + let e = Journal::open(Box::new(m)).err().unwrap().to_string(); + assert!(e.contains("\"segments\" folder") && e.contains("layout isn't one this version reads"), "v{version}: {e}"); + } + let m = MemStore::new(); + m.set("segments/0001.seg", b"photos live here".to_vec()); + assert_refused_untouched(&m); +} + +/// The same refusal through the native store, where the folder is a real directory: the snapshot +/// and log keep their bytes and no file is added (#3962). Before the fix the open succeeded. +#[test] +fn segments_folder_on_disk_is_refused_untouched() { + let (base, log, _) = legacy_parts(); + for version in READABLE { + let dir = std::env::temp_dir().join(format!("lc-layout-{version}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("segments")).unwrap(); + std::fs::write(dir.join("segments").join("0001.seg"), b"photos live here").unwrap(); + let snap = snap_at(version, &base, ""); + std::fs::write(dir.join(SNAPSHOT), &snap).unwrap(); + std::fs::write(dir.join(LOG), log.as_bytes()).unwrap(); + let names = |d: &std::path::Path| { + let mut v: Vec<_> = std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name()).collect(); + v.sort(); + v + }; + let before = names(&dir); + let e = Journal::open(Box::new(FsStore::open(&dir).unwrap())).err().expect("refused"); + assert!(matches!(e, CatalogError::Newer(_)), "{e:?}"); + assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), snap); + assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), log.as_bytes()); + assert_eq!(names(&dir), before, "no file added or renamed"); + std::fs::remove_dir_all(&dir).unwrap(); + } +} + +/// Controls for #3962: an ordinary library at a readable stamp still opens with its photos (a +/// `segments` *file* or a key-like string inside the catalog is no folder or top-level key), and a +/// stamp above [`VERSION`] is still refused for its version, even with an unknown key beside it. +#[test] +fn ordinary_layout_still_opens_and_a_newer_stamp_still_names_its_version() { + let (base, log, full) = legacy_parts(); + for version in READABLE { + let m = MemStore::new(); + m.set(SNAPSHOT, snap_at(version, &base, "")); + m.set(LOG, log.clone().into_bytes()); + m.set("segments", b"not a folder".to_vec()); + let (_, c, r) = Journal::open(Box::new(m)).unwrap(); + assert_eq!(c.to_snapshot(), full.to_snapshot()); + assert_eq!(r.upgraded_from, (version != VERSION).then_some(version)); + } + let m = MemStore::new(); + m.set(SNAPSHOT, snap_at(VERSION + 1, &base, r#""segments":[],"#)); + assert_refused_untouched(&m); + let e = Journal::open(Box::new(m)).err().unwrap().to_string(); + assert!(e.contains(&format!("is catalog format v{}", VERSION + 1)), "{e}"); +} + /// A log record with a valid CRC whose op this version doesn't know: refused, not taken for a /// torn tail (truncated) or damage (renamed) — wherever it is in the log. #[test] From 072ac30d551ec7d703fd116ba89cf2ccae328841 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:07:24 -0600 Subject: [PATCH 2/8] Log the unknown-layout refusal in the roadmap --- ROADMAP.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index ee50aed31b9..e588b5c36fc 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -114,6 +114,8 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ ## Progress log +- 2026-11-08: The catalog loader refuses a library with an unknown layout before anything is written (#3962): an unrecognized top-level key in `catalog.snap` (named in the error) or a `segments/` folder beside it now gets the "written by a newer version" refusal, at the current format and the previous one, instead of opening as an empty catalog and being overwritten on save. + - 2026-11-07: Compressed ORF support withdrawn pending provenance review; uncompressed support remains. Regenerated camera coverage: 557 verified, 665 unverified, 187 preview-only and 37 unsupported; 94% use-weighted coverage. See [ORF status](docs/orf-compression.md). - 2026-11-04: Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. @@ -199,6 +201,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ | Date | Change | Summary | |---|---|---| +| 2026-11-08 | patch | Catalog loader refuses an unknown layout (unrecognized `catalog.snap` key or a `segments/` folder) before any write, #3962; headline numbers unchanged | | 2026-10-24 | minor | Priority 7 (lens profile database) links its tracking issue #329; headline numbers unchanged | | 2026-10-24 | patch | Alpha rationale: tests run in CI on Linux x64 (#2667) and FreeBSD nightly, not on macOS or Windows; ranked item 8 now reads "Tests in CI on macOS and Windows, and the GPU tests in CI"; percentages and hours unchanged | | 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged | From 5eac51bfdcbaac4b6f480340680782f49cae17c6 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:01:05 -0600 Subject: [PATCH 3/8] Give the web store a has_folder so segments layouts are refused there too CodeRabbit round 1: the browser FilesStore kept the trait default (no folders), so a segments/ layout would have gone undetected in the web build. It now answers from its preloaded file names, wired in at start-up. New test fails with the override neutered and passes with it. --- apps/lightcraft-web/src/files.rs | 58 ++++++++++++++++++++++++++++++++ apps/lightcraft-web/src/web.rs | 20 +++++++++++ 2 files changed, 78 insertions(+) diff --git a/apps/lightcraft-web/src/files.rs b/apps/lightcraft-web/src/files.rs index 9cd934ce57d..14b1c46f982 100644 --- a/apps/lightcraft-web/src/files.rs +++ b/apps/lightcraft-web/src/files.rs @@ -47,6 +47,9 @@ enum Dirty { #[derive(Default)] struct Mirror { files: BTreeMap>, + /// Folders start-up found beside the files (not files themselves: never dirty, never + /// flushed), e.g. a `segments` folder the catalog store's `has_folder` check asks about. + folders: std::collections::BTreeSet, /// Dirty files, least recently modified first. dirty: Vec<(String, Dirty)>, /// Why the last flush to browser storage failed (quota, eviction…), until one succeeds. @@ -84,6 +87,21 @@ impl Files { self.lock().files.get(name).cloned() } + /// Note a folder start-up found in browser storage beside the library files (not a file: + /// it is never flushed back). The catalog's unknown-layout check (#3962) asks the store + /// about it through [`Store::has_folder`]. + pub fn preload_folder(&self, name: &str) { + self.lock().folders.insert(name.to_string()); + } + + /// Is there a folder called `name` among the stored library entries? A folder start-up + /// noted with [`Files::preload_folder`], or a stored entry under `name/` (the mirror's + /// way of holding a folder's files, like `MemStore`). + pub fn has_folder(&self, name: &str) -> bool { + let m = self.lock(); + m.folders.contains(name) || m.files.keys().any(|k| k.starts_with(&format!("{name}/"))) + } + /// Replace a file. pub fn write(&self, name: &str, data: &[u8]) { let mut m = self.lock(); @@ -193,6 +211,11 @@ impl Store for FilesStore { fn describe(&self) -> String { "browser storage".into() } + /// The mirror knows the folders start-up found in browser storage (#3962): without this + /// the trait default (`false`) would let a `segments` library open and be overwritten. + fn has_folder(&mut self, name: &str) -> io::Result { + Ok(self.0.has_folder(name)) + } } /// Names of the library files read at start-up. @@ -355,6 +378,41 @@ mod tests { assert_eq!(files.get("catalog.snap").as_deref(), Some(&b"snap"[..])); } + /// A `segments` folder in browser storage is a layout this version doesn't read (#3962): + /// opening through [`FilesStore`] refuses it untouched, like the native and memory + /// stores — before the fix `FilesStore` reported no folders, so the stored snapshot + /// would have been replaced by a partial catalog and its log reset. + #[test] + fn segments_folder_in_browser_storage_is_refused_untouched() { + // a saved library, copied the way a reload would read it back + let mut disk = BTreeMap::new(); + let files = Files::default(); + let mut s = Session::new(); + let stores = LibraryStores { dir: "browser".into(), catalog: Box::new(files.store()), files: Box::new(files.store()), on_disk: false }; + s.open_library_in(stores, true).unwrap(); + flush(&files, &mut disk); + let snap_before = disk.get("catalog.snap").cloned().unwrap(); + let log_before = disk.get("catalog.log").cloned().unwrap(); + + // the same files, with a `segments` folder beside them in browser storage + let files2 = Files::default(); + for (k, v) in &disk { + files2.preload(k, v.clone()); + } + files2.preload_folder("segments"); + let mut store = files2.store(); + assert!(store.has_folder("segments").unwrap()); + assert!(!store.has_folder("originals").unwrap()); + let mut s2 = Session::new(); + let stores = LibraryStores { dir: "browser".into(), catalog: Box::new(files2.store()), files: Box::new(files2.store()), on_disk: false }; + let Err(e) = s2.open_library_in(stores, true) else { panic!("refused") }; + let msg = e.to_string(); + assert!(msg.contains("segments") && msg.contains("layout isn't one this version reads"), "{msg}"); + assert_eq!(files2.get("catalog.snap").as_deref(), Some(&snap_before[..]), "snapshot untouched"); + assert_eq!(files2.get("catalog.log").as_deref(), Some(&log_before[..]), "log untouched"); + assert!(!files2.is_dirty(), "nothing was written"); + } + #[test] fn only_not_found_errors_mean_absent() { assert!(is_not_found(Some("NotFoundError"))); diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 79773918b47..af960da3ad5 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -440,6 +440,26 @@ async fn boot(opts: Options, bridge: Option) -> Boot { load_error = Some(e); } } + if load_error.is_none() { + // A `segments` folder beside the library files is a layout this version doesn't + // read (#3962): note it on the mirror, so the catalog store's `has_folder` check + // refuses the library before anything is written, as the native store does. An + // empty folder shows only in the library's own listing (OPFS); a folder holding + // files also lists under its own path (either backend). A check that couldn't + // be made stops start-up rather than risk overwriting the library (#1507). + let in_library = b.list(&lib_dir).await; + let in_segments = b.list(&format!("{lib_dir}/segments")).await; + match (in_library, in_segments) { + (Ok(names), Ok(entries)) => { + if names.iter().any(|n| n.as_str() == "segments") || !entries.is_empty() { + files.preload_folder("segments"); + } + } + (Err(e), _) | (_, Err(e)) => { + load_error = Some(format!("couldn't check browser storage for a segments folder beside the library ({e})")); + } + } + } let index_read = b.read(THUMB_INDEX).await; match &index_read { Ok(Some(j)) => index = ThumbIndex::from_json(j), From defeb5410295f61086091755938f2ef6ce8bd0c3 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:58:26 -0600 Subject: [PATCH 4/8] Tell a segments folder from a segments file in the web start-up probe CodeRabbit round 2: the probe treated a regular file named segments as a failed check on OPFS (a TypeMismatch became a load error and blocked the open) and as a folder on IndexedDB. It now goes through a new Backend::is_folder, which answers from how each backend actually stores the entry. --- apps/lightcraft-web/src/backend.rs | 36 ++++++++++++++++++++++++++++++ apps/lightcraft-web/src/web.rs | 21 +++++++---------- 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/apps/lightcraft-web/src/backend.rs b/apps/lightcraft-web/src/backend.rs index 1dbc2266b2a..597b298dec8 100644 --- a/apps/lightcraft-web/src/backend.rs +++ b/apps/lightcraft-web/src/backend.rs @@ -28,6 +28,11 @@ fn not_found(e: &JsValue) -> bool { crate::files::is_not_found(Reflect::get(e, &"name".into()).ok().and_then(|n| n.as_string()).as_deref()) } +/// Did an OPFS call fail because the entry is a file, not a directory (`TypeMismatchError`)? +fn type_mismatch(e: &JsValue) -> bool { + Reflect::get(e, &"name".into()).ok().and_then(|n| n.as_string()).as_deref() == Some("TypeMismatchError") +} + /// `navigator.storage` in a window or a worker. fn storage_manager() -> Option { let g = js_sys::global(); @@ -265,6 +270,37 @@ impl Backend { } } + /// Is there a folder at `path`? A regular file of the same name is not a folder: + /// OPFS says so with a type mismatch when the entry is opened as a directory, and + /// IndexedDB holds folders only as keys under `path/`, so a lone `path` key is a + /// file. A missing entry is not a folder either; any other failure is an error, + /// never "absent" (#1507). + pub async fn is_folder(&self, path: &str) -> Result { + match self { + Backend::Opfs(root) => { + let mut dir = root.clone(); + for p in path.split('/').filter(|p| !p.is_empty()) { + let opts = FileSystemGetDirectoryOptions::new(); + opts.set_create(false); + match JsFuture::from(dir.get_directory_handle_with_options(p, &opts)).await { + Ok(d) => dir = d.unchecked_into(), + Err(e) if not_found(&e) || type_mismatch(&e) => return Ok(false), + Err(e) => return Err(err(e)), + } + } + Ok(true) + } + Backend::Idb(db) => { + let (_tx, store) = Self::idb_store(db, false)?; + let prefix = format!("{path}/"); + let range = web_sys::IdbKeyRange::bound(&prefix.as_str().into(), &format!("{prefix}\u{ffff}").into()).map_err(err)?; + let keys = idb_req(&store.get_all_keys_with_key(&range).map_err(err)?).await?; + let arr: js_sys::Array = keys.unchecked_into(); + Ok(arr.length() > 0) + } + } + } + /// Names of the files directly inside `dir`. pub async fn list(&self, dir: &str) -> Result, String> { match self { diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index af960da3ad5..abcd58c7d03 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -443,19 +443,14 @@ async fn boot(opts: Options, bridge: Option) -> Boot { if load_error.is_none() { // A `segments` folder beside the library files is a layout this version doesn't // read (#3962): note it on the mirror, so the catalog store's `has_folder` check - // refuses the library before anything is written, as the native store does. An - // empty folder shows only in the library's own listing (OPFS); a folder holding - // files also lists under its own path (either backend). A check that couldn't - // be made stops start-up rather than risk overwriting the library (#1507). - let in_library = b.list(&lib_dir).await; - let in_segments = b.list(&format!("{lib_dir}/segments")).await; - match (in_library, in_segments) { - (Ok(names), Ok(entries)) => { - if names.iter().any(|n| n.as_str() == "segments") || !entries.is_empty() { - files.preload_folder("segments"); - } - } - (Err(e), _) | (_, Err(e)) => { + // refuses the library before anything is written, as the native store does. Only + // a folder counts — a regular file named `segments` is not one, on either + // backend. A check that couldn't be made stops start-up rather than risk + // overwriting the library (#1507). + match b.is_folder(&format!("{lib_dir}/segments")).await { + Ok(true) => files.preload_folder("segments"), + Ok(false) => {} + Err(e) => { load_error = Some(format!("couldn't check browser storage for a segments folder beside the library ({e})")); } } From a06f5122169f97f578ab6b9da2516691dd9754dd Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:58:26 -0600 Subject: [PATCH 5/8] Cover the segments file-key branch of the web store's has_folder A segments/ file key preloaded without an explicit folder entry is refused untouched, like the folder case. --- apps/lightcraft-web/src/files.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/apps/lightcraft-web/src/files.rs b/apps/lightcraft-web/src/files.rs index 14b1c46f982..0ecd901587f 100644 --- a/apps/lightcraft-web/src/files.rs +++ b/apps/lightcraft-web/src/files.rs @@ -413,6 +413,34 @@ mod tests { assert!(!files2.is_dirty(), "nothing was written"); } + /// The other way a folder shows up in browser storage: a file key under it + /// (`segments/…`) without an explicit folder entry. `has_folder` sees the key, + /// and the open is refused the same way. + #[test] + fn segments_file_key_in_browser_storage_is_refused_untouched() { + let mut disk = BTreeMap::new(); + let files = Files::default(); + let mut s = Session::new(); + let stores = LibraryStores { dir: "browser".into(), catalog: Box::new(files.store()), files: Box::new(files.store()), on_disk: false }; + s.open_library_in(stores, true).unwrap(); + flush(&files, &mut disk); + let snap_before = disk.get("catalog.snap").cloned().unwrap(); + + let files2 = Files::default(); + for (k, v) in &disk { + files2.preload(k, v.clone()); + } + files2.preload("segments/0001.seg", b"segment".to_vec()); + let mut store = files2.store(); + assert!(store.has_folder("segments").unwrap()); + let mut s2 = Session::new(); + let stores = LibraryStores { dir: "browser".into(), catalog: Box::new(files2.store()), files: Box::new(files2.store()), on_disk: false }; + let Err(e) = s2.open_library_in(stores, true) else { panic!("refused") }; + assert!(e.to_string().contains("segments"), "{e}"); + assert_eq!(files2.get("catalog.snap").as_deref(), Some(&snap_before[..]), "snapshot untouched"); + assert!(!files2.is_dirty(), "nothing was written"); + } + #[test] fn only_not_found_errors_mean_absent() { assert!(is_not_found(Some("NotFoundError"))); From 32fafb16bc344174f5857b66549e73d1c9459c96 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:28:38 -0600 Subject: [PATCH 6/8] Ask IndexedDB for one key, not all of them, in is_folder CodeRabbit round 3: the Idb branch of Backend::is_folder fetched every key in the store to answer whether anything sits under the folder. It now requests a single key inside the folder's range. --- apps/lightcraft-web/src/backend.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/lightcraft-web/src/backend.rs b/apps/lightcraft-web/src/backend.rs index 597b298dec8..0ed848496cf 100644 --- a/apps/lightcraft-web/src/backend.rs +++ b/apps/lightcraft-web/src/backend.rs @@ -294,7 +294,7 @@ impl Backend { let (_tx, store) = Self::idb_store(db, false)?; let prefix = format!("{path}/"); let range = web_sys::IdbKeyRange::bound(&prefix.as_str().into(), &format!("{prefix}\u{ffff}").into()).map_err(err)?; - let keys = idb_req(&store.get_all_keys_with_key(&range).map_err(err)?).await?; + let keys = idb_req(&store.get_all_keys_with_key_and_limit(&range, 1).map_err(err)?).await?; let arr: js_sys::Array = keys.unchecked_into(); Ok(arr.length() > 0) } From 53536f865b8b82022410759ecceb9559ae54a5b3 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:20:57 -0600 Subject: [PATCH 7/8] Bound the IndexedDB folder probe by the prefix successor, not U+FFFF CodeRabbit round 4: keys can sort past the prefix + U+FFFF upper bound, so a folder whose first key lands beyond it read as absent. The range is now [prefix, successor) via bound_with_lower_open_and_upper_open, so every key under the prefix matches. --- apps/lightcraft-web/src/backend.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/lightcraft-web/src/backend.rs b/apps/lightcraft-web/src/backend.rs index 0ed848496cf..0824953272c 100644 --- a/apps/lightcraft-web/src/backend.rs +++ b/apps/lightcraft-web/src/backend.rs @@ -293,7 +293,19 @@ impl Backend { Backend::Idb(db) => { let (_tx, store) = Self::idb_store(db, false)?; let prefix = format!("{path}/"); - let range = web_sys::IdbKeyRange::bound(&prefix.as_str().into(), &format!("{prefix}\u{ffff}").into()).map_err(err)?; + // Every key under `prefix`, and no other key: the exclusive upper bound is + // `prefix` with its last code unit bumped (`/` -> `0`), which sorts after + // every key that starts with `prefix`. Bounding by `prefix` + `\u{ffff}` + // instead would miss a key such as `segments/\u{ffff}part`, which starts + // with the prefix but sorts after that bound. + let upper = { + let mut u = prefix.clone(); + let last = u.pop().unwrap_or_default(); + u.push(char::from_u32(last as u32 + 1).unwrap_or(last)); + u + }; + let range = web_sys::IdbKeyRange::bound_with_lower_open_and_upper_open(&prefix.as_str().into(), &upper.as_str().into(), false, true) + .map_err(err)?; let keys = idb_req(&store.get_all_keys_with_key_and_limit(&range, 1).map_err(err)?).await?; let arr: js_sys::Array = keys.unchecked_into(); Ok(arr.length() > 0) From 50d245e8ea51c46730cd954e2c28a55dd860037d Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Tue, 10 Nov 2026 03:20:33 -0600 Subject: [PATCH 8/8] Address eliets2's round-6 review: one-pass snapshot read, has_folder contract, native web-logic tests The snapshot now reads in one pass with the previous check sequence kept as fallback, so outcomes and their order are unchanged. Around it: the has_folder error branch is tested on the fault double and the trait docs state the contract; the browser is_folder/boot logic moves into pure functions with native tests; non-object and on-disk segments cases are pinned; boot reads run concurrently through a small join helper; docs and ROADMAP say the refusal needs no snapshot. Drafted with AI assistance (Claude); gated locally. --- ROADMAP.md | 2 +- apps/lightcraft-web/src/backend.rs | 29 ++-- apps/lightcraft-web/src/files.rs | 163 +++++++++++++++++++++ apps/lightcraft-web/src/join.rs | 118 +++++++++++++++ apps/lightcraft-web/src/lib.rs | 4 + apps/lightcraft-web/src/web.rs | 64 ++++---- crates/catalog/src/journal.rs | 119 ++++++++++++--- crates/catalog/src/store.rs | 13 +- crates/catalog/src/tests_format_version.rs | 146 +++++++++++++++++- crates/catalog/src/tests_torn_append.rs | 15 +- 10 files changed, 593 insertions(+), 80 deletions(-) create mode 100644 apps/lightcraft-web/src/join.rs diff --git a/ROADMAP.md b/ROADMAP.md index e588b5c36fc..08b1d937bc8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -114,7 +114,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/ ## Progress log -- 2026-11-08: The catalog loader refuses a library with an unknown layout before anything is written (#3962): an unrecognized top-level key in `catalog.snap` (named in the error) or a `segments/` folder beside it now gets the "written by a newer version" refusal, at the current format and the previous one, instead of opening as an empty catalog and being overwritten on save. +- 2026-11-08: The catalog loader refuses a library with an unknown layout before anything is written (#3962): an unrecognized top-level key in `catalog.snap` (named in the error) or a `segments/` folder beside it now gets the "written by a newer version" refusal, at the current format and the previous one, instead of opening as an empty catalog and being overwritten on save. The `segments/` folder is refused with no `catalog.snap` present too, where a new empty snapshot would otherwise be written beside it, and a store that can't tell whether the folder is there stops the open with that error. - 2026-11-07: Compressed ORF support withdrawn pending provenance review; uncompressed support remains. Regenerated camera coverage: 557 verified, 665 unverified, 187 preview-only and 37 unsupported; 94% use-weighted coverage. See [ORF status](docs/orf-compression.md). diff --git a/apps/lightcraft-web/src/backend.rs b/apps/lightcraft-web/src/backend.rs index 0824953272c..435760c7f12 100644 --- a/apps/lightcraft-web/src/backend.rs +++ b/apps/lightcraft-web/src/backend.rs @@ -25,12 +25,18 @@ fn err(e: JsValue) -> String { /// Did an OPFS call fail because the entry doesn't exist (`NotFoundError`)? Any other failure /// (security, type mismatch, an unreadable or evicted store) is an error, never "absent" (#1507). fn not_found(e: &JsValue) -> bool { - crate::files::is_not_found(Reflect::get(e, &"name".into()).ok().and_then(|n| n.as_string()).as_deref()) + crate::files::is_not_found(dom_exception_name(e).as_deref()) } -/// Did an OPFS call fail because the entry is a file, not a directory (`TypeMismatchError`)? -fn type_mismatch(e: &JsValue) -> bool { - Reflect::get(e, &"name".into()).ok().and_then(|n| n.as_string()).as_deref() == Some("TypeMismatchError") +/// Did opening an OPFS entry as a directory fail because there is no folder there: nothing at the +/// path, or a regular file of that name (`TypeMismatchError`)? See [`crate::files::means_no_folder`]. +fn no_folder(e: &JsValue) -> bool { + crate::files::means_no_folder(dom_exception_name(e).as_deref()) +} + +/// The `name` of a `DOMException` (`NotFoundError`, `TypeMismatchError`…), if `e` has one. +fn dom_exception_name(e: &JsValue) -> Option { + Reflect::get(e, &"name".into()).ok().and_then(|n| n.as_string()) } /// `navigator.storage` in a window or a worker. @@ -284,7 +290,7 @@ impl Backend { opts.set_create(false); match JsFuture::from(dir.get_directory_handle_with_options(p, &opts)).await { Ok(d) => dir = d.unchecked_into(), - Err(e) if not_found(&e) || type_mismatch(&e) => return Ok(false), + Err(e) if no_folder(&e) => return Ok(false), Err(e) => return Err(err(e)), } } @@ -293,17 +299,8 @@ impl Backend { Backend::Idb(db) => { let (_tx, store) = Self::idb_store(db, false)?; let prefix = format!("{path}/"); - // Every key under `prefix`, and no other key: the exclusive upper bound is - // `prefix` with its last code unit bumped (`/` -> `0`), which sorts after - // every key that starts with `prefix`. Bounding by `prefix` + `\u{ffff}` - // instead would miss a key such as `segments/\u{ffff}part`, which starts - // with the prefix but sorts after that bound. - let upper = { - let mut u = prefix.clone(); - let last = u.pop().unwrap_or_default(); - u.push(char::from_u32(last as u32 + 1).unwrap_or(last)); - u - }; + // every key under `prefix`, and no other key (see `key_range_end` and its test) + let upper = crate::files::key_range_end(&prefix); let range = web_sys::IdbKeyRange::bound_with_lower_open_and_upper_open(&prefix.as_str().into(), &upper.as_str().into(), false, true) .map_err(err)?; let keys = idb_req(&store.get_all_keys_with_key_and_limit(&range, 1).map_err(err)?).await?; diff --git a/apps/lightcraft-web/src/files.rs b/apps/lightcraft-web/src/files.rs index 0ecd901587f..f5720de8a17 100644 --- a/apps/lightcraft-web/src/files.rs +++ b/apps/lightcraft-web/src/files.rs @@ -227,6 +227,54 @@ pub fn is_not_found(dom_exception_name: Option<&str>) -> bool { dom_exception_name == Some("NotFoundError") } +/// Does an OPFS failure to open `path` as a directory, by its `DOMException` name, mean "no folder +/// there"? `NotFoundError` (nothing at the path) and `TypeMismatchError` (a regular file of that +/// name, which is not a folder) do. Anything else (security, an unreadable or evicted store) says +/// nothing about the folder: the probe is an error, never "absent" (#1507, #3962). +pub fn means_no_folder(dom_exception_name: Option<&str>) -> bool { + is_not_found(dom_exception_name) || dom_exception_name == Some("TypeMismatchError") +} + +/// The exclusive upper bound of an IndexedDB key range holding every key that starts with +/// `prefix`, and no other: `prefix` with its last character bumped to the next one (`segments/` +/// → `segments0`). IndexedDB orders string keys by UTF-16 code units, and a key that extends +/// `prefix` sorts below that bound whatever follows the prefix; `prefix` + `\u{ffff}` instead +/// would miss a key such as `segments/\u{ffff}part`, which starts with the prefix but sorts after +/// it. An empty `prefix`, or one ending in a character with no next `char`, is returned unchanged +/// (no folder probe asks for one: theirs end in `/`). +pub fn key_range_end(prefix: &str) -> String { + let mut end = prefix.to_string(); + if let Some(last) = end.pop() { + end.push(char::from_u32(u32::from(last) + 1).unwrap_or(last)); + } + end +} + +/// Take start-up's answer to "is there a `segments` folder beside the library files?" (#3962): +/// a folder is noted on the mirror, so the catalog store's `has_folder` check refuses the library +/// before anything is written; no folder (a regular file of that name included) changes nothing; +/// a probe that failed stops start-up with the reason, like an unreadable library file (#1507), +/// rather than risk overwriting a library it couldn't see. +pub fn note_segments_probe(files: &Files, probe: Result) -> Result<(), String> { + match probe { + Ok(true) => { + files.preload_folder("segments"); + Ok(()) + } + Ok(false) => Ok(()), + Err(e) => Err(format!("couldn't check browser storage for a segments folder beside the library ({e})")), + } +} + +/// What start-up read about the library, taken in the order it is checked: the library files +/// ([`preload_library`]), then the `segments` probe ([`note_segments_probe`]). `Err`: start-up +/// stops with the reason, and the web host doesn't open the library (`load_error`), so nothing +/// in browser storage changes. The reads run at the same time; only their outcomes are ordered. +pub fn preload_start_up(files: &Files, reads: Vec<(&str, Result>, String>)>, segments: Result) -> Result<(), String> { + preload_library(files, reads)?; + note_segments_probe(files, segments) +} + /// Preload the library files read at start-up (`None`: the file doesn't exist yet). A file that /// exists but couldn't be read stops start-up instead (#1507): opening the library without it /// would show an incomplete catalog and then save over the stored copy. @@ -441,6 +489,121 @@ mod tests { assert!(!files2.is_dirty(), "nothing was written"); } + /// A saved library as a reload reads it back: its files in a fresh mirror. + fn saved_library() -> (Files, BTreeMap>) { + let mut disk = BTreeMap::new(); + let files = Files::default(); + let mut s = Session::new(); + let stores = LibraryStores { dir: "browser".into(), catalog: Box::new(files.store()), files: Box::new(files.store()), on_disk: false }; + s.open_library_in(stores, true).unwrap(); + flush(&files, &mut disk); + let files2 = Files::default(); + for (k, v) in &disk { + files2.preload(k, v.clone()); + } + (files2, disk) + } + + fn open(files: &Files) -> Result<(), String> { + let mut s = Session::new(); + let stores = LibraryStores { dir: "browser".into(), catalog: Box::new(files.store()), files: Box::new(files.store()), on_disk: false }; + s.open_library_in(stores, true).map(|_| ()).map_err(|e| e.to_string()) + } + + /// Control for #3962: a stored *file* named `segments` (no `segments/…` key, no folder noted) + /// is not a folder in browser storage, so the library opens and the file keeps its bytes. + #[test] + fn lone_segments_file_in_browser_storage_is_no_folder() { + let (files, _) = saved_library(); + files.preload("segments", b"not a folder".to_vec()); + assert!(!files.store().has_folder("segments").unwrap()); + open(&files).unwrap(); + assert_eq!(files.get("segments").as_deref(), Some(&b"not a folder"[..])); + } + + /// A `segments` folder in browser storage with no library files beside it is refused too + /// (#3962), with the layout message, and no `catalog.snap` or `catalog.log` is created: a new + /// library would otherwise be written beside the folder. + #[test] + fn segments_folder_without_a_snapshot_in_browser_storage_is_refused() { + for noted in [true, false] { + let files = Files::default(); + if noted { + files.preload_folder("segments"); + } else { + files.preload("segments/0001.seg", b"segment".to_vec()); + } + let e = open(&files).unwrap_err(); + assert!(e.contains("\"segments\" folder") && e.contains("layout isn't one this version reads"), "noted {noted}: {e}"); + assert_eq!(files.get("catalog.snap"), None, "noted {noted}: no snapshot created"); + assert_eq!(files.get("catalog.log"), None, "noted {noted}: no log created"); + assert!(!files.is_dirty(), "noted {noted}: nothing to flush"); + } + } + + /// OPFS folder probe: a missing entry and a regular file of the name (`TypeMismatchError` + /// when opened as a directory) are "no folder"; any other failure is an error (#1507, #3962). + #[test] + fn only_not_found_and_type_mismatch_mean_no_folder() { + assert!(means_no_folder(Some("NotFoundError"))); + assert!(means_no_folder(Some("TypeMismatchError"))); + for name in [Some("SecurityError"), Some("NotReadableError"), Some("InvalidStateError"), Some("UnknownError"), Some(""), None] { + assert!(!means_no_folder(name), "{name:?}"); + } + } + + /// IndexedDB folder probe: the key range `[prefix, key_range_end(prefix))`, compared the way + /// IndexedDB compares string keys (UTF-16 code units), holds every key under `segments/` and + /// nothing else — not the lone `segments` file key, nor neighbours that sort next to it. + #[test] + fn key_range_end_bounds_exactly_the_keys_under_the_prefix() { + let prefix = "segments/"; + let end = key_range_end(prefix); + assert_eq!(end, "segments0"); + let in_range = |k: &str| k.encode_utf16().ge(prefix.encode_utf16()) && k.encode_utf16().lt(end.encode_utf16()); + for k in ["segments/", "segments/0001.seg", "segments/a/b", "segments/\u{ffff}part", "segments/\u{10ffff}", "segments/~"] { + assert!(in_range(k), "{k:?} is under the prefix"); + } + for k in ["segments", "segments.bak", "segments0", "segments00", "segmentsA", "segment", "catalog.snap", "thumbs/x.jpg"] { + assert!(!in_range(k), "{k:?} is not under the prefix"); + } + assert_eq!(key_range_end(""), ""); + } + + /// Start-up as the web host runs it (#3962): the library files are taken first, then the + /// `segments` probe. A folder is noted and the open refused untouched; no folder opens; a + /// probe that failed stops start-up with its reason (the host then opens nothing); and an + /// unreadable library file still stops it first, naming the file. + #[test] + fn segments_probe_at_start_up() { + let (_, disk) = saved_library(); + let reads = || disk.iter().map(|(k, v)| (k.as_str(), Ok::<_, String>(Some(v.clone())))).collect::>(); + + let files = Files::default(); + preload_start_up(&files, reads(), Ok(true)).unwrap(); + assert!(files.has_folder("segments")); + let e = open(&files).unwrap_err(); + assert!(e.contains("layout isn't one this version reads"), "{e}"); + assert_eq!(files.get("catalog.snap"), disk.get("catalog.snap").cloned(), "snapshot untouched"); + assert!(!files.is_dirty(), "nothing written"); + + let files = Files::default(); + preload_start_up(&files, reads(), Ok(false)).unwrap(); + assert!(!files.has_folder("segments")); + open(&files).unwrap(); + + let files = Files::default(); + let e = preload_start_up(&files, reads(), Err("UnknownError: the storage backend didn't answer".into())).unwrap_err(); + assert!(e.contains("segments folder") && e.contains("UnknownError"), "{e}"); + assert!(!files.has_folder("segments") && !files.is_dirty()); + + let files = Files::default(); + let mut bad = reads(); + bad.push(("prefs.json", Err("NotReadableError: no".into()))); + let e = preload_start_up(&files, bad, Err("UnknownError".into())).unwrap_err(); + assert!(e.contains("prefs.json") && e.contains("NotReadableError"), "{e}"); + } + #[test] fn only_not_found_errors_mean_absent() { assert!(is_not_found(Some("NotFoundError"))); diff --git a/apps/lightcraft-web/src/join.rs b/apps/lightcraft-web/src/join.rs new file mode 100644 index 00000000000..739fe1465b9 --- /dev/null +++ b/apps/lightcraft-web/src/join.rs @@ -0,0 +1,118 @@ +//! Wait for several futures at once on the page's one thread, with no executor crate: start-up's +//! browser-storage reads (library files, the `segments` folder probe, the thumbnail index and +//! listing) are all in flight together, so start-up waits about as long as the slowest one, not +//! for the sum of their round trips (#3989). +//! +//! Each future is polled whenever the joined one is woken, until every one is done; the results +//! come back in the order the futures were given. Compiled natively too, so it has tests. + +use std::future::Future; +use std::pin::Pin; +use std::task::Poll; + +/// A boxed future of the page's thread (browser futures aren't `Send`). +pub type Local<'a, T> = Pin + 'a>>; + +/// Both futures' outputs, once both are done. +pub async fn join2(a: impl Future, b: impl Future) -> (A, B) { + let (mut a, mut b) = (Box::pin(a), Box::pin(b)); + let (mut ra, mut rb) = (None, None); + std::future::poll_fn(move |cx| { + if ra.is_none() + && let Poll::Ready(v) = a.as_mut().poll(cx) + { + ra = Some(v); + } + if rb.is_none() + && let Poll::Ready(v) = b.as_mut().poll(cx) + { + rb = Some(v); + } + match (ra.take(), rb.take()) { + (Some(x), Some(y)) => Poll::Ready((x, y)), + (x, y) => { + (ra, rb) = (x, y); + Poll::Pending + } + } + }) + .await +} + +/// Every future's output, in the order given, once all are done. +pub async fn join_all<'a, T>(futures: Vec>) -> Vec { + let mut slots: Vec<(Option>, Option)> = futures.into_iter().map(|f| (Some(f), None)).collect(); + std::future::poll_fn(move |cx| { + let mut pending = false; + for (future, out) in slots.iter_mut() { + if let Some(f) = future { + match f.as_mut().poll(cx) { + Poll::Ready(v) => { + *out = Some(v); + *future = None; + } + Poll::Pending => pending = true, + } + } + } + if pending { Poll::Pending } else { Poll::Ready(slots.iter_mut().filter_map(|(_, out)| out.take()).collect()) } + }) + .await +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + use std::rc::Rc; + use std::task::{Context, Waker}; + + /// Pending `turns` times (waking itself each time, like a browser promise settling later), + /// then ready with `value`; logs each poll as `(name, turn)`. + fn slow(name: &'static str, turns: u32, value: T, log: Rc>>) -> Local<'static, T> { + let mut turn = 0; + Box::pin(std::future::poll_fn(move |cx| { + log.borrow_mut().push((name, turn)); + if turn < turns { + turn += 1; + cx.waker().wake_by_ref(); + Poll::Pending + } else { + Poll::Ready(value.clone()) + } + })) + } + + /// Poll `f` until it is ready (at most `limit` times). + fn run(f: impl Future, limit: u32) -> T { + let mut f = Box::pin(f); + let mut cx = Context::from_waker(Waker::noop()); + for _ in 0..limit { + if let Poll::Ready(v) = f.as_mut().poll(&mut cx) { + return v; + } + } + panic!("not ready after {limit} polls"); + } + + /// The futures are in flight together: the second is polled before the first is done, and + /// the whole takes as many turns as the slowest, not their sum. Results keep their order. + #[test] + fn join2_waits_for_the_slowest_not_the_sum() { + let log = Rc::new(RefCell::new(Vec::new())); + let (a, b) = run(join2(slow("a", 3, 1, log.clone()), slow("b", 1, "two", log.clone())), 4); + assert_eq!((a, b), (1, "two")); + let log = log.borrow(); + assert_eq!(log[..2], [("a", 0), ("b", 0)], "both started on the first poll"); + assert_eq!(log.iter().filter(|(n, _)| *n == "b").count(), 2, "a finished future isn't polled again"); + } + + #[test] + fn join_all_keeps_the_order_given() { + let log = Rc::new(RefCell::new(Vec::new())); + let futures = vec![slow("x", 2, 'x', log.clone()), slow("y", 0, 'y', log.clone()), slow("z", 1, 'z', log.clone())]; + assert_eq!(run(join_all(futures), 3), ['x', 'y', 'z']); + assert_eq!(log.borrow()[..3], [("x", 0), ("y", 0), ("z", 0)], "all started on the first poll"); + assert_eq!(run(join_all(Vec::>::new()), 1), Vec::::new()); + } +} diff --git a/apps/lightcraft-web/src/lib.rs b/apps/lightcraft-web/src/lib.rs index 631e09f6343..85eeb36d647 100644 --- a/apps/lightcraft-web/src/lib.rs +++ b/apps/lightcraft-web/src/lib.rs @@ -30,6 +30,10 @@ pub mod bench; mod drop_gate; pub mod files; pub mod host; +// Start-up's concurrent storage reads, also compiled natively so the join has tests (unused in a +// native, non-test library build, like `drop_gate`). +#[cfg(any(test, target_arch = "wasm32"))] +mod join; pub mod store; pub mod wire; diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index abcd58c7d03..ff50400949d 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -430,32 +430,36 @@ async fn boot(opts: Options, bridge: Option) -> Boot { // not knowing which library is in use, any library opened could be the wrong one Err(e) => load_error = Some(format!("couldn't read which library is in use from browser storage ({e})")), } - if load_error.is_none() { - let mut reads = Vec::new(); - for name in LIBRARY_FILES { - reads.push((name, b.read(&library_key(&lib_dir, name)).await)); - } - if let Err(e) = crate::files::preload_library(&files, reads) { - log::error!("{e}"); - load_error = Some(e); - } - } - if load_error.is_none() { - // A `segments` folder beside the library files is a layout this version doesn't - // read (#3962): note it on the mirror, so the catalog store's `has_folder` check - // refuses the library before anything is written, as the native store does. Only - // a folder counts — a regular file named `segments` is not one, on either - // backend. A check that couldn't be made stops start-up rather than risk - // overwriting the library (#1507). - match b.is_folder(&format!("{lib_dir}/segments")).await { - Ok(true) => files.preload_folder("segments"), - Ok(false) => {} - Err(e) => { - load_error = Some(format!("couldn't check browser storage for a segments folder beside the library ({e})")); - } - } + // The rest of start-up's reads all at once (#3989), joined before the library opens: + // the library files, the `segments` folder probe, the thumbnail index and listing. + // A `segments` folder beside the library files is a layout this version doesn't read + // (#3962): `preload_start_up` notes it on the mirror, so the catalog store's + // `has_folder` check refuses the library before anything is written, as the native + // store does. Only a folder counts — a regular file named `segments` is not one, on + // either backend. A file that couldn't be read or a probe that couldn't be made stops + // start-up rather than risk overwriting the library (#1507). Not knowing which library + // is in use, neither is read. + let library_known = load_error.is_none(); + let library_reads: Vec>, String>)>> = if library_known { + let lib_dir = &lib_dir; + LIBRARY_FILES + .iter() + .map(|&name| Box::pin(async move { (name, b.read(&library_key(lib_dir, name)).await) }) as crate::join::Local<'_, _>) + .collect() + } else { + Vec::new() + }; + let segments_key = format!("{lib_dir}/segments"); + let segments_probe = async { if library_known { b.is_folder(&segments_key).await } else { Ok(false) } }; + let ((reads, segments), (index_read, thumbs)) = crate::join::join2( + crate::join::join2(crate::join::join_all(library_reads), segments_probe), + crate::join::join2(b.read(THUMB_INDEX), b.list("thumbs")), + ) + .await; + if library_known && let Err(e) = crate::files::preload_start_up(&files, reads, segments) { + log::error!("{e}"); + load_error = Some(e); } - let index_read = b.read(THUMB_INDEX).await; match &index_read { Ok(Some(j)) => index = ThumbIndex::from_json(j), Ok(None) => {} @@ -472,14 +476,8 @@ async fn boot(opts: Options, bridge: Option) -> Boot { // thumbnails stored without an index entry (index saved late, or lost): delete them; not // when the index couldn't be read, which would make every thumbnail look unindexed let b2 = b.clone(); - let known: std::collections::HashSet = b - .list("thumbs") - .await - .unwrap_or_default() - .into_iter() - .filter(|n| n.ends_with(".jpg")) - .map(|n| n.trim_end_matches(".jpg").to_string()) - .collect(); + let known: std::collections::HashSet = + thumbs.unwrap_or_default().into_iter().filter(|n| n.ends_with(".jpg")).map(|n| n.trim_end_matches(".jpg").to_string()).collect(); let orphans: Vec = if index_read.is_ok() { known.into_iter().filter(|k| !index.contains(k)).collect() } else { Vec::new() }; if !orphans.is_empty() { wasm_bindgen_futures::spawn_local(async move { diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 6ac1fc26587..375a6d5d971 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -83,6 +83,9 @@ //! top-level key other than `format`, `version`, `seq` and `catalog`, or a `segments` folder //! next to it, fails [`Journal::open`] with [`CatalogError::Newer`] the same way — the photos may //! live where this version doesn't look, and the upgrade rewrite would save an empty catalog. +//! The `segments` folder is refused with no `catalog.snap` at all too (with or without a log): +//! a new, empty snapshot would otherwise be written beside it. A store that can't tell whether +//! the folder is there fails the open with that error instead of guessing. use crate::store::Store; use crate::{Catalog, CatalogError, Op, Result}; @@ -430,22 +433,32 @@ const SNAP_KEYS: [&str; 4] = ["format", "version", "seq", "catalog"]; /// photos there). Its presence means the snapshot alone isn't the library (#3962). const SEGMENTS: &str = "segments"; +/// The reason every unknown-layout refusal ends with (#3962). +const LAYOUT: &str = "this library's layout isn't one this version reads"; + /// Refuse a library whose layout this version doesn't read, before anything reads it into the /// catalog or writes to it: a top-level key in `catalog.snap` outside [`SNAP_KEYS`] (`snap`), or a -/// [`SEGMENTS`] folder next to it. Without this guard such a library loads as an empty catalog and -/// the first snapshot overwrites it (#3962). +/// [`SEGMENTS`] folder next to it — also when there is no `catalog.snap` (`snap` is `None`), where +/// a new empty one would otherwise be written beside the folder. Without this guard such a library +/// loads as an empty catalog and the first snapshot overwrites it (#3962). A store that can't tell +/// whether the folder is there fails the open with its error: guessing "no" would let it write. fn refuse_unknown_layout(store: &mut dyn Store, snap: Option<&[u8]>) -> Result<()> { - let layout = "this library's layout isn't one this version reads"; if let Some(bytes) = snap { - // (values are skipped, not built: the catalog itself is parsed once, by `Journal::open`) + // (values are skipped, not built; only reached when the one-pass read in `read_snapshot` + // didn't finish, to give the same answer the checks give in order) type Keys = std::collections::BTreeMap; let keys: Keys = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; if let Some(key) = keys.keys().find(|k| !SNAP_KEYS.contains(&k.as_str())) { - return Err(newer(format!("{SNAPSHOT} has a top-level {key:?} this version doesn't know: {layout}"))); + return Err(newer(format!("{SNAPSHOT} has a top-level {key:?} this version doesn't know: {LAYOUT}"))); } } + refuse_segments_folder(store) +} + +/// The [`SEGMENTS`] half of [`refuse_unknown_layout`]. +fn refuse_segments_folder(store: &mut dyn Store) -> Result<()> { if store.has_folder(SEGMENTS).map_err(io)? { - return Err(newer(format!("the library has a {SEGMENTS:?} folder next to {SNAPSHOT}: {layout}"))); + return Err(newer(format!("the library has a {SEGMENTS:?} folder next to {SNAPSHOT}: {LAYOUT}"))); } Ok(()) } @@ -457,6 +470,83 @@ struct SnapFile { catalog: Catalog, } +/// `catalog.snap` read in one pass, when it is the snapshot this build writes: an object whose +/// `format` and `version` come before `catalog`, are this format and a readable version, and with +/// no key outside [`SNAP_KEYS`] and none twice. Then the catalog is built straight from the bytes, +/// with no pass beforehand to check the stamp and the keys (#3989: a large catalog was parsed +/// twice on every open). Anything else stops the pass at once ([`OnePass::deserialize`] errs), and +/// [`read_snapshot`] runs the checks one by one instead, so every outcome and its message stay what +/// the checks in order give. +struct OnePass { + version: u32, + file: SnapFile, +} + +impl<'de> serde::Deserialize<'de> for OnePass { + fn deserialize>(d: D) -> std::result::Result { + d.deserialize_map(OnePassVisitor) + } +} + +struct OnePassVisitor; + +impl<'de> serde::de::Visitor<'de> for OnePassVisitor { + type Value = OnePass; + + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a catalog snapshot laid out as this version writes it") + } + + fn visit_map>(self, mut map: A) -> std::result::Result { + use serde::de::Error; + // (the messages are never shown: any error here sends `read_snapshot` to the checks) + let stop = || A::Error::custom("not this build's snapshot layout"); + let (mut format, mut version, mut seq, mut catalog) = (None::, None::, None::, None::); + while let Some(key) = map.next_key::()? { + match key.as_str() { + "format" if format.is_none() => format = Some(map.next_value()?), + "version" if version.is_none() => version = Some(map.next_value()?), + "seq" if seq.is_none() => seq = Some(map.next_value()?), + // the catalog only once the stamp says this version can read it + "catalog" if catalog.is_none() && format.as_deref() == Some(FORMAT) && version.is_some_and(|v| v <= VERSION) => { + catalog = Some(map.next_value()?) + } + // an unknown or repeated key, or the catalog before a readable stamp + _ => return Err(stop()), + } + } + match (version, seq, catalog) { + (Some(version), Some(seq), Some(catalog)) => Ok(OnePass { version, file: SnapFile { seq, catalog } }), + _ => Err(stop()), + } + } +} + +/// Read `catalog.snap` and check it, in order: the stamp ([`SnapHeader`]: a snapshot of another +/// format is corrupt, a newer version is refused), then the layout ([`refuse_unknown_layout`]: an +/// unknown top-level key or a [`SEGMENTS`] folder is refused), then the catalog itself. One parse +/// when the file is laid out as this build writes it ([`OnePass`]); otherwise each check parses +/// the bytes it needs, as before. Nothing is written either way. +fn read_snapshot(store: &mut dyn Store, bytes: &[u8]) -> Result<(SnapFile, u32)> { + if let Ok(one) = serde_json::from_slice::(bytes) { + // format, version and keys were checked during the pass; the folder is all that's left + refuse_segments_folder(store)?; + return Ok((one.file, one.version)); + } + // the header first: a newer snapshot may not parse as this version's catalog + let h: SnapHeader = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + if h.format != FORMAT { + return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: not a LightCraft catalog (format {:?})", h.format))); + } + if h.version > VERSION { + return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version))); + } + // a readable stamp, but a layout this version doesn't read: refused untouched (#3962) + refuse_unknown_layout(store, Some(bytes))?; + let s: SnapFile = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + Ok((s, h.version)) +} + impl Journal { /// Open (or create) the catalog in `store`: load the snapshot, replay the log, repair a torn /// tail. Fails only if the snapshot itself is unreadable (then nothing is modified). @@ -467,17 +557,8 @@ impl Journal { report.created = snap.is_none() && log.is_none(); let (mut catalog, snapshot_seq, snapshot_version) = match snap { Some(bytes) => { - // the header first: a newer snapshot may not parse as this version's catalog - let h: SnapHeader = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; - if h.format != FORMAT { - return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: not a LightCraft catalog (format {:?})", h.format))); - } - if h.version > VERSION { - return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version))); - } - // a readable stamp, but a layout this version doesn't read: refused untouched (#3962) - refuse_unknown_layout(store.as_mut(), Some(bytes.as_slice()))?; - let s: SnapFile = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + // stamp, then layout (#3962), then catalog: refused untouched at any of them + let (s, version) = read_snapshot(store.as_mut(), &bytes)?; // a seq this high can't come from real use; the next record's seq would wrap if s.seq > MAX_SEQ { return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: seq {} is out of range", s.seq))); @@ -487,10 +568,10 @@ impl Journal { for r in &report.repaired { log::warn!("{SNAPSHOT}: {r}"); } - (catalog, s.seq, Some(h.version)) + (catalog, s.seq, Some(version)) } None => { - // no snapshot: a fresh one would otherwise be written beside the segments + // no snapshot: refused all the same, or a fresh one would be written beside the segments refuse_unknown_layout(store.as_mut(), None)?; (Catalog::new(), 0, None) } diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index 58c977f4495..d1a8c4b4d55 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -58,7 +58,18 @@ pub trait Store: Send { } /// Is there a folder called `name` among the files? The journal refuses a library laid out /// with a folder this version doesn't read (#3962) rather than load part of it and overwrite - /// the rest. The default: a flat store (no folders), so `false`. + /// the rest, so the answer decides whether [`crate::Journal::open`] may write. The rules: + /// - **Can't tell → an error**, never `false`: an unreadable directory, a permission or I/O + /// failure, a storage backend that won't answer. The open fails with it and writes nothing; + /// `false` would let it go on and save over a library it couldn't see. + /// - **A regular file called `name` is not a folder** (`Ok(false)`): only something that holds + /// other entries counts. A link to a folder does count ([`FsStore`] follows it: what it + /// points at is what another build would read). + /// - **A store that can hold folders must override this** — a filesystem directory + /// ([`FsStore`]), keys with `/` in them ([`MemStore`]: `name/…`), browser storage, a + /// network share. The default (`Ok(false)`) is right only for a store that is flat by + /// construction, where no folder can exist; for any other store it silently disables the + /// refusal. fn has_folder(&mut self, name: &str) -> io::Result { let _ = name; Ok(false) diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index ee70db46e52..645d6bd6cfd 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -193,9 +193,87 @@ fn segments_folder_is_refused_untouched() { let e = Journal::open(Box::new(m)).err().unwrap().to_string(); assert!(e.contains("\"segments\" folder") && e.contains("layout isn't one this version reads"), "v{version}: {e}"); } - let m = MemStore::new(); - m.set("segments/0001.seg", b"photos live here".to_vec()); + // no snapshot, with and without a log: refused for the folder, and no catalog.snap or + // catalog.log appears beside it + for log in [None, Some(log)] { + let m = MemStore::new(); + m.set("segments/0001.seg", b"photos live here".to_vec()); + if let Some(log) = &log { + m.set(LOG, log.clone().into_bytes()); + } + assert_refused_untouched(&m); + let e = Journal::open(Box::new(m.clone())).err().unwrap().to_string(); + assert!(e.contains("\"segments\" folder") && e.contains("layout isn't one this version reads"), "log {}: {e}", log.is_some()); + assert_eq!(m.get(SNAPSHOT), None, "no snapshot written beside the folder"); + assert_eq!(m.get(LOG).is_some(), log.is_some(), "no log created"); + } +} + +/// A store that can't tell whether a `segments` folder is there fails the open with that error, +/// before anything is written: guessing "no folder" would let the upgrade or a new snapshot save +/// over a library it couldn't see (#3962). With a snapshot and without one. +#[test] +fn a_folder_check_that_fails_stops_the_open_untouched() { + let (base, log, _) = legacy_parts(); + for snap in [Some(snap_at(VERSION - 1, &base, "")), None] { + let t = crate::tests_torn_append::Torn::default(); + if let Some(snap) = &snap { + t.files.set(SNAPSHOT, snap.clone()); + } + t.files.set(LOG, log.clone().into_bytes()); + t.folder_fails.store(true, std::sync::atomic::Ordering::SeqCst); + let before = t.files.files.lock().unwrap().clone(); + let e = Journal::open(Box::new(t.clone())).err().expect("the open fails"); + assert!(matches!(&e, CatalogError::Io(m) if m.contains("folder listing refused")), "snapshot {}: {e:?}", snap.is_some()); + assert_eq!(*t.files.files.lock().unwrap(), before, "nothing written, nothing renamed"); + // the same store once it can answer: the library opens + t.folder_fails.store(false, std::sync::atomic::Ordering::SeqCst); + Journal::open(Box::new(t)).unwrap(); + } +} + +/// A snapshot whose top level isn't an object is corrupt, not newer and not a catalog, and keeps +/// its bytes (#3962): an array, a string, a number or `null`, and an array that reads as the +/// stamp (`[format, version]`, which the header check takes) and so reaches the key check. +#[test] +fn non_object_snapshot_is_corrupt_and_untouched() { + let stamp_array = format!("[\"lightcraft-catalog\",{VERSION}]\n"); + for top in ["[]", "\"lightcraft-catalog\"", "7", "null", stamp_array.as_str()] { + let m = MemStore::new(); + m.set(SNAPSHOT, top.as_bytes().to_vec()); + let e = Journal::open(Box::new(m.clone())).err().expect("refused"); + assert!(matches!(&e, CatalogError::Corrupt(msg) if msg.starts_with(SNAPSHOT)), "{top:.20}: {e:?}"); + assert_eq!(m.get(SNAPSHOT).as_deref(), Some(top.as_bytes()), "{top:.20}: snapshot untouched"); + assert_eq!(m.get(LOG), None, "{top:.20}: no log created"); + } +} + +/// The checks behind the one-pass read keep their order (#3989): a snapshot whose keys come in +/// another order than this build writes them, or whose catalog doesn't parse, still gets the +/// answer of stamp, then layout, then catalog — not the first problem the pass ran into. +#[test] +fn snapshot_checks_keep_their_order_off_the_one_pass_read() { + let (base, log, full) = legacy_parts(); + let cat = base.to_snapshot(); + let open = |snap: String| { + let m = MemStore::new(); + m.set(SNAPSHOT, snap.into_bytes()); + m.set(LOG, log.clone().into_bytes()); + (Journal::open(Box::new(m.clone())), m) + }; + // the catalog first, the stamp last: still a readable library + let (r, _) = open(format!("{{\"catalog\":{cat},\"seq\":2,\"version\":{VERSION},\"format\":\"lightcraft-catalog\"}}")); + assert_eq!(r.unwrap().1.to_snapshot(), full.to_snapshot()); + // an unknown key after a catalog that doesn't parse: refused for the key, not corrupt + let (r, m) = open(format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"catalog\":{{\"photos\":7}},\"segments\":[]}}")); + assert!(matches!(r.err(), Some(CatalogError::Newer(e)) if e.contains("\"segments\""))); assert_refused_untouched(&m); + // a newer stamp after the catalog: refused for the version + let (r, _) = open(format!("{{\"format\":\"lightcraft-catalog\",\"catalog\":{cat},\"seq\":2,\"version\":{}}}", VERSION + 1)); + assert!(matches!(r.err(), Some(CatalogError::Newer(e)) if e.contains(&format!("v{}", VERSION + 1)))); + // a key twice: corrupt, as the header check finds it + let (r, _) = open(format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"version\":{VERSION},\"seq\":2,\"catalog\":{cat}}}")); + assert!(matches!(r.err(), Some(CatalogError::Corrupt(e)) if e.contains("duplicate field"))); } /// The same refusal through the native store, where the folder is a real directory: the snapshot @@ -211,11 +289,6 @@ fn segments_folder_on_disk_is_refused_untouched() { let snap = snap_at(version, &base, ""); std::fs::write(dir.join(SNAPSHOT), &snap).unwrap(); std::fs::write(dir.join(LOG), log.as_bytes()).unwrap(); - let names = |d: &std::path::Path| { - let mut v: Vec<_> = std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name()).collect(); - v.sort(); - v - }; let before = names(&dir); let e = Journal::open(Box::new(FsStore::open(&dir).unwrap())).err().expect("refused"); assert!(matches!(e, CatalogError::Newer(_)), "{e:?}"); @@ -226,6 +299,65 @@ fn segments_folder_on_disk_is_refused_untouched() { } } +/// The entries of `dir`, sorted (what an open may not add to or rename). +fn names(dir: &std::path::Path) -> Vec { + let mut v: Vec<_> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name()).collect(); + v.sort(); + v +} + +/// The native store's `has_folder` on disk (#3962): a regular file named `segments` is no folder +/// (the library opens), a `segments` folder with no snapshot beside it is refused and no +/// `catalog.snap` or `catalog.log` is created, and a link to a folder counts as the folder. +#[test] +fn segments_entries_on_disk() { + let (base, log, full) = legacy_parts(); + let dir = std::env::temp_dir().join(format!("lc-layout-entries-{}", std::process::id())); + + // a file called `segments`: no folder, the library opens + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("segments"), b"not a folder").unwrap(); + std::fs::write(dir.join(SNAPSHOT), snap_at(VERSION, &base, "")).unwrap(); + std::fs::write(dir.join(LOG), log.as_bytes()).unwrap(); + let mut store = FsStore::open(&dir).unwrap(); + assert!(!store.has_folder("segments").unwrap()); + let (_, c, _) = Journal::open(Box::new(store)).unwrap(); + assert_eq!(c.to_snapshot(), full.to_snapshot()); + assert_eq!(std::fs::read(dir.join("segments")).unwrap(), b"not a folder"); + + // a `segments` folder and nothing else: refused, nothing created beside it + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("segments")).unwrap(); + std::fs::write(dir.join("segments").join("0001.seg"), b"photos live here").unwrap(); + let before = names(&dir); + let e = Journal::open(Box::new(FsStore::open(&dir).unwrap())).err().expect("refused"); + assert!(matches!(&e, CatalogError::Newer(m) if m.contains("\"segments\" folder")), "{e:?}"); + assert_eq!(names(&dir), before, "no catalog.snap or catalog.log created"); + + // a link to a folder elsewhere: what another build would read, so refused too + #[cfg(unix)] + { + let elsewhere = std::env::temp_dir().join(format!("lc-layout-elsewhere-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&elsewhere); + std::fs::create_dir_all(&elsewhere).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::os::unix::fs::symlink(&elsewhere, dir.join("segments")).unwrap(); + let snap = snap_at(VERSION, &base, ""); + std::fs::write(dir.join(SNAPSHOT), &snap).unwrap(); + let before = names(&dir); + assert!(FsStore::open(&dir).unwrap().has_folder("segments").unwrap()); + let e = Journal::open(Box::new(FsStore::open(&dir).unwrap())).err().expect("refused"); + assert!(matches!(e, CatalogError::Newer(_)), "{e:?}"); + assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), snap); + assert_eq!(names(&dir), before, "no file added or renamed"); + assert_eq!(names(&elsewhere), Vec::::new(), "nothing written through the link"); + std::fs::remove_dir_all(&elsewhere).unwrap(); + } + std::fs::remove_dir_all(&dir).unwrap(); +} + /// Controls for #3962: an ordinary library at a readable stamp still opens with its photos (a /// `segments` *file* or a key-like string inside the catalog is no folder or top-level key), and a /// stamp above [`VERSION`] is still refused for its version, even with an unknown key beside it. diff --git a/crates/catalog/src/tests_torn_append.rs b/crates/catalog/src/tests_torn_append.rs index 12144d4b727..cdf002903b6 100644 --- a/crates/catalog/src/tests_torn_append.rs +++ b/crates/catalog/src/tests_torn_append.rs @@ -7,14 +7,17 @@ use std::sync::{Arc, Mutex}; use crate::journal::{LOG, RESYNC_CANDIDATES}; use crate::*; -/// A store whose next append writes only a prefix of its data, then fails. +/// A store whose next append writes only a prefix of its data, then fails. Also the failing +/// store of other tests in the crate (`folder_fails`: #3962). #[derive(Clone, Default)] -struct Torn { - files: MemStore, +pub(crate) struct Torn { + pub(crate) files: MemStore, /// The next append writes this many bytes, then returns an error. torn_at: Arc>>, /// `truncate` fails (the cut-back after a failed append can't be done right away). truncate_fails: Arc, + /// `has_folder` can't tell (an unreadable directory, a storage backend that won't answer). + pub(crate) folder_fails: Arc, } impl Torn { @@ -46,6 +49,12 @@ impl Store for Torn { fn describe(&self) -> String { "torn".into() } + fn has_folder(&mut self, name: &str) -> std::io::Result { + if self.folder_fails.load(Ordering::SeqCst) { + return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "folder listing refused")); + } + self.files.has_folder(name) + } } fn add_photo(c: &mut Catalog) -> Op {