mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 09:19:25 +01:00
Merge raw-negative-channels (with main) into camera-colour-pushed-shadows
This commit is contained in:
276 files changed
+27585
-1619
No files matched your search
@@ -14,3 +14,6 @@ plan/
|
||||
# model weights are never committed (SAM 3: docs/ai-masks.md)
|
||||
*.safetensors
|
||||
*.safetensors.part
|
||||
|
||||
# Python tools import their public operator family.
|
||||
__pycache__/
|
||||
@@ -38,9 +38,10 @@ of it.
|
||||
"unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]`
|
||||
+ `.expect("why it can't fail")`.
|
||||
- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed
|
||||
allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new
|
||||
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
|
||||
fallback where possible, and a line here naming it.
|
||||
allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile
|
||||
Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every
|
||||
other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper
|
||||
crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it.
|
||||
- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or
|
||||
arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative
|
||||
casts to `usize`; cap allocations sized by input; slice strings only at char boundaries.
|
||||
@@ -123,6 +124,12 @@ of it.
|
||||
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
|
||||
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
|
||||
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
|
||||
- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it
|
||||
passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with
|
||||
`#[ignore = "flaky: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
|
||||
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
|
||||
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
|
||||
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
|
||||
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
|
||||
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
|
||||
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
|
||||
|
||||
@@ -39,9 +39,10 @@ of it.
|
||||
"unsupported" error or is disabled. Sole exception: a provably infallible literal, as `#[allow(clippy::expect_used)]`
|
||||
+ `.expect("why it can't fail")`.
|
||||
- **`unsafe` lives only in `crates/sysmem`** (one FFI call, `malloc_zone_pressure_relief`, that returns freed
|
||||
allocator pages to macOS after raw decodes). Every other production crate root has `#![forbid(unsafe_code)]`. A new
|
||||
unsafe need goes in an isolated, well-tested helper crate like it: `// SAFETY:` on every block, a safe API, a safe
|
||||
fallback where possible, and a line here naming it.
|
||||
allocator pages to macOS after raw decodes) **and `crates/wincolor`** (Win32 calls that read the colour profile
|
||||
Windows assigns to the monitor showing the window, and whether Windows colour-manages that monitor itself). Every
|
||||
other production crate root has `#![forbid(unsafe_code)]`. A new unsafe need goes in an isolated, well-tested helper
|
||||
crate like them: `// SAFETY:` on every block, a safe API, a safe fallback where possible, and a line here naming it.
|
||||
- **Input-derived numbers are hostile:** `get()` instead of `[i]`/`[a..b]` for offsets from files, users, agents or
|
||||
arithmetic on them; checked/saturating math for lengths, offsets and counts; no division by zero, NaN/inf or negative
|
||||
casts to `usize`; cap allocations sized by input; slice strings only at char boundaries.
|
||||
@@ -137,6 +138,12 @@ of it.
|
||||
with `/usr/bin/time`. Record numbers in `plan/STATUS.md` → Metrics. Budgets: slider update ≤ 16 ms (draft) / loupe
|
||||
≤ 60 ms on ~2.5 MP; export ≤ 1 s per 24 MP JPEG.
|
||||
- Never commit media: test images are procedural (`lightcraft-scenes`) or CC0 downloads in the gitignored `corpus/`.
|
||||
- **Flaky tests:** a test that fails, then passes on a rerun of the same commit, is flaky. Don't rerun until it
|
||||
passes and move on: open an issue with the failing log, and if it failed on two unrelated PRs, quarantine it with
|
||||
`#[ignore = "flaky: #<issue>"]` (a doctest: an `ignore` code fence and a comment naming the issue) in a PR of its
|
||||
own until the issue is fixed. Never quarantine a test that fails every time; fix the code or the test. A test that
|
||||
hangs is a failure too: under `cargo test`, libtest's "has been running for over 60 seconds" line names it; under
|
||||
nextest (`LIGHTCRAFT_NEXTEST=1`), its `SLOW` lines do.
|
||||
- A test that can't run here (no GPU, corpus file, craft-fonts face, model) calls `lightcraft_testkit::skip!(Gpu, "why")`
|
||||
before it returns, not a bare `eprintln!`. `cargo xtask ci` then lists the skips and the machine's GPU adapters and
|
||||
data, and writes `target/ci/report.json` and `target/ci/summary.md` (Markdown for a PR).
|
||||
|
||||
Generated
+31
@@ -2139,6 +2139,16 @@ version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
|
||||
|
||||
[[package]]
|
||||
name = "fs4"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5"
|
||||
dependencies = [
|
||||
"rustix 1.1.5",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "futures-core"
|
||||
version = "0.3.34"
|
||||
@@ -3589,12 +3599,14 @@ dependencies = [
|
||||
"lightcraft-sysmem",
|
||||
"lightcraft-testkit",
|
||||
"lightcraft-ui-egui",
|
||||
"lightcraft-wincolor",
|
||||
"log",
|
||||
"muda",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"pollster 1.0.1",
|
||||
"raw-window-handle",
|
||||
"rfd",
|
||||
"serde_json",
|
||||
"winit",
|
||||
@@ -3732,6 +3744,7 @@ dependencies = [
|
||||
"ab_glyph",
|
||||
"chrono",
|
||||
"craft-docpath",
|
||||
"fs4",
|
||||
"harfrust 0.13.3",
|
||||
"jxl-oxide",
|
||||
"libc",
|
||||
@@ -3796,6 +3809,13 @@ dependencies = [
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-film"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-geocode"
|
||||
version = "0.18.0"
|
||||
@@ -4043,6 +4063,7 @@ dependencies = [
|
||||
"lightcraft-slideshow",
|
||||
"lightcraft-testkit",
|
||||
"log",
|
||||
"pollster 1.0.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"toml",
|
||||
@@ -4058,9 +4079,11 @@ dependencies = [
|
||||
"egui",
|
||||
"js-sys",
|
||||
"lightcraft-codecs",
|
||||
"lightcraft-color",
|
||||
"lightcraft-engine",
|
||||
"lightcraft-preview",
|
||||
"lightcraft-raster",
|
||||
"lightcraft-raw",
|
||||
"lightcraft-ui-egui",
|
||||
"log",
|
||||
"serde",
|
||||
@@ -4070,6 +4093,14 @@ dependencies = [
|
||||
"web-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lightcraft-wincolor"
|
||||
version = "0.18.0"
|
||||
dependencies = [
|
||||
"lightcraft-testkit",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linebender_resource_handle"
|
||||
version = "0.1.1"
|
||||
|
||||
@@ -23,6 +23,7 @@ lightcraft-denoise = { path = "crates/denoise", default-features = false }
|
||||
lightcraft-geom = { path = "crates/geom" }
|
||||
lightcraft-faces = { path = "crates/faces" }
|
||||
lightcraft-sysmem = { path = "crates/sysmem" }
|
||||
lightcraft-wincolor = { path = "crates/wincolor" }
|
||||
lightcraft-color = { path = "crates/color" }
|
||||
lightcraft-raster = { path = "crates/raster" }
|
||||
lightcraft-tiff = { path = "crates/tiff" }
|
||||
@@ -30,6 +31,7 @@ lightcraft-raw = { path = "crates/raw" }
|
||||
lightcraft-codecs = { path = "crates/codecs" }
|
||||
lightcraft-meta = { path = "crates/meta" }
|
||||
lightcraft-develop = { path = "crates/develop" }
|
||||
lightcraft-film = { path = "crates/film" }
|
||||
lightcraft-lensdb = { path = "crates/lensdb" }
|
||||
lightcraft-inpaint = { path = "crates/inpaint" }
|
||||
lightcraft-scenes = { path = "crates/scenes" }
|
||||
@@ -57,11 +59,14 @@ log = "0.4"
|
||||
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
|
||||
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
|
||||
rayon = "1"
|
||||
# free/total space of a drive (engine's low-disk alert); MIT OR Apache-2.0, pure Rust (rustix / windows-sys)
|
||||
fs4 = { version = "1.1", default-features = false }
|
||||
winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows
|
||||
proptest = "1"
|
||||
bytemuck = { version = "1", features = ["derive"] }
|
||||
crc32fast = "1"
|
||||
siphasher = "1"
|
||||
libm = "0.2" # pure-Rust maths for lightcraft-film (target-independent results)
|
||||
libc = "0.2" # dev-only: process CPU time in benches
|
||||
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
|
||||
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
//! `lightcraft-cli bench-cull FOLDER`: time what culling a shoot costs, headless, on real files.
|
||||
//!
|
||||
//! What a wedding photographer does most is open a folder of a few thousand raws, look at each
|
||||
//! one, rate it and move on. This times the engine side of each step on the files themselves (the
|
||||
//! desktop app's own frame timings come from `ui.inspect` → `perf.loupeSteps`, see
|
||||
//! `tools/cull-bench.py`):
|
||||
//!
|
||||
//! - browse: reading the folder into the Local view (`library.browse`, the whole folder);
|
||||
//! - grid thumbnails: the camera JPEG at 512 px for the first screen, on as many threads as the
|
||||
//! app renders with;
|
||||
//! - camera preview at loupe sizes (1280, 2560) and at full size (the 100 % view), one at a time;
|
||||
//! - LightCraft's render of the loupe (2560 px) from a cold source;
|
||||
//! - rating: `photo.rate` on many photos in a row, journal included;
|
||||
//! - import: adding N files in place to a fresh library, and copying M of them into it (`--n 0`:
|
||||
//! no import).
|
||||
//!
|
||||
//! `--files K` reads only the first K files (by name) of the folder, as browsing reads them: a
|
||||
//! sample of a folder on a network share, where reading thousands of raws takes hours.
|
||||
//!
|
||||
//! Each number is printed as `name: X ms wall` (median, with p95 and n), the format
|
||||
//! `cargo xtask bench` parses, and the lot as one JSON object with `--json FILE`. Nothing is
|
||||
//! written next to the photos: every library is made in a new folder of the run's own under
|
||||
//! `--work` (default: a folder in the system temp directory; nothing already there is deleted),
|
||||
//! XMP auto-write stays off, and the source folder is only read.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use lightcraft_engine::Session;
|
||||
use lightcraft_engine::catalog::PhotoId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const USAGE: &str = "lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]";
|
||||
|
||||
/// Threads the app renders thumbnails with (`Renderer::default`: cores − 1, at most 6).
|
||||
fn render_threads() -> usize {
|
||||
std::thread::available_parallelism().map(|n| n.get().saturating_sub(1)).unwrap_or(2).clamp(2, 6)
|
||||
}
|
||||
|
||||
/// Median, p95 and count of `ms` (milliseconds).
|
||||
fn stats(ms: &[f64]) -> Value {
|
||||
if ms.is_empty() {
|
||||
return Value::Null;
|
||||
}
|
||||
let mut v = ms.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
let at = |q: f64| v.get(((v.len() - 1) as f64 * q).round() as usize).copied().unwrap_or(0.0);
|
||||
json!({"p50": round(at(0.5)), "p95": round(at(0.95)), "max": round(at(1.0)), "n": v.len()})
|
||||
}
|
||||
|
||||
fn round(x: f64) -> f64 {
|
||||
(x * 10.0).round() / 10.0
|
||||
}
|
||||
|
||||
fn ms_since(t: Instant) -> f64 {
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Print one result line the way `xtask bench` parses it (`name: X ms wall`).
|
||||
fn line(name: &str, s: &Value) {
|
||||
if let Some(p50) = s.get("p50").and_then(Value::as_f64) {
|
||||
println!("{name}: {p50:.1} ms wall (p95 {} ms, n {})", s["p95"], s["n"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, empty folder `name` in this run's own folder; never deletes anything already there.
|
||||
fn fresh_dir(root: &Path, name: &str) -> Result<PathBuf, String> {
|
||||
let d = root.join(name);
|
||||
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// A folder of this run's own under `work`, which must not exist yet: a run never deletes or
|
||||
/// reuses what is already under `--work`.
|
||||
fn run_dir(work: &Path) -> Result<PathBuf, String> {
|
||||
std::fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?;
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = RUNS.fetch_add(1, Ordering::Relaxed);
|
||||
let d = work.join(format!("bench-cull-run-{}-{stamp}-{n}", std::process::id()));
|
||||
std::fs::create_dir(&d).map_err(|e| format!("{}: {e}", d.display()))?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// `take` items of `v` after the first `skip` (photos the stages before have read, so cold in the
|
||||
/// file cache), or, when `v` has no more than `skip`, its first `take`: a small folder is measured
|
||||
/// on photos already read rather than not at all.
|
||||
fn sample_after<T>(v: &[T], skip: usize, take: usize) -> &[T] {
|
||||
let from = if v.len() > skip { skip } else { 0 };
|
||||
let rest = v.get(from..).unwrap_or_default();
|
||||
rest.get(..take.min(rest.len())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether `path` names a file in `folder` (the source folder, which a run only reads), checked
|
||||
/// twice: where its own entry sits (the folder holding it, the final link not followed: writing the
|
||||
/// results replaces that entry, so a link to a file elsewhere that sits in the source folder, maybe
|
||||
/// standing for a photo, would be replaced; CodeRabbit on #3080), and where it resolves to: a file
|
||||
/// that is there by itself (a link to a photo there is the photo), a link that points nowhere yet
|
||||
/// by where writing through it would create the file, and anything else by its nearest folder that
|
||||
/// exists (a `--work` folder may not be there yet).
|
||||
fn inside_source(path: &Path, folder: &Path) -> bool {
|
||||
let Ok(folder) = std::fs::canonicalize(folder) else { return false };
|
||||
entry_inside(path, &folder) || resolves_inside(path, &folder, 0)
|
||||
}
|
||||
|
||||
/// Whether the folder holding `path`'s own entry (its nearest folder that exists, resolved) is in
|
||||
/// `folder` (already resolved). The entry itself is not followed.
|
||||
fn entry_inside(path: &Path, folder: &Path) -> bool {
|
||||
let mut p = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
loop {
|
||||
if let Ok(c) = std::fs::canonicalize(p) {
|
||||
return c.starts_with(folder);
|
||||
}
|
||||
match p.parent() {
|
||||
Some(up) if !up.as_os_str().is_empty() => p = up,
|
||||
Some(_) => p = Path::new("."),
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`inside_source`] for a `folder` already resolved; `hops`: links followed so far (a loop of
|
||||
/// links counts as inside: refused).
|
||||
fn resolves_inside(path: &Path, folder: &Path, hops: u32) -> bool {
|
||||
if let Ok(c) = std::fs::canonicalize(path) {
|
||||
return c.starts_with(folder);
|
||||
}
|
||||
if let Ok(target) = std::fs::read_link(path) {
|
||||
if hops >= 40 {
|
||||
return true;
|
||||
}
|
||||
let target = path.parent().map_or_else(|| target.clone(), |dir| dir.join(&target));
|
||||
return resolves_inside(&target, folder, hops + 1);
|
||||
}
|
||||
entry_inside(path, folder)
|
||||
}
|
||||
|
||||
/// Refuse `--json` or `--work` in the folder being measured: nothing is written next to the photos,
|
||||
/// the results and the run's libraries included. Checked before anything is made.
|
||||
fn check_outputs(folder: &Path, json: Option<&Path>, work: &Path) -> Result<(), String> {
|
||||
// a `..` after a folder not made yet can't be resolved now, and the run makes that folder:
|
||||
// `--json NEW/../FOLDER/r.json` would pass the checks below and land in the source folder
|
||||
// (CodeRabbit on #3544)
|
||||
for (name, p) in [("--json", json), ("--work", Some(work))] {
|
||||
if let Some(p) = p.filter(|p| p.components().any(|c| c == std::path::Component::ParentDir)) {
|
||||
return Err(format!("{}: {name} must not contain \"..\"; give the folder without it", p.display()));
|
||||
}
|
||||
}
|
||||
if let Some(j) = json.filter(|j| inside_source(j, folder)) {
|
||||
return Err(format!("{}: --json must not be in the folder being measured", j.display()));
|
||||
}
|
||||
if inside_source(&work.join("run"), folder) {
|
||||
return Err(format!("{}: --work must not be in the folder being measured", work.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn library(dir: &Path) -> Result<Session, String> {
|
||||
let mut s = Session::new().with_fs().with_system_clock();
|
||||
s.open_library(dir, false).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
// nothing is ever written next to the photos
|
||||
s.execute("library.xmpPreferences", &json!({"autoWrite": false})).map_err(|e| e.to_string())?;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn run(args: &[String]) -> Result<(), String> {
|
||||
let mut folder = None;
|
||||
let mut n = 2000usize;
|
||||
let mut copy = 200usize;
|
||||
let mut work = None;
|
||||
let mut json_out = None;
|
||||
let mut files = None;
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
let value = |i: usize| args.get(i + 1).cloned().ok_or_else(|| format!("{} needs a value\n{USAGE}", args[i]));
|
||||
match args[i].as_str() {
|
||||
"--n" => {
|
||||
n = value(i)?.parse().map_err(|_| "--n needs a number".to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
"--copy" => {
|
||||
copy = value(i)?.parse().map_err(|_| "--copy needs a number".to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
"--files" => {
|
||||
files = Some(value(i)?.parse::<usize>().map_err(|_| "--files needs a number".to_string())?);
|
||||
i += 1;
|
||||
}
|
||||
"--work" => {
|
||||
work = Some(PathBuf::from(value(i)?));
|
||||
i += 1;
|
||||
}
|
||||
"--json" => {
|
||||
json_out = Some(PathBuf::from(value(i)?));
|
||||
i += 1;
|
||||
}
|
||||
"-h" | "--help" => {
|
||||
println!("{USAGE}");
|
||||
return Ok(());
|
||||
}
|
||||
a if a.starts_with("--") => return Err(format!("unknown option {a}\n{USAGE}")),
|
||||
// (a second folder would replace the first and be timed in its place: CodeRabbit on #3583)
|
||||
a if folder.is_some() => return Err(format!("{a}: one FOLDER only\n{USAGE}")),
|
||||
a => folder = Some(PathBuf::from(a)),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
let folder = folder.ok_or_else(|| USAGE.to_string())?;
|
||||
if !folder.is_dir() {
|
||||
return Err(format!("{}: not a folder", folder.display()));
|
||||
}
|
||||
let work = work.unwrap_or_else(|| std::env::temp_dir().join(format!("lightcraft-bench-cull-{}", std::process::id())));
|
||||
check_outputs(&folder, json_out.as_deref(), &work)?;
|
||||
let work = run_dir(&work)?;
|
||||
let mut out = json!({"folder": folder.display().to_string(), "threads": render_threads()});
|
||||
|
||||
// --- browse: the whole folder into the Local view -------------------------------------------
|
||||
let mut s = library(&fresh_dir(&work, "lib-browse")?)?;
|
||||
// `--files K`: only the first K files by name, read as browsing reads them (a sample of a slow
|
||||
// network folder)
|
||||
let t = Instant::now();
|
||||
let (photos, ids): (u64, Vec<PhotoId>) = match files {
|
||||
None => {
|
||||
let r = s.execute("library.browse", &json!({"path": folder.display().to_string()})).map_err(|e| e.to_string())?;
|
||||
(r["photos"].as_u64().unwrap_or(0), s.visible_cloned())
|
||||
}
|
||||
Some(k) => {
|
||||
let mut list: Vec<String> = std::fs::read_dir(&folder)
|
||||
.map_err(|e| format!("{}: {e}", folder.display()))?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file() && lightcraft_engine::import::is_supported(p))
|
||||
.map(|p| p.display().to_string())
|
||||
.collect();
|
||||
list.sort();
|
||||
list.truncate(k);
|
||||
let r = s.execute("library.import", &json!({"paths": list, "mode": "add", "local": true})).map_err(|e| e.to_string())?;
|
||||
let ids: Vec<PhotoId> = r["imported"].as_array().into_iter().flatten().filter_map(Value::as_u64).map(PhotoId).collect();
|
||||
(ids.len() as u64, ids)
|
||||
}
|
||||
};
|
||||
let browse_ms = ms_since(t);
|
||||
let what = if files.is_some() { "first files" } else { "whole folder" };
|
||||
println!("browse {photos} photos ({what}): {browse_ms:.1} ms wall");
|
||||
out["browse"] = json!({"ms": round(browse_ms), "photos": photos, "perPhotoMs": round(browse_ms / photos.max(1) as f64)});
|
||||
let paths: Vec<String> = ids
|
||||
.iter()
|
||||
.filter_map(|id| match &s.catalog.photo(*id)?.source {
|
||||
lightcraft_engine::catalog::Source::File { path } => Some(path.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if paths.is_empty() {
|
||||
return Err(format!("{}: no photos", folder.display()));
|
||||
}
|
||||
let loader = s.media.preview_loader.clone().ok_or("no preview loader")?;
|
||||
|
||||
// --- grid thumbnails: the first screen, in parallel ------------------------------------------
|
||||
let screen: Vec<String> = paths.iter().take(48).cloned().collect();
|
||||
let next = Arc::new(AtomicUsize::new(0));
|
||||
let t = Instant::now();
|
||||
let per: Vec<(f64, f64)> = std::thread::scope(|sc| {
|
||||
let workers: Vec<_> = (0..render_threads())
|
||||
.map(|_| {
|
||||
let (next, loader, screen) = (next.clone(), loader.clone(), &screen);
|
||||
sc.spawn(move || {
|
||||
let mut done = Vec::new();
|
||||
while let Some(p) = screen.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
let a = Instant::now();
|
||||
let _ = loader(p, 512);
|
||||
done.push((ms_since(a), ms_since(t)));
|
||||
}
|
||||
done
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
workers.into_iter().flat_map(|w| w.join().unwrap_or_default()).collect()
|
||||
});
|
||||
let first = per.iter().map(|p| p.1).fold(f64::INFINITY, f64::min);
|
||||
let all = per.iter().map(|p| p.1).fold(0.0, f64::max);
|
||||
let each = stats(&per.iter().map(|p| p.0).collect::<Vec<_>>());
|
||||
println!("grid: first thumbnail: {first:.1} ms wall");
|
||||
println!("grid: {} thumbnails: {all:.1} ms wall", per.len());
|
||||
line("grid: one 512 px thumbnail", &each);
|
||||
out["thumbs"] = json!({"firstMs": round(first), "allMs": round(all), "count": per.len(), "each": each});
|
||||
|
||||
// --- camera previews at loupe sizes, one at a time (what a step costs without look-ahead) -----
|
||||
let sample = sample_after(&paths, 48, 20);
|
||||
for edge in [1280usize, 2560, usize::MAX] {
|
||||
let ms: Vec<f64> = sample
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let a = Instant::now();
|
||||
let _ = loader(p, edge);
|
||||
ms_since(a)
|
||||
})
|
||||
.collect();
|
||||
let name = if edge == usize::MAX { "camera preview full size (100 %)".to_string() } else { format!("camera preview {edge} px") };
|
||||
let st = stats(&ms);
|
||||
line(&name, &st);
|
||||
out[if edge == usize::MAX { "cameraFull".to_string() } else { format!("camera{edge}") }] = st;
|
||||
}
|
||||
|
||||
// --- LightCraft's loupe render (2560 px) from a cold source --------------------------------
|
||||
let ms: Vec<f64> = sample_after(&ids, 80, 5)
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
let job = s.loupe_job(*id, 2560, 1708, true)?;
|
||||
let a = Instant::now();
|
||||
let r = job.run();
|
||||
let t = ms_since(a);
|
||||
r.rendered.is_ok().then_some(t)
|
||||
})
|
||||
.collect();
|
||||
let st = stats(&ms);
|
||||
line("loupe render 2560 px (cold)", &st);
|
||||
out["loupeRender"] = st;
|
||||
|
||||
// --- rating: a culling pass of keypresses ---------------------------------------------------
|
||||
let ms: Vec<f64> = ids
|
||||
.iter()
|
||||
.take(50)
|
||||
.enumerate()
|
||||
.filter_map(|(k, id)| {
|
||||
// the key acts on the selected photo, as in the loupe
|
||||
s.execute("library.select", &json!({"ids": [id.0], "active": id.0})).ok()?;
|
||||
let a = Instant::now();
|
||||
s.execute("photo.rate", &json!({"rating": (k % 5) + 1})).ok()?;
|
||||
Some(ms_since(a))
|
||||
})
|
||||
.collect();
|
||||
let st = stats(&ms);
|
||||
line("rate one photo (journal written)", &st);
|
||||
out["rate"] = st;
|
||||
drop(s);
|
||||
|
||||
// --- import: add in place, then copy ----------------------------------------------------------
|
||||
if n == 0 {
|
||||
return finish(out, json_out);
|
||||
}
|
||||
let add: Vec<String> = paths.iter().take(n).cloned().collect();
|
||||
let mut s = library(&fresh_dir(&work, "lib-add")?)?;
|
||||
let t = Instant::now();
|
||||
let r = s.execute("library.import", &json!({"paths": add, "mode": "add"})).map_err(|e| e.to_string())?;
|
||||
let add_ms = ms_since(t);
|
||||
let added = r["imported"].as_array().map(Vec::len).unwrap_or(0);
|
||||
println!("import {added} photos in place: {add_ms:.1} ms wall");
|
||||
out["importAdd"] = json!({"ms": round(add_ms), "photos": added, "perPhotoMs": round(add_ms / added.max(1) as f64)});
|
||||
drop(s);
|
||||
if copy > 0 {
|
||||
let some: Vec<String> = paths.iter().take(copy).cloned().collect();
|
||||
let lib = fresh_dir(&work, "lib-copy")?;
|
||||
let mut s = library(&lib)?;
|
||||
let t = Instant::now();
|
||||
let r = s
|
||||
.execute("library.import", &json!({"paths": some, "mode": "copy", "destination": lib.join("Originals").display().to_string()}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let copy_ms = ms_since(t);
|
||||
let copied = r["imported"].as_array().map(Vec::len).unwrap_or(0);
|
||||
println!("import {copied} photos by copying: {copy_ms:.1} ms wall");
|
||||
out["importCopy"] = json!({"ms": round(copy_ms), "photos": copied, "perPhotoMs": round(copy_ms / copied.max(1) as f64)});
|
||||
drop(s);
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
}
|
||||
finish(out, json_out)
|
||||
}
|
||||
|
||||
fn finish(out: Value, json_out: Option<PathBuf>) -> Result<(), String> {
|
||||
if let Some(p) = json_out {
|
||||
write_replacing(&p, serde_json::to_string_pretty(&out).unwrap_or_default().as_bytes())?;
|
||||
}
|
||||
println!("{}", serde_json::to_string(&out).unwrap_or_default());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `bytes` to `path` through a new file next to it, renamed over `path`: an existing `path`
|
||||
/// is replaced as a name, never written into. A hard link there shares its data with another file
|
||||
/// (maybe a photo in the source folder, which [`inside_source`] can't tell), and writing into it
|
||||
/// would overwrite that file too (CodeRabbit on #3077). The temporary file is removed on error.
|
||||
fn write_replacing(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
use std::io::Write;
|
||||
let err = |e: std::io::Error| format!("{}: {e}", path.display());
|
||||
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
|
||||
let name = path.file_name().ok_or_else(|| format!("{}: not a file name", path.display()))?;
|
||||
static TEMPS: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = TEMPS.fetch_add(1, Ordering::Relaxed);
|
||||
let mut tmp_name = std::ffi::OsString::from(".");
|
||||
tmp_name.push(name);
|
||||
tmp_name.push(format!(".{}-{n}.tmp", std::process::id()));
|
||||
let tmp = dir.join(tmp_name);
|
||||
let written =
|
||||
std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|()| f.sync_all()));
|
||||
if let Err(e) = written.and_then(|()| std::fs::rename(&tmp, path)) {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return Err(err(e));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_second_folder_is_an_error() {
|
||||
let e = run(&["a".to_string(), "b".to_string()]).unwrap_err();
|
||||
assert!(e.starts_with("b: one FOLDER only"), "{e}");
|
||||
}
|
||||
|
||||
/// `--work` may hold anything: a run makes a new folder of its own there and never deletes
|
||||
/// what is already in it (it used to remove `lib-browse`, `lib-add` and `lib-copy` there).
|
||||
#[test]
|
||||
fn a_run_never_deletes_what_is_under_work() {
|
||||
// a folder this test owns (made new), so the cleanup below removes nothing else
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let keep = work.join("lib-browse").join("keep.txt");
|
||||
std::fs::create_dir_all(keep.parent().unwrap()).unwrap();
|
||||
std::fs::write(&keep, b"mine").unwrap();
|
||||
let a = run_dir(&work).unwrap();
|
||||
let b = run_dir(&work).unwrap();
|
||||
assert_ne!(a, b);
|
||||
fresh_dir(&a, "lib-browse").unwrap();
|
||||
assert!(fresh_dir(&a, "lib-browse").is_err(), "an existing folder is never reused");
|
||||
assert_eq!(std::fs::read(&keep).unwrap(), b"mine");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// A folder too small for the disjoint samples is measured on the photos it has (CodeRabbit on #3077).
|
||||
#[test]
|
||||
fn a_small_folder_is_sampled_from_its_start() {
|
||||
let v: Vec<u32> = (0..100).collect();
|
||||
assert_eq!(sample_after(&v, 48, 20), &v[48..68]);
|
||||
assert_eq!(sample_after(&v, 90, 20), &v[90..100]);
|
||||
assert_eq!(sample_after(&v[..3], 48, 20), &v[..3]);
|
||||
assert_eq!(sample_after(&v[..48], 48, 5), &v[..5]);
|
||||
assert!(sample_after::<u32>(&[], 48, 20).is_empty());
|
||||
}
|
||||
|
||||
/// A file link at `at` to `target`.
|
||||
#[cfg(unix)]
|
||||
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
|
||||
std::os::unix::fs::symlink(target, at)
|
||||
}
|
||||
|
||||
/// A file link at `at` to `target` (Windows: needs Developer Mode or the right to make links).
|
||||
#[cfg(windows)]
|
||||
fn link(target: &Path, at: &Path) -> std::io::Result<()> {
|
||||
std::os::windows::fs::symlink_file(target, at)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn link(_: &Path, _: &Path) -> std::io::Result<()> {
|
||||
Err(std::io::Error::other("no file links here"))
|
||||
}
|
||||
|
||||
/// `--json` naming a link (made elsewhere) to a file in the source folder is refused: writing
|
||||
/// the results would follow it and overwrite a photo (CodeRabbit on #3080). So is a link that
|
||||
/// points to a file not made yet in the source folder, and a loop of links.
|
||||
#[test]
|
||||
fn a_json_link_into_the_source_folder_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let photo = src.join("a.jpg");
|
||||
std::fs::write(&photo, b"photo").unwrap();
|
||||
let to_photo = work.join("report.json");
|
||||
if let Err(e) = link(&photo, &to_photo) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
|
||||
return;
|
||||
}
|
||||
assert!(inside_source(&to_photo, &src), "a link to a photo in the source folder");
|
||||
let e = check_outputs(&src, Some(&to_photo), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json"), "{e}");
|
||||
let to_new = work.join("new.json");
|
||||
link(&src.join("not-yet.json"), &to_new).unwrap();
|
||||
assert!(inside_source(&to_new, &src), "a link to a file not made yet in the source folder");
|
||||
let (x, y) = (work.join("x.json"), work.join("y.json"));
|
||||
link(&y, &x).unwrap();
|
||||
link(&x, &y).unwrap();
|
||||
assert!(inside_source(&x, &src), "a loop of links");
|
||||
let to_elsewhere = work.join("fine.json");
|
||||
link(&work.join("out.json"), &to_elsewhere).unwrap();
|
||||
assert!(!inside_source(&to_elsewhere, &src), "a link to a file outside is fine");
|
||||
assert_eq!(std::fs::read(&photo).unwrap(), b"photo");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a link that sits in the source folder and points to a file outside it is
|
||||
/// refused: writing the results would replace the link itself, an entry of the source folder
|
||||
/// (CodeRabbit on #3080). The link stays as it was.
|
||||
#[test]
|
||||
fn a_json_link_in_the_source_folder_to_a_file_outside_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let outside = work.join("out.json");
|
||||
std::fs::write(&outside, b"outside").unwrap();
|
||||
let in_src = src.join("a.jpg");
|
||||
if let Err(e) = link(&outside, &in_src) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a file link here ({e}); Windows needs Developer Mode");
|
||||
return;
|
||||
}
|
||||
assert!(inside_source(&in_src, &src), "a link in the source folder, wherever it points");
|
||||
let e = check_outputs(&src, Some(&in_src), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json"), "{e}");
|
||||
assert!(std::fs::symlink_metadata(&in_src).unwrap().file_type().is_symlink(), "the link stays");
|
||||
assert_eq!(std::fs::read_link(&in_src).unwrap(), outside);
|
||||
assert_eq!(std::fs::read(&outside).unwrap(), b"outside");
|
||||
// a new file in the source folder (nothing there yet) is refused too
|
||||
assert!(check_outputs(&src, Some(&src.join("new.json")), &work.join("elsewhere")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a hard link (made elsewhere) to a photo in the source folder passes
|
||||
/// [`inside_source`] (a hard link has no target to resolve), so the results replace the link
|
||||
/// instead of writing into it: the photo keeps its bytes (CodeRabbit on #3077).
|
||||
#[test]
|
||||
fn a_json_hard_link_to_a_photo_leaves_the_photo_alone() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let photo = src.join("a.jpg");
|
||||
std::fs::write(&photo, b"photo").unwrap();
|
||||
let report = work.join("report.json");
|
||||
if let Err(e) = std::fs::hard_link(&photo, &report) {
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
lightcraft_testkit::skip!(System, "can't make a hard link here ({e})");
|
||||
return;
|
||||
}
|
||||
finish(json!({"browse": 1}), Some(report.clone())).unwrap();
|
||||
assert_eq!(std::fs::read(&photo).unwrap(), b"photo", "the photo is unchanged");
|
||||
let written: Value = serde_json::from_slice(&std::fs::read(&report).unwrap()).unwrap();
|
||||
assert_eq!(written["browse"], 1);
|
||||
let left: Vec<_> = std::fs::read_dir(&work).unwrap().flatten().map(|e| e.file_name()).collect();
|
||||
assert_eq!(left.len(), 2, "no temporary file is left: {left:?}");
|
||||
// a folder that isn't there: an error, nothing panics
|
||||
assert!(write_replacing(&work.join("missing").join("r.json"), b"x").is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--json` naming a file in the source folder is refused (CodeRabbit on #3077); elsewhere it is fine.
|
||||
#[test]
|
||||
fn the_results_never_go_in_the_source_folder() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let sub = fresh_dir(&src, "sub").unwrap();
|
||||
assert!(inside_source(&src.join("a.png"), &src));
|
||||
assert!(inside_source(&sub.join("x.json"), &src));
|
||||
assert!(inside_source(&src.join("sub").join("..").join("a.png"), &src));
|
||||
assert!(!inside_source(&work.join("out.json"), &src));
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// `--work` in the source folder is refused before anything is made there, also when it doesn't
|
||||
/// exist yet (CodeRabbit on #3077); elsewhere it is fine.
|
||||
#[test]
|
||||
fn the_work_folder_never_goes_in_the_source_folder() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let inside = src.join("out").join("deeper");
|
||||
let e = check_outputs(&src, None, &inside).unwrap_err();
|
||||
assert!(e.contains("--work"), "{e}");
|
||||
assert!(check_outputs(&src, None, &src).is_err(), "the source folder itself");
|
||||
assert!(!src.join("out").exists(), "nothing was made in the source folder");
|
||||
assert!(check_outputs(&src, None, &work.join("elsewhere")).is_ok());
|
||||
assert!(check_outputs(&src, Some(&src.join("r.json")), &work.join("elsewhere")).is_err());
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
|
||||
/// A `..` in `--json` or `--work` is refused: after a folder the run hasn't made yet it can't be
|
||||
/// resolved now, and would lead into the source folder once the run makes it (CodeRabbit on #3544).
|
||||
#[test]
|
||||
fn a_dot_dot_in_the_outputs_is_refused() {
|
||||
let work = run_dir(&std::env::temp_dir()).unwrap();
|
||||
let src = fresh_dir(&work, "src").unwrap();
|
||||
let sneaky = work.join("new").join("..").join("src").join("r.json");
|
||||
let e = check_outputs(&src, Some(&sneaky), &work.join("elsewhere")).unwrap_err();
|
||||
assert!(e.contains("--json") && e.contains(".."), "{e}");
|
||||
let e = check_outputs(&src, None, &work.join("new").join("..").join("src")).unwrap_err();
|
||||
assert!(e.contains("--work"), "{e}");
|
||||
assert!(!work.join("new").exists(), "nothing was made");
|
||||
let _ = std::fs::remove_dir_all(&work);
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,13 @@
|
||||
//! lightcraft-cli commands [--json]
|
||||
//! lightcraft-cli controls [--json]
|
||||
//! lightcraft-cli calibrate [--max N] [--out DIR] FOLDERS/FILES…
|
||||
//! lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
|
||||
//! ```
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod alloc_release;
|
||||
mod bench_cull;
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
@@ -110,6 +112,12 @@ USAGE:
|
||||
model, written as <model>.json to DIR (default: the profiles folder LightCraft reads,
|
||||
<config>/camera-profiles, or $LIGHTCRAFT_CAMERA_PROFILES). Raws of a profiled model then
|
||||
take their colour from the profile and only their tone from their own JPEG.
|
||||
lightcraft-cli bench-cull FOLDER [--files K] [--n N] [--copy M] [--work DIR] [--json FILE]
|
||||
Time what culling a shoot costs on its own files: reading the folder (browse), the first
|
||||
screen of grid thumbnails, camera previews at loupe sizes and full size, a loupe render,
|
||||
rating, and importing N files in place (default 2000) and copying M (default 200). Libraries
|
||||
are made in a new folder under DIR (default: the temp folder); nothing is written next to the
|
||||
photos. --files K reads only the first K files by name (a sample of a slow network folder).
|
||||
lightcraft-cli --version | --help
|
||||
";
|
||||
|
||||
@@ -176,6 +184,7 @@ fn main() -> ExitCode {
|
||||
Some("controls") => controls(&args[1..]),
|
||||
Some("denoise-serve") => denoise_serve(&args[1..]),
|
||||
Some("calibrate") => calibrate(&args[1..]),
|
||||
Some("bench-cull") => bench_cull::run(&args[1..]),
|
||||
Some("--version" | "-V" | "version") => {
|
||||
println!("lightcraft-cli {}", env!("CARGO_PKG_VERSION"));
|
||||
Ok(())
|
||||
|
||||
@@ -101,6 +101,75 @@ fn gradient_png(path: &std::path::Path) {
|
||||
std::fs::write(path, png).unwrap();
|
||||
}
|
||||
|
||||
/// PERF-CULL-5: `bench-cull` times a folder end to end and writes nothing next to the photos.
|
||||
#[test]
|
||||
fn bench_cull_times_a_folder_and_leaves_it_untouched() {
|
||||
let dir = tmp("bench-cull-src");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for (seed, name) in ["a.png", "b.png", "c.png"].iter().enumerate() {
|
||||
// three different pictures (the same bytes would import as one photo)
|
||||
let img = lightcraft_raster::Rgba8::from_fn(120, 80, |x, y| [(x * 2) as u8, (y * 3) as u8, (seed * 80) as u8, 255]);
|
||||
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
|
||||
std::fs::write(dir.join(name), png).unwrap();
|
||||
}
|
||||
// every file's name and bytes: nothing added, and no photo written into (CodeRabbit on #3577)
|
||||
let listing = |d: &std::path::Path| {
|
||||
let mut v: Vec<(String, Vec<u8>)> = std::fs::read_dir(d)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap())
|
||||
.map(|e| (e.file_name().to_string_lossy().to_string(), std::fs::read(e.path()).unwrap()))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
};
|
||||
let before = listing(&dir);
|
||||
let work = tmp("bench-cull-work");
|
||||
let json_out = tmp("bench-cull.json");
|
||||
let r = Command::new(binary())
|
||||
.arg("bench-cull")
|
||||
.arg(&dir)
|
||||
.args(["--n", "3", "--copy", "1", "--work"])
|
||||
.arg(&work)
|
||||
.arg("--json")
|
||||
.arg(&json_out)
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&r.stdout);
|
||||
assert!(r.status.success(), "{stdout}{}", String::from_utf8_lossy(&r.stderr));
|
||||
assert!(stdout.contains("browse 3 photos") && stdout.contains("ms wall"), "{stdout}");
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(&json_out).unwrap()).unwrap();
|
||||
assert_eq!(v["browse"]["photos"], 3);
|
||||
assert_eq!(v["importAdd"]["photos"], 3);
|
||||
assert_eq!(v["importCopy"]["photos"], 1);
|
||||
assert_eq!(v["rate"]["n"], 3);
|
||||
// a folder smaller than the samples is measured on the photos it has, not reported empty
|
||||
for stage in ["camera1280", "camera2560", "cameraFull", "loupeRender"] {
|
||||
assert_eq!(v[stage]["n"], 3, "{stage}: {}", v[stage]);
|
||||
}
|
||||
assert_eq!(listing(&dir), before, "nothing written next to the photos");
|
||||
// results asked for in the source folder: refused, the photo untouched
|
||||
let photo = std::fs::read(dir.join("a.png")).unwrap();
|
||||
let r = Command::new(binary())
|
||||
.arg("bench-cull")
|
||||
.arg(&dir)
|
||||
.args(["--n", "0", "--work"])
|
||||
.arg(&work)
|
||||
.arg("--json")
|
||||
.arg(dir.join("a.png"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("--json"), "{}", String::from_utf8_lossy(&r.stderr));
|
||||
assert_eq!(std::fs::read(dir.join("a.png")).unwrap(), photo);
|
||||
assert_eq!(listing(&dir), before);
|
||||
// a sample of the folder, no import
|
||||
let r = Command::new(binary()).arg("bench-cull").arg(&dir).args(["--files", "2", "--n", "0", "--work"]).arg(&work).output().unwrap();
|
||||
let stdout = String::from_utf8_lossy(&r.stdout);
|
||||
assert!(r.status.success() && stdout.contains("browse 2 photos (first files)") && !stdout.contains("import"), "{stdout}");
|
||||
// a bad folder is an error, not a panic
|
||||
let r = Command::new(binary()).args(["bench-cull", "/no/such/folder"]).output().unwrap();
|
||||
assert!(!r.status.success() && String::from_utf8_lossy(&r.stderr).contains("not a folder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calibrate_reads_raf_inputs_and_reports_bad_files() {
|
||||
let input = tmp("invalid.RAF");
|
||||
|
||||
@@ -80,3 +80,5 @@ heif = ["lightcraft-codecs/heif"]
|
||||
|
||||
[dev-dependencies]
|
||||
egui = { workspace = true }
|
||||
lightcraft-color = { workspace = true }
|
||||
lightcraft-raw = { workspace = true }
|
||||
@@ -12,7 +12,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use lightcraft_engine::files::{load_bytes, probe_bytes};
|
||||
use lightcraft_engine::files::{load_bytes_decoded, probe_bytes};
|
||||
use lightcraft_engine::media::{FileLoader, FileProbe};
|
||||
|
||||
/// Prefix of the catalog paths of files kept in browser storage.
|
||||
@@ -144,9 +144,11 @@ impl Originals {
|
||||
/// Engine hooks that decode/probe from memory.
|
||||
pub fn hooks(&self) -> (FileLoader, FileProbe) {
|
||||
let s = self.clone();
|
||||
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize| {
|
||||
// (an imported camera profile is not applied on the web, as in the render worker: a raw keeps its own colour,
|
||||
// whether it decodes in a worker or inline when workers are unavailable)
|
||||
let loader: FileLoader = Arc::new(move |path: &str, max_edge: usize, with: lightcraft_engine::media::RawDecode<'_>| {
|
||||
let bytes = s.get(path).ok_or_else(|| format!("{path}: the original is still loading from browser storage"))?;
|
||||
load_bytes(&bytes, max_edge)
|
||||
load_bytes_decoded(&bytes, max_edge, lightcraft_engine::media::RawDecode { dcp: None, outliers: with.outliers })
|
||||
});
|
||||
let s = self.clone();
|
||||
let probe: FileProbe = Arc::new(move |path: &str| {
|
||||
@@ -237,6 +239,64 @@ mod tests {
|
||||
assert_eq!(out.image.width, 20);
|
||||
}
|
||||
|
||||
/// CodeRabbit on #1063: without web workers a render runs inline and handed the selected camera profile to this
|
||||
/// loader, which applied it, so the picture differed from the worker's (which keeps the raw's own colour, the
|
||||
/// documented web behaviour). The loader now ignores it.
|
||||
#[test]
|
||||
fn the_web_loader_keeps_a_raws_own_colour_with_a_camera_profile() {
|
||||
use lightcraft_raw::*;
|
||||
let (w, h) = (32usize, 24usize);
|
||||
let raw = RawImage {
|
||||
format: RawFormat::Dng,
|
||||
width: w,
|
||||
height: h,
|
||||
cpp: 1,
|
||||
data: RawData::U16((0..w * h).map(|i| 256 + ((i % w) * 300 + (i / w) * 200) as u16).collect()),
|
||||
cfa: Cfa::bayer("RGGB"),
|
||||
bits: 14,
|
||||
black: BlackLevel::uniform(256.0),
|
||||
white: vec![16000.0],
|
||||
active_area: Rect::new(0, 0, w, h),
|
||||
crop: Rect::new(0, 0, w, h),
|
||||
orientation: Orientation::Normal,
|
||||
color: ColorData {
|
||||
illuminant: [21, 0],
|
||||
color_matrix: [Some(lightcraft_color::Mat3([[0.9, 0.2, -0.15], [-0.3, 1.25, 0.08], [0.02, -0.12, 0.85]])), None],
|
||||
as_shot_neutral: Some([0.5, 1.0, 0.7]),
|
||||
..Default::default()
|
||||
},
|
||||
wb_multipliers: None,
|
||||
linearized: false,
|
||||
pixel_aspect: 1.0,
|
||||
opcodes: OpcodeLists::default(),
|
||||
metadata: Default::default(),
|
||||
lens_metadata: Default::default(),
|
||||
};
|
||||
let dng = write_dng(&raw, &DngWriteOptions::default()).unwrap();
|
||||
// our own numbers: a matrix that swaps the camera's red and blue
|
||||
let swap = lightcraft_color::Mat3([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]).mul(&lightcraft_color::Mat3([
|
||||
[3.2406, -1.5372, -0.4986],
|
||||
[-0.9689, 1.8758, 0.0415],
|
||||
[0.0557, -0.2040, 1.0570],
|
||||
]));
|
||||
let profile = dcp::DcpProfile {
|
||||
name: "Swap".into(),
|
||||
camera_model: "LightCraft Test Camera".into(),
|
||||
color: ColorData { illuminant: [21, 0], color_matrix: [Some(swap), None], ..Default::default() },
|
||||
};
|
||||
assert_ne!(
|
||||
lightcraft_engine::files::load_bytes_with(&dng, 64, Some(&profile)).unwrap().0.data,
|
||||
lightcraft_engine::files::load_bytes_with(&dng, 64, None).unwrap().0.data,
|
||||
"the profile changes a raw's colour where it is applied"
|
||||
);
|
||||
let store = Originals::default();
|
||||
store.insert("h1", Arc::from(dng));
|
||||
let (loader, _) = store.hooks();
|
||||
let with = loader("web/h1/a.dng", 64, lightcraft_engine::media::RawDecode { dcp: Some(&profile), outliers: false }).unwrap();
|
||||
let without = loader("web/h1/a.dng", 64, Default::default()).unwrap();
|
||||
assert_eq!(with.0.data, without.0.data, "the web loader leaves it out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_names() {
|
||||
assert_eq!(download_name("dir/x-lightcraft.png"), "x-lightcraft.png");
|
||||
|
||||
@@ -129,7 +129,9 @@ impl WireJob {
|
||||
/// Identifies the decoded source this job needs.
|
||||
fn source_key(&self) -> String {
|
||||
match &self.origin {
|
||||
Source::File { path } => format!("{}:{:?}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge),
|
||||
Source::File { path } => {
|
||||
format!("{}:{:?}:{}:{}:{path}", self.cache_generation, self.source_identity, self.max_edge, self.settings.removes_hot_pixels())
|
||||
}
|
||||
Source::Demo { scene } => format!("{}:{:?}:{}:demo:{scene}", self.cache_generation, self.source_identity, self.max_edge),
|
||||
}
|
||||
}
|
||||
@@ -181,8 +183,10 @@ impl WorkerCore {
|
||||
None => {
|
||||
let src = match (&job.origin, original) {
|
||||
(Source::File { .. }, Some(bytes)) => {
|
||||
let (image, info) = lightcraft_engine::files::load_bytes(bytes, job.max_edge)?;
|
||||
DecodedSource::new(Arc::new(image), Some(info))
|
||||
let outliers = job.settings.removes_hot_pixels();
|
||||
let with = lightcraft_engine::media::RawDecode { dcp: None, outliers };
|
||||
let (image, info) = lightcraft_engine::files::load_bytes_decoded(bytes, job.max_edge, with)?;
|
||||
DecodedSource { outliers, ..DecodedSource::new(Arc::new(image), Some(info)) }
|
||||
}
|
||||
(Source::File { path }, None) => return Err(format!("{path}: original not found in browser storage")),
|
||||
(origin @ Source::Demo { .. }, _) => self.media.origin_ref(origin, job.max_edge).load_source()?,
|
||||
|
||||
@@ -318,6 +318,7 @@ impl Workers {
|
||||
loaded: None,
|
||||
quick: None,
|
||||
display: None,
|
||||
frame: None,
|
||||
};
|
||||
g.done.push((b.slot, r, 0.0));
|
||||
}
|
||||
@@ -409,6 +410,7 @@ impl Workers {
|
||||
loaded: None,
|
||||
quick: None,
|
||||
display: None,
|
||||
frame: None,
|
||||
},
|
||||
ms,
|
||||
));
|
||||
@@ -463,6 +465,7 @@ impl RenderOffload for Workers {
|
||||
loaded: None,
|
||||
quick: None,
|
||||
display: None,
|
||||
frame: None,
|
||||
};
|
||||
g.done.push((slot, r, 0.0));
|
||||
return None;
|
||||
|
||||
@@ -58,3 +58,6 @@ lightcraft-testkit = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# the colour profile of the monitor showing the window (`win_screen_profile`)
|
||||
lightcraft-wincolor = { workspace = true }
|
||||
raw-window-handle = "0.6"
|
||||
@@ -18,8 +18,6 @@ use std::time::Duration;
|
||||
const POLL: Duration = Duration::from_secs(3);
|
||||
/// A wait before trying again when colord isn't there (not installed, no system bus).
|
||||
const RETRY: Duration = Duration::from_secs(30);
|
||||
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
|
||||
const MAX_PROFILE: u64 = 16 << 20;
|
||||
|
||||
const SERVICE: &str = "org.freedesktop.ColorManager";
|
||||
const DEVICE: &str = "org.freedesktop.ColorManager.Device";
|
||||
@@ -72,7 +70,7 @@ fn read(conn: &zbus::blocking::Connection) -> Option<Vec<u8>> {
|
||||
}
|
||||
}
|
||||
let file = pick(&files)?;
|
||||
load(std::path::Path::new(file))
|
||||
crate::profile_file::load(std::path::Path::new(file))
|
||||
}
|
||||
|
||||
/// The profile to use for these displays' profile files: the one they share, `None` with none or
|
||||
@@ -83,15 +81,6 @@ fn pick(files: &[String]) -> Option<&str> {
|
||||
named.all(|f| f == first).then_some(first)
|
||||
}
|
||||
|
||||
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
|
||||
fn load(path: &std::path::Path) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
|
||||
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -105,21 +94,4 @@ mod tests {
|
||||
assert_eq!(pick(&s(&["/a.icc", "/b.icc"])), None, "which one the window is on isn't known");
|
||||
assert_eq!(pick(&s(&[""])), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_files_are_read_with_a_size_cap() {
|
||||
let dir = std::env::temp_dir().join(format!("colord-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let small = dir.join("small.icc");
|
||||
std::fs::write(&small, b"acsp").unwrap();
|
||||
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
|
||||
let empty = dir.join("empty.icc");
|
||||
std::fs::write(&empty, b"").unwrap();
|
||||
assert_eq!(load(&empty), None);
|
||||
assert_eq!(load(&dir.join("missing.icc")), None);
|
||||
let big = dir.join("big.icc");
|
||||
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
|
||||
assert_eq!(load(&big), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,12 @@ mod hdr_display;
|
||||
mod logging;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native_menu;
|
||||
#[cfg(any(target_os = "linux", windows))]
|
||||
mod profile_file;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod screen_profile;
|
||||
#[cfg(windows)]
|
||||
mod win_screen_profile;
|
||||
mod window_gpu;
|
||||
|
||||
use dialog_filter::FileDialogExt as _;
|
||||
@@ -79,7 +83,67 @@ fn app_icon() -> egui::IconData {
|
||||
eframe::icon_data::from_png_bytes(png).unwrap_or_default()
|
||||
}
|
||||
|
||||
struct App(LightcraftApp, PrefsWriter, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
|
||||
struct App(LightcraftApp, PrefsWriter, Option<WindowTextures>, #[cfg(target_os = "macos")] Option<native_menu::NativeMenu>);
|
||||
|
||||
/// Draws renders that stayed on the GPU: registers their textures with the window's egui-wgpu
|
||||
/// renderer (the GPU renderer runs on the window's device, see [`adopt_window_device`]).
|
||||
struct WindowTextures {
|
||||
device: eframe::wgpu::Device,
|
||||
queue: eframe::wgpu::Queue,
|
||||
renderer: std::sync::Arc<egui::mutex::RwLock<eframe::egui_wgpu::Renderer>>,
|
||||
}
|
||||
|
||||
impl lightcraft_ui_egui::render::ScreenTextures for WindowTextures {
|
||||
fn show(&mut self, frame: &lightcraft_engine::media::ScreenFrame, id: Option<egui::TextureId>) -> Option<egui::TextureId> {
|
||||
let view = frame.texture.create_view(&Default::default());
|
||||
let mut r = self.renderer.write();
|
||||
let filter = eframe::wgpu::FilterMode::Linear;
|
||||
Some(match id {
|
||||
Some(id) => {
|
||||
r.update_egui_texture_from_wgpu_texture(&self.device, &view, filter, id);
|
||||
id
|
||||
}
|
||||
None => r.register_native_texture(&self.device, &view, filter),
|
||||
})
|
||||
}
|
||||
|
||||
fn free(&mut self, id: egui::TextureId) {
|
||||
self.renderer.write().free_texture(&id);
|
||||
}
|
||||
|
||||
fn read(&self, frame: &lightcraft_engine::media::ScreenFrame) -> Option<egui::ColorImage> {
|
||||
match lightcraft_engine::gpu::read_texture(&self.device, &self.queue, &frame.texture, frame.width, frame.height) {
|
||||
Ok(img) => Some(egui::ColorImage::from_rgba_unmultiplied([img.width, img.height], img.data.as_flattened())),
|
||||
Err(e) => {
|
||||
log::warn!("gpu: a view can't be read back for the screenshot: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render on the window's device (off the UI thread: building the kernels takes a moment), so the
|
||||
/// loupe's drafts are drawn straight from the GPU; the textures they leave are shown through
|
||||
/// [`WindowTextures`] once that worked. Otherwise the GPU renderer makes a device of its own, as
|
||||
/// before, and every render comes back as pixels.
|
||||
fn adopt_window_device(rs: &eframe::egui_wgpu::RenderState, ctx: &egui::Context) -> WindowTextures {
|
||||
let (device, queue, info) = (rs.device.clone(), rs.queue.clone(), rs.adapter.get_info());
|
||||
let ctx = ctx.clone();
|
||||
// before the first frame's GPU warm-up can start a device of its own
|
||||
lightcraft_engine::gpu::set_window_device_pending(true);
|
||||
let spawned = std::thread::Builder::new().name("lc-gpu-window".into()).spawn(move || {
|
||||
match lightcraft_engine::gpu::adopt_window_device(device, queue, info) {
|
||||
Ok(()) => log::info!("gpu: rendering on the window's device"),
|
||||
Err(e) => log::info!("gpu: renders come back as pixels: {e}"),
|
||||
}
|
||||
ctx.request_repaint();
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("gpu: {e}");
|
||||
lightcraft_engine::gpu::set_window_device_pending(false);
|
||||
}
|
||||
WindowTextures { device: rs.device.clone(), queue: rs.queue.clone(), renderer: rs.renderer.clone() }
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
|
||||
@@ -89,7 +153,7 @@ impl eframe::App for App {
|
||||
}
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Some(m) = self.2.as_mut()
|
||||
if let Some(m) = self.3.as_mut()
|
||||
&& m.update(&mut self.0, ctx)
|
||||
&& lightcraft_ui_egui::panels::notices::may_close(&mut self.0)
|
||||
{
|
||||
@@ -109,6 +173,13 @@ impl eframe::App for App {
|
||||
}
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0);
|
||||
// the GPU renderer adopted the window's device: its renders can be drawn as they are
|
||||
if self.2.is_some()
|
||||
&& lightcraft_engine::gpu::on_window_device()
|
||||
&& let Some(t) = self.2.take()
|
||||
{
|
||||
self.0.renderer.set_screen_textures(Box::new(t));
|
||||
}
|
||||
self.0.ui(ui);
|
||||
}
|
||||
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
|
||||
@@ -304,6 +375,7 @@ fn main() -> eframe::Result {
|
||||
app.notices.extend(launch_notices);
|
||||
app.notices.extend(window_notice);
|
||||
app.gpu_notice = true;
|
||||
app.disk_space_notice = true;
|
||||
// an empty library opens where Import is offered (a grid, with the sidebar); before
|
||||
// the snapshot below, so this alone isn't written to the settings file
|
||||
if problem.is_none() && files.is_empty() {
|
||||
@@ -358,9 +430,16 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "macos")]
|
||||
let menu =
|
||||
(std::env::var_os("LIGHTCRAFT_NO_NATIVE_MENU").is_none()).then(|| native_menu::NativeMenu::install(&mut app, &cc.egui_ctx));
|
||||
// the GPU renderer on the window's device, when GPU rendering is on
|
||||
// (LIGHTCRAFT_GPU_WINDOW=0: a device of its own, renders read back - for comparison or a driver
|
||||
// that misbehaves with compute and drawing on one device)
|
||||
let window_device = std::env::var_os("LIGHTCRAFT_GPU_WINDOW").is_none_or(|v| v != "0");
|
||||
let window_textures =
|
||||
cc.wgpu_render_state.as_ref().filter(|_| gpu_on && window_device).map(|rs| adopt_window_device(rs, &cc.egui_ctx));
|
||||
Ok(Box::new(App(
|
||||
app,
|
||||
writer,
|
||||
window_textures,
|
||||
#[cfg(target_os = "macos")]
|
||||
menu,
|
||||
)))
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Reading a display's ICC profile file for the screen-profile services (`colord` on Linux,
|
||||
//! `win_screen_profile` on Windows).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// The largest profile file read (real display profiles are a few KiB to a few MiB).
|
||||
pub const MAX_PROFILE: u64 = 16 << 20;
|
||||
|
||||
/// The bytes of profile file `path`, `None` when it can't be read or is implausibly large.
|
||||
pub fn load(path: &Path) -> Option<Vec<u8>> {
|
||||
use std::io::Read as _;
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_PROFILE + 1).read_to_end(&mut bytes).ok()?;
|
||||
(!bytes.is_empty() && bytes.len() as u64 <= MAX_PROFILE).then_some(bytes)
|
||||
}
|
||||
|
||||
/// A profile file read again only when it changes: the services are asked about once a second, and
|
||||
/// calibration software rewrites its profile under the same name.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
#[derive(Default)]
|
||||
pub struct Cached {
|
||||
/// The file last read: its path, length and modification time.
|
||||
stamp: Option<(PathBuf, u64, Option<SystemTime>)>,
|
||||
bytes: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
impl Cached {
|
||||
/// The bytes of profile file `path`, read again when it isn't the file read last time or has
|
||||
/// changed since (see [`load`]).
|
||||
pub fn read(&mut self, path: &Path) -> Option<Vec<u8>> {
|
||||
let stamp = std::fs::metadata(path).ok().map(|m| (path.to_path_buf(), m.len(), m.modified().ok()));
|
||||
if stamp.is_none() || stamp != self.stamp {
|
||||
self.bytes = stamp.as_ref().and_then(|_| load(path));
|
||||
self.stamp = stamp;
|
||||
}
|
||||
self.bytes.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn profile_files_are_read_with_a_size_cap() {
|
||||
let dir = std::env::temp_dir().join(format!("profile-file-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let small = dir.join("small.icc");
|
||||
std::fs::write(&small, b"acsp").unwrap();
|
||||
assert_eq!(load(&small).as_deref(), Some(&b"acsp"[..]));
|
||||
let empty = dir.join("empty.icc");
|
||||
std::fs::write(&empty, b"").unwrap();
|
||||
assert_eq!(load(&empty), None);
|
||||
assert_eq!(load(&dir.join("missing.icc")), None);
|
||||
let big = dir.join("big.icc");
|
||||
std::fs::File::create(&big).unwrap().set_len(MAX_PROFILE + 1).unwrap();
|
||||
assert_eq!(load(&big), None);
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cached_profile_is_read_again_when_the_file_changes() {
|
||||
let dir = std::env::temp_dir().join(format!("profile-cache-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let (a, b) = (dir.join("a.icc"), dir.join("b.icc"));
|
||||
std::fs::write(&a, b"first").unwrap();
|
||||
std::fs::write(&b, b"other").unwrap();
|
||||
let mut cache = Cached::default();
|
||||
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
|
||||
assert_eq!(cache.read(&a).as_deref(), Some(&b"first"[..]));
|
||||
// another monitor's profile
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"other"[..]));
|
||||
// rewritten under the same name (a different length, so the change shows whatever the
|
||||
// file system's time resolution)
|
||||
std::fs::write(&b, b"calibrated").unwrap();
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"calibrated"[..]));
|
||||
// gone: nothing, then read again once it is back
|
||||
std::fs::remove_file(&b).unwrap();
|
||||
assert_eq!(cache.read(&b), None);
|
||||
std::fs::write(&b, b"back").unwrap();
|
||||
assert_eq!(cache.read(&b).as_deref(), Some(&b"back"[..]));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,11 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::
|
||||
// Linux: the profile the desktop assigns in colord, read off the UI thread
|
||||
#[cfg(target_os = "linux")]
|
||||
screen_profile: Some(colord::service()),
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
// Windows: the profile it uses for the window's monitor, unless it colour-manages the
|
||||
// desktop itself (HDR, Auto Color Management)
|
||||
#[cfg(windows)]
|
||||
screen_profile: win_screen_profile::service(cc),
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
|
||||
screen_profile: None,
|
||||
pick_display_profile: Some(Box::new(|| {
|
||||
let mut d = file_dialog()
|
||||
|
||||
@@ -5,6 +5,7 @@ fn desktop_clear_color_stays_opaque_with_a_modal_open() {
|
||||
let mut app = App(
|
||||
LightcraftApp::new(Session::new(), Services::default()),
|
||||
PrefsWriter::default(),
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
);
|
||||
@@ -566,6 +567,7 @@ fn on_exit_ends_the_process_on_macos() {
|
||||
let mut app = App(
|
||||
app,
|
||||
PrefsWriter::default(),
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
);
|
||||
@@ -598,6 +600,7 @@ fn on_exit_removes_the_lock_owner_note() {
|
||||
let mut app = App(
|
||||
LightcraftApp::new(session, Services::default()),
|
||||
PrefsWriter::default(),
|
||||
None,
|
||||
#[cfg(target_os = "macos")]
|
||||
None,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The ICC profile Windows assigns to the monitor showing LightCraft's window.
|
||||
//!
|
||||
//! On an SDR desktop Windows passes what an app draws to the monitor unchanged, so sRGB previews
|
||||
//! look oversaturated on a wide-gamut monitor and ignore a calibration. While no monitor profile is
|
||||
//! chosen in Settings ▸ Display, previews are shown through the profile Windows uses for the window's
|
||||
//! monitor (`Services::screen_profile`, see `lightcraft_wincolor`), followed when the window moves to
|
||||
//! another monitor or the profile changes in Windows' Color Management. When Windows colour-manages
|
||||
//! the desktop itself (HDR, Auto Color Management) previews stay sRGB, as Windows expects then.
|
||||
|
||||
use lightcraft_wincolor::MonitorColor;
|
||||
|
||||
/// The service the UI polls, for the window `cc` belongs to; `None` when its handle isn't a Win32 one.
|
||||
pub fn service(cc: &eframe::CreationContext<'_>) -> Option<lightcraft_ui_egui::ScreenProfileFn> {
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
let RawWindowHandle::Win32(handle) = cc.window_handle().ok()?.as_raw() else { return None };
|
||||
let hwnd = handle.hwnd.get();
|
||||
let mut file = crate::profile_file::Cached::default();
|
||||
let mut last: Option<MonitorColor> = None;
|
||||
Some(Box::new(move || {
|
||||
let answer = lightcraft_wincolor::monitor_color(hwnd);
|
||||
if last.as_ref() != Some(&answer) {
|
||||
log::info!("screen profile: {}", describe(&answer));
|
||||
last = Some(answer.clone());
|
||||
}
|
||||
match answer {
|
||||
MonitorColor::Profile(path) => file.read(&path),
|
||||
MonitorColor::ManagedByWindows | MonitorColor::NoProfile | MonitorColor::Unknown => None,
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// For the log: what the window's monitor answered.
|
||||
fn describe(answer: &MonitorColor) -> String {
|
||||
match answer {
|
||||
MonitorColor::Profile(path) => format!("the monitor's profile, {}", path.display()),
|
||||
MonitorColor::ManagedByWindows => "Windows colour-manages this monitor (HDR or Auto Color Management): previews are sRGB".into(),
|
||||
MonitorColor::NoProfile => "no profile is assigned to the monitor: previews are sRGB".into(),
|
||||
MonitorColor::Unknown => "not known for this monitor: previews are sRGB".into(),
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,15 @@ pub fn base_options() -> WgpuConfiguration {
|
||||
n.instance_descriptor.backend_options = backend::backend_options();
|
||||
// no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250)
|
||||
n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags);
|
||||
// the GPU renderer may run on this device (`adopt_window_device`): it needs the adapter's
|
||||
// buffer limits (a 24 MP photo is a 275 MiB buffer), not wgpu's defaults
|
||||
let default = n.device_descriptor.clone();
|
||||
n.device_descriptor = std::sync::Arc::new(move |adapter| {
|
||||
if adapter.get_info().backend == wgpu::Backend::Gl {
|
||||
return default(adapter);
|
||||
}
|
||||
wgpu::DeviceDescriptor { label: Some("lightcraft window"), required_limits: adapter.limits(), ..Default::default() }
|
||||
});
|
||||
}
|
||||
c
|
||||
}
|
||||
@@ -192,7 +201,8 @@ fn probe(backends: Backends, compose_window: bool) -> Result<WgpuSetupExisting,
|
||||
..Default::default()
|
||||
}))
|
||||
.map_err(|e| format!("no adapter: {e}"))?;
|
||||
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() };
|
||||
// (not GL: the adapter's own limits, which the GPU renderer needs when it adopts this device)
|
||||
let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { adapter.limits() };
|
||||
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("egui wgpu device"),
|
||||
required_limits: wgpu::Limits { max_texture_dimension_2d: 8192, ..base },
|
||||
|
||||
@@ -68,6 +68,10 @@ sync_github_name = true
|
||||
[people.ronibalthazar]
|
||||
sync_github_name = true
|
||||
|
||||
[people.esli1283]
|
||||
real_name = "Aaron Lopez"
|
||||
sync_github_name = false
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Fault injection for the catalog log's writer thread (tests only: nothing in the product
|
||||
//! installs a hook, and with none installed a check is one uncontended lock of an empty list).
|
||||
//!
|
||||
//! A test makes the drive under one library directory slow (a hook that sleeps) or failing (a
|
||||
//! hook that returns an error) and proves that a flag never waits for it and that nothing handed
|
||||
//! over is lost: `crates/catalog/src/tests_log_thread.rs`, `crates/engine/src/tests/slow_drive.rs`.
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
/// Where the log thread is about to touch the drive.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Step {
|
||||
/// Writing bytes to the log (or to the file that replaces it).
|
||||
Write,
|
||||
/// Syncing them.
|
||||
Sync,
|
||||
}
|
||||
|
||||
/// Runs before each [`Step`] in the hooked directory: an error fails that step.
|
||||
pub type Hook = Arc<dyn Fn(Step) -> io::Result<()> + Send + Sync>;
|
||||
|
||||
static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Run `hook` before every write and sync of the catalog log in `dir` (replacing an earlier one).
|
||||
#[doc(hidden)]
|
||||
pub fn install(dir: &Path, hook: Hook) {
|
||||
let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
hooks.retain(|(d, _)| d != dir);
|
||||
hooks.push((dir.to_path_buf(), hook));
|
||||
}
|
||||
|
||||
/// Remove the hook of `dir`.
|
||||
#[doc(hidden)]
|
||||
pub fn remove(dir: &Path) {
|
||||
HOOKS.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| d != dir);
|
||||
}
|
||||
|
||||
static ON_CALLER: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Write the log in `dir` on the caller's thread, syncing before each append returns, as builds
|
||||
/// before PERF-STEP-STALL did: a test's "before" (stores opened afterwards; the hooks run there too).
|
||||
#[doc(hidden)]
|
||||
pub fn write_on_caller(dir: &Path, on: bool) {
|
||||
let mut dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
dirs.retain(|d| d != dir);
|
||||
if on {
|
||||
dirs.push(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_caller(dir: &Path) -> bool {
|
||||
let dirs = ON_CALLER.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
!dirs.is_empty() && dirs.iter().any(|d| d == dir)
|
||||
}
|
||||
|
||||
pub(crate) fn check(dir: &Path, step: Step) -> io::Result<()> {
|
||||
let hook = {
|
||||
let hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if hooks.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
hooks.iter().find(|(d, _)| d == dir).map(|(_, h)| h.clone())
|
||||
};
|
||||
match hook {
|
||||
Some(h) => h(step),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,10 @@
|
||||
//! rename).
|
||||
//! - `catalog.log` — JSON lines, one per op applied after the snapshot:
|
||||
//! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are
|
||||
//! fsynced before [`Journal::append`] returns.
|
||||
//! fsynced before [`Journal::append`] returns, except natively: [`crate::FsStore`] hands them to
|
||||
//! a thread of its own that writes and syncs them in order right after (so a flag never waits
|
||||
//! for the drive), holds and retries whatever fails ([`Journal::unwritten`]) and refuses later
|
||||
//! appends meanwhile, so the log never has a gap and nothing handed over is dropped.
|
||||
//!
|
||||
//! Loading = snapshot + replay of the records with `seq > snapshot seq`. Recovery rules:
|
||||
//! - a **torn final record** (crash mid-append: truncated line or bad CRC at the end) is dropped
|
||||
@@ -195,6 +198,10 @@ pub struct Journal {
|
||||
/// A failed append may have left part of its records after `log_bytes`, and cutting them off
|
||||
/// failed too: the next append cuts the log back to `log_bytes` first.
|
||||
tail_dirty: bool,
|
||||
/// An append failed (natively that can be the store's own log thread failing to write records
|
||||
/// handed over before, which it holds and retries): the next chance writes a snapshot, a fresh
|
||||
/// file holding everything, in case only the log's file is broken.
|
||||
snapshot_due: bool,
|
||||
}
|
||||
|
||||
/// A background snapshot in flight.
|
||||
@@ -383,6 +390,7 @@ impl Journal {
|
||||
pending: None,
|
||||
retry_at_records: 0,
|
||||
tail_dirty: false,
|
||||
snapshot_due: false,
|
||||
};
|
||||
let log = log.unwrap_or_default();
|
||||
|
||||
@@ -516,6 +524,7 @@ impl Journal {
|
||||
self.tail_dirty = false;
|
||||
}
|
||||
if let Err(e) = self.store.append(LOG, buf.as_bytes()) {
|
||||
self.snapshot_due = true;
|
||||
// Part of the batch may be in the file. Cut it back to the last whole record, so the
|
||||
// retry (same seqs) starts on a clean line instead of after a fragment that would
|
||||
// read back as damage.
|
||||
@@ -678,6 +687,7 @@ impl Journal {
|
||||
}
|
||||
|
||||
fn record_snapshot(&mut self, t: SnapshotTiming) {
|
||||
self.snapshot_due = false;
|
||||
self.stats.snapshots += 1;
|
||||
self.stats.last_snapshot = t;
|
||||
self.stats.max_snapshot_ms = self.stats.max_snapshot_ms.max(t.total_ms);
|
||||
@@ -697,6 +707,23 @@ impl Journal {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait until every appended record is in the file and synced (natively the store writes the
|
||||
/// log on a thread of its own, [`crate::FsStore`]): before the files are read or copied from
|
||||
/// outside. An error says why some aren't yet: they are held and retried, never dropped.
|
||||
pub fn flush(&mut self) -> Result<()> {
|
||||
self.store.flush().map_err(io)
|
||||
}
|
||||
|
||||
/// Appended records the store holds because writing them failed (retried), and why; `None`
|
||||
/// when nothing is held back. Never waits for the drive.
|
||||
pub fn unwritten(&self) -> Option<(usize, String)> {
|
||||
// a snapshot that holds every op holds whatever the log's thread still holds
|
||||
if self.snapshot_seq >= self.seq && self.pending.is_none() {
|
||||
return None;
|
||||
}
|
||||
self.store.unwritten()
|
||||
}
|
||||
|
||||
/// Where persistence time went so far.
|
||||
pub fn stats(&self) -> PersistStats {
|
||||
PersistStats { snapshot_running: self.pending.is_some(), ..self.stats }
|
||||
@@ -706,7 +733,10 @@ impl Journal {
|
||||
pub fn wants_snapshot(&self) -> bool {
|
||||
self.pending.is_none()
|
||||
&& self.log_records >= self.retry_at_records
|
||||
&& (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes)
|
||||
&& (self.snapshot_due
|
||||
|| self.unwritten().is_some()
|
||||
|| self.log_records >= self.policy.max_records
|
||||
|| self.log_bytes >= self.policy.max_bytes)
|
||||
}
|
||||
|
||||
pub fn seq(&self) -> u64 {
|
||||
|
||||
@@ -14,12 +14,17 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod dates;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[doc(hidden)]
|
||||
pub mod fault;
|
||||
pub mod folders;
|
||||
mod index;
|
||||
pub mod journal;
|
||||
pub mod keywords;
|
||||
pub mod local;
|
||||
pub mod lock;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod log_writer;
|
||||
pub mod model;
|
||||
pub mod query;
|
||||
pub mod rules;
|
||||
@@ -1490,6 +1495,8 @@ mod tests_journal;
|
||||
mod tests_local;
|
||||
#[cfg(test)]
|
||||
mod tests_lock;
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_log_thread;
|
||||
#[cfg(test)]
|
||||
mod tests_repair;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
//! The thread that writes the catalog log for [`crate::FsStore`] (natively).
|
||||
//!
|
||||
//! An append hands its bytes over and returns; the thread writes them in order and makes each batch
|
||||
//! durable (`sync_data`) before the next. The caller (the UI thread, for the app) never waits for
|
||||
//! the drive: on Windows a write to a file waits for a sync of that file in flight, so with the log
|
||||
//! written and synced on the UI thread every flag, rating and step waited for the drive, 30–90 ms
|
||||
//! on a busy disk in a test and over a second on a photographer's machine while previews were
|
||||
//! written.
|
||||
//!
|
||||
//! **Nothing handed over is ever dropped.** The store's log is the file's first `good` bytes (written
|
||||
//! and synced) followed by `held`, the bytes handed over and not yet synced. A write or sync that
|
||||
//! fails keeps `held` and retries it (on every later message, and every [`RETRY`] meanwhile), first
|
||||
//! cutting the file back to `good` so a fragment of the failed write never stays in it. While a
|
||||
//! failure stands, [`LogWriter::append`] refuses new bytes with the failure (the journal keeps those
|
||||
//! records queued, as for any failed append) and [`LogWriter::unwritten`] says how many records are
|
||||
//! held, so the app counts them as not saved and its quit prompt warns before anything could be
|
||||
//! lost. Cutting the log back, replacing it and reading it act on that logical content, after
|
||||
//! everything handed over before; the caller waits for them. Dropping the writer waits for
|
||||
//! everything handed over and tries a last time.
|
||||
|
||||
use std::io::{self, Seek, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long a caller waits for the thread at most (a cut, a replace, a read, a flush).
|
||||
const WAIT: Duration = Duration::from_secs(60);
|
||||
/// How often held bytes are retried while a failure stands and nothing else arrives.
|
||||
pub(crate) const RETRY: Duration = Duration::from_millis(500);
|
||||
|
||||
enum Msg {
|
||||
Append(Vec<u8>),
|
||||
Truncate(u64, Sender<io::Result<()>>),
|
||||
Replace(Vec<u8>, Sender<io::Result<()>>),
|
||||
Read(Sender<io::Result<Option<Vec<u8>>>>),
|
||||
/// Reply once everything before is written and synced (or why it isn't).
|
||||
Flush(Sender<io::Result<()>>),
|
||||
}
|
||||
|
||||
/// What the caller can see without waiting.
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
/// Why the held bytes couldn't be written (until they are, or the log is cut or replaced).
|
||||
failed: Option<String>,
|
||||
/// Records (lines) handed over and not yet written and synced, while `failed` stands.
|
||||
held_records: usize,
|
||||
}
|
||||
|
||||
pub(crate) struct LogWriter {
|
||||
pub(crate) name: String,
|
||||
tx: Option<Sender<Msg>>,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
thread: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
fn stopped() -> io::Error {
|
||||
io::Error::other("the catalog log writer stopped")
|
||||
}
|
||||
|
||||
fn not_written(why: &str) -> io::Error {
|
||||
io::Error::other(format!("the catalog log could not be written: {why}"))
|
||||
}
|
||||
|
||||
impl LogWriter {
|
||||
/// A writer for `dir/name` (`None` when no thread can start: the store then writes itself).
|
||||
pub(crate) fn start(dir: PathBuf, name: &str) -> Option<LogWriter> {
|
||||
let (tx, rx) = channel::<Msg>();
|
||||
let shared = Arc::new(Mutex::new(Shared::default()));
|
||||
let sh = shared.clone();
|
||||
let mut w = Writer::new(dir, name);
|
||||
let thread = std::thread::Builder::new().name("catalog-log".into()).spawn(move || w.run(&rx, &sh)).ok()?;
|
||||
Some(LogWriter { name: name.to_string(), tx: Some(tx), shared, thread: Some(thread) })
|
||||
}
|
||||
|
||||
fn send(&self, m: Msg) -> io::Result<()> {
|
||||
self.tx.as_ref().ok_or_else(stopped)?.send(m).map_err(|_| stopped())
|
||||
}
|
||||
|
||||
fn ask<T>(&self, make: impl FnOnce(Sender<io::Result<T>>) -> Msg) -> io::Result<T> {
|
||||
let (tx, rx) = channel();
|
||||
self.send(make(tx))?;
|
||||
rx.recv_timeout(WAIT).map_err(|e| match e {
|
||||
RecvTimeoutError::Timeout => io::Error::new(io::ErrorKind::TimedOut, "the drive took over a minute to write the catalog log"),
|
||||
RecvTimeoutError::Disconnected => stopped(),
|
||||
})?
|
||||
}
|
||||
|
||||
/// Hand `data` over (never waits for the drive). Refused while bytes handed over before can't
|
||||
/// be written: the caller keeps `data` and appends it again later.
|
||||
pub(crate) fn append(&self, data: &[u8]) -> io::Result<()> {
|
||||
if let Some(why) = self.shared.lock().unwrap_or_else(PoisonError::into_inner).failed.clone() {
|
||||
return Err(not_written(&why));
|
||||
}
|
||||
self.send(Msg::Append(data.to_vec()))
|
||||
}
|
||||
|
||||
/// Cut the log to `len` bytes, after everything handed over; waits for it.
|
||||
pub(crate) fn truncate(&self, len: u64) -> io::Result<()> {
|
||||
self.ask(|r| Msg::Truncate(len, r))
|
||||
}
|
||||
|
||||
/// Replace the log with `data` (atomically, durably), after everything handed over; waits.
|
||||
pub(crate) fn replace(&self, data: &[u8]) -> io::Result<()> {
|
||||
self.ask(|r| Msg::Replace(data.to_vec(), r))
|
||||
}
|
||||
|
||||
/// The log as appended so far (written or still held), after everything handed over.
|
||||
pub(crate) fn read(&self) -> io::Result<Option<Vec<u8>>> {
|
||||
self.ask(Msg::Read)
|
||||
}
|
||||
|
||||
/// Wait until everything handed over is written and synced; an error says why it isn't (the
|
||||
/// bytes are still held and retried).
|
||||
pub(crate) fn flush(&self) -> io::Result<()> {
|
||||
self.ask(Msg::Flush)
|
||||
}
|
||||
|
||||
/// Records handed over that can't be written yet, and why (`None`: nothing is held back by a
|
||||
/// failure). Never waits.
|
||||
pub(crate) fn unwritten(&self) -> Option<(usize, String)> {
|
||||
let sh = self.shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
sh.failed.clone().map(|why| (sh.held_records.max(1), why))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LogWriter {
|
||||
fn drop(&mut self) {
|
||||
drop(self.tx.take());
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread's side: the file and what is held for it.
|
||||
struct Writer {
|
||||
dir: PathBuf,
|
||||
path: PathBuf,
|
||||
tmp: PathBuf,
|
||||
file: Option<std::fs::File>,
|
||||
/// Bytes of the file written whole and synced (`None` until the file was first opened).
|
||||
good: Option<u64>,
|
||||
/// Handed over, not yet written and synced.
|
||||
held: Vec<u8>,
|
||||
failed: Option<String>,
|
||||
}
|
||||
|
||||
fn lines(b: &[u8]) -> usize {
|
||||
b.iter().filter(|c| **c == b'\n').count()
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
fn new(dir: PathBuf, name: &str) -> Writer {
|
||||
let path = dir.join(name);
|
||||
let tmp = dir.join(format!("{name}.tmp"));
|
||||
Writer { dir, path, tmp, file: None, good: None, held: Vec::new(), failed: None }
|
||||
}
|
||||
|
||||
fn hook(&self, step: crate::fault::Step) -> io::Result<()> {
|
||||
crate::fault::check(&self.dir, step)
|
||||
}
|
||||
|
||||
/// Open the file positioned at `good` (a fragment past it, from a write that failed, is cut).
|
||||
fn open(&mut self) -> io::Result<u64> {
|
||||
if let (Some(_), Some(g)) = (&self.file, self.good) {
|
||||
return Ok(g);
|
||||
}
|
||||
// (a link or a device planted at the name meanwhile is refused, as at the first append)
|
||||
crate::store::check_regular_directory_entry(&self.path)?;
|
||||
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(false).open(&self.path)?;
|
||||
let len = f.metadata()?.len();
|
||||
let good = match self.good {
|
||||
None => len,
|
||||
Some(g) if len > g => {
|
||||
f.set_len(g)?;
|
||||
g
|
||||
}
|
||||
Some(g) if len < g => {
|
||||
// shorter than what was synced: someone else cut it; continue at its end
|
||||
log::error!("catalog: {} is {len} bytes, {g} were written", self.path.display());
|
||||
len
|
||||
}
|
||||
Some(g) => g,
|
||||
};
|
||||
f.seek(io::SeekFrom::Start(good))?;
|
||||
self.good = Some(good);
|
||||
self.file = Some(f);
|
||||
Ok(good)
|
||||
}
|
||||
|
||||
/// Write and sync what is held.
|
||||
fn write_held(&mut self) -> io::Result<()> {
|
||||
if self.held.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let r = (|| {
|
||||
self.hook(crate::fault::Step::Write)?;
|
||||
self.open()?;
|
||||
let f = self.file.as_mut().ok_or_else(|| io::Error::other("catalog log not open"))?;
|
||||
f.write_all(&self.held)?;
|
||||
self.hook(crate::fault::Step::Sync)?;
|
||||
self.file.as_ref().ok_or_else(|| io::Error::other("catalog log not open"))?.sync_data()
|
||||
})();
|
||||
match r {
|
||||
Ok(()) => {
|
||||
let n = self.held.len() as u64;
|
||||
self.good = Some(self.good.unwrap_or(0).saturating_add(n));
|
||||
self.held.clear();
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
// the handle may be dead (a network share that reconnected, a removed volume): the
|
||||
// retry opens the file again and cuts what this attempt left past `good`
|
||||
self.file = None;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cut the logical log (file then held) to `len` bytes.
|
||||
fn truncate(&mut self, len: u64) -> io::Result<()> {
|
||||
let good = match self.good {
|
||||
Some(g) => g,
|
||||
None => match self.open() {
|
||||
Ok(g) => g,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => 0,
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
};
|
||||
// (to exactly `good` with bytes held: the file is cut, since a write that failed may have
|
||||
// left some of them past `good`)
|
||||
if len > good || (len == good && self.held.is_empty()) {
|
||||
// within what is held: nothing on the drive changes (what a failed write left past
|
||||
// `good` is cut before the next write)
|
||||
let keep = usize::try_from(len - good).unwrap_or(usize::MAX).min(self.held.len());
|
||||
self.held.truncate(keep);
|
||||
return Ok(());
|
||||
}
|
||||
self.file = None;
|
||||
let f = match std::fs::OpenOptions::new().write(true).open(&self.path) {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
self.good = None;
|
||||
self.held.clear();
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
f.set_len(len)?;
|
||||
f.sync_all()?;
|
||||
self.good = Some(len);
|
||||
self.held.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn replace(&mut self, data: &[u8]) -> io::Result<()> {
|
||||
self.file = None;
|
||||
let written = (|| {
|
||||
self.hook(crate::fault::Step::Write)?;
|
||||
let mut f = crate::store::create_staging(&self.tmp)?;
|
||||
f.write_all(data)?;
|
||||
self.hook(crate::fault::Step::Sync)?;
|
||||
f.sync_all()?;
|
||||
drop(f);
|
||||
std::fs::rename(&self.tmp, &self.path)
|
||||
})();
|
||||
match written {
|
||||
Ok(()) => {
|
||||
// what was held is part of what the caller replaced the log with (a snapshot holds
|
||||
// the records before it, `data` the ones after)
|
||||
self.good = Some(data.len() as u64);
|
||||
self.held.clear();
|
||||
self.failed = None;
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(&self.tmp);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read(&mut self) -> io::Result<Option<Vec<u8>>> {
|
||||
let mut bytes = match std::fs::read(&self.path) {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound && self.held.is_empty() => return Ok(None),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if let Some(g) = self.good {
|
||||
bytes.truncate(usize::try_from(g).unwrap_or(usize::MAX));
|
||||
}
|
||||
bytes.extend_from_slice(&self.held);
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
fn publish(&self, shared: &Mutex<Shared>) {
|
||||
let mut sh = shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
sh.failed = self.failed.clone().filter(|_| !self.held.is_empty());
|
||||
sh.held_records = if sh.failed.is_some() { lines(&self.held) } else { 0 };
|
||||
}
|
||||
|
||||
fn run(&mut self, rx: &Receiver<Msg>, shared: &Mutex<Shared>) {
|
||||
loop {
|
||||
let first = if self.failed.is_some() && !self.held.is_empty() {
|
||||
match rx.recv_timeout(RETRY) {
|
||||
Ok(m) => Some(m),
|
||||
Err(RecvTimeoutError::Timeout) => None,
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
} else {
|
||||
match rx.recv() {
|
||||
Ok(m) => Some(m),
|
||||
Err(_) => break,
|
||||
}
|
||||
};
|
||||
let mut batch: Vec<Msg> = first.into_iter().collect();
|
||||
while let Ok(m) = rx.try_recv() {
|
||||
batch.push(m);
|
||||
}
|
||||
let mut flushes = Vec::new();
|
||||
for m in batch {
|
||||
match m {
|
||||
Msg::Append(data) => self.held.extend_from_slice(&data),
|
||||
// (published before the reply: the caller reads what it left at once)
|
||||
Msg::Truncate(len, reply) => {
|
||||
let r = self.truncate(len);
|
||||
self.publish(shared);
|
||||
let _ = reply.send(r);
|
||||
}
|
||||
Msg::Replace(data, reply) => {
|
||||
let r = self.replace(&data);
|
||||
self.publish(shared);
|
||||
let _ = reply.send(r);
|
||||
}
|
||||
Msg::Read(reply) => {
|
||||
let _ = reply.send(self.read());
|
||||
}
|
||||
Msg::Flush(reply) => flushes.push(reply),
|
||||
}
|
||||
}
|
||||
self.step();
|
||||
self.publish(shared);
|
||||
for r in flushes {
|
||||
let _ = r.send(match &self.failed {
|
||||
Some(why) if !self.held.is_empty() => Err(not_written(why)),
|
||||
_ => Ok(()),
|
||||
});
|
||||
}
|
||||
}
|
||||
// the store is closing: everything handed over gets one more try
|
||||
self.step();
|
||||
self.publish(shared);
|
||||
if !self.held.is_empty() {
|
||||
log::error!("catalog: {} record(s) could not be written to {} (the closing snapshot holds them)", lines(&self.held), self.path.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// Write what is held; a failure is kept (and logged when it is new).
|
||||
fn step(&mut self) {
|
||||
match self.write_held() {
|
||||
Ok(()) => {
|
||||
if self.failed.take().is_some() {
|
||||
log::info!("catalog: {} written again", self.path.display());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let why = e.to_string();
|
||||
if self.failed.as_deref() != Some(why.as_str()) {
|
||||
log::error!("catalog: {}: {why} ({} record(s) held, retried)", self.path.display(), lines(&self.held));
|
||||
}
|
||||
self.failed = Some(why);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
-6
@@ -28,7 +28,9 @@ pub trait Store: Send {
|
||||
self.write_atomic(name, &buf)?;
|
||||
Ok(buf.len() as u64)
|
||||
}
|
||||
/// Append and make durable (fsync) before returning. On an error, part of `data` may have
|
||||
/// Append and make durable (fsync): before returning, or, natively, by the store's own log
|
||||
/// thread right after ([`FsStore`]: a write that fails is returned by a later append, and a
|
||||
/// read through the store sees every byte handed over). On an error, part of `data` may have
|
||||
/// been written (a full disk, a dropped network share): the journal cuts the file back to its
|
||||
/// previous length with [`Store::truncate`] before appending again.
|
||||
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()>;
|
||||
@@ -43,12 +45,23 @@ pub trait Store: Send {
|
||||
fn background_writer(&self) -> Option<Box<dyn Store>> {
|
||||
None
|
||||
}
|
||||
/// Wait until every append handed over is in the file and synced ([`FsStore`] writes them on a
|
||||
/// thread of its own; the default has nothing to wait for). An error says why some aren't: they
|
||||
/// are still held and retried, never dropped.
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
/// Records handed over by [`Store::append`] that can't be written yet (a write or sync on the
|
||||
/// store's own thread failed: they are held and retried), and why. `None`: nothing held back.
|
||||
fn unwritten(&self) -> Option<(usize, String)> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends and truncates open the name's own file, so anything else at the name is the library's
|
||||
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
|
||||
/// hangs the open. Refused with an error the open can show, before anything is written through.
|
||||
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
|
||||
pub(crate) fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(md) if md.is_file() => Ok(()),
|
||||
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
|
||||
@@ -60,15 +73,24 @@ fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
|
||||
/// Files in a directory.
|
||||
pub struct FsStore {
|
||||
dir: PathBuf,
|
||||
/// Open append handle (kept between appends; dropped on rewrite/truncate).
|
||||
/// Open append handle (kept between appends; dropped on rewrite/truncate). Used when no thread
|
||||
/// writes the log (the browser build, or one that couldn't start).
|
||||
appender: Option<(String, std::fs::File)>,
|
||||
/// The thread that writes the log (natively; started by the first append).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
log: Option<crate::log_writer::LogWriter>,
|
||||
}
|
||||
|
||||
impl FsStore {
|
||||
/// Use `dir` (created if missing).
|
||||
pub fn open(dir: impl AsRef<Path>) -> io::Result<FsStore> {
|
||||
std::fs::create_dir_all(dir.as_ref())?;
|
||||
Ok(FsStore { dir: dir.as_ref().to_path_buf(), appender: None })
|
||||
Ok(FsStore {
|
||||
dir: dir.as_ref().to_path_buf(),
|
||||
appender: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
log: None,
|
||||
})
|
||||
}
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
@@ -76,6 +98,21 @@ impl FsStore {
|
||||
fn path(&self, name: &str) -> PathBuf {
|
||||
self.dir.join(name)
|
||||
}
|
||||
/// The log thread, when it writes `name`.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn log_for(&self, name: &str) -> Option<&crate::log_writer::LogWriter> {
|
||||
self.log.as_ref().filter(|w| w.name == name)
|
||||
}
|
||||
|
||||
/// Wait until the log thread has written and synced everything handed to it.
|
||||
pub fn flush_log(&self) -> io::Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = &self.log {
|
||||
return w.flush();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_dir(&self) {
|
||||
// Makes the rename durable on POSIX; opening a directory fails on Windows (where
|
||||
// `rename` is already journaled by NTFS), so errors are ignored.
|
||||
@@ -97,6 +134,11 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result<std::fs::File>
|
||||
|
||||
impl Store for FsStore {
|
||||
fn read(&mut self, name: &str) -> io::Result<Option<Vec<u8>>> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
// what was handed over, written or still held
|
||||
return w.read();
|
||||
}
|
||||
match std::fs::read(self.path(name)) {
|
||||
Ok(b) => Ok(Some(b)),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
|
||||
@@ -106,6 +148,13 @@ impl Store for FsStore {
|
||||
|
||||
fn write_atomic(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
// (after the appends handed over before)
|
||||
w.replace(data)?;
|
||||
self.sync_dir();
|
||||
return Ok(());
|
||||
}
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
}
|
||||
@@ -122,6 +171,15 @@ impl Store for FsStore {
|
||||
|
||||
fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result<u64> {
|
||||
use std::io::Write;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
// (the log is small: buffered, and replaced by its thread after the appends before)
|
||||
let mut buf = Vec::new();
|
||||
fill(&mut buf)?;
|
||||
w.replace(&buf)?;
|
||||
self.sync_dir();
|
||||
return Ok(buf.len() as u64);
|
||||
}
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
}
|
||||
@@ -148,6 +206,23 @@ impl Store for FsStore {
|
||||
|
||||
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
if self.log.is_none() && !crate::fault::on_caller(&self.dir) {
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
if !self.path(name).exists() {
|
||||
// created here, so the open's errors are this append's and its entry is durable
|
||||
std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
|
||||
self.sync_dir();
|
||||
}
|
||||
self.appender = None;
|
||||
self.log = crate::log_writer::LogWriter::start(self.dir.clone(), name);
|
||||
}
|
||||
// (another name than the log's is written here, as without a thread)
|
||||
if let Some(w) = self.log_for(name) {
|
||||
return w.append(data);
|
||||
}
|
||||
}
|
||||
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
|
||||
check_regular_directory_entry(&self.path(name))?;
|
||||
let existed = self.path(name).exists();
|
||||
@@ -158,6 +233,12 @@ impl Store for FsStore {
|
||||
self.appender = Some((name.to_string(), f));
|
||||
}
|
||||
let Some((_, f)) = self.appender.as_mut() else { return Err(io::Error::other("appender not open")) };
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let written = crate::fault::check(&self.dir, crate::fault::Step::Write)
|
||||
.and_then(|()| f.write_all(data))
|
||||
.and_then(|()| crate::fault::check(&self.dir, crate::fault::Step::Sync))
|
||||
.and_then(|()| f.sync_data());
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let written = f.write_all(data).and_then(|()| f.sync_data());
|
||||
if written.is_err() {
|
||||
// The handle may be dead (a network share that reconnected, a removed volume): the next
|
||||
@@ -169,6 +250,10 @@ impl Store for FsStore {
|
||||
}
|
||||
|
||||
fn truncate(&mut self, name: &str, len: u64) -> io::Result<()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(w) = self.log_for(name) {
|
||||
return w.truncate(len);
|
||||
}
|
||||
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
|
||||
self.appender = None;
|
||||
}
|
||||
@@ -189,7 +274,16 @@ impl Store for FsStore {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn background_writer(&self) -> Option<Box<dyn Store>> {
|
||||
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None }))
|
||||
Some(Box::new(FsStore { dir: self.dir.clone(), appender: None, log: None }))
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.flush_log()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn unwritten(&self) -> Option<(usize, String)> {
|
||||
self.log.as_ref().and_then(|w| w.unwritten())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,13 +350,13 @@ impl Store for MemStore {
|
||||
}
|
||||
}
|
||||
|
||||
// (its one test plants a symlink, so the module is Unix-only: elsewhere `use super::*` would be unused)
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests_staging {
|
||||
use super::*;
|
||||
|
||||
/// A link planted at a staging name (`<name>.tmp`) is removed, never followed: the file it points to keeps its
|
||||
/// bytes and the save still lands (issue #1502).
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_link_at_the_staging_name_is_never_written_through() {
|
||||
let dir = std::env::temp_dir().join(format!("lc-staging-link-{}", std::process::id()));
|
||||
|
||||
@@ -269,9 +269,10 @@ fn fs_store_background_snapshot() {
|
||||
}
|
||||
// a previous crash mid-snapshot left a partial temp file
|
||||
std::fs::write(dir.join(format!("{SNAPSHOT}.tmp")), b"{\"format\":\"lightcraft-catal").unwrap();
|
||||
// (closed first: its log thread writes what was handed over)
|
||||
drop(j);
|
||||
let (mut j2, c2, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
assert_eq!((c2.to_snapshot(), r.snapshot_seq), (live.to_snapshot(), 0));
|
||||
drop(j);
|
||||
let n = j2.seq();
|
||||
j2.snapshot_in_background(&live).unwrap();
|
||||
for k in 200..260 {
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! PERF-STEP-STALL: the catalog log's own thread ([`crate::log_writer`]). Appends return at once
|
||||
//! however slow the drive is; everything handed over is written in order; a write that fails is
|
||||
//! held, reported and retried, never dropped, and the log never has a gap.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::fault::{self, Step};
|
||||
use crate::store::{FsStore, Store};
|
||||
|
||||
const LOG: &str = "catalog.log";
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lc-log-thread-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
d
|
||||
}
|
||||
|
||||
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
|
||||
let t = Instant::now();
|
||||
while !done() {
|
||||
assert!(t.elapsed() < Duration::from_secs(20), "{what}");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends are written by the thread in order; a read through the store sees every one; a cut
|
||||
/// and a replace come after the appends before them; dropping the store writes what is left.
|
||||
#[test]
|
||||
fn appends_are_written_in_order_and_cuts_and_replaces_come_after_them() {
|
||||
let dir = temp_dir("order");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
let mut want = Vec::new();
|
||||
for i in 0..200u32 {
|
||||
let line = format!("{i}\n");
|
||||
store.append(LOG, line.as_bytes()).unwrap();
|
||||
want.extend_from_slice(line.as_bytes());
|
||||
if i % 50 == 0 {
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), want, "all of it, through the store");
|
||||
}
|
||||
}
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want, "all of it, in the file");
|
||||
store.truncate(LOG, 4).unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
|
||||
// never longer than it is
|
||||
store.truncate(LOG, 400).unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n");
|
||||
store.append(LOG, b"x\n").unwrap();
|
||||
store.write_atomic(LOG, b"tail\n").unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\n");
|
||||
store.append(LOG, b"more\n").unwrap();
|
||||
drop(store);
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"tail\nmore\n");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// (a) Each sync takes 300 ms: 100 appends still return at once, and a flush then finds all of
|
||||
/// them in the file (before, each append waited for its own sync: 30 s for these).
|
||||
#[test]
|
||||
fn an_append_never_waits_for_a_slow_sync() {
|
||||
let dir = temp_dir("slow");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.append(LOG, b"first\n").unwrap();
|
||||
let syncs = Arc::new(AtomicUsize::new(0));
|
||||
let n = syncs.clone();
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(move |step| {
|
||||
if step == Step::Sync {
|
||||
n.fetch_add(1, Ordering::SeqCst);
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
);
|
||||
let mut want = b"first\n".to_vec();
|
||||
let mut slowest = Duration::ZERO;
|
||||
for i in 0..100u32 {
|
||||
let line = format!("{i}\n");
|
||||
let t = Instant::now();
|
||||
store.append(LOG, line.as_bytes()).unwrap();
|
||||
slowest = slowest.max(t.elapsed());
|
||||
want.extend_from_slice(line.as_bytes());
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
assert!(slowest < Duration::from_millis(50), "an append waited {slowest:?}");
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), want);
|
||||
// batched: far fewer syncs than appends
|
||||
assert!(syncs.load(Ordering::SeqCst) < 50, "{} syncs", syncs.load(Ordering::SeqCst));
|
||||
fault::remove(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// (c) Writes fail for a while: what was handed over is held (reported, with the reason), later
|
||||
/// appends are refused so the caller keeps them, and once writes work again the held bytes land,
|
||||
/// in order, with no fragment of the failed attempts and no gap.
|
||||
#[test]
|
||||
fn a_failed_write_is_held_reported_and_retried() {
|
||||
let dir = temp_dir("fail");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store.append(LOG, b"0\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
let fail = Arc::new(AtomicBool::new(true));
|
||||
let f = fail.clone();
|
||||
fault::install(&dir, Arc::new(move |_| if f.load(Ordering::SeqCst) { Err(std::io::Error::other("disk full (test)")) } else { Ok(()) }));
|
||||
// (one append: the log thread can fail the first before a second arrives, and then refuses it)
|
||||
store.append(LOG, b"1\n2\n").unwrap();
|
||||
wait_until("the failure is published", || store.unwritten().is_some());
|
||||
let (held, why) = store.unwritten().unwrap();
|
||||
assert!(why.contains("disk full"), "{why}");
|
||||
assert!(held >= 1, "{held}");
|
||||
let refused = store.append(LOG, b"3\n");
|
||||
assert!(refused.is_err(), "refused while held");
|
||||
assert!(store.flush().is_err(), "a flush says it isn't written");
|
||||
// a read through the store still sees what was handed over
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
|
||||
// a cut within what is held keeps it (the journal cuts back to its own length on an error)
|
||||
store.truncate(LOG, 6).unwrap();
|
||||
assert_eq!(store.read(LOG).unwrap().unwrap(), b"0\n1\n2\n");
|
||||
// a fragment of a failed write left in the file is cut before the retry
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut file = std::fs::OpenOptions::new().append(true).open(dir.join(LOG)).unwrap();
|
||||
file.write_all(b"{\"seq\":").unwrap();
|
||||
}
|
||||
fail.store(false, Ordering::SeqCst);
|
||||
wait_until("retried on its own", || store.unwritten().is_none());
|
||||
store.append(LOG, b"3\n").unwrap();
|
||||
store.flush().unwrap();
|
||||
assert_eq!(std::fs::read(dir.join(LOG)).unwrap(), b"0\n1\n2\n3\n");
|
||||
fault::remove(&dir);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// (b, c) Through the journal: ops appended while the drive is slow or failing all reopen, and a
|
||||
/// journal over a log that failed has no gap (no damage on load).
|
||||
#[test]
|
||||
fn the_journal_reopens_every_op_after_a_slow_then_failing_drive() {
|
||||
use crate::{Catalog, Journal, Op, Photo, PhotoId, Source};
|
||||
let dir = temp_dir("journal");
|
||||
let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
let fail = Arc::new(AtomicBool::new(false));
|
||||
let f = fail.clone();
|
||||
fault::install(
|
||||
&dir,
|
||||
Arc::new(move |step| {
|
||||
if f.load(Ordering::SeqCst) {
|
||||
return Err(std::io::Error::other("network share dropped (test)"));
|
||||
}
|
||||
if step == Step::Sync {
|
||||
std::thread::sleep(Duration::from_millis(40));
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
);
|
||||
let mut queued: Vec<Op> = Vec::new();
|
||||
for id in 1..=60u64 {
|
||||
if id == 20 {
|
||||
fail.store(true, Ordering::SeqCst);
|
||||
}
|
||||
if id == 40 {
|
||||
fail.store(false, Ordering::SeqCst);
|
||||
}
|
||||
let p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 4, 3, "2026-11-02");
|
||||
let op = Op::AddPhoto { photo: Box::new(p) };
|
||||
c.apply(op.clone()).unwrap();
|
||||
queued.push(op);
|
||||
// as the engine does: a failed append keeps its ops queued for the next one
|
||||
if j.append(&queued).is_ok() {
|
||||
queued.clear();
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
wait_until("everything written", || {
|
||||
if !queued.is_empty() && j.append(&queued).is_ok() {
|
||||
queued.clear();
|
||||
}
|
||||
queued.is_empty() && j.unwritten().is_none()
|
||||
});
|
||||
j.flush().unwrap();
|
||||
let expect = c.to_snapshot();
|
||||
drop(j);
|
||||
fault::remove(&dir);
|
||||
let (_, again, report): (_, Catalog, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap();
|
||||
assert!(report.damaged.is_none(), "{report:?}");
|
||||
assert_eq!(again.to_snapshot(), expect);
|
||||
assert_eq!(again.len(), 60);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A sync that fails leaves the written bytes past the synced length in the file; a cut to exactly
|
||||
/// that length removes them from the file too, so they never come back on the next open (review
|
||||
/// of #3557).
|
||||
#[test]
|
||||
fn a_cut_to_the_synced_length_removes_bytes_a_failed_sync_left() {
|
||||
let dir = temp_dir("cut-synced");
|
||||
let mut store = FsStore::open(&dir).unwrap();
|
||||
store
|
||||
.append(
|
||||
LOG, b"0
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
store.flush().unwrap();
|
||||
fault::install(&dir, Arc::new(|step| if step == Step::Sync { Err(std::io::Error::other("sync failed (test)")) } else { Ok(()) }));
|
||||
store
|
||||
.append(
|
||||
LOG, b"1
|
||||
",
|
||||
)
|
||||
.unwrap();
|
||||
wait_until("the failure is published", || store.unwritten().is_some());
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join(LOG)).unwrap(),
|
||||
b"0
|
||||
1
|
||||
",
|
||||
"written, not synced"
|
||||
);
|
||||
store.truncate(LOG, 2).unwrap();
|
||||
fault::remove(&dir);
|
||||
drop(store);
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join(LOG)).unwrap(),
|
||||
b"0
|
||||
"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -88,6 +88,9 @@ fn partial_append_then_retry_loads_cleanly() {
|
||||
assert!(j.append(&batch).is_err(), "tear at {tear}");
|
||||
// cut back to the last whole record
|
||||
assert_eq!(t.files.get(LOG).unwrap().len(), good_len, "tear at {tear}");
|
||||
// and a snapshot is due (records handed over before may be missing from a log written
|
||||
// by a thread of its own: note 2 of 2026-10-25)
|
||||
assert!(j.wants_snapshot(), "tear at {tear}");
|
||||
j.append(&batch).unwrap();
|
||||
let more = apply(&mut c, vec![Op::SetLabel { id, label: Some(ColorLabel::ALL[0]) }]);
|
||||
j.append(&more).unwrap();
|
||||
|
||||
@@ -55,5 +55,8 @@ fn a_file_path_rule_allocates_nothing_per_photo() {
|
||||
}
|
||||
let blocks = dhat::HeapStats::get().total_blocks - before;
|
||||
assert!(hits > 0, "the rules matched nothing: the test measures nothing");
|
||||
assert_eq!(blocks, 0, "{blocks} heap blocks for {} rule tests", 100 * rules.len() * photos.len());
|
||||
// dhat counts every thread, and the test harness's own thread can allocate a few blocks while this
|
||||
// runs. An allocation per photo would be thousands, two per rule test.
|
||||
let tests = 100 * rules.len() * photos.len();
|
||||
assert!(blocks < 64, "{blocks} heap blocks for {tests} rule tests");
|
||||
}
|
||||
@@ -862,3 +862,210 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`crate::decode_jpeg_srgb8_fit`]: a plain 8-bit sRGB JPEG decoded (DCT-scaled when that still
|
||||
/// covers the box) and area-averaged in linear light straight into 8-bit sRGB, without the
|
||||
/// float image the general path builds (for a 45 MP camera preview fitted to 2560 px that float
|
||||
/// image and its conversions were half the time). `Ok(None)` for anything else.
|
||||
pub(crate) fn srgb8_fit(bytes: &[u8], max_w: u32, max_h: u32) -> Result<Option<(lightcraft_raster::Rgba8, u16)>> {
|
||||
// (a Samsung SEF trailer read as the file it stands for, as the general decode does: CodeRabbit on #3583)
|
||||
let bytes = &*without_sef_trailer(bytes);
|
||||
let Some(m) = parse_markers(bytes) else { return Ok(None) };
|
||||
let plain = matches!(m.components, 1 | 3)
|
||||
&& m.precision == 8
|
||||
&& matches!(m.sof, 0xC0..=0xC2)
|
||||
&& m.icc.is_none()
|
||||
&& !m.icc_invalid
|
||||
&& m.adobe_transform.is_none();
|
||||
let summary = m.exif.as_deref().map(exif::summarize).unwrap_or_default();
|
||||
if !plain || summary.adobe_rgb_hint || max_w == 0 || max_h == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let budget = DecodeOptions::default();
|
||||
check_size(F, m.width as u64, m.height as u64, &budget)?;
|
||||
// as in the general decode: the decoders below walk every APP1 again
|
||||
if m.app1 > MAX_APP1 {
|
||||
return Err(Error::Malformed(F, "too many APP1 markers".into()));
|
||||
}
|
||||
let scale_to = (m.width >= max_w.saturating_mul(2) || m.height >= max_h.saturating_mul(2)).then_some((max_w, max_h));
|
||||
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
|
||||
let raw =
|
||||
if scale_to.is_some() || non_interleaved { decode_jpeg_decoder(bytes, &m, scale_to, &budget)? } else { decode_zune(bytes, &m, &budget)? };
|
||||
let Buf::U8(px) = &raw.buf else { return Ok(None) };
|
||||
let ch = match raw.model {
|
||||
Model::Rgb => 3,
|
||||
Model::Gray => 1,
|
||||
Model::Cmyk => return Ok(None),
|
||||
};
|
||||
let (w, h) = (raw.width, raw.height);
|
||||
if w == 0 || h == 0 || px.len() < w.saturating_mul(h).saturating_mul(ch) {
|
||||
return Err(Error::Malformed(F, "short output".into()));
|
||||
}
|
||||
// the size `lightcraft_raster::resample::fit` gives: within the box, aspect kept, never larger
|
||||
let s = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0);
|
||||
let tw = ((w as f64 * s).round() as usize).clamp(1, w);
|
||||
let th = ((h as f64 * s).round() as usize).clamp(1, h);
|
||||
let orientation = summary.orientation.filter(|o| (1..=8).contains(o)).unwrap_or(1);
|
||||
Ok(Some((area_average_srgb8(px, w, h, ch, tw, th), orientation)))
|
||||
}
|
||||
|
||||
/// Source pixels and weights each output pixel along one axis covers: a box of the scale's width
|
||||
/// (`n` source pixels onto `out`), partly covered pixels at its ends weighted by their share.
|
||||
fn box_taps(n: usize, out: usize) -> Vec<(usize, Vec<f32>)> {
|
||||
let scale = n as f64 / out as f64;
|
||||
(0..out)
|
||||
.map(|o| {
|
||||
let (a, b) = (o as f64 * scale, ((o + 1) as f64 * scale).min(n as f64));
|
||||
let first = (a.floor() as usize).min(n - 1);
|
||||
let last = ((b.ceil() as usize).max(first + 1)).min(n);
|
||||
let ws: Vec<f32> =
|
||||
(first..last).map(|j| ((b.min(j as f64 + 1.0) - a.max(j as f64)).max(0.0) / (b - a).max(f64::MIN_POSITIVE)) as f32).collect();
|
||||
(first, ws)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `px` (`w × h`, `ch` = 1 or 3 interleaved 8-bit sRGB samples) averaged over boxes in linear
|
||||
/// light into `tw × th` opaque 8-bit sRGB pixels. A copy when the size doesn't change.
|
||||
fn area_average_srgb8(px: &[u8], w: usize, h: usize, ch: usize, tw: usize, th: usize) -> lightcraft_raster::Rgba8 {
|
||||
use lightcraft_color::transfer::{decode_srgb8, encode_srgb8};
|
||||
let mut out = lightcraft_raster::Rgba8::new(tw, th);
|
||||
let sample = |x: usize, y: usize, c: usize| px.get((y * w + x) * ch + if ch == 3 { c } else { 0 }).copied().unwrap_or(0);
|
||||
if (tw, th) == (w, h) {
|
||||
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = [sample(x, y, 0), sample(x, y, 1), sample(x, y, 2), 255];
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
let lut: [f32; 256] = std::array::from_fn(|i| decode_srgb8(i as u8));
|
||||
let xs = box_taps(w, tw);
|
||||
let ys = box_taps(h, th);
|
||||
// one source row filtered across into linear RGB at the output width
|
||||
let across = |sy: usize, buf: &mut Vec<[f32; 3]>| {
|
||||
buf.clear();
|
||||
let Some(src) = px.get(sy * w * ch..(sy + 1) * w * ch) else {
|
||||
buf.resize(tw, [0.0; 3]);
|
||||
return;
|
||||
};
|
||||
for (x0, wx) in &xs {
|
||||
let mut a = [0f32; 3];
|
||||
if let Some(span) = src.get(x0 * ch..(x0 + wx.len()) * ch) {
|
||||
for (p, &k) in span.chunks_exact(ch).zip(wx) {
|
||||
match p {
|
||||
[r, g, b] => {
|
||||
a[0] += lut[*r as usize] * k;
|
||||
a[1] += lut[*g as usize] * k;
|
||||
a[2] += lut[*b as usize] * k;
|
||||
}
|
||||
[v] => {
|
||||
let l = lut[*v as usize] * k;
|
||||
a = [a[0] + l, a[1] + l, a[2] + l];
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
buf.push(a);
|
||||
}
|
||||
};
|
||||
lightcraft_raster::par_rows(&mut out.data, tw, |y, row| {
|
||||
let Some((y0, wy)) = ys.get(y) else { return };
|
||||
let mut acc = vec![[0f32; 3]; tw];
|
||||
let mut line = Vec::with_capacity(tw);
|
||||
for (dy, &k) in wy.iter().enumerate() {
|
||||
across(y0 + dy, &mut line);
|
||||
for (a, l) in acc.iter_mut().zip(&line) {
|
||||
a[0] += l[0] * k;
|
||||
a[1] += l[1] * k;
|
||||
a[2] += l[2] * k;
|
||||
}
|
||||
}
|
||||
for (o, a) in row.iter_mut().zip(&acc) {
|
||||
*o = [encode_srgb8(a[0]), encode_srgb8(a[1]), encode_srgb8(a[2]), 255];
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod srgb8_fit_tests {
|
||||
use super::*;
|
||||
|
||||
fn jpeg(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
|
||||
let data: Vec<[u8; 4]> = (0..w * h)
|
||||
.map(|i| {
|
||||
let [r, g, b] = f(i % w, i / w);
|
||||
[r, g, b, 255]
|
||||
})
|
||||
.collect();
|
||||
let img = lightcraft_raster::Rgba8 { width: w, height: h, data };
|
||||
crate::encode_jpeg(&crate::EncodeImage::rgba8(&img), 95, crate::ChromaSubsampling::S420, &crate::EncodeMeta::default()).unwrap()
|
||||
}
|
||||
|
||||
/// The fast path shows what the general decode shows for a plain sRGB JPEG, at the same size.
|
||||
#[test]
|
||||
fn matches_the_general_decode_within_a_few_levels() {
|
||||
let b = jpeg(1203, 801, |x, y| [((x * 7) ^ (y * 3)) as u8, (x / 5 + y / 3) as u8, ((x * y) % 251) as u8]);
|
||||
for (mw, mh) in [(300u32, 300u32), (640, 640), (1203, 801), (5000, 5000), (500, 120)] {
|
||||
let (fast, o) = srgb8_fit(&b, mw, mh).unwrap().unwrap();
|
||||
let slow = crate::decode(&b, DecodeOptions::fit(mw, mh)).unwrap().to_srgb8();
|
||||
assert_eq!((fast.width, fast.height), (slow.width, slow.height), "box {mw}×{mh}");
|
||||
assert_eq!(o, 1);
|
||||
let diff: Vec<u32> =
|
||||
fast.data.iter().zip(&slow.data).flat_map(|(a, b)| (0..3).map(move |c| (a[c] as i32 - b[c] as i32).unsigned_abs())).collect();
|
||||
let mean = diff.iter().sum::<u32>() as f64 / diff.len() as f64;
|
||||
assert!(mean < 3.0, "box {mw}×{mh}: mean difference {mean}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Anything but plain 8-bit sRGB goes the general way; junk is an error or `None`, never a panic.
|
||||
#[test]
|
||||
fn declines_what_it_does_not_cover_and_never_panics() {
|
||||
let b = jpeg(64, 48, |x, _| [x as u8, 0, 0]);
|
||||
assert!(srgb8_fit(&b, 0, 10).unwrap().is_none());
|
||||
assert!(srgb8_fit(b"not a jpeg", 10, 10).unwrap().is_none());
|
||||
for cut in [0, 2, 20, b.len() / 2, b.len() - 3] {
|
||||
let _ = srgb8_fit(&b[..cut], 32, 32);
|
||||
}
|
||||
// a 1-pixel-wide image into a box much smaller in one axis
|
||||
let thin = jpeg(1, 300, |_, y| [y as u8, y as u8, y as u8]);
|
||||
let (img, _) = srgb8_fit(&thin, 10, 10).unwrap().unwrap();
|
||||
assert_eq!((img.width, img.height), (1, 10));
|
||||
}
|
||||
|
||||
/// An incomplete ICC_PROFILE sequence (chunk 1 of 2) is "has a profile we can't read", not
|
||||
/// "plain sRGB": the general decode handles it, as the doc says (CodeRabbit on #3577).
|
||||
#[test]
|
||||
fn an_incomplete_icc_sequence_goes_the_general_way() {
|
||||
let b = jpeg(16, 16, |x, y| [x as u8, y as u8, 0]);
|
||||
let mut seg = vec![0xFF, 0xE2, 0, 0];
|
||||
seg.extend_from_slice(b"ICC_PROFILE | ||||