Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[rust] Add guardrail checks for the CLI and library crates (#14314)

Manav Rathif48440e1d222
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index c25bad22f2..cafe458283 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2653,6 +2653,7 @@ dependencies = [
"image",
"jxl-oxide",
"kamadak-exif",
+ "log",
"moxcms 0.9.1",
"png",
"tempfile",
diff --git a/rust/apps/cli/src/args.rs b/rust/apps/cli/src/args.rs
index ead3d1057e..b8f08f9278 100644
--- a/rust/apps/cli/src/args.rs
+++ b/rust/apps/cli/src/args.rs
@@ -168,7 +168,10 @@ Fish loads a saved script on demand. Write it once, and again after upgrading:
Prints the script to stdout, including when --json is set."
)]
- Completion { shell: Shell },
+ Completion {
+ #[arg(help = "Shell to generate the script for")]
+ shell: Shell,
+ },
#[command(about = "Administer an Ente server", after_long_help = ADMIN_HELP)]
Admin {
#[command(flatten)]
@@ -1119,3 +1122,60 @@ impl App {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::command;
+
+ fn commands(command: &clap::Command, path: &str) -> Vec<(String, clap::Command)> {
+ let path = format!("{path} {}", command.get_name()).trim().to_owned();
+ let mut all = vec![(path.clone(), command.clone())];
+ for child in command.get_subcommands() {
+ all.extend(commands(child, &path));
+ }
+ all
+ }
+
+ #[test]
+ fn help_shape() {
+ let mut root = command();
+ root.build();
+ for (path, command) in commands(&root, "") {
+ let about = command
+ .get_about()
+ .map(ToString::to_string)
+ .unwrap_or_default();
+ assert!(
+ !about.is_empty() && !about.ends_with('.'),
+ "{path}: about {about:?}"
+ );
+ for arg in command.get_arguments() {
+ let help = arg
+ .get_help()
+ .or(arg.get_long_help())
+ .map(ToString::to_string);
+ assert!(
+ help.is_some_and(|help| !help.is_empty()),
+ "{path}: {} has no help",
+ arg.get_id()
+ );
+ }
+ let notes = [command.get_after_help(), command.get_after_long_help()]
+ .into_iter()
+ .flatten()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join("\n");
+ let Some(examples) = notes.split("Examples:\n").nth(1) else {
+ continue;
+ };
+ assert!(
+ !command.has_subcommands(),
+ "{path}: group help carries examples"
+ );
+ for line in examples.lines().take_while(|line| !line.is_empty()) {
+ assert!(line.starts_with(" ente "), "{path}: example {line:?}");
+ }
+ }
+ }
+}
diff --git a/rust/apps/cli/src/db.rs b/rust/apps/cli/src/db.rs
index 8b583ea29c..ee32325cd5 100644
--- a/rust/apps/cli/src/db.rs
+++ b/rust/apps/cli/src/db.rs
@@ -69,4 +69,21 @@ mod tests {
assert!(!bytes.starts_with(b"SQLite format 3"));
assert!(scratch(&path).is_err());
}
+
+ #[test]
+ fn released_migrations_are_append_only() {
+ let hashes: Vec<u64> = MIGRATIONS
+ .iter()
+ .map(|script| {
+ script.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
+ (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3)
+ })
+ })
+ .collect();
+ assert_eq!(
+ hashes,
+ [8_546_364_548_145_080_129, 12_408_635_783_593_254_159],
+ "released migrations are append-only; add a new entry and record its hash"
+ );
+ }
}
diff --git a/rust/apps/cli/tests/cli/export.rs b/rust/apps/cli/tests/cli/export.rs
index 37ce958da0..ad4468dc70 100644
--- a/rust/apps/cli/tests/cli/export.rs
+++ b/rust/apps/cli/tests/cli/export.rs
@@ -1082,8 +1082,6 @@ fn export_excludes_another_writer_while_downloads_are_running() -> TestResult {
"--json",
]))?;
held.wait_for(2);
- std::thread::sleep(Duration::from_millis(500));
- assert_eq!(objects.reads() - reads, 2);
let second = ExportChild::spawn(&mut other.command(&[
"photos",
"export",
@@ -1091,6 +1089,7 @@ fn export_excludes_another_writer_while_downloads_are_running() -> TestResult {
"--adopt",
]))?;
assert!(failure(&second.wait_with_output()?).contains("another writer"));
+ assert_eq!(objects.reads() - reads, 2);
drop(held);
let result: Value = serde_json::from_slice(&success(child.wait_with_output()?).stdout)?;
assert_eq!(result["copies"]["completed"], 4);
@@ -1263,6 +1262,45 @@ fn read_json(path: &Path) -> Value {
serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
}
+fn verify_layout(root: &Path) {
+ fn visit(root: &Path, directory: &Path) {
+ for entry in fs::read_dir(directory).unwrap() {
+ let path = entry.unwrap().path();
+ let relative = path.strip_prefix(root).unwrap();
+ let parts: Vec<&str> = relative.iter().map(|part| part.to_str().unwrap()).collect();
+ let album = match parts.as_slice() {
+ ["export.json"] => continue,
+ ["Trash", album @ ..] => album,
+ album => album,
+ };
+ let valid = if path.is_dir() {
+ visit(root, &path);
+ match album {
+ [] | [_, "metadata"] => true,
+ [_] => path.join("metadata.json").is_file(),
+ _ => false,
+ }
+ } else {
+ match album {
+ [_, "metadata.json"] => true,
+ [_, "metadata", json] => json
+ .strip_suffix(".json")
+ .is_some_and(|name| path.parent().unwrap().with_file_name(name).is_file()),
+ [_, name] => path
+ .parent()
+ .unwrap()
+ .join("metadata")
+ .join(format!("{name}.json"))
+ .is_file(),
+ _ => false,
+ }
+ };
+ assert!(valid, "unexpected export entry {}", relative.display());
+ }
+ }
+ visit(root, root);
+}
+
fn export_database(home: &TestHome) -> rusqlite::Connection {
let state = home.read_vault();
let account = &state["accounts"][0];
@@ -1459,6 +1497,7 @@ fn export_names_are_portable_and_stable() -> TestResult {
export(&fresh, &root, &[])["changes"],
json!({"exported":0,"metadataUpdated":0,"renamed":0,"movedToTrash":0})
);
+ verify_layout(&root);
Ok(())
})
}
@@ -1837,6 +1876,7 @@ fn export_adopts_go_and_desktop_fixtures_with_a_real_source_account() -> TestRes
read_json(&root.join("Family/metadata/Photo.jpg.json"))["ente"]["fileID"],
file.to_string()
);
+ verify_layout(&root);
}
Ok(())
})
diff --git a/rust/checks/cli-env-vars/check.mjs b/rust/checks/cli-env-vars/check.mjs
new file mode 100644
index 0000000000..595f04b066
--- /dev/null
+++ b/rust/checks/cli-env-vars/check.mjs
@@ -0,0 +1,42 @@
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+
+const root = resolve(process.argv[2]);
+const documented = new Set([
+ "ENTE_CLI_HOME",
+ "ENTE_CLI_PASSWORD",
+ "ENTE_CLI_VAULT_KEY",
+]);
+const reads = /\benv::var(?:_os)?\s*\(\s*([^)]*?)\s*\)/g;
+const sources = execFileSync(
+ "git",
+ [
+ "ls-files",
+ "--cached",
+ "--others",
+ "--exclude-standard",
+ "-z",
+ "--",
+ "rust/apps/cli/src",
+ ],
+ { cwd: root, encoding: "utf8" },
+)
+ .split("\0")
+ .filter((path) => path.endsWith(".rs") && existsSync(resolve(root, path)));
+
+for (const path of sources) {
+ const source = readFileSync(resolve(root, path), "utf8");
+ for (const match of source.matchAll(reads)) {
+ const line = source.slice(0, match.index).split("\n").length;
+ const name = match[1].match(/^"([^"]*)"$/)?.[1];
+ if (name === undefined) {
+ console.error(`${path}:${line}: env::var takes a string literal`);
+ } else if (!documented.has(name)) {
+ console.error(
+ `${path}:${line}: ${name} is not a documented environment variable`,
+ );
+ } else continue;
+ process.exitCode = 1;
+ }
+}
diff --git a/rust/checks/cli-env-vars/test.mjs b/rust/checks/cli-env-vars/test.mjs
new file mode 100644
index 0000000000..6625074c48
--- /dev/null
+++ b/rust/checks/cli-env-vars/test.mjs
@@ -0,0 +1,40 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+const check = join(import.meta.dirname, "check.mjs");
+
+let result = run(
+ 'let home = std::env::var_os("ENTE_CLI_HOME");\nlet key = env::var("ENTE_CLI_VAULT_KEY");\nfor (name, value) in env::vars() {}\n',
+);
+assert.equal(result.status, 0, result.stderr);
+assert.equal(result.stderr, "");
+
+result = run(
+ 'let other = env::var("ENTE_CLI_OTHER");\nlet value = env::var_os(name);\n',
+);
+assert.equal(result.status, 1, result.stderr);
+assert.equal(
+ result.stderr,
+ "rust/apps/cli/src/fixture.rs:1: ENTE_CLI_OTHER is not a documented environment variable\nrust/apps/cli/src/fixture.rs:2: env::var takes a string literal\n",
+);
+
+result = run(
+ 'let other = env::var("ENTE_CLI_OTHER");\n',
+ "rust/apps/cli/tests/cli/fixture.rs",
+);
+assert.equal(result.status, 0, result.stderr);
+
+function run(source, path = "rust/apps/cli/src/fixture.rs") {
+ const root = mkdtempSync(join(tmpdir(), "ente-cli-env-vars-"));
+ try {
+ spawnSync("git", ["init", "-q"], { cwd: root });
+ mkdirSync(join(root, dirname(path)), { recursive: true });
+ writeFileSync(join(root, path), source);
+ return spawnSync(process.execPath, [check, root], { encoding: "utf8" });
+ } finally {
+ rmSync(root, { recursive: true });
+ }
+}
diff --git a/rust/checks/cli-test-sleeps/allowed.json b/rust/checks/cli-test-sleeps/allowed.json
new file mode 100644
index 0000000000..11a42e6fae
--- /dev/null
+++ b/rust/checks/cli-test-sleeps/allowed.json
@@ -0,0 +1,12 @@
+{
+ "rust/apps/cli/tests/cli/export.rs": ["export_refills_transfers"],
+ "rust/apps/cli/tests/cli/export_maintenance.rs": [
+ "export_reports_progress_and_keeps_account_storage_while_workers_run"
+ ],
+ "rust/apps/cli/tests/cli/export_process.rs": ["wait_with_output"],
+ "rust/apps/cli/tests/cli/export_resources.rs": [
+ "export_many_records_unchanged_resource_check",
+ "measure"
+ ],
+ "rust/apps/cli/tests/cli/mail.rs": ["new"]
+}
diff --git a/rust/checks/cli-test-sleeps/check.mjs b/rust/checks/cli-test-sleeps/check.mjs
new file mode 100644
index 0000000000..1549106f14
--- /dev/null
+++ b/rust/checks/cli-test-sleeps/check.mjs
@@ -0,0 +1,50 @@
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+
+const root = resolve(process.argv[2]);
+const listPath = "rust/checks/cli-test-sleeps/allowed.json";
+const allowed = JSON.parse(readFileSync(resolve(root, listPath), "utf8"));
+const unused = new Map(
+ Object.entries(allowed).map(([path, names]) => [path, new Set(names)]),
+);
+const sleeps = /\bsleep\s*\(/g;
+const functions = /\bfn\s+([A-Za-z_][A-Za-z0-9_]*)/g;
+const sources = execFileSync(
+ "git",
+ [
+ "ls-files",
+ "--cached",
+ "--others",
+ "--exclude-standard",
+ "-z",
+ "--",
+ "rust/apps/cli/tests",
+ ],
+ { cwd: root, encoding: "utf8" },
+)
+ .split("\0")
+ .filter((path) => path.endsWith(".rs") && existsSync(resolve(root, path)));
+
+for (const path of sources) {
+ const source = readFileSync(resolve(root, path), "utf8");
+ const names = [...source.matchAll(functions)];
+ for (const match of source.matchAll(sleeps)) {
+ const name = names.findLast((name) => name.index < match.index)?.[1];
+ if (unused.get(path)?.delete(name)) continue;
+ const line = source.slice(0, match.index).split("\n").length;
+ console.error(
+ `${path}:${line}: sleep in ${name}; use the ObjectStoreControl barriers in ente-test-support`,
+ );
+ process.exitCode = 1;
+ }
+}
+
+for (const [path, names] of unused) {
+ for (const name of names) {
+ console.error(
+ `${path}: ${name} no longer sleeps; remove it from ${listPath}`,
+ );
+ process.exitCode = 1;
+ }
+}
diff --git a/rust/checks/cli-test-sleeps/test.mjs b/rust/checks/cli-test-sleeps/test.mjs
new file mode 100644
index 0000000000..0fcdb93d1a
--- /dev/null
+++ b/rust/checks/cli-test-sleeps/test.mjs
@@ -0,0 +1,43 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+const check = join(import.meta.dirname, "check.mjs");
+const listPath = "rust/checks/cli-test-sleeps/allowed.json";
+
+let result = run({
+ "rust/apps/cli/tests/cli/wait.rs":
+ "fn wait() {\n while pending() {\n std::thread::sleep(Duration::from_millis(10));\n }\n}\nfn done() {}\n",
+ [listPath]: '{"rust/apps/cli/tests/cli/wait.rs":["wait"]}',
+});
+assert.equal(result.status, 0, result.stderr);
+assert.equal(result.stderr, "");
+
+result = run({
+ "rust/apps/cli/tests/cli/wait.rs":
+ "async fn pace() {\n tokio::time::sleep(Duration::from_millis(300)).await;\n}\nfn settle() {\n let delay = || thread::sleep(Duration::from_millis(500));\n sleep(Duration::from_millis(1));\n}\n",
+ "rust/apps/cli/src/main.rs":
+ "fn main() {\n std::thread::sleep(Duration::from_secs(1));\n}\n",
+ [listPath]: '{"rust/apps/cli/tests/cli/wait.rs":["settle","wait"]}',
+});
+assert.equal(result.status, 1, result.stderr);
+assert.equal(
+ result.stderr,
+ "rust/apps/cli/tests/cli/wait.rs:2: sleep in pace; use the ObjectStoreControl barriers in ente-test-support\nrust/apps/cli/tests/cli/wait.rs:6: sleep in settle; use the ObjectStoreControl barriers in ente-test-support\nrust/apps/cli/tests/cli/wait.rs: wait no longer sleeps; remove it from rust/checks/cli-test-sleeps/allowed.json\n",
+);
+
+function run(files) {
+ const root = mkdtempSync(join(tmpdir(), "ente-cli-test-sleeps-"));
+ try {
+ spawnSync("git", ["init", "-q"], { cwd: root });
+ for (const [path, source] of Object.entries(files)) {
+ mkdirSync(join(root, dirname(path)), { recursive: true });
+ writeFileSync(join(root, path), source);
+ }
+ return spawnSync(process.execPath, [check, root], { encoding: "utf8" });
+ } finally {
+ rmSync(root, { recursive: true });
+ }
+}
diff --git a/rust/checks/dependency-boundaries/check.mjs b/rust/checks/dependency-boundaries/check.mjs
index 944e3461ba..9f1f6554c2 100644
--- a/rust/checks/dependency-boundaries/check.mjs
+++ b/rust/checks/dependency-boundaries/check.mjs
@@ -28,25 +28,41 @@ const domain = metadata.packages.filter((pkg) =>
pathFromRoot(pkg.manifest_path).startsWith("rust/crates/"),
);
-const httpOwners = new Set([
+const httpOwners = sorted("httpOwners", [
"rust/apps/cli/Cargo.toml",
"rust/crates/assets/Cargo.toml",
"rust/crates/core/Cargo.toml",
"rust/tools/location-dataset/Cargo.toml",
]);
-if ([...httpOwners].some((path, i, paths) => i > 0 && paths[i - 1] > path)) {
- throw new Error("httpOwners must be sorted");
-}
+const cryptoOwner = "rust/crates/core/Cargo.toml";
+const cryptoExceptions = sorted("cryptoExceptions", [
+ "hkdf rust/crates/ensu-crypto/Cargo.toml",
+ "hmac rust/crates/legacy/Cargo.toml",
+ "srp rust/crates/accounts/Cargo.toml",
+]);
+const cryptoName =
+ /^(?:aes|argon2|bcrypt|chacha|crypto[-_]|curve25519|ecdsa|ed25519|hkdf|hmac|hpke|kyber|libcrux|ml-kem|p256|pbkdf|poly1305|salsa|scrypt|secp256|sodium|x25519|ring$|srp$)/;
for (const pkg of metadata.packages) {
const manifest = pathFromRoot(pkg.manifest_path);
- if (httpOwners.has(manifest)) continue;
- for (const dependency of pkg.dependencies) {
- if (dependency.name !== "reqwest") continue;
- console.error(
- `${manifest}: use ente-core::http instead of a direct reqwest dependency`,
- );
- process.exitCode = 1;
+ for (const { name, path } of pkg.dependencies) {
+ if (name === "reqwest" && !httpOwners.has(manifest)) {
+ console.error(
+ `${manifest}: use ente-core::http instead of a direct reqwest dependency`,
+ );
+ process.exitCode = 1;
+ }
+ if (
+ cryptoName.test(name) &&
+ !inside(crates, path) &&
+ manifest !== cryptoOwner &&
+ !cryptoExceptions.has(`${name} ${manifest}`)
+ ) {
+ console.error(
+ `${manifest}: ${name} is a cryptographic dependency; use ente-core::crypto`,
+ );
+ process.exitCode = 1;
+ }
}
}
@@ -142,6 +158,13 @@ function git(...args) {
return execFileSync("git", args, { cwd: root, encoding: "utf8" });
}
+function sorted(name, values) {
+ if (values.some((value, i) => i > 0 && values[i - 1] > value)) {
+ throw new Error(`${name} must be sorted`);
+ }
+ return new Set(values);
+}
+
function inside(directory, path) {
if (!path) return false;
const local = relative(directory, path);
diff --git a/rust/checks/dependency-boundaries/test.mjs b/rust/checks/dependency-boundaries/test.mjs
index 834adb16b7..b892659a4a 100644
--- a/rust/checks/dependency-boundaries/test.mjs
+++ b/rust/checks/dependency-boundaries/test.mjs
@@ -133,6 +133,25 @@ for (const domainName of ["core", "assets"]) {
assert.equal(result.status, 0, result.stderr);
}
+for (const framework of ["argon2", "aes-gcm", "ring"]) {
+ result = run({ framework });
+ assert.equal(result.status, 1, result.stderr);
+ assert.match(
+ result.stderr,
+ new RegExp(`${framework} is a cryptographic dependency`),
+ );
+}
+
+for (const [framework, domainName] of [
+ ["argon2", "core"],
+ ["srp", "accounts"],
+ ["keyring", "domain"],
+]) {
+ result = run({ framework, domainName });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, "");
+}
+
result = run({
projections: {
"rust/bindings/wasm/lib/src/projection.rs":
diff --git a/rust/checks/library-prints/check.mjs b/rust/checks/library-prints/check.mjs
new file mode 100644
index 0000000000..77d2b0c74c
--- /dev/null
+++ b/rust/checks/library-prints/check.mjs
@@ -0,0 +1,52 @@
+import { execFileSync } from "node:child_process";
+import { existsSync, readFileSync } from "node:fs";
+import { resolve } from "node:path";
+
+const root = resolve(process.argv[2]);
+const library =
+ /^rust\/(?:crates\/(?!test-support\/)[^/]+|bindings\/[^/]+\/[^/]+)\/src\/.*\.rs$/;
+const literals =
+ /\/\/[^\n]*|\/\*[\s\S]*?\*\/|b?r(#*)"[\s\S]*?"\1|b?"(?:\\[\s\S]|[^"\\])*"|b?'(?:\\.|[^'\\\n])'/g;
+const tokens = /#\[cfg\(test\)\]|\b(e?print(?:ln)?)!|[{};]/g;
+const sources = execFileSync(
+ "git",
+ [
+ "ls-files",
+ "--cached",
+ "--others",
+ "--exclude-standard",
+ "-z",
+ "--",
+ "rust/crates",
+ "rust/bindings",
+ ],
+ { cwd: root, encoding: "utf8" },
+)
+ .split("\0")
+ .filter((path) => library.test(path) && existsSync(resolve(root, path)));
+
+for (const path of sources) {
+ const source = readFileSync(resolve(root, path), "utf8").replace(
+ literals,
+ (text) => text.replace(/[^\n]/g, " "),
+ );
+ let skipping = 0;
+ let depth = 0;
+ for (const match of source.matchAll(tokens)) {
+ const [token, macro] = match;
+ if (token === "#[cfg(test)]") skipping ||= 1;
+ else if (token === "{" && skipping) {
+ skipping = 2;
+ depth++;
+ } else if (token === "}" && skipping === 2 && --depth === 0) {
+ skipping = 0;
+ } else if (token === ";" && skipping === 1) skipping = 0;
+ else if (macro && !skipping) {
+ const line = source.slice(0, match.index).split("\n").length;
+ console.error(
+ `${path}:${line}: ${macro}! in a library crate; use the log macros`,
+ );
+ process.exitCode = 1;
+ }
+ }
+}
diff --git a/rust/checks/library-prints/test.mjs b/rust/checks/library-prints/test.mjs
new file mode 100644
index 0000000000..bc65651113
--- /dev/null
+++ b/rust/checks/library-prints/test.mjs
@@ -0,0 +1,49 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+
+const check = join(import.meta.dirname, "check.mjs");
+
+let result = run(
+ 'pub fn f() {\n let s = "println!(x)";\n}\n// eprintln!("no")\n#[cfg(test)]\nuse std::fmt;\n#[cfg(test)]\nfn helper() {\n eprintln!("test");\n}\n#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n println!("{}", 1);\n }\n}\n',
+);
+assert.equal(result.status, 0, result.stderr);
+assert.equal(result.stderr, "");
+
+result = run(
+ 'pub fn f() {\n print!("a");\n log::warn!("b");\n}\n#[cfg(test)]\nmod tests {}\nfn g() {\n eprintln!("c");\n}\n',
+);
+assert.equal(result.status, 1, result.stderr);
+assert.equal(
+ result.stderr,
+ "rust/crates/domain/src/lib.rs:2: print! in a library crate; use the log macros\nrust/crates/domain/src/lib.rs:8: eprintln! in a library crate; use the log macros\n",
+);
+
+for (const path of [
+ "rust/crates/test-support/src/lib.rs",
+ "rust/crates/domain/examples/run.rs",
+ "rust/apps/cli/src/main.rs",
+]) {
+ result = run('fn f() {\n println!("x");\n}\n', path);
+ assert.equal(result.status, 0, result.stderr);
+}
+
+result = run(
+ 'fn f() {\n println!("x");\n}\n',
+ "rust/bindings/wasm/lib/src/lib.rs",
+);
+assert.equal(result.status, 1, result.stderr);
+
+function run(source, path = "rust/crates/domain/src/lib.rs") {
+ const root = mkdtempSync(join(tmpdir(), "ente-library-prints-"));
+ try {
+ spawnSync("git", ["init", "-q"], { cwd: root });
+ mkdirSync(join(root, dirname(path)), { recursive: true });
+ writeFileSync(join(root, path), source);
+ return spawnSync(process.execPath, [check, root], { encoding: "utf8" });
+ } finally {
+ rmSync(root, { recursive: true });
+ }
+}
diff --git a/rust/crates/image/Cargo.toml b/rust/crates/image/Cargo.toml
index 7d0e10e490..bdf9541bab 100644
--- a/rust/crates/image/Cargo.toml
+++ b/rust/crates/image/Cargo.toml
@@ -10,6 +10,7 @@ fast_image_resize.workspace = true
image.workspace = true
jxl-oxide = { version = "0.12.6", features = ["image"] }
kamadak-exif = "0.6.1"
+log.workspace = true
moxcms = { workspace = true, features = ["in_place"] }
png = "0.18.1"
thiserror.workspace = true
diff --git a/rust/crates/image/src/color_management.rs b/rust/crates/image/src/color_management.rs
index 2015ff7246..59e6dee5df 100644
--- a/rust/crates/image/src/color_management.rs
+++ b/rust/crates/image/src/color_management.rs
@@ -54,7 +54,7 @@ impl<'a> IccConverter<'a> {
) {
Ok(image) => image,
Err((image, err)) => {
- eprintln!("[ml][decode] failed to convert embedded ICC profile to sRGB: {err}");
+ log::warn!("failed to convert embedded ICC profile to sRGB: {err}");
self.source_profile = None;
image
}
@@ -81,7 +81,7 @@ fn conversion_profile(icc_profile: Option<&[u8]>) -> Option<Arc<ColorProfile>> {
let source_profile = match cached_color_profile(icc_profile) {
Ok(profile) => profile,
Err(err) => {
- eprintln!("[ml][decode] failed to parse embedded ICC profile: {err}");
+ log::warn!("failed to parse embedded ICC profile: {err}");
return None;
}
};
@@ -91,8 +91,8 @@ fn conversion_profile(icc_profile: Option<&[u8]>) -> Option<Arc<ColorProfile>> {
}
if profile_uses_hdr_transfer(&source_profile) {
- eprintln!(
- "[ml][decode] embedded ICC profile uses PQ/HLG transfer; skipping ICC transform because tone mapping is not implemented"
+ log::warn!(
+ "embedded ICC profile uses PQ/HLG transfer; skipping ICC transform because tone mapping is not implemented"
);
return None;
}
diff --git a/rust/crates/image/src/decode.rs b/rust/crates/image/src/decode.rs
index 801f87ae7f..c92f6f7dca 100644
--- a/rust/crates/image/src/decode.rs
+++ b/rust/crates/image/src/decode.rs
@@ -129,8 +129,8 @@ fn decode_with_image_crate(image_path: &str) -> ImageResult<DecodedDynamicImage>
match decode_reader_with_image_crate(reader) {
Ok(decoded) => Ok(decoded),
Err(primary_error) if should_attempt_tiff_fallback(guessed_format) => {
- eprintln!(
- "[ml][decode] image crate TIFF decode failed for '{image_path}': {primary_error}. Retrying with tiff crate fallback"
+ log::warn!(
+ "image crate TIFF decode failed for '{image_path}': {primary_error}. Retrying with tiff crate fallback"
);
match decode_with_tiff_crate(image_path) {
@@ -194,14 +194,14 @@ where
let icc_profile = match decoder.icc_profile() {
Ok(icc_profile) => icc_profile,
Err(err) => {
- eprintln!("[ml][decode] failed to read embedded ICC profile: {err}");
+ log::warn!("failed to read embedded ICC profile: {err}");
None
}
};
let orientation = match decoder.orientation() {
Ok(orientation) => Some(orientation),
Err(err) => {
- eprintln!("[ml][decode] failed to read image orientation from decoder: {err}");
+ log::warn!("failed to read image orientation from decoder: {err}");
None
}
};
@@ -464,8 +464,8 @@ fn init_image_decoders() {
let has_heif_family_support = heic_hook_active || heif_hook_active;
if !has_heif_family_support {
- eprintln!(
- "[ml][decode] failed to activate HEIF/HEIC decoder hooks; registration_result=(heic:{}, heif:{}, avif:{}), active_hooks=(heic:{}, heif:{}, avif:{})",
+ log::warn!(
+ "failed to activate HEIF/HEIC decoder hooks; registration_result=(heic:{}, heif:{}, avif:{}), active_hooks=(heic:{}, heif:{}, avif:{})",
registration.heic_decoder_hook_registered,
registration.heif_decoder_hook_registered,
registration.avif_decoder_hook_registered,
@@ -474,8 +474,8 @@ fn init_image_decoders() {
avif_hook_active,
);
} else if !registration.all_decoder_hooks_registered() {
- eprintln!(
- "[ml][decode] ente_heic decoder hooks only partially registered (usually because another initializer registered first); registration_result=(heic:{}, heif:{}, avif:{}), active_hooks=(heic:{}, heif:{}, avif:{})",
+ log::warn!(
+ "ente_heic decoder hooks only partially registered (usually because another initializer registered first); registration_result=(heic:{}, heif:{}, avif:{}), active_hooks=(heic:{}, heif:{}, avif:{})",
registration.heic_decoder_hook_registered,
registration.heif_decoder_hook_registered,
registration.avif_decoder_hook_registered,
@@ -491,8 +491,8 @@ fn init_image_decoders() {
);
if !jxl_hook_active {
- eprintln!(
- "[ml][decode] failed to activate JPEG XL decoder hook; registered_now={jxl_registered_now}, active_hook={jxl_hook_active}"
+ log::warn!(
+ "failed to activate JPEG XL decoder hook; registered_now={jxl_registered_now}, active_hook={jxl_hook_active}"
);
}
@@ -541,8 +541,8 @@ fn apply_heif_exif_orientation_hint(image: DynamicImage, image_path: &Path) -> D
let hint = match exif_orientation_hint_from_path(image_path) {
Ok(hint) => hint,
Err(err) => {
- eprintln!(
- "[ml][decode] failed to inspect HEIF EXIF orientation for '{}': {}",
+ log::warn!(
+ "failed to inspect HEIF EXIF orientation for '{}': {}",
image_path.display(),
err
);
diff --git a/rust/crates/photos-export/src/store.rs b/rust/crates/photos-export/src/store.rs
index 00efb642af..b6f600f5c4 100644
--- a/rust/crates/photos-export/src/store.rs
+++ b/rust/crates/photos-export/src/store.rs
@@ -325,20 +325,7 @@ impl Store {
db.execute_batch(
"PRAGMA foreign_keys = ON; PRAGMA temp_store = MEMORY; PRAGMA journal_mode = WAL;",
)?;
- let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
- let current: i64 =
- transaction.pragma_query_value(None, "user_version", |row| row.get(0))?;
- ensure!(
- current <= 1,
- "database version {current} is newer than this build supports (1)"
- );
- if current == 0 {
- transaction.execute_batch(SCHEMA)?;
- transaction.pragma_update(None, "user_version", 1)?;
- transaction.commit()?;
- } else {
- drop(transaction);
- }
+ migrate(&mut db)?;
let connection = &db;
let existing: Option<Vec<u8>> = connection
.query_row("SELECT destination FROM export WHERE id=1", [], |r| {
@@ -654,6 +641,27 @@ impl Store {
}
}
+fn migrate(db: &mut Connection) -> Result<()> {
+ let target = MIGRATIONS.len() as i64;
+ let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
+ let current: i64 = transaction.pragma_query_value(None, "user_version", |row| row.get(0))?;
+ ensure!(
+ current <= target,
+ "database version {current} is newer than this build supports ({target})"
+ );
+ if current == target {
+ return Ok(());
+ }
+ for script in &MIGRATIONS[current as usize..] {
+ transaction.execute_batch(script)?;
+ }
+ transaction.pragma_update(None, "user_version", target)?;
+ transaction.commit()?;
+ Ok(())
+}
+
+const MIGRATIONS: &[&str] = &[SCHEMA];
+
const SCHEMA: &str = "
CREATE TABLE export (id INTEGER PRIMARY KEY CHECK(id=1), destination BLOB NOT NULL, bound INTEGER NOT NULL DEFAULT 0);
CREATE TABLE albums (key TEXT PRIMARY KEY, id INTEGER NOT NULL, retained INTEGER NOT NULL, name TEXT NOT NULL, path TEXT NOT NULL UNIQUE, parent TEXT NOT NULL, folded TEXT NOT NULL);
@@ -699,3 +707,23 @@ fn read_json<T: DeserializeOwned>(row: &Row<'_>, column: usize) -> rusqlite::Res
rusqlite::Error::FromSqlConversionFailure(column, rusqlite::types::Type::Text, Box::new(e))
})
}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn released_migrations_are_append_only() {
+ let hashes: Vec<u64> = super::MIGRATIONS
+ .iter()
+ .map(|script| {
+ script.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
+ (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3)
+ })
+ })
+ .collect();
+ assert_eq!(
+ hashes,
+ [10_135_794_253_735_637_244],
+ "released migrations are append-only; add a new entry and record its hash"
+ );
+ }
+}
diff --git a/rust/scripts/lint.sh b/rust/scripts/lint.sh
index 456a3c864c..5d602aafdb 100755
--- a/rust/scripts/lint.sh
+++ b/rust/scripts/lint.sh
@@ -8,8 +8,14 @@ python3 checks/cargo-versions/check.py ..
python3 checks/cargo-versions/test.py
python3 checks/cargo-workspace-dependencies/check.py ..
python3 checks/cargo-workspace-dependencies/test.py
+node checks/cli-env-vars/check.mjs ..
+node checks/cli-env-vars/test.mjs
+node checks/cli-test-sleeps/check.mjs ..
+node checks/cli-test-sleeps/test.mjs
node checks/dependency-boundaries/check.mjs ..
node checks/dependency-boundaries/test.mjs
+node checks/library-prints/check.mjs ..
+node checks/library-prints/test.mjs
node checks/lint-exceptions/check.mjs ..
node checks/lint-exceptions/test.mjs
cargo fmt --check