From 64da90d2f20db0814fa23faf86a905bb40d2a212 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 11 Oct 2026 22:36:02 +0100 Subject: [PATCH] feat(develop): Revelar, the synced editor with one engine on web, desktop and server engine/core renders with the LightCraft pipeline; engine/wasm runs it in the browser; workers/render replays op logs and renders originals natively. Op log with live fan-out and offline outbox; edited thumbnails and deliveries rendered from the original. Revelar page with Basic and optional modules, crop with aspect presets and straighten, before/after, undo/redo, copy/paste settings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW --- .gitea/workflows/ci.yml | 4 + .gitignore | 1 + Cargo.lock | 620 +++++++++++++++++- Cargo.toml | 15 +- apps/api/.env.example | 3 + .../20261011210000_develop/migration.sql | 40 ++ apps/api/prisma/schema.prisma | 104 ++- apps/api/src/app.ts | 5 + apps/api/src/config.ts | 3 + apps/api/src/delivery/render.ts | 32 +- apps/api/src/delivery/service.ts | 17 +- apps/api/src/develop/engine.ts | 64 ++ apps/api/src/develop/routes.ts | 46 ++ apps/api/src/develop/service.ts | 219 +++++++ apps/api/src/faces/process.ts | 109 +-- apps/api/src/lib/line-process.ts | 112 ++++ apps/api/src/library/photos.ts | 11 +- apps/api/src/library/serialize.ts | 11 +- apps/api/src/storage/storage.ts | 25 +- apps/api/src/worker.ts | 15 +- apps/api/test/develop.test.ts | 160 +++++ apps/api/test/render-process.test.ts | 53 ++ apps/app/src/App.tsx | 2 + apps/app/src/develop/Panels.tsx | 138 ++++ apps/app/src/develop/Viewer.tsx | 262 ++++++++ apps/app/src/develop/engine.ts | 49 ++ apps/app/src/develop/render.worker.ts | 47 ++ apps/app/src/develop/session.test.ts | 135 ++++ apps/app/src/develop/session.ts | 335 ++++++++++ apps/app/src/i18n.ts | 45 +- apps/app/src/library/store.test.ts | 3 +- apps/app/src/library/store.ts | 2 + apps/app/src/pages/DevelopPage.tsx | 351 ++++++++++ apps/app/src/pages/LibraryPage.tsx | 23 +- apps/app/src/pages/Shell.tsx | 4 +- apps/app/src/styles.css | 41 ++ docs/ARCHITECTURE.md | 31 +- docs/DEPLOY.md | 6 + engine/core/Cargo.toml | 11 +- engine/core/src/lib.rs | 9 +- engine/core/src/render.rs | 123 ++++ engine/wasm/Cargo.toml | 14 + engine/wasm/src/lib.rs | 120 ++++ infra/deploy/deploy.sh | 10 +- infra/engine/build-wasm.sh | 15 + packages/contracts/src/commands.ts | 29 + packages/contracts/src/library.ts | 11 +- packages/sdk/src/client.ts | 13 +- workers/render/Cargo.toml | 11 + workers/render/src/main.rs | 136 ++++ 50 files changed, 3476 insertions(+), 169 deletions(-) create mode 100644 apps/api/prisma/migrations/20261011210000_develop/migration.sql create mode 100644 apps/api/src/develop/engine.ts create mode 100644 apps/api/src/develop/routes.ts create mode 100644 apps/api/src/develop/service.ts create mode 100644 apps/api/src/lib/line-process.ts create mode 100644 apps/api/test/develop.test.ts create mode 100644 apps/api/test/render-process.test.ts create mode 100644 apps/app/src/develop/Panels.tsx create mode 100644 apps/app/src/develop/Viewer.tsx create mode 100644 apps/app/src/develop/engine.ts create mode 100644 apps/app/src/develop/render.worker.ts create mode 100644 apps/app/src/develop/session.test.ts create mode 100644 apps/app/src/develop/session.ts create mode 100644 apps/app/src/pages/DevelopPage.tsx create mode 100644 engine/core/src/render.rs create mode 100644 engine/wasm/Cargo.toml create mode 100644 engine/wasm/src/lib.rs create mode 100755 infra/engine/build-wasm.sh create mode 100644 workers/render/Cargo.toml create mode 100644 workers/render/src/main.rs diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 2d077ee..ff09117 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -45,6 +45,10 @@ jobs: - run: cargo fmt --all --check - run: cargo clippy --workspace --all-targets -- -D warnings - run: cargo test --workspace + - name: Browser engine builds (wasm32) + run: | + rustup target add wasm32-unknown-unknown + cargo build --locked --profile wasm --target wasm32-unknown-unknown -p photoreport-engine-wasm - name: Generated controls are up to date run: | cargo run -q -p photoreport-engine --example export_controls > packages/contracts/src/controls.generated.json diff --git a/.gitignore b/.gitignore index 0bf6890..1ef0ace 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ coverage/ .DS_Store *.log apps/api/src/generated/ +apps/app/public/engine/ diff --git a/Cargo.lock b/Cargo.lock index 00b1cad..33cfc00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,12 +8,33 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "block-buffer" version = "0.10.4" @@ -23,6 +44,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -34,6 +65,20 @@ name = "bytemuck" version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.7", +] [[package]] name = "byteorder-lite" @@ -47,6 +92,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -56,6 +107,46 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "crypto-common" version = "0.1.7" @@ -76,6 +167,38 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -110,6 +233,27 @@ dependencies = [ "version_check", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + [[package]] name = "image" version = "0.25.10" @@ -118,18 +262,48 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", - "moxcms", + "color_quant", + "gif", + "image-webp", + "moxcms 0.8.1", "num-traits", + "png", + "tiff", "zune-core", "zune-jpeg", ] +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jpeg-decoder" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" +dependencies = [ + "rayon", +] + +[[package]] +name = "jpeg-encoder" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6" + [[package]] name = "js-sys" version = "0.3.106" @@ -141,12 +315,211 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jxl-bitstream" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b480e752277e29eb4054f69546887a9b84656fe78c08f54ba5850ced98a378fe" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-coding" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd972bcd125e776f1eb241ac50e39f956095a1c2770c64736c968f8946bd9a3c" +dependencies = [ + "jxl-bitstream", + "tracing", +] + +[[package]] +name = "jxl-color" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f316b1358c1711755b3ee8e8cb5c4a1dad12e796233088a7a513440782de80b2" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-image", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-frame" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d967c6fd669c7c01060b5022d8835fa82fd46b06ffc98b549f17600a097c2b3" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-grid" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01671307879a033bfa52e6e8784b941aca770b3f3a7d33830b455b6844f793fb" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-image" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5f752d62577c702a94dbbce4045caf08cb58639e8a4d56464b40ecf33ffe565" +dependencies = [ + "jxl-bitstream", + "jxl-grid", + "jxl-oxide-common", + "tracing", +] + +[[package]] +name = "jxl-jbr" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46" +dependencies = [ + "brotli-decompressor", + "jxl-bitstream", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-modular" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a2f045b24c738dd91d482be385512b512721ae08a671bd4b27bf1c47f215235" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-oxide" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3" +dependencies = [ + "brotli-decompressor", + "jxl-bitstream", + "jxl-color", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-jbr", + "jxl-oxide-common", + "jxl-render", + "jxl-threadpool", + "tracing", +] + +[[package]] +name = "jxl-oxide-common" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62394c5021b3a9e7e0dbb2d639d555d019090c9946c39f6d3b09d390db4157b" +dependencies = [ + "jxl-bitstream", +] + +[[package]] +name = "jxl-render" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34386bfdb6a19b5a30cc9beb4d475d537422c31ae8c39bb69640fcce3fcaf19" +dependencies = [ + "bytemuck", + "jxl-bitstream", + "jxl-coding", + "jxl-color", + "jxl-frame", + "jxl-grid", + "jxl-image", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "jxl-vardct", + "tracing", +] + +[[package]] +name = "jxl-threadpool" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25f15eb830aa77a7f21148d72e153562a26bfe570139bd4922eab1908dd499d3" +dependencies = [ + "tracing", +] + +[[package]] +name = "jxl-vardct" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce72a18c6d3a47172ab6c479be2bdb56f22066b5d7092663f03b4490820b4511" +dependencies = [ + "jxl-bitstream", + "jxl-coding", + "jxl-grid", + "jxl-modular", + "jxl-oxide-common", + "jxl-threadpool", + "tracing", +] + [[package]] name = "libc" version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +[[package]] +name = "lightcraft-codecs" +version = "0.6.0" +source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +dependencies = [ + "bytemuck", + "image", + "image-webp", + "jpeg-decoder", + "jpeg-encoder", + "lightcraft-color", + "lightcraft-geom", + "lightcraft-raster", + "moxcms 0.9.1", + "png", + "rayon", + "serde", + "thiserror", + "tiff", + "zune-core", + "zune-jpeg", +] + [[package]] name = "lightcraft-color" version = "0.6.0" @@ -163,7 +536,7 @@ source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab5592 dependencies = [ "lightcraft-color", "lightcraft-geom", - "miniz_oxide", + "miniz_oxide 0.8.9", "serde", "serde_json", ] @@ -190,6 +563,70 @@ dependencies = [ "serde", ] +[[package]] +name = "lightcraft-meta" +version = "0.6.0" +source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +dependencies = [ + "lightcraft-geom", + "lightcraft-tiff", + "quick-xml", + "serde", +] + +[[package]] +name = "lightcraft-pipeline" +version = "0.6.0" +source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +dependencies = [ + "lightcraft-color", + "lightcraft-develop", + "lightcraft-geom", + "lightcraft-raster", + "lightcraft-raw", + "rayon", + "serde", +] + +[[package]] +name = "lightcraft-raster" +version = "0.6.0" +source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +dependencies = [ + "lightcraft-color", + "lightcraft-geom", + "rayon", + "serde", +] + +[[package]] +name = "lightcraft-raw" +version = "0.6.0" +source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +dependencies = [ + "jxl-oxide", + "lightcraft-color", + "lightcraft-geom", + "lightcraft-meta", + "lightcraft-raster", + "lightcraft-tiff", + "miniz_oxide 0.8.9", + "rayon", + "serde", + "thiserror", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "lightcraft-tiff" +version = "0.6.0" +source = "git+https://github.com/storytold/lightcraft?rev=0dd6593d9db55a17ab559261bac4d766f015c345#0dd6593d9db55a17ab559261bac4d766f015c345" +dependencies = [ + "serde", + "thiserror", +] + [[package]] name = "matrixmultiply" version = "0.3.11" @@ -213,6 +650,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", ] [[package]] @@ -225,6 +673,16 @@ dependencies = [ "pxfm", ] +[[package]] +name = "moxcms" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396077b717181ce3f9a6b66739b269b82d756be5ec0f76be0bc40a7c51775830" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "ndarray" version = "0.17.2" @@ -277,12 +735,25 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" name = "photoreport-engine" version = "0.1.0" dependencies = [ + "lightcraft-codecs", "lightcraft-develop", + "lightcraft-geom", + "lightcraft-pipeline", + "lightcraft-raster", "serde", "serde_json", "thiserror", ] +[[package]] +name = "photoreport-engine-wasm" +version = "0.1.0" +dependencies = [ + "photoreport-engine", + "serde_json", + "wasm-bindgen", +] + [[package]] name = "photoreport-faces" version = "0.1.0" @@ -294,12 +765,34 @@ dependencies = [ "sha2", ] +[[package]] +name = "photoreport-render" +version = "0.1.0" +dependencies = [ + "photoreport-engine", + "serde", + "serde_json", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -330,6 +823,21 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.38.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" +dependencies = [ + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -345,6 +853,26 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -378,7 +906,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.7", ] [[package]] @@ -405,12 +933,29 @@ dependencies = [ "digest", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.7" @@ -439,7 +984,40 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.7", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", ] [[package]] @@ -492,7 +1070,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn", + "syn 3.0.7", "wasm-bindgen-shared", ] @@ -515,6 +1093,38 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "zerocopy" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 3cc15b3..cb5f872 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["engine/core", "workers/faces"] +members = ["engine/core", "engine/wasm", "workers/render", "workers/faces"] # The desktop shell needs WebKitGTK/WebView2 system libraries, so it builds on its own (desktop release workflow). exclude = ["apps/desktop/src-tauri"] @@ -11,7 +11,20 @@ publish = false [workspace.dependencies] # LightCraft is consumed, never forked. Bump `rev` deliberately and run the reference-image tests. lightcraft-develop = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" } +lightcraft-codecs = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345", default-features = false } +lightcraft-pipeline = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" } +lightcraft-raster = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" } +lightcraft-geom = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" } lightcraft-faces = { git = "https://github.com/storytold/lightcraft", rev = "0dd6593d9db55a17ab559261bac4d766f015c345" } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" + +# The browser module: small and fast enough for slider drags (same trade-off as LightCraft's `web` profile). +[profile.wasm] +inherits = "release" +opt-level = 3 +lto = "fat" +codegen-units = 1 +panic = "abort" +strip = true diff --git a/apps/api/.env.example b/apps/api/.env.example index e3bfa90..04fb5d1 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -29,3 +29,6 @@ FACES_BIN=/srv/photoreport/target/release/photoreport-faces FACES_MODELS_DIR=/srv/photoreport-data/models FACES_EMBEDDER=auraface FACES_PROCESSES=2 +# Develop: replays edits and renders edited thumbnails and deliveries (workers/render). +RENDER_BIN=/srv/photoreport/target/release/photoreport-render +RENDER_PROCESSES=2 diff --git a/apps/api/prisma/migrations/20261011210000_develop/migration.sql b/apps/api/prisma/migrations/20261011210000_develop/migration.sql new file mode 100644 index 0000000..f2c454f --- /dev/null +++ b/apps/api/prisma/migrations/20261011210000_develop/migration.sql @@ -0,0 +1,40 @@ +-- CreateEnum +CREATE TYPE "RenderStatus" AS ENUM ('NONE', 'PENDING', 'RUNNING', 'DONE', 'FAILED'); + +-- AlterTable +ALTER TABLE "photos" ADD COLUMN "develop_seq" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "develop_snapshot" JSONB, +ADD COLUMN "edited_at" TIMESTAMP(3), +ADD COLUMN "render_status" "RenderStatus" NOT NULL DEFAULT 'NONE', +ADD COLUMN "rendered_seq" INTEGER NOT NULL DEFAULT 0, +ADD COLUMN "snapshot_seq" INTEGER NOT NULL DEFAULT 0; + +-- CreateTable +CREATE TABLE "photo_edits" ( + "id" UUID NOT NULL, + "photo_id" UUID NOT NULL, + "seq" INTEGER NOT NULL, + "op_id" TEXT NOT NULL, + "client_id" TEXT NOT NULL, + "command" JSONB NOT NULL, + "user_id" UUID, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "photo_edits_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "photo_edits_photo_id_seq_key" ON "photo_edits"("photo_id", "seq"); + +-- CreateIndex +CREATE UNIQUE INDEX "photo_edits_photo_id_op_id_key" ON "photo_edits"("photo_id", "op_id"); + +-- AddForeignKey +ALTER TABLE "photo_edits" ADD CONSTRAINT "photo_edits_photo_id_fkey" FOREIGN KEY ("photo_id") REFERENCES "photos"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "photo_edits" ADD CONSTRAINT "photo_edits_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE; + + +-- The render worker looks for photos whose edits have paused. +CREATE INDEX "photos_render_pending_idx" ON "photos" ("edited_at") WHERE "render_status" = 'PENDING'; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index ef200d4..d8ad13e 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -46,6 +46,7 @@ model User { assignments EventAssignment[] uploads Photo[] ftpAccounts FtpAccount[] + edits PhotoEdit[] @@map("users") } @@ -235,48 +236,60 @@ model FtpAccount { } model Photo { - id String @id @default(uuid()) @db.Uuid - organizationId String @map("organization_id") @db.Uuid + id String @id @default(uuid()) @db.Uuid + organizationId String @map("organization_id") @db.Uuid /// Null while no event matches (the editor's inbox). - eventId String? @map("event_id") @db.Uuid - uploaderId String? @map("uploader_id") @db.Uuid - source PhotoSource - originalName String @map("original_name") - sha256 String - byteSize Int @map("byte_size") - storageKey String @map("storage_key") - status PhotoStatus @default(PROCESSING) - error String? - width Int? - height Int? - capturedAt DateTime? @map("captured_at") - cameraMake String? @map("camera_make") - cameraModel String? @map("camera_model") - cameraSerial String? @map("camera_serial") - lens String? - focalLength Float? @map("focal_length") - aperture Float? - exposureTime Float? @map("exposure_time") - iso Int? - rating Int @default(0) - flag PhotoFlag @default(NONE) - colorLabel ColorLabel @default(NONE) @map("color_label") + eventId String? @map("event_id") @db.Uuid + uploaderId String? @map("uploader_id") @db.Uuid + source PhotoSource + originalName String @map("original_name") + sha256 String + byteSize Int @map("byte_size") + storageKey String @map("storage_key") + status PhotoStatus @default(PROCESSING) + error String? + width Int? + height Int? + capturedAt DateTime? @map("captured_at") + cameraMake String? @map("camera_make") + cameraModel String? @map("camera_model") + cameraSerial String? @map("camera_serial") + lens String? + focalLength Float? @map("focal_length") + aperture Float? + exposureTime Float? @map("exposure_time") + iso Int? + rating Int @default(0) + flag PhotoFlag @default(NONE) + colorLabel ColorLabel @default(NONE) @map("color_label") /// Names of the people in the photo (go to IPTC Title and Persons Shown). - players String[] @default([]) + players String[] @default([]) /// Per-photo IPTC overrides on top of the event template (packages/metadata IptcTemplate). - iptcOverrides Json? @map("iptc_overrides") + iptcOverrides Json? @map("iptc_overrides") /// IPTC found in the file as it arrived (camera presets or an earlier caption), for reference. - embeddedIptc Json? @map("embedded_iptc") + embeddedIptc Json? @map("embedded_iptc") /// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED. - facesStatus FacesStatus @default(NONE) @map("faces_status") - createdAt DateTime @default(now()) @map("created_at") - updatedAt DateTime @updatedAt @map("updated_at") + facesStatus FacesStatus @default(NONE) @map("faces_status") + /// Last op-log sequence number (0: never edited). + developSeq Int @default(0) @map("develop_seq") + /// Develop settings replayed up to `snapshotSeq` by the render worker (LightCraft JSON); clients + /// replay the ops after it. + developSnapshot Json? @map("develop_snapshot") + snapshotSeq Int @default(0) @map("snapshot_seq") + /// Edited thumb/preview: PENDING after an edit, rendered by the worker once edits pause. + renderStatus RenderStatus @default(NONE) @map("render_status") + /// The op-log sequence the edited thumb/preview show (0: they show the original). + renderedSeq Int @default(0) @map("rendered_seq") + editedAt DateTime? @map("edited_at") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull) uploader User? @relation(fields: [uploaderId], references: [id], onDelete: SetNull) deliveries DeliveryItem[] faces Face[] + edits PhotoEdit[] /// The same file sent twice (FTP retries, two cards) is stored once. @@unique([organizationId, sha256]) @@ -285,6 +298,35 @@ model Photo { @@map("photos") } +enum RenderStatus { + NONE + PENDING + RUNNING + DONE + FAILED +} + +/// The develop op log: every edit command, in the order the server accepted it. Last writer wins per control. +model PhotoEdit { + id String @id @default(uuid()) @db.Uuid + photoId String @map("photo_id") @db.Uuid + seq Int + /// Client-generated id: a retried send (offline queue) is stored once. + opId String @map("op_id") + /// The window that sent it, so it can skip its own echo. + clientId String @map("client_id") + command Json + userId String? @map("user_id") @db.Uuid + createdAt DateTime @default(now()) @map("created_at") + + photo Photo @relation(fields: [photoId], references: [id], onDelete: Cascade) + user User? @relation(fields: [userId], references: [id], onDelete: SetNull) + + @@unique([photoId, seq]) + @@unique([photoId, opId]) + @@map("photo_edits") +} + /// Code replacements (`\v7\`), one list per organization, kept as the tab-separated text people edit. model CodeList { id String @id @default(uuid()) @db.Uuid diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 9f78560..b6744a4 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -17,6 +17,8 @@ import { registerFtpRoutes } from "./library/ftp.js"; import { registerPhotoRoutes } from "./library/photos.js"; import { registerUploadRoutes } from "./library/uploads.js"; import { IngestService } from "./ingest/service.js"; +import { registerDevelopRoutes } from "./develop/routes.js"; +import { DevelopService } from "./develop/service.js"; import { registerFaceRoutes } from "./faces/routes.js"; import { FaceService } from "./faces/service.js"; import { registerOrgRoutes } from "./orgs/routes.js"; @@ -84,6 +86,9 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr const faces = new FaceService({ db, storage, broadcaster, log: app.log }); await registerFaceRoutes(app, { db, sessions, faces, signer, storage }); await registerDeliveryRoutes(app, { db, sessions, secrets, delivery }); + // Edits are stored and fanned out here; the worker replays and renders them. + const develop = new DevelopService({ db, storage, signer, broadcaster, log: app.log }); + await registerDevelopRoutes(app, { db, sessions, develop }); // Validation-only endpoint for the edit contract; the realtime path reuses the same schema. app.post("/v1/edits/validate", async (req) => { diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 59f7e63..45f2ee1 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -44,6 +44,9 @@ const Env = z.object({ FACES_EMBEDDER: z.enum(["auraface", "sface"]).default("auraface"), /** Face processes in parallel (one CPU core each). */ FACES_PROCESSES: z.coerce.number().int().positive().default(2), + /** Render worker binary (workers/render): edited thumbnails and deliveries of edited photos. */ + RENDER_BIN: z.string().optional(), + RENDER_PROCESSES: z.coerce.number().int().positive().default(2), COOKIE_SECURE: z .enum(["true", "false"]) .optional() diff --git a/apps/api/src/delivery/render.ts b/apps/api/src/delivery/render.ts index 418cc87..32efdb1 100644 --- a/apps/api/src/delivery/render.ts +++ b/apps/api/src/delivery/render.ts @@ -4,6 +4,13 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import sharp from "sharp"; +import type { RenderEngine, Settings } from "../develop/engine.js"; + +/** The photo was edited: render it with these develop settings. */ +export interface DeliveryEdit { + engine: RenderEngine; + settings: Settings; +} export interface RenderOptions { longEdge: number; @@ -14,17 +21,26 @@ export interface RenderOptions { * The delivered JPEG: oriented, at most `longEdge` px on the longest side (never enlarged), 4:4:4 chroma at * the requested quality, camera EXIF and colour profile kept, IPTC written into both IIM and XMP. */ -export async function renderDelivery(original: string, iptc: IptcValues, opts: RenderOptions, created?: CreatedStamp): Promise { - const image = await sharp(original) - .rotate() - .resize({ width: opts.longEdge, height: opts.longEdge, fit: "inside", withoutEnlargement: true }) - .keepExif() - .keepIccProfile() - .jpeg({ quality: opts.quality, chromaSubsampling: "4:4:4", mozjpeg: false }) - .toBuffer(); +export async function renderDelivery(original: string, iptc: IptcValues, opts: RenderOptions, created?: CreatedStamp, edit?: DeliveryEdit): Promise { const dir = await mkdtemp(path.join(tmpdir(), "pr-render-")); const file = path.join(dir, "out.jpg"); try { + if (edit) { + // Edited: the develop engine renders the original (crop and all) straight to the delivered size and quality, + // in sRGB. The camera EXIF is copied back, without the orientation (the pixels are already upright). + await edit.engine.render({ input: original, output: file, settings: edit.settings, maxEdge: opts.longEdge, quality: opts.quality }); + await exiftool.write(file, {}, { + writeArgs: ["-overwrite_original", "-TagsFromFile", original, "-EXIF:all", "--Orientation", "--ThumbnailImage", "--PreviewImage", "-Orientation#=1", ...toExiftoolArgs(iptc, created)], + }); + return await readFile(file); + } + const image = await sharp(original) + .rotate() + .resize({ width: opts.longEdge, height: opts.longEdge, fit: "inside", withoutEnlargement: true }) + .keepExif() + .keepIccProfile() + .jpeg({ quality: opts.quality, chromaSubsampling: "4:4:4", mozjpeg: false }) + .toBuffer(); await writeFile(file, image); await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...toExiftoolArgs(iptc, created)] }); return await readFile(file); diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 1b49132..3e02f13 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -8,7 +8,8 @@ import { iptcForPhoto } from "../library/iptc.js"; import type { Broadcaster } from "../realtime.js"; import type { LocalStorage } from "../storage/storage.js"; import { NextcloudClient, NextcloudError } from "./nextcloud.js"; -import { renderDelivery } from "./render.js"; +import type { RenderEngine, Settings } from "../develop/engine.js"; +import { type DeliveryEdit, renderDelivery } from "./render.js"; import type { SecretBox } from "./secrets.js"; export const MAX_ATTEMPTS = 5; @@ -48,6 +49,8 @@ export interface DeliveryDeps { broadcaster: Broadcaster; log: IngestLogger; fetchImpl?: typeof fetch; + /** Edited photos are rendered through it (worker only). */ + develop?: { settings(photoId: string): Promise<{ settings: Settings | null }>; engine: RenderEngine | undefined } | undefined; } /** @@ -60,6 +63,15 @@ export class DeliveryService { constructor(private readonly deps: DeliveryDeps) {} + /** Develop settings for an edited photo; an edited photo is never delivered unedited. */ + private async editFor(photoId: string, developSeq: number): Promise { + if (developSeq === 0) return undefined; + const develop = this.deps.develop; + if (!develop?.engine) throw new Error("photo is edited but the render worker is not configured (RENDER_BIN)"); + const { settings } = await develop.settings(photoId); + return settings ? { engine: develop.engine, settings } : undefined; + } + async enqueue(input: { organizationId: string; targetId: string; photoIds: string[]; again: boolean; requestedById: string }): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> { const { db } = this.deps; const target = await db.deliveryTarget.findFirst({ where: { id: input.targetId, organizationId: input.organizationId, disabledAt: null } }); @@ -159,7 +171,8 @@ export class DeliveryService { const folder = renderFolder(item.target.folderTemplate, vars); const fileName = renderFileName(item.target.fileNameTemplate, vars, item.photo.originalName); const iptc = await iptcForPhoto(db, item.photoId); - const data = await renderDelivery(storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined); + const edit = await this.editFor(item.photoId, item.photo.developSeq); + const data = await renderDelivery(storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined, edit); const client = this.client(item.target); await client.ensureFolder(folder); await client.upload(folder + fileName, data); diff --git a/apps/api/src/develop/engine.ts b/apps/api/src/develop/engine.ts new file mode 100644 index 0000000..7fd93de --- /dev/null +++ b/apps/api/src/develop/engine.ts @@ -0,0 +1,64 @@ +import { LeastBusy, LineProcess } from "../lib/line-process.js"; + +export type Settings = Record; + +export interface Replayed { + settings: Settings; + skipped: number[]; + unedited: boolean; +} + +export interface RenderJob { + input: string; + output: string; + settings: Settings | null; + /** Long edge in pixels (0: full size). */ + maxEdge: number; + quality: number; +} + +/** The develop engine on the server: replays op logs and renders originals (`workers/render`). */ +export interface RenderEngine { + /** `unedited`: the result equals the defaults (e.g. after a reset), so the original is shown as is. */ + replay(base: Settings | null, commands: unknown[]): Promise; + render(job: RenderJob): Promise<{ width: number; height: number }>; + close(): Promise; +} + +export class RenderProcess implements RenderEngine { + private readonly proc: LineProcess; + + constructor(opts: { bin: string; timeoutMs?: number }) { + this.proc = new LineProcess({ name: "render worker", bin: opts.bin, timeoutMs: opts.timeoutMs ?? 300_000 }); + } + + async replay(base: Settings | null, commands: unknown[]) { + const r = await this.proc.request({ base, commands }); + return { settings: r.settings as Settings, skipped: (r.skipped as number[] | undefined) ?? [], unedited: r.unedited === true }; + } + + async render(job: RenderJob) { + const r = await this.proc.request({ ...job }); + return { width: Number(r.width), height: Number(r.height) }; + } + + close(): Promise { + return this.proc.close(); + } +} + +export class RenderPool implements RenderEngine { + private readonly pool: LeastBusy; + constructor(private readonly engines: RenderEngine[]) { + this.pool = new LeastBusy(engines); + } + replay(base: Settings | null, commands: unknown[]) { + return this.pool.use((e) => e.replay(base, commands)); + } + render(job: RenderJob) { + return this.pool.use((e) => e.render(job)); + } + async close(): Promise { + await Promise.all(this.engines.map((e) => e.close())); + } +} diff --git a/apps/api/src/develop/routes.ts b/apps/api/src/develop/routes.ts new file mode 100644 index 0000000..40fa16f --- /dev/null +++ b/apps/api/src/develop/routes.ts @@ -0,0 +1,46 @@ +import { PostEdits } from "@photoreport/contracts"; +import type { FastifyInstance } from "fastify"; +import { z } from "zod"; +import { ROLE_RANK, currentUserId, requireAuth, requireMembership } from "../auth/guard.js"; +import type { SessionService } from "../auth/sessions.js"; +import type { Db } from "../db.js"; +import { badRequest, forbidden, notFound } from "../lib/errors.js"; +import { type DevelopService, EditRejected } from "./service.js"; + +const PhotoParams = z.object({ photoId: z.uuid() }); +const StateQuery = z.object({ since: z.coerce.number().int().min(0).optional() }); + +export async function registerDevelopRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; develop: DevelopService }) { + const { db, develop } = deps; + const authenticate = requireAuth(deps.sessions); + + /** Editors edit any photo of the organization; photographers only the ones they sent. */ + async function photoFor(req: Parameters[0], photoId: string) { + const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, uploaderId: true, status: true } }); + if (!photo) throw notFound("photo_not_found"); + const membership = await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER"); + if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER && photo.uploaderId !== membership.userId) throw forbidden("not_your_photo"); + return photo; + } + + /** The develop state: snapshot plus the ops after it, or (with `since`) just the ops after that position. */ + app.get("/v1/photos/:photoId/develop", { preHandler: authenticate }, async (req) => { + const { photoId } = PhotoParams.parse(req.params); + const { since } = StateQuery.parse(req.query); + await photoFor(req, photoId); + return develop.state(photoId, since); + }); + + app.post("/v1/photos/:photoId/edits", { preHandler: authenticate }, async (req) => { + const { photoId } = PhotoParams.parse(req.params); + const body = PostEdits.parse(req.body); + const photo = await photoFor(req, photoId); + if (photo.status !== "READY") throw badRequest("photo_not_ready"); + try { + return await develop.append(photoId, currentUserId(req), body); + } catch (err) { + if (err instanceof EditRejected) throw badRequest(err.code); + throw err; + } + }); +} diff --git a/apps/api/src/develop/service.ts b/apps/api/src/develop/service.ts new file mode 100644 index 0000000..113c451 --- /dev/null +++ b/apps/api/src/develop/service.ts @@ -0,0 +1,219 @@ +import { type DevelopState, type EditCommand, type EditLogEntry, type PostEdits, getControl } from "@photoreport/contracts"; +import type { Db } from "../db.js"; +import { Prisma, type PhotoEdit } from "../generated/prisma/client.js"; +import type { IngestLogger } from "../ingest/service.js"; +import { photoUrls } from "../library/serialize.js"; +import type { Broadcaster } from "../realtime.js"; +import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.js"; +import type { RenderEngine, Settings } from "./engine.js"; + +/** Edits pause this long before the worker renders new thumbnails (a slider drag sends many). */ +export const RENDER_QUIET_MS = 2000; +const STALE_RUNNING_MS = 5 * 60_000; + +export class EditRejected extends Error { + constructor(readonly code: string) { + super(code); + } +} + +function toEntry(e: PhotoEdit): EditLogEntry { + return { seq: e.seq, opId: e.opId, clientId: e.clientId, command: e.command as EditCommand, userId: e.userId, at: e.createdAt.toISOString() }; +} + +/** Commands are checked against the controls of the pinned engine, so a stale client cannot fill the log with junk. */ +function validate(command: EditCommand): void { + if (command.command !== "develop.set") return; + for (const [id, value] of Object.entries(command.params.values)) { + const control = getControl(id); + if (!control) throw new EditRejected("unknown_control"); + if (value < control.min || value > control.max) throw new EditRejected("value_out_of_range"); + } +} + +/** + * The develop op log. Clients send commands (never pixels); the server orders them per photo, stores them and + * fans them out, so every open window (web or desktop) replays the same sequence with its own engine. The + * worker keeps a settings snapshot, renders edited thumbnails once edits pause, and deliveries render from it. + */ +export class DevelopService { + constructor( + private readonly deps: { db: Db; storage: LocalStorage; signer: UrlSigner; broadcaster: Broadcaster; log: IngestLogger; engine?: RenderEngine | undefined }, + ) {} + + get engine(): RenderEngine | undefined { + return this.deps.engine; + } + + async state(photoId: string, since?: number): Promise { + const photo = await this.deps.db.photo.findUniqueOrThrow({ where: { id: photoId }, select: { developSeq: true, developSnapshot: true, snapshotSeq: true } }); + const useSnapshot = since === undefined || since < photo.snapshotSeq; + const from = useSnapshot ? photo.snapshotSeq : since; + const ops = await this.deps.db.photoEdit.findMany({ where: { photoId, seq: { gt: from } }, orderBy: { seq: "asc" } }); + return { + photoId, + developSeq: photo.developSeq, + snapshotSeq: from, + snapshot: useSnapshot ? ((photo.developSnapshot as Settings | null) ?? null) : null, + ops: ops.map(toEntry), + }; + } + + /** Appends ops in order. A repeated `opId` (a retry) returns the stored entry and is not broadcast again. */ + async append(photoId: string, userId: string, body: PostEdits): Promise<{ developSeq: number; ops: EditLogEntry[] }> { + for (const op of body.ops) validate(op.command); + const { db, broadcaster } = this.deps; + const result = await db.$transaction(async (tx) => { + const [locked] = await tx.$queryRaw<{ develop_seq: number; organization_id: string; event_id: string | null }[]>` + SELECT develop_seq, organization_id, event_id FROM photos WHERE id = ${photoId}::uuid FOR UPDATE`; + if (!locked) throw new EditRejected("photo_not_found"); + let seq = locked.develop_seq; + const existing = new Map( + (await tx.photoEdit.findMany({ where: { photoId, opId: { in: body.ops.map((o) => o.opId) } } })).map((e) => [e.opId, e]), + ); + const out: EditLogEntry[] = []; + const fresh: EditLogEntry[] = []; + for (const op of body.ops) { + const known = existing.get(op.opId); + if (known) { + out.push(toEntry(known)); + continue; + } + seq++; + const row = await tx.photoEdit.create({ + data: { photoId, seq, opId: op.opId, clientId: body.clientId, command: op.command as Prisma.InputJsonValue, userId }, + }); + existing.set(op.opId, row); + const entry = toEntry(row); + out.push(entry); + fresh.push(entry); + } + if (fresh.length) await tx.photo.update({ where: { id: photoId }, data: { developSeq: seq, editedAt: new Date(), renderStatus: "PENDING" } }); + return { organizationId: locked.organization_id, eventId: locked.event_id, developSeq: seq, out, fresh }; + }); + if (result.fresh.length) { + broadcaster.library(result.organizationId, { + type: "photo.edited", + photoId, + eventId: result.eventId, + clientId: body.clientId, + developSeq: result.developSeq, + ops: result.fresh, + }); + } + return { developSeq: result.developSeq, ops: result.out }; + } + + /** + * Settings at the photo's current op-log position (null: never edited, or edited back to defaults), refreshing + * the stored snapshot when ops came after it. Needs the engine. + */ + async settings(photoId: string): Promise<{ settings: Settings | null; seq: number }> { + const { db, engine } = this.deps; + const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId }, select: { developSeq: true, developSnapshot: true, snapshotSeq: true } }); + if (photo.developSeq === 0) return { settings: null, seq: 0 }; + if (photo.snapshotSeq === photo.developSeq) return { settings: (photo.developSnapshot as Settings | null) ?? null, seq: photo.developSeq }; + if (!engine) throw new Error("render worker not configured (RENDER_BIN)"); + const ops = await db.photoEdit.findMany({ where: { photoId, seq: { gt: photo.snapshotSeq, lte: photo.developSeq } }, orderBy: { seq: "asc" } }); + const replayed = await engine.replay((photo.developSnapshot as Settings | null) ?? null, ops.map((o) => o.command)); + if (replayed.skipped.length) this.deps.log.warn({ photoId, skipped: replayed.skipped.map((i) => ops[i]?.seq) }, "develop: commands refused by the engine"); + const settings = replayed.unedited ? null : replayed.settings; + // Only move forward: a concurrent replay may already have stored a later snapshot. + await db.photo.updateMany({ + where: { id: photoId, snapshotSeq: { lt: photo.developSeq } }, + data: { developSnapshot: (settings as Prisma.InputJsonValue | null) ?? Prisma.DbNull, snapshotSeq: photo.developSeq }, + }); + return { settings, seq: photo.developSeq }; + } + + async claimRenders(limit: number, now = new Date()): Promise { + if (limit <= 0) return []; + const quiet = new Date(now.getTime() - RENDER_QUIET_MS); + const rows = await this.deps.db.$queryRaw<{ id: string }[]>` + UPDATE photos SET render_status = 'RUNNING', updated_at = now() + WHERE id IN ( + SELECT id FROM photos WHERE render_status = 'PENDING' AND edited_at <= ${quiet} + ORDER BY edited_at LIMIT ${limit} FOR UPDATE SKIP LOCKED + ) + RETURNING id`; + return rows.map((r) => r.id); + } + + async requeueStale(now = new Date()): Promise { + const r = await this.deps.db.photo.updateMany({ + where: { renderStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } }, + data: { renderStatus: "PENDING" }, + }); + return r.count; + } + + /** Renders the edited thumb and preview of one claimed photo. Never throws. */ + async render(photoId: string): Promise { + const { db, storage, signer, broadcaster, log, engine } = this.deps; + try { + if (!engine) throw new Error("render worker not configured (RENDER_BIN)"); + const { settings, seq } = await this.settings(photoId); + const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId } }); + const renderedSeq = settings ? seq : 0; + if (settings) { + for (const variant of ["preview", "thumb"] as const) { + await engine.render({ + input: storage.resolve(photo.storageKey), + output: storage.resolve(storage.editedKey(photo.organizationId, photo.sha256, seq, variant)), + settings, + maxEdge: VARIANT_SIZE[variant], + quality: variant === "thumb" ? 80 : 88, + }); + } + } + // Edits that arrived while rendering leave the photo pending for the next round. + const updated = await db.photo.update({ + where: { id: photoId }, + data: { renderedSeq, renderStatus: (await db.photo.count({ where: { id: photoId, developSeq: seq } })) ? "DONE" : "PENDING" }, + }); + if (photo.renderedSeq && photo.renderedSeq !== renderedSeq) { + for (const variant of ["preview", "thumb"] as const) await storage.remove(storage.editedKey(photo.organizationId, photo.sha256, photo.renderedSeq, variant)); + } + const urls = photoUrls(updated, signer); + broadcaster.library(photo.organizationId, { type: "photo.rendered", photoId, renderedSeq, urls: { thumb: urls.thumb, preview: urls.preview } }); + log.info({ photoId, seq: renderedSeq }, "develop: edit rendered"); + } catch (err) { + log.warn({ photoId, err: (err as Error).message }, "develop: render failed"); + await db.photo.update({ where: { id: photoId }, data: { renderStatus: "FAILED" } }).catch(() => {}); + } + } +} + +export class RenderWorker { + private inFlight = 0; + private timer: NodeJS.Timeout | undefined; + private stopped = false; + + constructor( + private readonly service: DevelopService, + private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger }, + ) {} + + start(): void { + void this.service.requeueStale(); + const tick = async () => { + try { + for (const id of await this.service.claimRenders(this.opts.concurrency - this.inFlight)) { + this.inFlight++; + void this.service.render(id).finally(() => { + this.inFlight--; + }); + } + } catch (err) { + this.opts.log.warn({ err }, "develop: poll failed"); + } + if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs); + }; + this.timer = setTimeout(tick, 0); + } + + stop(): void { + this.stopped = true; + if (this.timer) clearTimeout(this.timer); + } +} diff --git a/apps/api/src/faces/process.ts b/apps/api/src/faces/process.ts index ba863b5..c23c640 100644 --- a/apps/api/src/faces/process.ts +++ b/apps/api/src/faces/process.ts @@ -1,5 +1,4 @@ -import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; -import { createInterface } from "node:readline"; +import { LeastBusy, LineProcess } from "../lib/line-process.js"; export interface DetectedFace { x0: number; @@ -34,114 +33,40 @@ export type EmbedderName = keyof typeof MODEL_IDS; */ export class FaceProcess implements FaceEngine { readonly model: string; - private child: ChildProcessWithoutNullStreams | undefined; - private ready: Promise | undefined; - private pending = new Map void; reject: (e: Error) => void; timer: NodeJS.Timeout }>(); - private queue: Promise = Promise.resolve(); - private seq = 0; + private readonly proc: LineProcess; - constructor( - private readonly opts: { bin: string; modelsDir: string; embedder: EmbedderName; minScore?: number; timeoutMs?: number }, - ) { + constructor(opts: { bin: string; modelsDir: string; embedder: EmbedderName; minScore?: number; timeoutMs?: number }) { this.model = MODEL_IDS[opts.embedder]; - } - - private start(): Promise { - if (this.ready) return this.ready; - const args = ["--models", this.opts.modelsDir, "--embedder", this.opts.embedder, "--min-score", String(this.opts.minScore ?? 0.6)]; - const child = spawn(this.opts.bin, args, { stdio: ["pipe", "pipe", "pipe"] }); - this.child = child; - let stderr = ""; - child.stderr.on("data", (d: Buffer) => { - stderr = (stderr + d.toString()).slice(-2000); + this.proc = new LineProcess({ + name: "face worker", + bin: opts.bin, + args: ["--models", opts.modelsDir, "--embedder", opts.embedder, "--min-score", String(opts.minScore ?? 0.6)], + timeoutMs: opts.timeoutMs ?? 120_000, }); - this.ready = new Promise((resolve, reject) => { - const lines = createInterface({ input: child.stdout }); - let started = false; - lines.on("line", (line) => { - let msg: { ready?: boolean; id?: string; error?: string } & Partial; - try { - msg = JSON.parse(line); - } catch { - return; - } - if (!started && msg.ready) { - started = true; - resolve(); - return; - } - const waiting = msg.id ? this.pending.get(msg.id) : undefined; - if (!waiting || !msg.id) return; - this.pending.delete(msg.id); - clearTimeout(waiting.timer); - if (msg.error) waiting.reject(new Error(msg.error)); - else waiting.resolve({ width: msg.width ?? 0, height: msg.height ?? 0, faces: msg.faces ?? [] }); - }); - child.on("exit", (code) => { - const err = new Error(`face worker exited (${code}): ${stderr.trim()}`); - if (!started) reject(err); - for (const [, p] of this.pending) { - clearTimeout(p.timer); - p.reject(err); - } - this.pending.clear(); - this.child = undefined; - this.ready = undefined; - }); - child.on("error", (e) => { - if (!started) reject(e); - }); - }); - return this.ready; } - /** Requests are serialised: the Rust side is single-threaded; run several processes for parallelism. */ - analyse(path: string): Promise { - const run = async () => { - await this.start(); - const id = String(++this.seq); - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - this.pending.delete(id); - reject(new Error("face worker timed out")); - this.child?.kill(); - }, this.opts.timeoutMs ?? 120_000); - this.pending.set(id, { resolve, reject, timer }); - this.child?.stdin.write(JSON.stringify({ id, path }) + "\n"); - }); - }; - const result = this.queue.then(run, run); - this.queue = result.catch(() => undefined); - return result; + async analyse(path: string): Promise { + const msg = (await this.proc.request({ path })) as Partial; + return { width: msg.width ?? 0, height: msg.height ?? 0, faces: msg.faces ?? [] }; } - async close(): Promise { - this.child?.stdin.end(); - this.child?.kill(); - this.child = undefined; - this.ready = undefined; + close(): Promise { + return this.proc.close(); } } /** Several face processes behind one engine; each request goes to the least busy one. */ export class FacePool implements FaceEngine { readonly model: string; - private readonly busy: number[]; + private readonly pool: LeastBusy; constructor(private readonly engines: FaceEngine[]) { - if (!engines.length) throw new Error("face pool needs at least one engine"); + this.pool = new LeastBusy(engines); this.model = engines[0]!.model; - this.busy = engines.map(() => 0); } - async analyse(path: string): Promise { - const i = this.busy.indexOf(Math.min(...this.busy)); - this.busy[i]!++; - try { - return await this.engines[i]!.analyse(path); - } finally { - this.busy[i]!--; - } + analyse(path: string): Promise { + return this.pool.use((e) => e.analyse(path)); } async close(): Promise { diff --git a/apps/api/src/lib/line-process.ts b/apps/api/src/lib/line-process.ts new file mode 100644 index 0000000..7ff3a12 --- /dev/null +++ b/apps/api/src/lib/line-process.ts @@ -0,0 +1,112 @@ +import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; +import { createInterface } from "node:readline"; + +/** + * A long-running helper process that speaks JSON lines over stdin/stdout (the Rust workers): it prints + * `{"ready": true, ...}` once, then answers each `{"id": ..., ...}` request with a line carrying the same id. + * Requests are serialised (the helpers are single-threaded; run several for parallelism). The process is + * restarted after a crash; a request that hangs is failed after `timeoutMs` and the process killed. + */ +export class LineProcess { + private child: ChildProcessWithoutNullStreams | undefined; + private ready: Promise> | undefined; + private pending = new Map) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>(); + private queue: Promise = Promise.resolve(); + private seq = 0; + + constructor(private readonly opts: { name: string; bin: string; args?: string[]; timeoutMs?: number }) {} + + /** Starts the process if needed and resolves with its ready line. */ + start(): Promise> { + if (this.ready) return this.ready; + const child = spawn(this.opts.bin, this.opts.args ?? [], { stdio: ["pipe", "pipe", "pipe"] }); + this.child = child; + let stderr = ""; + child.stderr.on("data", (d: Buffer) => { + stderr = (stderr + d.toString()).slice(-2000); + }); + this.ready = new Promise((resolve, reject) => { + const lines = createInterface({ input: child.stdout }); + let started = false; + lines.on("line", (line) => { + let msg: Record; + try { + msg = JSON.parse(line) as Record; + } catch { + return; + } + if (!started && msg.ready) { + started = true; + resolve(msg); + return; + } + const id = typeof msg.id === "string" ? msg.id : undefined; + const waiting = id ? this.pending.get(id) : undefined; + if (!waiting || !id) return; + this.pending.delete(id); + clearTimeout(waiting.timer); + if (typeof msg.error === "string") waiting.reject(new Error(msg.error)); + else waiting.resolve(msg); + }); + child.on("exit", (code) => { + const err = new Error(`${this.opts.name} exited (${code}): ${stderr.trim()}`); + if (!started) reject(err); + for (const [, p] of this.pending) { + clearTimeout(p.timer); + p.reject(err); + } + this.pending.clear(); + this.child = undefined; + this.ready = undefined; + }); + child.on("error", (e) => { + if (!started) reject(e); + }); + }); + return this.ready; + } + + request(payload: Record): Promise> { + const run = async () => { + await this.start(); + const id = String(++this.seq); + return new Promise>((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(id); + reject(new Error(`${this.opts.name} timed out`)); + this.child?.kill(); + }, this.opts.timeoutMs ?? 120_000); + this.pending.set(id, { resolve, reject, timer }); + this.child?.stdin.write(JSON.stringify({ ...payload, id }) + "\n"); + }); + }; + const result = this.queue.then(run, run); + this.queue = result.catch(() => undefined); + return result; + } + + async close(): Promise { + this.child?.stdin.end(); + this.child?.kill(); + this.child = undefined; + this.ready = undefined; + } +} + +/** Picks the least busy of several workers. */ +export class LeastBusy { + private readonly busy: number[]; + constructor(readonly items: T[]) { + if (!items.length) throw new Error("pool needs at least one worker"); + this.busy = items.map(() => 0); + } + async use(fn: (item: T) => Promise): Promise { + const i = this.busy.indexOf(Math.min(...this.busy)); + this.busy[i]!++; + try { + return await fn(this.items[i]!); + } finally { + this.busy[i]!--; + } + } +} diff --git a/apps/api/src/library/photos.ts b/apps/api/src/library/photos.ts index 500e287..c25676a 100644 --- a/apps/api/src/library/photos.ts +++ b/apps/api/src/library/photos.ts @@ -24,7 +24,7 @@ const ListQuery = z.object({ offset: z.coerce.number().int().min(0).default(0), limit: z.coerce.number().int().min(1).max(500).default(200), }); -const FileParams = z.object({ photoId: z.uuid(), variant: z.enum(["thumb", "preview", "original"]) }); +const FileParams = z.object({ photoId: z.uuid(), variant: z.enum(["thumb", "preview", "source", "original"]) }); const FileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(10).max(100) }); const CodeListBody = z.object({ content: z.string().max(500_000) }); @@ -107,9 +107,14 @@ export async function registerPhotoRoutes( const { photoId, variant } = FileParams.parse(req.params); const { exp, sig } = FileQuery.parse(req.query); if (variant === "original" || !signer.verify(photoId, variant as Variant, exp, sig)) throw notFound("file_not_found"); - const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, sha256: true, status: true } }); + const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, sha256: true, status: true, renderedSeq: true } }); if (!photo || photo.status !== "READY") throw notFound("file_not_found"); - const key = storage.derivedKey(photo.organizationId, photo.sha256, variant); + const size = variant === "source" ? "preview" : variant; + let key = storage.derivedKey(photo.organizationId, photo.sha256, size); + if (variant !== "source" && photo.renderedSeq > 0) { + const edited = storage.editedKey(photo.organizationId, photo.sha256, photo.renderedSeq, size); + if (await storage.exists(edited)) key = edited; + } if (!(await storage.exists(key))) throw notFound("file_not_found"); return reply .header("content-type", "image/jpeg") diff --git a/apps/api/src/library/serialize.ts b/apps/api/src/library/serialize.ts index 6678d06..2bf92d9 100644 --- a/apps/api/src/library/serialize.ts +++ b/apps/api/src/library/serialize.ts @@ -26,6 +26,15 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum colorLabel: photo.colorLabel, players: photo.players, uploader: photo.uploader, - urls: { thumb: signer.url(photo.id, "thumb"), preview: signer.url(photo.id, "preview") }, + developSeq: photo.developSeq, + urls: photoUrls(photo, signer), + }; +} + +export function photoUrls(photo: { id: string; renderedSeq: number }, signer: UrlSigner): PhotoSummary["urls"] { + return { + thumb: signer.url(photo.id, "thumb", photo.renderedSeq), + preview: signer.url(photo.id, "preview", photo.renderedSeq), + source: signer.url(photo.id, "source"), }; } diff --git a/apps/api/src/storage/storage.ts b/apps/api/src/storage/storage.ts index 2571827..dfd4557 100644 --- a/apps/api/src/storage/storage.ts +++ b/apps/api/src/storage/storage.ts @@ -3,10 +3,11 @@ import { createReadStream } from "node:fs"; import { copyFile, mkdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; -export type Variant = "original" | "thumb" | "preview"; +/** `source` is the unedited preview (the editor renders on top of it); `thumb`/`preview` show the edit. */ +export type Variant = "original" | "thumb" | "preview" | "source"; /** Long side in pixels for the derived JPEGs. Thumb: grid; preview: loupe and editor. */ -export const VARIANT_SIZE: Record, number> = { thumb: 480, preview: 2048 }; +export const VARIANT_SIZE: Record<"thumb" | "preview", number> = { thumb: 480, preview: 2048 }; /** * Files on local disk, one tree per organization: @@ -29,10 +30,19 @@ export class LocalStorage { return `${orgId}/people/${personId}.jpg`; } - derivedKey(orgId: string, sha256: string, variant: Exclude): string { + derivedKey(orgId: string, sha256: string, variant: "thumb" | "preview"): string { return `${orgId}/derived/${sha256.slice(0, 2)}/${sha256}.${variant}.jpg`; } + /** Thumb/preview of the edit at op-log position `seq`. */ + editedKey(orgId: string, sha256: string, seq: number, variant: "thumb" | "preview"): string { + return `${orgId}/derived/${sha256.slice(0, 2)}/${sha256}.e${seq}.${variant}.jpg`; + } + + async remove(key: string): Promise { + await rm(this.resolve(key), { force: true }); + } + resolve(key: string): string { const full = path.resolve(this.root, key); if (!full.startsWith(this.root + path.sep)) throw new Error(`storage key escapes root: ${key}`); @@ -100,11 +110,14 @@ export class UrlSigner { return `/v1/files/persons/${personId}/reference?exp=${exp}&sig=${this.mac(personId, "reference", exp)}`; } - /** Expiry is rounded up to the next ttl/4 so URLs stay stable (and cacheable) for a while. */ - url(photoId: string, variant: Variant): string { + /** + * Expiry is rounded up to the next ttl/4 so URLs stay stable (and cacheable) for a while. `version` (the + * rendered edit) is not signed: it only makes the URL change when the picture does. + */ + url(photoId: string, variant: Variant, version = 0): string { const step = Math.max(60, Math.floor(this.ttlSec / 4)); const exp = Math.ceil((Math.floor(this.now() / 1000) + this.ttlSec) / step) * step; - return `/v1/files/photos/${photoId}/${variant}?exp=${exp}&sig=${this.mac(photoId, variant, exp)}`; + return `/v1/files/photos/${photoId}/${variant}?exp=${exp}&sig=${this.mac(photoId, variant, exp)}${version ? `&v=${version}` : ""}`; } verify(photoId: string, variant: Variant | "reference", exp: number, sig: string): boolean { diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index c6ee951..d4d612a 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -4,6 +4,8 @@ import { createDb } from "./db.js"; import { closeRenderer } from "./delivery/render.js"; import { SecretBox } from "./delivery/secrets.js"; import { DeliveryService, DeliveryWorker } from "./delivery/service.js"; +import { RenderPool, RenderProcess } from "./develop/engine.js"; +import { DevelopService, RenderWorker } from "./develop/service.js"; import { FacePool, FaceProcess } from "./faces/process.js"; import { FaceService, FaceWorker } from "./faces/service.js"; import { IngestScanner } from "./ingest/scanner.js"; @@ -33,7 +35,15 @@ const scanner = new IngestScanner(ingest, config.INGEST_ROOT, { intervalMs: conf const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined; if (!secrets) log.warn("DELIVERY_SECRET_KEY is not set: deliveries will fail until it is"); -const deliveries = new DeliveryWorker(new DeliveryService({ db, storage, secrets, broadcaster, log }), { +const signer = new UrlSigner(config.JWT_SECRET, config.FILE_URL_TTL_SEC); +const renderEngine = config.RENDER_BIN + ? new RenderPool(Array.from({ length: config.RENDER_PROCESSES }, () => new RenderProcess({ bin: config.RENDER_BIN! }))) + : undefined; +if (!renderEngine) log.warn("RENDER_BIN not set: edited photos get no new thumbnails and cannot be delivered"); +const develop = new DevelopService({ db, storage, signer, broadcaster, log, engine: renderEngine }); +const renders = renderEngine ? new RenderWorker(develop, { concurrency: config.RENDER_PROCESSES, intervalMs: 500, log }) : undefined; + +const deliveries = new DeliveryWorker(new DeliveryService({ db, storage, secrets, broadcaster, log, develop }), { concurrency: config.DELIVERY_CONCURRENCY, intervalMs: 1000, log, @@ -53,6 +63,7 @@ if (!faces) log.warn("FACES_BIN/FACES_MODELS_DIR not set: face analysis is off i scanner.start(); deliveries.start(); faces?.start(); +renders?.start(); log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started"); const shutdown = async (signal: string) => { @@ -60,7 +71,9 @@ const shutdown = async (signal: string) => { scanner.stop(); deliveries.stop(); faces?.stop(); + renders?.stop(); await faceEngine?.close(); + await renderEngine?.close(); await closeRenderer(); await broadcaster.close(); await db.$disconnect(); diff --git a/apps/api/test/develop.test.ts b/apps/api/test/develop.test.ts new file mode 100644 index 0000000..43da29b --- /dev/null +++ b/apps/api/test/develop.test.ts @@ -0,0 +1,160 @@ +import { copyFile, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import sharp from "sharp"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import type { RenderEngine, RenderJob, Settings } from "../src/develop/engine.js"; +import { DevelopService, RENDER_QUIET_MS } from "../src/develop/service.js"; +import { IngestService } from "../src/ingest/service.js"; +import { MemoryBroadcaster } from "../src/realtime.js"; +import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; +import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; + +const quiet = { info: () => {}, warn: () => {} }; + +/** Stands in for workers/render: "settings" are the merged `develop.set` values; render copies the file. */ +class FakeEngine implements RenderEngine { + renders: RenderJob[] = []; + async replay(base: Settings | null, commands: unknown[]) { + let s: Record = { ...((base as Record | null) ?? {}) }; + const skipped: number[] = []; + commands.forEach((c, i) => { + const cmd = c as { command: string; params?: { values?: Record } }; + if (cmd.command === "develop.set") s = { ...s, ...cmd.params!.values }; + else if (cmd.command === "develop.reset") s = {}; + else skipped.push(i); + }); + const unedited = Object.values(s).every((v) => v === 0); + return { settings: s, skipped, unedited }; + } + async render(job: RenderJob) { + this.renders.push(job); + await copyFile(job.input, job.output); + return { width: 600, height: 400 }; + } + async close() {} +} + +const set = (opId: string, values: Record) => ({ opId, command: { command: "develop.set", params: { values } } }); + +describe("develop op log", () => { + let ctx: TestContext; + let dir: string; + let ingestRoot: string; + let ingest: IngestService; + let develop: DevelopService; + let engine: FakeEngine; + const broadcaster = new MemoryBroadcaster(); + + beforeAll(async () => { + dir = await mkdtemp(path.join(tmpdir(), "pr-develop-")); + ingestRoot = path.join(dir, "ingest"); + ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }, broadcaster); + const storage = new LocalStorage(ctx.config.STORAGE_ROOT); + const signer = new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC); + engine = new FakeEngine(); + ingest = new IngestService({ db: ctx.db, storage, signer, broadcaster, ingestRoot, log: quiet }); + develop = new DevelopService({ db: ctx.db, storage, signer, broadcaster, log: quiet, engine }); + }); + afterAll(async () => { + await ctx.app.close(); + await ctx.db.$disconnect(); + await rm(dir, { recursive: true, force: true }); + }); + beforeEach(async () => { + await resetDb(ctx.db); + broadcaster.sent.length = 0; + engine.renders = []; + }); + + let n = 0; + async function setup() { + const { org, user } = await seedUser(ctx.db, "editor@fpa.pt", { org: "fpa", role: "EDITOR" }); + await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); + await ctx.db.ftpAccount.create({ data: { organizationId: org!.id, userId: user.id, login: "cam" } }); + const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: ++n, g: 90, b: 40 } } }).jpeg().toBuffer(); + const file = path.join(ingestRoot, "cam", `IMG_${n}.jpg`); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, data); + const out = await ingest.ingestFile(file); + if (out.status !== "ingested") throw new Error(JSON.stringify(out)); + return { + orgId: org!.id, + photoId: out.photoId, + editor: (await login(ctx.app, "editor@fpa.pt")).body.accessToken, + photographer: (await login(ctx.app, "foto@fpa.pt")).body.accessToken, + }; + } + + const post = (token: string, photoId: string, ops: unknown[], clientId = "web-1") => + ctx.app.inject({ method: "POST", url: `/v1/photos/${photoId}/edits`, headers: bearer(token), payload: { clientId, ops } }); + + it("orders edits per photo, stores a retried op once, and fans them out", async () => { + const { photoId, editor } = await setup(); + const first = await post(editor, photoId, [set("a", { "light.exposure": 0.5 }), set("b", { "effects.clarity": 20 })]); + expect(first.statusCode).toBe(200); + expect(first.json()).toMatchObject({ developSeq: 2, ops: [{ seq: 1, opId: "a" }, { seq: 2, opId: "b" }] }); + // The offline queue sends "b" again together with a new op. + const retry = await post(editor, photoId, [set("b", { "effects.clarity": 20 }), set("c", { "light.exposure": 0.7 })]); + expect(retry.json()).toMatchObject({ developSeq: 3, ops: [{ seq: 2, opId: "b" }, { seq: 3, opId: "c" }] }); + const edited = broadcaster.sent.filter((s) => s.message.type === "photo.edited").map((s) => s.message as { ops: { seq: number }[]; clientId: string }); + expect(edited.map((m) => m.ops.map((o) => o.seq))).toEqual([[1, 2], [3]]); + expect(edited[0]!.clientId).toBe("web-1"); + + const state = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${photoId}/develop`, headers: bearer(editor) })).json(); + expect(state).toMatchObject({ developSeq: 3, snapshotSeq: 0, snapshot: null }); + expect(state.ops).toHaveLength(3); + const since = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${photoId}/develop?since=2`, headers: bearer(editor) })).json(); + expect(since.ops.map((o: { seq: number }) => o.seq)).toEqual([3]); + }); + + it("refuses controls the engine does not have, values out of range, and other photographers", async () => { + const { photoId, editor, photographer } = await setup(); + expect((await post(editor, photoId, [set("x", { "light.nope": 1 })])).json()).toMatchObject({ error: "unknown_control" }); + expect((await post(editor, photoId, [set("x", { "light.exposure": 99 })])).json()).toMatchObject({ error: "value_out_of_range" }); + expect((await post(photographer, photoId, [set("x", { "light.exposure": 1 })])).statusCode).toBe(403); + expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).developSeq).toBe(0); + }); + + it("renders edited thumbnails once edits pause, and keeps the unedited source for the editor", async () => { + const { photoId, editor } = await setup(); + await post(editor, photoId, [set("a", { "light.exposure": 0.5 })]); + expect(await develop.claimRenders(5)).toEqual([]); // still editing + const later = new Date(Date.now() + RENDER_QUIET_MS + 100); + const [claimed] = await develop.claimRenders(5, later); + expect(claimed).toBe(photoId); + await develop.render(photoId); + + const photo = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } }); + expect(photo).toMatchObject({ renderedSeq: 1, snapshotSeq: 1, renderStatus: "DONE", developSnapshot: { "light.exposure": 0.5 } }); + expect(engine.renders.map((r) => [r.maxEdge, r.settings])).toEqual([ + [2048, { "light.exposure": 0.5 }], + [480, { "light.exposure": 0.5 }], + ]); + const rendered = broadcaster.sent.find((s) => s.message.type === "photo.rendered")!.message as { urls: { thumb: string } }; + expect(rendered.urls.thumb).toContain("&v=1"); + expect((await ctx.app.inject({ method: "GET", url: rendered.urls.thumb })).statusCode).toBe(200); + + const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${photo.organizationId}/photos`, headers: bearer(editor) })).json() as { + photos: { developSeq: number; urls: { thumb: string; source: string } }[]; + }; + expect(list.photos[0]).toMatchObject({ developSeq: 1 }); + expect(list.photos[0]!.urls.thumb).toContain("&v=1"); + expect((await ctx.app.inject({ method: "GET", url: list.photos[0]!.urls.source })).statusCode).toBe(200); + + // State now starts from the snapshot. + const state = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${photoId}/develop`, headers: bearer(editor) })).json(); + expect(state).toMatchObject({ developSeq: 1, snapshotSeq: 1, snapshot: { "light.exposure": 0.5 }, ops: [] }); + }); + + it("goes back to the original thumbnails after a reset", async () => { + const { photoId, editor } = await setup(); + await post(editor, photoId, [set("a", { "light.exposure": 0.5 })]); + await develop.render(photoId); + await post(editor, photoId, [{ opId: "r", command: { command: "develop.reset" } }]); + await develop.render(photoId); + const photo = await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } }); + expect(photo).toMatchObject({ renderedSeq: 0, snapshotSeq: 2, developSnapshot: null }); + expect(await develop.settings(photoId)).toEqual({ settings: null, seq: 2 }); + }); +}); diff --git a/apps/api/test/render-process.test.ts b/apps/api/test/render-process.test.ts new file mode 100644 index 0000000..3205233 --- /dev/null +++ b/apps/api/test/render-process.test.ts @@ -0,0 +1,53 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import exifr from "exifr"; +import sharp from "sharp"; +import { afterAll, describe, expect, it } from "vitest"; +import { RenderProcess } from "../src/develop/engine.js"; +import { closeRenderer, renderDelivery } from "../src/delivery/render.js"; + +const BIN = process.env.RENDER_TEST_BIN; + +/** Runs the real Rust render worker (`cargo build --release -p photoreport-render`; RENDER_TEST_BIN=target/release/photoreport-render). */ +describe.skipIf(!BIN)("render worker (real binary)", () => { + const engine = new RenderProcess({ bin: BIN ?? "" }); + afterAll(async () => { + await engine.close(); + await closeRenderer(); + }); + + it("replays commands, and delivers an edited photo upright with its EXIF and our IPTC", async () => { + const replayed = await engine.replay(null, [ + { command: "develop.set", params: { values: { "light.exposure": 1 } } }, + { command: "develop.set", params: { values: { "light.nope": 1 } } }, + { command: "crop.set", params: { rect: { x0: 0, y0: 0, x1: 0.5, y1: 1 }, angle: 0, aspect: null } }, + ]); + expect(replayed.skipped).toEqual([1]); + expect(replayed.unedited).toBe(false); + + const dir = await mkdtemp(path.join(tmpdir(), "pr-render-real-")); + try { + // 600x400 stored, EXIF orientation 6 (rotate 90°): upright it is 400x600. + const original = path.join(dir, "in.jpg"); + const pixels = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: 60, g: 60, b: 60 } } }) + .jpeg() + .withMetadata({ orientation: 6 }) + .withExifMerge({ IFD0: { Make: "Canon", Model: "Canon EOS R1" } }) + .toBuffer(); + await writeFile(original, pixels); + const out = await renderDelivery(original, { title: "Rui Costa (ABC)" }, { longEdge: 4000, quality: 95 }, undefined, { engine, settings: replayed.settings }); + const meta = await sharp(out).metadata(); + // Upright 400x600, cropped to the left half: 200x600. + expect([meta.width, meta.height]).toEqual([200, 600]); + const tags = await exifr.parse(out, { iptc: true, xmp: true }); + expect(tags.Orientation === undefined || tags.Orientation === 1 || tags.Orientation === "Horizontal (normal)").toBe(true); + expect(tags.Model).toBe("Canon EOS R1"); + expect(tags.ObjectName ?? tags.title?.value ?? tags.title).toContain("Rui Costa"); + const { channels } = await sharp(out).stats(); + expect(channels[0]!.mean).toBeGreaterThan(75); // +1 EV brightened the grey (60 before) + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/apps/app/src/App.tsx b/apps/app/src/App.tsx index 1d9850e..48941c3 100644 --- a/apps/app/src/App.tsx +++ b/apps/app/src/App.tsx @@ -2,6 +2,7 @@ import type { ApiClient } from "@photoreport/sdk"; import { BrowserRouter, Navigate, Route, Routes, useLocation } from "react-router"; import { AuthProvider, useAuth } from "./auth.js"; import { t } from "./i18n.js"; +import { DevelopPage } from "./pages/DevelopPage.js"; import { DeliveryPage } from "./pages/DeliveryPage.js"; import { DevicePage } from "./pages/DevicePage.js"; import { LibraryPage } from "./pages/LibraryPage.js"; @@ -22,6 +23,7 @@ function Gate() { } /> }> } /> + } /> } /> } /> } /> diff --git a/apps/app/src/develop/Panels.tsx b/apps/app/src/develop/Panels.tsx new file mode 100644 index 0000000..ed735cf --- /dev/null +++ b/apps/app/src/develop/Panels.tsx @@ -0,0 +1,138 @@ +import { CONTROLS, type ControlInfo, type Module, getControl } from "@photoreport/contracts"; +import { useState } from "react"; +import { t } from "../i18n.js"; + +const BASIC_GROUPS: { key: keyof typeof t.dev.groups; ids: string[] }[] = [ + { key: "wb", ids: ["wb.temp", "wb.tint"] }, + { key: "tone", ids: ["light.exposure", "light.contrast", "light.highlights", "light.shadows", "light.whites", "light.blacks"] }, + { key: "presence", ids: ["effects.texture", "effects.clarity", "effects.dehaze", "color.vibrance", "color.saturation"] }, + { key: "profile", ids: ["profile.amount"] }, +]; + +export function formatValue(c: ControlInfo, v: number): string { + if (!Number.isFinite(v)) return "—"; + if (c.id === "wb.temp") return `${Math.round(v)} K`; + const decimals = c.step < 0.1 ? 2 : c.step < 1 ? 1 : 0; + const s = v.toFixed(decimals); + return c.min < 0 && v > 0 ? `+${s}` : s; +} + +/** Where the track's fill starts: the default (zero for most controls), like Lightroom's centred sliders. */ +function fill(c: ControlInfo, v: number) { + const at = (x: number) => ((x - c.min) / (c.max - c.min)) * 100; + const a = at(Math.min(Math.max(c.default, c.min), c.max)); + const b = at(Math.min(Math.max(v, c.min), c.max)); + return { left: `${Math.min(a, b)}%`, width: `${Math.abs(b - a)}%` }; +} + +export function Slider(props: { + control: ControlInfo; + value: number; + disabled?: boolean; + onChange: (id: string, value: number) => void; + onEnd: () => void; +}) { + const { control: c, value: v } = props; + const label = t.dev.labels[c.id] ?? c.label; + const reset = () => { + props.onChange(c.id, c.default); + props.onEnd(); + }; + // Temperature spans 2000-50000 K: a log scale puts daylight in the middle of the track, as photographers expect. + const log = c.id === "wb.temp"; + const toTrack = (x: number) => (log ? Math.log(x) : x); + const fromTrack = (x: number) => (log ? Math.round(Math.exp(x) / c.step) * c.step : x); + return ( +
+ + +
+ ); +} + +function Section({ title, children, open: initial = true, onReset }: { title: string; children: React.ReactNode; open?: boolean; onReset?: () => void }) { + const [open, setOpen] = useState(initial); + return ( +
+
+ + {onReset && ( + + )} +
+ {open &&
{children}
} +
+ ); +} + +/** Basic plus whichever extra modules the user switched on in their preferences (synced across devices). */ +export function DevelopPanels(props: { + modules: readonly Module[]; + value: (id: string) => number; + disabled?: boolean; + onChange: (id: string, value: number) => void; + onEnd: () => void; + onSet: (values: Record) => void; +}) { + const slider = (id: string) => { + const c = getControl(id); + return c ? : null; + }; + const resetIds = (ids: string[]) => props.onSet(Object.fromEntries(ids.map((id) => [id, getControl(id)?.default ?? 0]))); + const extra = props.modules.filter((m) => m !== "crop" && m !== "basic"); + return ( + <> + {props.modules.includes("basic") && ( +
resetIds(BASIC_GROUPS.flatMap((g) => g.ids))}> + {BASIC_GROUPS.map((g) => ( +
+

{t.dev.groups[g.key]}

+ {g.ids.map(slider)} +
+ ))} +
+ )} + {extra.map((m) => { + const ids = CONTROLS.filter((c) => c.module === m).map((c) => c.id); + if (!ids.length) return null; + return ( +
resetIds(ids)}> + {ids.map(slider)} +
+ ); + })} + + ); +} + +export { Section }; diff --git a/apps/app/src/develop/Viewer.tsx b/apps/app/src/develop/Viewer.tsx new file mode 100644 index 0000000..4604495 --- /dev/null +++ b/apps/app/src/develop/Viewer.tsx @@ -0,0 +1,262 @@ +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; +import type { WorkerReply, WorkerRequest } from "./engine.js"; +import type { Crop } from "./session.js"; + +type Rect = Crop["rect"]; + +/** One render worker for the page; created lazily (absent in tests and very old browsers). */ +let shared: Worker | undefined; +function renderWorker(): Worker | undefined { + if (typeof Worker === "undefined") return undefined; + shared ??= new Worker(new URL("./render.worker.ts", import.meta.url), { type: "module" }); + return shared; +} + +interface ViewerProps { + photoKey: string; + sourceUrl: string; + settings: string; + /** While a slider or the crop frame is moving: fast draft renders, then one full render when it stops. */ + dragging: boolean; + cropping: boolean; + crop: Crop; + /** Width/height of the photo as shot (oriented), for aspect-locked crops. */ + onSourceSize?: (w: number, h: number) => void; + onCrop?: (rect: Rect, final: boolean) => void; + onError?: (message: string) => void; +} + +/** + * The develop loupe: the photo rendered by the engine in a worker, at the size it is shown (device pixels), + * with the crop frame on top while cropping. Renders never queue up: one in flight, the latest settings next. + */ +export function Viewer(props: ViewerProps) { + const { photoKey, sourceUrl, settings, dragging, cropping } = props; + const box = useRef(null); + const canvas = useRef(null); + const [size, setSize] = useState({ w: 0, h: 0 }); + const [opened, setOpened] = useState(null); + const [frame, setFrame] = useState<{ w: number; h: number } | null>(null); + const inFlight = useRef(false); + const next = useRef(null); + const ticket = useRef(0); + const settle = useRef>(undefined); + const callbacks = useRef(props); + callbacks.current = props; + + useLayoutEffect(() => { + const el = box.current; + if (!el) return; + const ro = new ResizeObserver(([entry]) => { + const r = entry!.contentRect; + setSize({ w: Math.round(r.width), h: Math.round(r.height) }); + }); + ro.observe(el); + return () => ro.disconnect(); + }, []); + + const send = useCallback((req: WorkerRequest) => { + const w = renderWorker(); + if (!w) return; + if (inFlight.current) { + next.current = req; + return; + } + inFlight.current = true; + w.postMessage(req); + }, []); + + useEffect(() => { + const w = renderWorker(); + if (!w) return; + const onMessage = (e: MessageEvent) => { + const msg = e.data; + if (msg.type === "opened") { + if (msg.key === photoKey) { + setOpened(msg.key); + callbacks.current.onSourceSize?.(msg.sourceWidth, msg.sourceHeight); + } + return; + } + if (msg.type === "error") { + inFlight.current = false; + callbacks.current.onError?.(msg.message); + return; + } + inFlight.current = false; + const queued = next.current; + next.current = null; + if (queued) send(queued); + if (msg.key !== photoKey || !canvas.current) return; + const c = canvas.current; + if (c.width !== msg.width || c.height !== msg.height) { + c.width = msg.width; + c.height = msg.height; + } + c.getContext("2d")?.putImageData(new ImageData(msg.pixels as Uint8ClampedArray, msg.width, msg.height), 0, 0); + setFrame({ w: msg.width, h: msg.height }); + }; + w.addEventListener("message", onMessage); + setOpened(null); + setFrame(null); + w.postMessage({ type: "open", key: photoKey, url: sourceUrl } satisfies WorkerRequest); + return () => w.removeEventListener("message", onMessage); + }, [photoKey, sourceUrl, send]); + + useEffect(() => { + if (opened !== photoKey || !size.w || !size.h) return; + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const full = { maxW: Math.min(2048, Math.round(size.w * dpr)), maxH: Math.min(2048, Math.round(size.h * dpr)) }; + const request = (draft: boolean): WorkerRequest => ({ + type: "render", + ticket: ++ticket.current, + key: photoKey, + settings, + // Drafts at about half the pixels keep a drag at screen rate on modest laptops. + maxW: draft ? Math.round(full.maxW * 0.6) : full.maxW, + maxH: draft ? Math.round(full.maxH * 0.6) : full.maxH, + draft, + applyCrop: !cropping, + }); + clearTimeout(settle.current); + if (dragging) { + send(request(true)); + settle.current = setTimeout(() => send(request(false)), 250); + } else send(request(false)); + return () => clearTimeout(settle.current); + }, [opened, photoKey, settings, size.w, size.h, dragging, cropping, send]); + + return ( +
+
+ + {cropping && frame && callbacks.current.onCrop?.(r, f)} />} +
+ {!frame &&

…

} +
+ ); +} + +function fitStyle(frame: { w: number; h: number }, box: { w: number; h: number }) { + const pad = 24; + const s = Math.min((box.w - pad * 2) / frame.w, (box.h - pad * 2) / frame.h); + return { width: Math.max(1, Math.floor(frame.w * s)), height: Math.max(1, Math.floor(frame.h * s)) }; +} + +type Handle = "move" | "nw" | "ne" | "sw" | "se" | "n" | "s" | "e" | "w"; + +/** Crop rectangle over the whole (uncropped) frame: drag inside to move, corners and edges to resize. */ +function CropFrame({ crop, onCrop }: { crop: Crop; onCrop: (rect: Rect, final: boolean) => void }) { + const el = useRef(null); + const drag = useRef<{ handle: Handle; x: number; y: number; start: Rect } | null>(null); + const r = crop.rect; + + const onDown = (handle: Handle) => (e: React.PointerEvent) => { + e.preventDefault(); + e.stopPropagation(); + (e.target as Element).setPointerCapture(e.pointerId); + drag.current = { handle, x: e.clientX, y: e.clientY, start: { ...r } }; + }; + const onMove = (e: React.PointerEvent) => { + const d = drag.current; + const box = el.current?.getBoundingClientRect(); + if (!d || !box) return; + onCrop(moveRect(d.start, d.handle, (e.clientX - d.x) / box.width, (e.clientY - d.y) / box.height, crop.aspect ? (crop.aspect[0] / crop.aspect[1]) * (box.height / box.width) : null), false); + }; + const onUp = (e: React.PointerEvent) => { + if (!drag.current) return; + drag.current = null; + (e.target as Element).releasePointerCapture?.(e.pointerId); + onCrop(r, true); + }; + + const pct = (v: number) => `${v * 100}%`; + const corner = "absolute h-3 w-3 border-2 border-white bg-black/40"; + return ( +
+ {/* Shade outside the crop. */} +
+
+
+
+
+ {/* Rule of thirds. */} +
+ {Array.from({ length: 9 }, (_, i) => ( + + ))} +
+ + + + + {!crop.aspect && ( + <> + + + + + + )} +
+
+ ); +} + +const MIN = 0.04; +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); + +/** + * The crop after dragging `handle` by (dx, dy) (fractions of the frame). `ratio` is the locked width/height in + * frame fractions (null: free). Exported for tests. + */ +export function moveRect(start: Rect, handle: Handle, dx: number, dy: number, ratio: number | null): Rect { + let { x0, y0, x1, y1 } = start; + if (handle === "move") { + const w = x1 - x0; + const h = y1 - y0; + x0 = Math.min(1 - w, Math.max(0, x0 + dx)); + y0 = Math.min(1 - h, Math.max(0, y0 + dy)); + return { x0, y0, x1: x0 + w, y1: y0 + h }; + } + if (handle.includes("w")) x0 = Math.min(x1 - MIN, clamp01(x0 + dx)); + if (handle.includes("e")) x1 = Math.max(x0 + MIN, clamp01(x1 + dx)); + if (handle.includes("n")) y0 = Math.min(y1 - MIN, clamp01(y0 + dy)); + if (handle.includes("s")) y1 = Math.max(y0 + MIN, clamp01(y1 + dy)); + if (ratio && handle.length === 2) { + // Keep the aspect: the height follows the width, anchored at the opposite corner, shrinking if it would leave the frame. + let w = x1 - x0; + let h = w / ratio; + const room = handle.includes("n") ? y1 : 1 - y0; + if (h > room) { + h = room; + w = h * ratio; + if (handle.includes("w")) x0 = x1 - w; + else x1 = x0 + w; + } + if (handle.includes("n")) y0 = y1 - h; + else y1 = y0 + h; + } + return { x0, y0, x1, y1 }; +} + +/** The largest rect of `ratio` (width/height in frame fractions) centred on `r`, inside the frame. */ +export function fitAspect(r: Rect, ratio: number): Rect { + const cx = (r.x0 + r.x1) / 2; + const cy = (r.y0 + r.y1) / 2; + let w = r.x1 - r.x0; + let h = w / ratio; + if (h > r.y1 - r.y0) { + h = r.y1 - r.y0; + w = h * ratio; + } + const x0 = Math.min(1 - w, Math.max(0, cx - w / 2)); + const y0 = Math.min(1 - h, Math.max(0, cy - h / 2)); + return { x0, y0, x1: x0 + w, y1: y0 + h }; +} diff --git a/apps/app/src/develop/engine.ts b/apps/app/src/develop/engine.ts new file mode 100644 index 0000000..2bc34f1 --- /dev/null +++ b/apps/app/src/develop/engine.ts @@ -0,0 +1,49 @@ +/** + * The develop engine in the browser: `engine/wasm` built by `infra/engine/build-wasm.sh` into `public/engine/`. + * It is loaded at run time (not bundled), so the app builds and type-checks without the Rust toolchain. + */ +export interface WasmPhoto { + readonly sourceWidth: number; + readonly sourceHeight: number; + readonly width: number; + readonly height: number; + render(settings: string, maxW: number, maxH: number, draft: boolean, applyCrop: boolean): void; + pixels(): Uint8Array; + free(): void; +} + +export interface EngineModule { + default(init?: { module_or_path: string }): Promise; + controls(): string; + defaultSettings(): string; + apply(settings: string, command: string): string; + value(settings: string, id: string): number; + isUnedited(settings: string): boolean; + Photo: new (bytes: Uint8Array, maxEdge: number) => WasmPhoto; +} + +const BASE = `${import.meta.env.BASE_URL ?? "/"}engine/`; + +let loading: Promise | undefined; + +export function loadEngine(): Promise { + loading ??= (async () => { + const mod = (await import(/* @vite-ignore */ `${BASE}photoreport_engine_wasm.js`)) as EngineModule; + await mod.default({ module_or_path: `${BASE}photoreport_engine_wasm_bg.wasm` }); + return mod; + })(); + loading.catch(() => { + loading = undefined; + }); + return loading; +} + +/** Messages to and from `render.worker.ts`. */ +export type WorkerRequest = + | { type: "open"; key: string; url: string } + | { type: "render"; ticket: number; key: string; settings: string; maxW: number; maxH: number; draft: boolean; applyCrop: boolean }; + +export type WorkerReply = + | { type: "opened"; key: string; sourceWidth: number; sourceHeight: number } + | { type: "frame"; ticket: number; key: string; width: number; height: number; pixels: Uint8ClampedArray } + | { type: "error"; key: string; ticket?: number; message: string }; diff --git a/apps/app/src/develop/render.worker.ts b/apps/app/src/develop/render.worker.ts new file mode 100644 index 0000000..85865ac --- /dev/null +++ b/apps/app/src/develop/render.worker.ts @@ -0,0 +1,47 @@ +/// +import { loadEngine, type WasmPhoto, type WorkerReply, type WorkerRequest } from "./engine.js"; + +/** + * Decodes and renders off the main thread. Holds one photo (the one being edited); the page sends settings and + * gets pixels back. Requests are handled in order; the page keeps at most one render in flight. + */ +let current: { key: string; photo: WasmPhoto } | undefined; +const opening = new Map>(); + +const post = (msg: WorkerReply, transfer: Transferable[] = []) => (self as unknown as DedicatedWorkerGlobalScope).postMessage(msg, transfer); + +async function open(key: string, url: string): Promise { + if (current?.key === key) return current.photo; + let p = opening.get(key); + if (!p) { + p = (async () => { + const [engine, res] = await Promise.all([loadEngine(), fetch(url)]); + if (!res.ok) throw new Error(`photo download failed (${res.status})`); + const photo = new engine.Photo(new Uint8Array(await res.arrayBuffer()), 2048); + current?.photo.free(); + current = { key, photo }; + return photo; + })(); + opening.set(key, p); + p.finally(() => opening.delete(key)).catch(() => {}); + } + return p; +} + +self.onmessage = async (e: MessageEvent) => { + const msg = e.data; + try { + if (msg.type === "open") { + const photo = await open(msg.key, msg.url); + post({ type: "opened", key: msg.key, sourceWidth: photo.sourceWidth, sourceHeight: photo.sourceHeight }); + return; + } + const photo = current?.key === msg.key ? current.photo : await opening.get(msg.key); + if (!photo) throw new Error("photo not open"); + photo.render(msg.settings, msg.maxW, msg.maxH, msg.draft, msg.applyCrop); + const pixels = new Uint8ClampedArray(photo.pixels().buffer); + post({ type: "frame", ticket: msg.ticket, key: msg.key, width: photo.width, height: photo.height, pixels }, [pixels.buffer]); + } catch (err) { + post({ type: "error", key: msg.key, ...(msg.type === "render" && { ticket: msg.ticket }), message: err instanceof Error ? err.message : String(err) }); + } +}; diff --git a/apps/app/src/develop/session.test.ts b/apps/app/src/develop/session.test.ts new file mode 100644 index 0000000..56a682e --- /dev/null +++ b/apps/app/src/develop/session.test.ts @@ -0,0 +1,135 @@ +import type { DevelopState, EditCommand, EditLogEntry, PostEdits } from "@photoreport/contracts"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { DevelopSession, type OutboxStore, type PendingOp, type SettingsEngine } from "./session.js"; + +/** Settings as a flat map of control values; enough to check ordering, undo and sync. */ +const engine: SettingsEngine = { + defaultSettings: () => "{}", + apply(settings, command) { + const s = JSON.parse(settings) as Record; + const c = JSON.parse(command) as EditCommand; + if (c.command === "develop.set") return JSON.stringify({ ...s, ...c.params.values }); + if (c.command === "develop.reset") return "{}"; + if (c.command === "develop.merge") return JSON.stringify(c.params.partial); + return JSON.stringify({ ...s, crop: c.params }); + }, + value: (settings, id) => ((JSON.parse(settings) as Record)[id] ?? 0), +}; + +/** An in-memory server: one op log, every accepted op fanned out to the other sessions. */ +class FakeServer { + log: EditLogEntry[] = []; + down = false; + sessions: DevelopSession[] = []; + async developState(_photoId: string, since?: number): Promise { + const from = since ?? 0; + return { photoId: "p", developSeq: this.log.length, snapshotSeq: from, snapshot: null, ops: this.log.filter((o) => o.seq > from) }; + } + async postEdits(_photoId: string, body: PostEdits) { + if (this.down) throw Object.assign(new Error("offline"), { status: 0 }); + const out: EditLogEntry[] = []; + const fresh: EditLogEntry[] = []; + for (const op of body.ops) { + const known = this.log.find((o) => o.opId === op.opId); + if (known) { + out.push(known); + continue; + } + const entry = { seq: this.log.length + 1, opId: op.opId, clientId: body.clientId, command: op.command, userId: null, at: "" }; + this.log.push(entry); + out.push(entry); + fresh.push(entry); + } + for (const s of this.sessions) void s.remote({ clientId: body.clientId, ops: fresh }); + return { developSeq: this.log.length, ops: out }; + } +} + +const set = (values: Record): EditCommand => ({ command: "develop.set", params: { values } }); + +describe("DevelopSession", () => { + let server: FakeServer; + const open = async (clientId: string, outbox?: OutboxStore) => { + const s = new DevelopSession("p", { engine, api: server, clientId, outbox }); + server.sessions.push(s); + await s.load(); + return s; + }; + + beforeEach(() => { + vi.useFakeTimers(); + server = new FakeServer(); + }); + afterEach(() => vi.useRealTimers()); + + it("shows edits at once and sends a drag as few ops with one undo step", async () => { + const web = await open("web"); + web.edit(set({ "light.exposure": 0.1 }), "light.exposure"); + web.edit(set({ "light.exposure": 0.2 }), "light.exposure"); + expect(web.value("light.exposure")).toBe(0.2); + await vi.advanceTimersByTimeAsync(200); + web.edit(set({ "light.exposure": 0.6 }), "light.exposure"); + web.endGesture(); + await vi.advanceTimersByTimeAsync(200); + expect(server.log.map((o) => (o.command as { params: { values: Record } }).params.values["light.exposure"])).toEqual([0.2, 0.6]); + expect(web.seq).toBe(2); + expect(web.hasPending).toBe(false); + + web.undo(); + expect(web.value("light.exposure")).toBe(0); + web.redo(); + expect(web.value("light.exposure")).toBe(0.6); + }); + + it("keeps two windows in step, last writer winning per control", async () => { + const web = await open("web"); + const desktop = await open("desktop"); + web.edit(set({ "light.exposure": 1 })); + desktop.edit(set({ "effects.clarity": 30 })); + await vi.advanceTimersByTimeAsync(300); + desktop.edit(set({ "light.exposure": -0.5 })); + await vi.advanceTimersByTimeAsync(300); + for (const s of [web, desktop]) { + expect(s.value("light.exposure")).toBe(-0.5); + expect(s.value("effects.clarity")).toBe(30); + expect(s.seq).toBe(3); + } + }); + + it("queues edits while offline, survives a reload, and stores a retried op once", async () => { + const saved = new Map(); + const outbox: OutboxStore = { load: (id) => saved.get(id) ?? [], save: (id, ops) => void saved.set(id, ops) }; + server.down = true; + const web = await open("web", outbox); + web.edit(set({ "light.exposure": 0.7 })); + await vi.advanceTimersByTimeAsync(300); + expect(web.offline).toBe(true); + expect(saved.get("p")).toHaveLength(1); + web.close(); + + server.down = false; + const again = await open("web", outbox); + expect(again.value("light.exposure")).toBe(0.7); + await vi.advanceTimersByTimeAsync(50); + expect(server.log).toHaveLength(1); + expect(saved.get("p")).toEqual([]); + await again.flush(); + expect(server.log).toHaveLength(1); + }); + + it("catches up when it missed ops", async () => { + const web = await open("web"); + server.sessions = []; // messages to web are lost + const other = new DevelopSession("p", { engine, api: server, clientId: "other" }); + await other.load(); + other.edit(set({ "light.contrast": 10 })); + other.edit(set({ "light.contrast": 20 })); + await vi.advanceTimersByTimeAsync(300); + server.sessions = [web]; + other.edit(set({ "light.whites": 5 })); + await vi.advanceTimersByTimeAsync(300); + expect(web.value("light.contrast")).toBe(20); + expect(web.value("light.whites")).toBe(5); + expect(web.seq).toBe(3); + }); +}); diff --git a/apps/app/src/develop/session.ts b/apps/app/src/develop/session.ts new file mode 100644 index 0000000..0a86a90 --- /dev/null +++ b/apps/app/src/develop/session.ts @@ -0,0 +1,335 @@ +import type { DevelopState, EditCommand, EditLogEntry, PostEdits } from "@photoreport/contracts"; + +/** What the session needs from the engine (the WASM module in the app; a fake in tests). */ +export interface SettingsEngine { + defaultSettings(): string; + apply(settings: string, command: string): string; + value(settings: string, id: string): number; +} + +/** What the session needs from the API. */ +export interface DevelopApi { + developState(photoId: string, since?: number): Promise; + postEdits(photoId: string, body: PostEdits): Promise<{ developSeq: number; ops: EditLogEntry[] }>; +} + +/** Durable outbox, so edits made offline survive a reload (localStorage in the app). */ +export interface OutboxStore { + load(photoId: string): PendingOp[]; + save(photoId: string, ops: PendingOp[]): void; +} + +export interface PendingOp { + opId: string; + command: EditCommand; + /** Edits of the same control during one drag replace each other instead of piling up. */ + coalesce?: string | undefined; + sent?: boolean; +} + +interface Step { + undo: EditCommand; + redo: EditCommand; +} + +const SEND_DELAY_MS = 120; +const RETRY_MAX_MS = 30_000; + +let counter = 0; +const newOpId = () => `${Date.now().toString(36)}-${(++counter).toString(36)}-${Math.random().toString(36).slice(2, 8)}`; + +/** + * One photo being developed. Settings are the server's op log replayed by the local engine (`base`, up to + * `confirmedSeq`) plus this window's edits not yet acknowledged (`pending`), so edits show instantly and remote + * edits slot in underneath. Last writer wins per control, as on the server. Edits are sent in small batches; + * unsent ones stay in the outbox (and on disk) and are retried until accepted; a retried op is stored once. + */ +export class DevelopSession { + private base = ""; + private confirmedSeq = 0; + private pending: PendingOp[] = []; + private undoStack: Step[] = []; + private redoStack: Step[] = []; + private gesture: string | undefined; + private timer: ReturnType | undefined; + private sending = false; + private retryMs = 1000; + private listeners = new Set<() => void>(); + private cachedSettings: string | undefined; + private closed = false; + /** Set while the last send failed (offline): the UI shows it. */ + offline = false; + loaded = false; + + constructor( + readonly photoId: string, + private readonly deps: { engine: SettingsEngine; api: DevelopApi; clientId: string; outbox?: OutboxStore | undefined }, + ) {} + + async load(): Promise { + const state = await this.deps.api.developState(this.photoId); + let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings(); + for (const op of state.ops) base = this.safeApply(base, op.command); + this.base = base; + this.confirmedSeq = state.developSeq; + this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? []; + this.loaded = true; + this.changed(); + if (this.pending.length) this.schedule(0); + } + + close(): void { + this.closed = true; + clearTimeout(this.timer); + this.listeners.clear(); + } + + subscribe(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + /** Current settings JSON: confirmed edits plus this window's pending ones. */ + get settings(): string { + this.cachedSettings ??= this.pending.reduce((s, op) => this.safeApply(s, op.command), this.base); + return this.cachedSettings; + } + + get seq(): number { + return this.confirmedSeq; + } + + get hasPending(): boolean { + return this.pending.length > 0; + } + + value(id: string): number { + return this.deps.engine.value(this.settings, id); + } + + get canUndo(): boolean { + return this.undoStack.length > 0; + } + + get canRedo(): boolean { + return this.redoStack.length > 0; + } + + /** + * Applies a command locally and queues it. `gesture` groups a drag: while the same gesture continues, the + * queued command and the undo step are updated in place (one undo step per drag, few ops on the wire). + */ + edit(command: EditCommand, gesture?: string): void { + const before = this.settings; + const last = this.pending.at(-1); + // Not yet sent: the drag's latest position replaces the queued one. Already sent: a new op follows it, + // so other windows see the drag live (one op per send interval). + if (gesture !== undefined && last && !last.sent && last.coalesce === gesture) last.command = merge(last.command, command); + else this.pending.push({ opId: newOpId(), command, coalesce: gesture }); + const top = this.undoStack.at(-1); + if (gesture !== undefined && this.gesture === gesture && top) top.redo = merge(top.redo, command); + else { + const step = this.undoStep(before, command); + if (step) this.undoStack.push(step); + } + this.redoStack = []; + this.gesture = gesture; + this.changed(); + this.persist(); + this.schedule(SEND_DELAY_MS); + } + + /** Ends a drag: the next edit starts a new op and a new undo step. */ + endGesture(): void { + this.gesture = undefined; + const last = this.pending.at(-1); + if (last) last.coalesce = undefined; + this.schedule(0); + } + + undo(): void { + this.gesture = undefined; + const step = this.undoStack.pop(); + if (!step) return; + this.pending.push({ opId: newOpId(), command: step.undo }); + this.redoStack.push(step); + this.changed(); + this.persist(); + this.schedule(0); + } + + redo(): void { + const step = this.redoStack.pop(); + if (!step) return; + this.pending.push({ opId: newOpId(), command: step.redo }); + this.undoStack.push(step); + this.changed(); + this.persist(); + this.schedule(0); + } + + /** A `photo.edited` message from the server. Our own echo is skipped (the send's answer covers it). */ + async remote(message: { clientId: string; ops: EditLogEntry[] }): Promise { + if (message.clientId === this.deps.clientId) return; + await this.accept(message.ops); + } + + private async accept(ops: EditLogEntry[]): Promise { + for (const op of ops) { + if (op.seq <= this.confirmedSeq) { + this.dropPending(op.opId); + continue; + } + if (op.seq !== this.confirmedSeq + 1) { + await this.catchUp(); + return; + } + this.base = this.safeApply(this.base, op.command); + this.confirmedSeq = op.seq; + this.dropPending(op.opId); + } + this.changed(); + } + + /** Missed some ops (reconnect, a message lost): fetch everything after what we have, in order. */ + async catchUp(): Promise { + const state = await this.deps.api.developState(this.photoId, this.confirmedSeq); + if (state.snapshot) { + // The server answered with a snapshot (we were too far behind): start over from it. + this.base = JSON.stringify(state.snapshot); + this.confirmedSeq = state.snapshotSeq; + } + for (const op of state.ops) { + if (op.seq !== this.confirmedSeq + 1) continue; + this.base = this.safeApply(this.base, op.command); + this.confirmedSeq = op.seq; + this.dropPending(op.opId); + } + this.changed(); + } + + /** Sends what is queued now (also used before leaving the photo). */ + async flush(): Promise { + clearTimeout(this.timer); + if (this.sending || this.closed) return; + const batch = this.pending.filter((p) => !p.sent).slice(0, 200); + if (!batch.length) return; + this.sending = true; + for (const op of batch) op.sent = true; + try { + const res = await this.deps.api.postEdits(this.photoId, { clientId: this.deps.clientId, ops: batch.map((p) => ({ opId: p.opId, command: p.command })) }); + this.offline = false; + this.retryMs = 1000; + await this.accept(res.ops); + this.persist(); + } catch (err) { + for (const op of batch) op.sent = false; + const status = (err as { status?: number }).status; + if (status && status >= 400 && status < 500 && status !== 401 && status !== 408 && status !== 429) { + // Refused for good (unknown control, no permission): drop it, the server state stands. + for (const op of batch) this.dropPending(op.opId); + this.persist(); + this.changed(); + } else { + this.offline = true; + this.changed(); + this.schedule(this.retryMs); + this.retryMs = Math.min(this.retryMs * 2, RETRY_MAX_MS); + } + } finally { + this.sending = false; + } + if (!this.offline && this.pending.some((p) => !p.sent)) this.schedule(SEND_DELAY_MS); + } + + private schedule(ms: number): void { + if (this.closed) return; + clearTimeout(this.timer); + this.timer = setTimeout(() => void this.flush(), ms); + } + + private dropPending(opId: string): void { + const i = this.pending.findIndex((p) => p.opId === opId); + if (i >= 0) this.pending.splice(i, 1); + } + + private persist(): void { + this.deps.outbox?.save( + this.photoId, + this.pending.map(({ opId, command }) => ({ opId, command })), + ); + } + + private changed(): void { + this.cachedSettings = undefined; + for (const fn of this.listeners) fn(); + } + + private safeApply(settings: string, command: EditCommand): string { + try { + return this.deps.engine.apply(settings, JSON.stringify(command)); + } catch { + return settings; // a command this engine does not know (newer client): skipped, like the server + } + } + + /** The command that puts back what `command` is about to change. */ + private undoStep(before: string, command: EditCommand): Step | undefined { + switch (command.command) { + case "develop.set": { + const values: Record = {}; + for (const id of Object.keys(command.params.values)) values[id] = this.deps.engine.value(before, id); + return { undo: { command: "develop.set", params: { values } }, redo: command }; + } + case "crop.set": { + const crop = cropOf(before); + return { undo: { command: "crop.set", params: crop }, redo: command }; + } + case "develop.reset": + case "develop.merge": + return { undo: { command: "develop.merge", params: { partial: JSON.parse(before) as Record } }, redo: command }; + } + } +} + +/** Two commands of one gesture: values merge, anything else is replaced by the newer one. */ +function merge(a: EditCommand, b: EditCommand): EditCommand { + if (a.command === "develop.set" && b.command === "develop.set") return { command: "develop.set", params: { values: { ...a.params.values, ...b.params.values } } }; + return b; +} + +export interface Crop { + rect: { x0: number; y0: number; x1: number; y1: number }; + angle: number; + aspect: [number, number] | null; +} + +/** The crop part of a settings document (LightCraft JSON). */ +export function cropOf(settings: string): Crop { + const s = JSON.parse(settings) as { crop?: { aspect?: [number, number] | null; geometry?: { angle?: number; rect?: Crop["rect"] } } }; + return { + rect: s.crop?.geometry?.rect ?? { x0: 0, y0: 0, x1: 1, y1: 1 }, + angle: s.crop?.geometry?.angle ?? 0, + aspect: s.crop?.aspect ?? null, + }; +} + +/** localStorage-backed outbox (per photo); quietly does nothing where storage is unavailable. */ +export const localOutbox: OutboxStore = { + load(photoId) { + try { + const raw = localStorage.getItem(`pr:outbox:${photoId}`); + return raw ? (JSON.parse(raw) as PendingOp[]) : []; + } catch { + return []; + } + }, + save(photoId, ops) { + try { + if (ops.length) localStorage.setItem(`pr:outbox:${photoId}`, JSON.stringify(ops)); + else localStorage.removeItem(`pr:outbox:${photoId}`); + } catch { + // private mode or full: the edits still go out while the page is open + } + }, +}; diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 167ae62..eddd496 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -39,7 +39,7 @@ export const t = { noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.", filter: "Filtro", filters: { all: "Todas", PICK: "Escolhidas", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas", stars: "★ 3+", noPlayers: "Sem jogador" }, - shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · Enter lupa · Esc grelha", + shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · Enter lupa · Esc grelha · D revelar", selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`), ofTotal: (n: number, total: number) => `${n} de ${total}`, players: "Jogadores", @@ -155,6 +155,49 @@ export const t = { PHOTOGRAPHER: "Fotógrafo", CLIENT: "Cliente", }, + dev: { + loading: "A abrir o motor de revelação…", + engineMissing: "O motor de revelação não está disponível neste servidor (falta compilar engine/wasm).", + noPhoto: "Escolhe uma foto na biblioteca (ou aqui em baixo) para revelar.", + reset: "Repor", + resetAll: "Repor tudo", + undo: "Anular", + redo: "Refazer", + before: "Antes", + after: "Depois", + offline: "Sem ligação: as alterações ficam guardadas e seguem quando voltar", + saving: "A guardar…", + saved: "Guardado", + crop: "Recortar", + cropDone: "Concluir", + aspect: "Proporção", + aspectFree: "Livre", + aspectOriginal: "Original", + straighten: "Endireitar", + copy: "Copiar ajustes", + paste: "Colar ajustes", + pasted: (n: number) => `Ajustes colados em ${n} ${n === 1 ? "foto" : "fotos"}`, + noAccess: "Só podes revelar fotos que enviaste.", + shortcuts: "← → foto · \\ antes/depois · R recortar · Ctrl+Z anular · Ctrl+Shift+Z refazer · duplo clique num cursor repõe", + groups: { wb: "Equilíbrio de brancos", tone: "Tom", presence: "Presença", profile: "Perfil" }, + labels: { + "profile.amount": "Intensidade", + "wb.temp": "Temperatura", + "wb.tint": "Matiz", + "light.exposure": "Exposição", + "light.contrast": "Contraste", + "light.highlights": "Realces", + "light.shadows": "Sombras", + "light.whites": "Brancos", + "light.blacks": "Pretos", + "effects.texture": "Textura", + "effects.clarity": "Claridade", + "effects.dehaze": "Remover névoa", + "color.vibrance": "Vivacidade", + "color.saturation": "Saturação", + "crop.angle": "Ângulo", + } as Record, + }, modules: { crop: "Recorte", basic: "Básico", diff --git a/apps/app/src/library/store.test.ts b/apps/app/src/library/store.test.ts index 61a55d9..e7defb2 100644 --- a/apps/app/src/library/store.test.ts +++ b/apps/app/src/library/store.test.ts @@ -21,7 +21,8 @@ const photo = (id: string, capturedAt: string, extra: Partial = {} colorLabel: "NONE", players: [], uploader: null, - urls: { thumb: "", preview: "" }, + developSeq: 0, + urls: { thumb: "", preview: "", source: "" }, ...extra, }); diff --git a/apps/app/src/library/store.ts b/apps/app/src/library/store.ts index 2a3dabd..3f2e4f9 100644 --- a/apps/app/src/library/store.ts +++ b/apps/app/src/library/store.ts @@ -58,6 +58,8 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr return { ...state, photos: [...state.photos, m.photo].sort(byCapture) }; } if (m.type === "photo.updated") return libraryReducer(state, { type: "patch", ids: m.ids, patch: m.patch }); + if (m.type === "photo.edited") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)) }; + if (m.type === "photo.rendered") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)) }; return state; } case "patch": { diff --git a/apps/app/src/pages/DevelopPage.tsx b/apps/app/src/pages/DevelopPage.tsx new file mode 100644 index 0000000..dc8a700 --- /dev/null +++ b/apps/app/src/pages/DevelopPage.tsx @@ -0,0 +1,351 @@ +import { CONTROLS, DEFAULT_MODULES, type EditCommand, type LibraryMessage, type PhotoSummary } from "@photoreport/contracts"; +import { hasRole } from "@photoreport/sdk"; +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; +import { useNavigate, useParams } from "react-router"; +import { useAuth } from "../auth.js"; +import { type EngineModule, loadEngine } from "../develop/engine.js"; +import { DevelopPanels, Section, Slider } from "../develop/Panels.js"; +import { cropOf, DevelopSession, localOutbox } from "../develop/session.js"; +import { fitAspect, Viewer } from "../develop/Viewer.js"; +import { t } from "../i18n.js"; +import { useLibraryLive } from "../library/realtime.js"; +import { prefs } from "../platform.js"; + +/** One id per window: the server tags our edits with it so this window skips its own echo. */ +const CLIENT_ID = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `w-${Date.now()}-${Math.random()}`; + +const ASPECTS: { label: string; value: [number, number] | "original" | null }[] = [ + { label: t.dev.aspectFree, value: null }, + { label: t.dev.aspectOriginal, value: "original" }, + { label: "1:1", value: [1, 1] }, + { label: "3:2", value: [3, 2] }, + { label: "2:3", value: [2, 3] }, + { label: "4:3", value: [4, 3] }, + { label: "4:5", value: [4, 5] }, + { label: "16:9", value: [16, 9] }, +]; + +const CLIPBOARD = "develop.clipboard"; + +/** Controls a "copy settings" carries: everything numeric except the crop, which belongs to each photo. */ +export function copyableValues(value: (id: string) => number): Record { + const out: Record = {}; + for (const c of CONTROLS) { + if (c.module === "crop") continue; + const v = value(c.id); + if (Number.isFinite(v) && v !== c.default) out[c.id] = v; + } + return out; +} + +/** A reset of everything a paste carries, plus the pasted values. */ +export function pasteCommand(values: Record): EditCommand { + const all: Record = {}; + for (const c of CONTROLS) if (c.module !== "crop") all[c.id] = c.default; + return { command: "develop.set", params: { values: { ...all, ...values } } }; +} + +const isTyping = (target: EventTarget | null) => + target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName) && (target as HTMLInputElement).type !== "range"); + +/** Develop module ("Revelar"): the photo in the middle, panels on the right, the event's photos below. */ +export function DevelopPage() { + const { api, organization, role, me } = useAuth(); + const orgId = organization?.id ?? ""; + const { photoId } = useParams(); + const navigate = useNavigate(); + const [photos, setPhotos] = useState([]); + const [engine, setEngine] = useState("loading"); + const [session, setSession] = useState(null); + const [dragging, setDragging] = useState(false); + const [before, setBefore] = useState(false); + const [cropping, setCropping] = useState(false); + const [sourceSize, setSourceSize] = useState<{ w: number; h: number } | null>(null); + const [note, setNote] = useState(null); + const strip = useRef(null); + const modules = me?.preferences.editorModules ?? DEFAULT_MODULES; + + useEffect(() => { + loadEngine().then(setEngine, () => setEngine("missing")); + }, []); + + // The event (or inbox) the library has open. + useEffect(() => { + if (!orgId) return; + const scope = prefs.get(`scope:${orgId}`) ?? undefined; + api.listPhotos(orgId, { ...(scope && { event: scope }), limit: 500 }).then( + (r) => setPhotos(r.photos.filter((p) => p.status === "READY")), + () => setPhotos([]), + ); + }, [api, orgId]); + + const current = photos.find((p) => p.id === photoId) ?? null; + useEffect(() => { + if (!photoId && photos[0]) navigate(`/develop/${photos[0].id}`, { replace: true }); + }, [photoId, photos, navigate]); + + const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id); + + useEffect(() => { + if (!current || typeof engine !== "object") return; + const s = new DevelopSession(current.id, { engine, api, clientId: CLIENT_ID, outbox: localOutbox }); + setSession(s); + setSourceSize(null); + setCropping(false); + s.load().catch(() => setNote(t.unexpectedError)); + return () => { + void s.flush().finally(() => s.close()); + }; + }, [current?.id, engine, api]); // eslint-disable-line react-hooks/exhaustive-deps + + const version = useSyncExternalStore( + useCallback((fn: () => void) => session?.subscribe(fn) ?? (() => {}), [session]), + () => (session ? [session.loaded, session.seq, session.offline, session.hasPending, session.canUndo, session.canRedo, session.settings].join("|") : ""), + ); + void version; + + const onMessage = useCallback( + (m: LibraryMessage) => { + if (m.type === "photo.edited") { + if (session && m.photoId === session.photoId) void session.remote(m); + setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p))); + } else if (m.type === "photo.rendered") { + setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p))); + } + }, + [session], + ); + const live = useLibraryLive(api, onMessage); + // Reconnected: anything sent meanwhile is fetched in order. + useEffect(() => { + if (live === "live" && session?.loaded) void session.catchUp(); + }, [live, session]); + + const index = current ? photos.findIndex((p) => p.id === current.id) : -1; + const go = useCallback( + (delta: number) => { + const next = photos[index + delta]; + if (next) navigate(`/develop/${next.id}`); + }, + [photos, index, navigate], + ); + + useEffect(() => { + strip.current?.querySelector('[aria-current="true"]')?.scrollIntoView({ block: "nearest", inline: "nearest" }); + }, [current?.id]); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (isTyping(e.target)) return; + // Arrows move a focused slider, not the photo. + if (e.target instanceof HTMLInputElement && e.target.type === "range" && e.key.startsWith("Arrow")) return; + const mod = e.metaKey || e.ctrlKey; + if (mod && e.key.toLowerCase() === "z") { + e.preventDefault(); + if (e.shiftKey) session?.redo(); + else session?.undo(); + } else if (mod && e.key.toLowerCase() === "y") { + e.preventDefault(); + session?.redo(); + } else if (e.key === "ArrowRight") go(1); + else if (e.key === "ArrowLeft") go(-1); + else if (e.key === "\\") setBefore((b) => !b); + else if (e.key.toLowerCase() === "r" && canEdit) setCropping((c) => !c); + else if (e.key === "Escape") setCropping(false); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [session, go, canEdit]); + + const settings = session?.loaded ? session.settings : null; + const crop = useMemo(() => (settings ? cropOf(settings) : { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null }), [settings]); + const shown = settings && before && typeof engine === "object" ? engine.defaultSettings() : settings; + + const setValue = useCallback( + (id: string, value: number) => { + setDragging(true); + session?.edit({ command: "develop.set", params: { values: { [id]: value } } }, id); + }, + [session], + ); + const endGesture = useCallback(() => { + setDragging(false); + session?.endGesture(); + }, [session]); + + const frameRatio = (aspect: [number, number] | null) => { + if (!aspect) return null; + const src = sourceSize ? sourceSize.w / sourceSize.h : 1.5; + return aspect[0] / aspect[1] / src; + }; + const setAspect = (choice: (typeof ASPECTS)[number]["value"]) => { + if (!session || !sourceSize) return; + const aspect: [number, number] | null = choice === "original" ? [sourceSize.w, sourceSize.h] : choice; + const ratio = frameRatio(aspect); + const rect = ratio ? fitAspect(crop.rect, ratio) : crop.rect; + session.edit({ command: "crop.set", params: { rect, angle: crop.angle, aspect } }); + session.endGesture(); + }; + + if (!organization) return

{t.noAccess}

; + + const status = !session?.loaded ? "" : session.offline ? t.dev.offline : session.hasPending ? t.dev.saving : t.dev.saved; + const angle = CONTROLS.find((c) => c.id === "crop.angle"); + const clip = prefs.get(CLIPBOARD); + + return ( +
+
+
+
+ {current ? `${current.originalName} · ${index + 1}/${photos.length}` : ""} + + + + + + {status} + + +
+
+ {engine === "missing" ? ( +

{t.dev.engineMissing}

+ ) : !current ? ( +

{photos.length ? "…" : t.dev.noPhoto}

+ ) : engine === "loading" || !shown ? ( +

{t.dev.loading}

+ ) : ( + setSourceSize({ w, h })} + onError={(m) => setNote(m)} + onCrop={(rect, final) => { + setDragging(!final); + session?.edit({ command: "crop.set", params: { rect, angle: crop.angle, aspect: crop.aspect } }, "crop"); + if (final) session?.endGesture(); + }} + /> + )} +
+
+ + +
+ +
+ {photos.map((p) => ( + + ))} +
+
{t.dev.shortcuts}
+
+ ); +} diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index cef629e..57c5736 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -1,7 +1,9 @@ import type { LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts"; import { hasRole, type DeliveryTarget, type EventSummary } from "@photoreport/sdk"; import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react"; +import { useNavigate } from "react-router"; import { useAuth } from "../auth.js"; +import { pasteCommand } from "./DevelopPage.js"; import { t } from "../i18n.js"; import { EventForm } from "../library/EventForm.js"; import { EventsPanel } from "../library/EventsPanel.js"; @@ -22,6 +24,7 @@ const isTyping = (target: EventTarget | null) => /** Library module: events on the left, the grid (or loupe) in the middle, photo details and delivery on the right. */ export function LibraryPage() { const { api, organization, role } = useAuth(); + const navigate = useNavigate(); const orgId = organization?.id ?? ""; const canCull = role !== null && hasRole(role, "INGESTER"); const canCreate = role !== null && hasRole(role, "EDITOR"); @@ -133,6 +136,7 @@ export function LibraryPage() { return; } if (e.key === "Enter" && focus) return setLoupe(true); + if (e.key.toLowerCase() === "d" && focus) return navigate(`/develop/${focus.id}`); if (e.key === "Escape") return setLoupe(false); const change = patchForKey(e.key); if (!change) return; @@ -146,7 +150,7 @@ export function LibraryPage() { }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [visibleIds, selection, focus, loupe, patch]); + }, [visibleIds, selection, focus, loupe, patch, navigate]); const onPick = useCallback( (id: string, e: React.MouseEvent) => dispatch({ type: "select", id, mode: e.shiftKey ? "range" : e.metaKey || e.ctrlKey ? "toggle" : "single", visible: visibleIds }), @@ -207,6 +211,23 @@ export function LibraryPage() { + {canCull && prefs.get("develop.clipboard") && selection.length > 0 && ( + + )} | - + {t.develop} - + {canCull && ( <>