From 81628d4b511d76e3f1be25c885f87e13e935dcbf Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 16 Nov 2026 13:53:44 +0100 Subject: [PATCH] [worker] pictor-worker: JSON-lines ops, Job Object memory cap, time caps, hostile PDF tests --- Cargo.lock | 1605 ++++++++++++++++++++++++++++ crates/worker/Cargo.toml | 35 + crates/worker/src/client.rs | 312 ++++++ crates/worker/src/lib.rs | 93 ++ crates/worker/src/main.rs | 54 + crates/worker/src/ops.rs | 443 ++++++++ crates/worker/tests/hostile_pdf.rs | 294 +++++ 7 files changed, 2836 insertions(+) create mode 100644 Cargo.lock create mode 100644 crates/worker/Cargo.toml create mode 100644 crates/worker/src/client.rs create mode 100644 crates/worker/src/lib.rs create mode 100644 crates/worker/src/main.rs create mode 100644 crates/worker/src/ops.rs create mode 100644 crates/worker/tests/hostile_pdf.rs diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..0369da4 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1605 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aes" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures", +] + +[[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 = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] + +[[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.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "console_error_panic_hook" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + +[[package]] +name = "console_log" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86919cef3e37b9356ccf54d4421208c17ecfda01beae61393e7ffd72916c0ef1" +dependencies = [ + "log", + "web-sys", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[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.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "ecb" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" +dependencies = [ + "cipher", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[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 = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "g2gen" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5a7e0eb46f83a20260b850117d204366674e85d3a908d90865c78df9a6b1dfc" +dependencies = [ + "g2poly", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "g2p" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "539e2644c030d3bf4cd208cb842d2ce2f80e82e6e8472390bcef83ceba0d80ad" +dependencies = [ + "g2gen", + "g2poly", +] + +[[package]] +name = "g2poly" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312d2295c7302019c395cfb90dacd00a82a2eabd700429bba9c7a3f38dbbe11b" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + +[[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 = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "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 2.0.1", +] + +[[package]] +name = "img-parts" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93567ea8788640e566a8992a28f4ff64a89b88a369ad05c4198ea6dc8a42ce2b" +dependencies = [ + "bytes", + "crc32fast", + "miniz_oxide 0.9.1", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "kamadak-exif" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8772c92c0f41c4a672cbdee6728253e5ae8fcc1c5eb5c6c676579565684bbf68" +dependencies = [ + "mutate_once", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lopdf" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6ad532ff9262dd4bfd6e085400cbb39959d48cb8d08518b01b68f77bdf6feca" +dependencies = [ + "aes", + "bitflags", + "brotli-decompressor", + "cbc", + "ecb", + "encoding_rs", + "flate2", + "getrandom", + "indexmap", + "itoa", + "log", + "md-5", + "nom", + "rand", + "rangemap", + "sha2", + "stringprep", + "thiserror", + "weezl 0.2.1", +] + +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +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", + "serde", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "mutate_once" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af" + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pdfium-render" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "296b1146652b486ea6eea0d316e85ab6837ff69e8d2b1568e6fa7bc38bd4c00e" +dependencies = [ + "bitflags", + "bytemuck", + "bytes", + "chrono", + "console_error_panic_hook", + "console_log", + "image", + "itertools", + "js-sys", + "libloading", + "log", + "maybe-owned", + "once_cell", + "utf16string", + "vecmath", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "pictor-meta" +version = "0.1.0" +dependencies = [ + "image", + "img-parts", + "kamadak-exif", + "lopdf", + "serde", + "thiserror", +] + +[[package]] +name = "pictor-pdf" +version = "0.1.0" +dependencies = [ + "flate2", + "getrandom", + "image", + "lopdf", + "pdfium-render", + "pictor-meta", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "pictor-qr" +version = "0.1.0" +dependencies = [ + "image", + "qrcode", + "rqrr", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "pictor-raster" +version = "0.1.0" +dependencies = [ + "image", + "proptest", + "serde", + "thiserror", + "windows", +] + +[[package]] +name = "pictor-save" +version = "0.1.0" +dependencies = [ + "tempfile", + "thiserror", +] + +[[package]] +name = "pictor-worker" +version = "0.1.0" +dependencies = [ + "base64", + "flate2", + "image", + "lopdf", + "pictor-meta", + "pictor-pdf", + "pictor-qr", + "pictor-raster", + "pictor-save", + "serde", + "serde_json", + "tempfile", + "thiserror", + "windows", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piston-float" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad78bf43dcf80e8f950c92b84f938a0fc7590b7f6866fbcbeca781609c115590" + +[[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 = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rqrr" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d084c50c5cfa397a081850da329566c8667b0b6c4e81da16abff1fef27de93b" +dependencies = [ + "g2p", + "image", + "lru", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error 1.2.3", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[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.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[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 2.0.1", + "weezl 0.1.12", + "zune-jpeg", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "utf16string" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b62a1e85e12d5d712bf47a85f426b73d303e2d00a90de5f3004df3596e9d216" +dependencies = [ + "byteorder", +] + +[[package]] +name = "vecmath" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956ae1e0d85bca567dee1dcf87fb1ca2e792792f66f87dced8381f99cd91156a" +dependencies = [ + "piston-float", +] + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "weezl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/crates/worker/Cargo.toml b/crates/worker/Cargo.toml new file mode 100644 index 0000000..f5e4e16 --- /dev/null +++ b/crates/worker/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "pictor-worker" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lib] +name = "pictor_worker" +path = "src/lib.rs" + +[[bin]] +name = "pictor-worker" +path = "src/main.rs" + +[dependencies] +thiserror.workspace = true +serde.workspace = true +serde_json.workspace = true +base64.workspace = true +image.workspace = true +pictor-raster.workspace = true +pictor-pdf.workspace = true +pictor-meta.workspace = true +pictor-qr.workspace = true +pictor-save.workspace = true + +[target.'cfg(windows)'.dependencies] +windows = { workspace = true, features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_Security"] } + +[dev-dependencies] +tempfile.workspace = true +lopdf.workspace = true +flate2.workspace = true diff --git a/crates/worker/src/client.rs b/crates/worker/src/client.rs new file mode 100644 index 0000000..7909bfb --- /dev/null +++ b/crates/worker/src/client.rs @@ -0,0 +1,312 @@ +//! The app's side of the worker: spawn, send, wait with a time cap, and survive whatever the worker does. +//! +//! On Windows the worker runs inside a Job Object that caps its memory and kills it when the job handle closes (so +//! a worker never outlives the app). A request that exceeds its time cap kills the worker; the next request starts +//! a fresh one (open PDFs must then be opened again: the error kind says `restarted`). +use crate::{OpError, PROTOCOL}; +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +#[derive(Debug, Clone)] +pub struct WorkerOptions { + pub exe: PathBuf, + /// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR). + pub pdfium_dir: Option, + /// The worker's memory cap. + pub memory_mb: u64, + /// Enables the debug.* operations (tests). + pub debug: bool, +} + +impl WorkerOptions { + pub fn new(exe: impl Into) -> WorkerOptions { + WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum WorkerError { + /// The operation failed cleanly (bad file, wrong password, …): show `message`. + #[error("{0}")] + Op(OpError), + #[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")] + TimedOut(u64), + #[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")] + OutOfMemory, + #[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")] + Crashed(String), + #[error("Pictor's file reader could not start: {0}")] + Spawn(String), +} + +impl WorkerError { + /// A short machine-readable kind, like [`OpError::kind`]. + pub fn kind(&self) -> &str { + match self { + WorkerError::Op(e) => &e.kind, + WorkerError::TimedOut(_) => "timed_out", + WorkerError::OutOfMemory => "out_of_memory", + WorkerError::Crashed(_) => "crashed", + WorkerError::Spawn(_) => "spawn", + } + } +} + +struct Running { + child: Child, + stdin: ChildStdin, + lines: Receiver, + stderr: Arc>, + #[cfg(windows)] + _job: job::Job, +} + +pub struct Worker { + opts: WorkerOptions, + running: Option, + next_id: u64, + /// Set when the worker had to be restarted since the caller last asked (open documents are gone). + restarted: bool, +} + +impl Worker { + pub fn new(opts: WorkerOptions) -> Worker { + Worker { opts, running: None, next_id: 1, restarted: false } + } + + pub fn exe(&self) -> &Path { + &self.opts.exe + } + + /// True once after the worker was restarted (its open documents are gone). + pub fn take_restarted(&mut self) -> bool { + std::mem::take(&mut self.restarted) + } + + fn spawn(&mut self) -> Result<(), WorkerError> { + let mut cmd = Command::new(&self.opts.exe); + cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + if let Some(d) = &self.opts.pdfium_dir { + cmd.env("PICTOR_PDFIUM_DIR", d); + } + if self.opts.debug { + cmd.env("PICTOR_WORKER_DEBUG", "1"); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + cmd.creation_flags(CREATE_NO_WINDOW); + } + let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?; + #[cfg(windows)] + let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) { + Ok(j) => j, + Err(e) => { + let _ = child.kill(); + return Err(WorkerError::Spawn(format!("job object: {e}"))); + } + }; + let stdin = child.stdin.take().expect("piped"); + let stdout = child.stdout.take().expect("piped"); + let stderr_pipe = child.stderr.take().expect("piped"); + let (tx, rx) = channel(); + std::thread::spawn(move || { + let mut r = BufReader::new(stdout); + loop { + let mut line = String::new(); + match r.read_line(&mut line) { + Ok(0) | Err(_) => return, + Ok(_) => { + if tx.send(line).is_err() { + return; + } + } + } + } + }); + let stderr = Arc::new(Mutex::new(String::new())); + let sink = stderr.clone(); + std::thread::spawn(move || { + let mut r = BufReader::new(stderr_pipe); + let mut line = String::new(); + while let Ok(n) = r.read_line(&mut line) { + if n == 0 { + return; + } + let mut s = sink.lock().unwrap_or_else(|p| p.into_inner()); + if s.len() < 16 << 10 { + s.push_str(&line); + } + line.clear(); + } + }); + let mut running = Running { + child, + stdin, + lines: rx, + stderr, + #[cfg(windows)] + _job: job, + }; + let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| { + let _ = running.child.kill(); + WorkerError::Spawn("it did not answer".into()) + })?; + let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?; + if hello["protocol"].as_u64() != Some(PROTOCOL as u64) { + let _ = running.child.kill(); + return Err(WorkerError::Spawn(format!("it speaks protocol {}, Pictor needs {PROTOCOL}", hello["protocol"]))); + } + self.running = Some(running); + Ok(()) + } + + fn kill(&mut self) { + if let Some(mut r) = self.running.take() { + let _ = r.child.kill(); + let _ = r.child.wait(); + self.restarted = true; + } + } + + /// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed. + pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result { + if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) { + self.kill(); + } + if self.running.is_none() { + self.spawn()?; + } + let id = self.next_id; + self.next_id += 1; + let r = self.running.as_mut().expect("spawned"); + let line = json!({"id": id, "op": op, "args": args}).to_string(); + if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() { + return Err(self.died()); + } + let deadline = std::time::Instant::now() + timeout; + loop { + let r = self.running.as_mut().expect("spawned"); + let left = deadline.saturating_duration_since(std::time::Instant::now()); + match r.lines.recv_timeout(left) { + Ok(text) => { + let v: Value = match serde_json::from_str(&text) { + Ok(v) => v, + Err(_) => continue, + }; + if v["id"].as_u64() != Some(id) { + continue; // a late answer to a request that already timed out + } + if let Some(ok) = v.get("ok") { + return Ok(ok.clone()); + } + let err: OpError = serde_json::from_value(v["err"].clone()) + .unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer.")); + return Err(WorkerError::Op(err)); + } + Err(RecvTimeoutError::Timeout) => { + self.kill(); + return Err(WorkerError::TimedOut(timeout.as_secs().max(1))); + } + Err(RecvTimeoutError::Disconnected) => return Err(self.died()), + } + } + } + + fn died(&mut self) -> WorkerError { + let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default(); + // Give the stderr thread a moment to collect the last words. + std::thread::sleep(Duration::from_millis(50)); + let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr); + // pdfium aborts without a word when an allocation fails; the job's peak memory tells that story. + #[cfg(windows)] + let hit_cap = self.running.as_ref().and_then(|r| r._job.peak_bytes()).is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9); + #[cfg(not(windows))] + let hit_cap = false; + self.kill(); + if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") { + WorkerError::OutOfMemory + } else { + WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string()) + } + } +} + +impl Drop for Worker { + fn drop(&mut self) { + self.kill(); + } +} + +#[cfg(windows)] +mod job { + use windows::Win32::Foundation::{CloseHandle, HANDLE}; + use windows::Win32::System::JobObjects::*; + use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE}; + + pub struct Job(HANDLE); + unsafe impl Send for Job {} + + impl Job { + pub fn new(memory_mb: u64) -> Result { + unsafe { + let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?; + let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20; + SetInformationJobObject( + h, + JobObjectExtendedLimitInformation, + &info as *const _ as *const _, + std::mem::size_of::() as u32, + ) + .map_err(|e| { + let _ = CloseHandle(h); + e.to_string() + })?; + Ok(Job(h)) + } + } + + pub fn assign(&self, child: &std::process::Child) -> Result<(), String> { + unsafe { + let p = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?; + let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string()); + let _ = CloseHandle(p); + r + } + } + } + + impl Job { + /// The most memory the worker ever committed, in bytes. + pub fn peak_bytes(&self) -> Option { + unsafe { + let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + QueryInformationJobObject( + Some(self.0), + JobObjectExtendedLimitInformation, + &mut info as *mut _ as *mut _, + std::mem::size_of::() as u32, + None, + ) + .ok()?; + Some(info.PeakProcessMemoryUsed as u64) + } + } + } + + impl Drop for Job { + fn drop(&mut self) { + unsafe { + let _ = CloseHandle(self.0); + } + } + } +} diff --git a/crates/worker/src/lib.rs b/crates/worker/src/lib.rs new file mode 100644 index 0000000..1247fe3 --- /dev/null +++ b/crates/worker/src/lib.rs @@ -0,0 +1,93 @@ +//! `pictor-worker`: the only Pictor process that parses outside files. +//! +//! The app (the tray process) starts it, sends one JSON request per line on stdin and reads one JSON response per +//! line on stdout (the protocol is in `docs/FORMATS.md`). [`client::Worker`] does that from the app's side: it puts +//! the worker in a Windows Job Object with a memory cap, gives every request a time cap, and kills and restarts the +//! worker when it hangs or crashes — so a hostile PDF can take down a worker, never the tray. +pub mod client; +pub mod ops; + +use serde::Serialize; + +/// The protocol version in the worker's hello line; the client refuses another. +pub const PROTOCOL: u32 = 1; + +/// A typed error the UI can act on (`kind`) with a plain sentence for the user (`message`). +#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)] +pub struct OpError { + pub kind: String, + pub message: String, +} + +impl OpError { + pub fn new(kind: &str, message: impl Into) -> OpError { + OpError { kind: kind.into(), message: message.into() } + } +} + +impl std::fmt::Display for OpError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl From for OpError { + fn from(e: pictor_pdf::PdfError) -> Self { + use pictor_pdf::PdfError as E; + let kind = match &e { + E::EngineMissing(_) => "engine_missing", + E::NeedsPassword => "needs_password", + E::WrongPassword => "wrong_password", + E::Damaged(_) => "damaged", + E::Unsupported(_) => "unsupported", + E::NoSuchPage(_) | E::Invalid(_) => "invalid", + E::Write(_) => "io", + E::TooLarge(_) => "too_large", + }; + OpError::new(kind, e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_raster::RasterError) -> Self { + let text = format!("{e:?}"); + let kind = match text.split([' ', '{', '(']).next().unwrap_or("") { + "HeifCodecMissing" | "AvifCodecMissing" => "codec_missing", + "InputTooLarge" | "TooManyPixels" | "TooMuchMemory" => "too_large", + "UnknownFormat" | "UnsupportedFeature" | "CannotWrite" => "unsupported", + "CannotReachTarget" => "cannot_reach_target", + "Empty" | "InvalidCrop" | "InvalidSize" | "InvalidTarget" => "invalid", + _ => "damaged", + }; + OpError::new(kind, e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_meta::MetaError) -> Self { + use pictor_meta::MetaError as E; + let kind = match &e { + E::Encrypted => "needs_password", + E::Unsupported(_) => "unsupported", + E::TooLarge { .. } | E::TooBig(_) => "too_large", + E::Write(_) => "io", + _ => "damaged", + }; + OpError::new(kind, e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_qr::QrError) -> Self { + OpError::new("invalid", e.to_string()) + } +} + +impl From for OpError { + fn from(e: pictor_save::SaveError) -> Self { + match e { + pictor_save::SaveError::Exists(_) => OpError::new("exists", e.to_string()), + _ => OpError::new("io", e.to_string()), + } + } +} diff --git a/crates/worker/src/main.rs b/crates/worker/src/main.rs new file mode 100644 index 0000000..48161fa --- /dev/null +++ b/crates/worker/src/main.rs @@ -0,0 +1,54 @@ +//! pictor-worker.exe: reads one JSON request per line on stdin, writes one JSON response per line on stdout. +//! → {"id": 1, "op": "pdf.open", "args": {...}} +//! ← {"id": 1, "ok": {...}} or {"id": 1, "err": {"kind": "...", "message": "..."}} +//! The first line it writes is {"hello": "pictor-worker", "protocol": 1, "version": "..."}. +//! Environment: PICTOR_PDFIUM_DIR (where pdfium.dll is; default: next to this exe), PICTOR_WORKER_DEBUG=1 (tests). +use pictor_worker::{OpError, PROTOCOL, ops}; +use serde_json::{Value, json}; +use std::io::{BufRead, Read, Write}; + +fn main() { + let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf())); + let pdfium_dir = std::env::var_os("PICTOR_PDFIUM_DIR").map(Into::into).or(exe_dir); + let debug = std::env::var("PICTOR_WORKER_DEBUG").as_deref() == Ok("1"); + let mut state = ops::State::new(pdfium_dir, debug); + let stdout = std::io::stdout(); + let mut out = stdout.lock(); + let hello = json!({"hello": "pictor-worker", "protocol": PROTOCOL, "version": env!("CARGO_PKG_VERSION")}); + if writeln!(out, "{hello}").and_then(|_| out.flush()).is_err() { + return; + } + let stdin = std::io::stdin(); + let mut line = String::new(); + let mut input = stdin.lock(); + loop { + line.clear(); + // Requests are small (paths and edits); refuse absurd lines instead of buffering them. + match input.by_ref().take(64 << 20).read_line(&mut line) { + Ok(0) | Err(_) => return, + Ok(_) => {} + } + let req: Value = match serde_json::from_str(line.trim_end()) { + Ok(v) => v, + Err(e) => { + let _ = writeln!(out, "{}", json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))})); + let _ = out.flush(); + continue; + } + }; + let id = req.get("id").cloned().unwrap_or(Value::Null); + let op = req.get("op").and_then(Value::as_str).unwrap_or("").to_string(); + let args = req.get("args").cloned().unwrap_or(json!({})); + // A panic inside a library becomes a typed error, not a dead worker (an abort still kills it; the client + // reports that as a crash). + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| ops::dispatch(&mut state, &op, args))) + .unwrap_or_else(|_| Err(OpError::new("damaged", "Pictor could not read this file (it is damaged)."))); + let resp = match result { + Ok(v) => json!({"id": id, "ok": v}), + Err(e) => json!({"id": id, "err": e}), + }; + if writeln!(out, "{resp}").and_then(|_| out.flush()).is_err() { + return; + } + } +} diff --git a/crates/worker/src/ops.rs b/crates/worker/src/ops.rs new file mode 100644 index 0000000..18a35b5 --- /dev/null +++ b/crates/worker/src/ops.rs @@ -0,0 +1,443 @@ +//! The worker's operations. Each takes the request's JSON arguments and returns JSON or an [`OpError`]. +//! Files are read and written here (the paths come from the app); open PDFs stay in memory as sessions. +use crate::OpError; +use base64::Engine as _; +use pictor_pdf::{Edits, Engine, PageFit, PageSpec}; +use pictor_raster::{Format, Limits}; +use serde::Deserialize; +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +/// Largest outside file the worker reads at all. +pub const MAX_FILE_BYTES: u64 = 1 << 30; + +pub struct State { + engine: Option<&'static Engine>, + pdfium_dir: Option, + docs: HashMap, + next_doc: u32, + debug: bool, +} + +struct Doc { + bytes: Vec, + password: Option, +} + +impl State { + pub fn new(pdfium_dir: Option, debug: bool) -> State { + State { engine: None, pdfium_dir, docs: HashMap::new(), next_doc: 1, debug } + } + + fn engine(&mut self) -> Result<&'static Engine, OpError> { + if let Some(e) = self.engine { + return Ok(e); + } + let e = Engine::load(self.pdfium_dir.as_deref())?; + self.engine = Some(e); + Ok(e) + } + + fn doc(&self, id: u32) -> Result<&Doc, OpError> { + self.docs.get(&id).ok_or_else(|| OpError::new("not_open", "That PDF is no longer open. Open it again.")) + } +} + +fn b64(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +fn read_file(path: &str) -> Result, OpError> { + let meta = std::fs::metadata(path).map_err(|e| OpError::new("io", format!("Pictor could not open {path}: {e}")))?; + if !meta.is_file() { + return Err(OpError::new("io", format!("{path} is not a file."))); + } + if meta.len() > MAX_FILE_BYTES { + return Err(OpError::new("too_large", "This file is larger than 1 GB, which Pictor does not open.")); + } + std::fs::read(path).map_err(|e| OpError::new("io", format!("Pictor could not read {path}: {e}"))) +} + +fn args Deserialize<'de>>(v: Value) -> Result { + serde_json::from_value(v).map_err(|e| OpError::new("invalid", format!("bad request: {e}"))) +} + +#[derive(Deserialize)] +#[serde(rename_all = "snake_case")] +enum SaveMode { + /// A new file; refuses to replace one. + New, + /// Replace the file, keeping a .bak. + Overwrite, +} + +fn write_out(path: &str, bytes: &[u8], mode: SaveMode) -> Result { + let p = Path::new(path); + match mode { + SaveMode::New => { + pictor_save::save_new(p, bytes)?; + Ok(json!({"path": path, "bytes": bytes.len()})) + } + SaveMode::Overwrite => { + let bak = pictor_save::save_overwrite(p, bytes)?; + Ok(json!({"path": path, "bytes": bytes.len(), "bak": bak.exists().then(|| bak.display().to_string())})) + } + } +} + +fn png(img: &image::DynamicImage) -> Result, OpError> { + let mut out = Vec::new(); + image::codecs::png::PngEncoder::new_with_quality( + &mut out, + image::codecs::png::CompressionType::Fast, + image::codecs::png::FilterType::Sub, + ) + .write_image(img.as_bytes(), img.width(), img.height(), img.color().into()) + .map_err(|e| OpError::new("io", e.to_string()))?; + Ok(out) +} + +use image::ImageEncoder; + +pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result { + match op { + // ---- PDF sessions ------------------------------------------------------------------------------------- + "pdf.open" => { + #[derive(Deserialize)] + struct A { + path: String, + password: Option, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let engine = state.engine()?; + let info = pictor_pdf::info(engine, &bytes, a.password.as_deref())?; + let id = state.next_doc; + state.next_doc += 1; + state.docs.insert(id, Doc { bytes, password: a.password }); + Ok(json!({"doc": id, "info": info})) + } + "pdf.close" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + state.docs.remove(&a.doc); + Ok(json!({})) + } + "pdf.render" => { + #[derive(Deserialize)] + struct A { + doc: u32, + page: usize, + width: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let img = pictor_pdf::render_page(engine, &d.bytes, d.password.as_deref(), a.page, a.width)?; + Ok(json!({"png": b64(&png(&img)?), "width": img.width(), "height": img.height()})) + } + "pdf.text" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"pages": pictor_pdf::extract_text(engine, &d.bytes, d.password.as_deref())?})) + } + "pdf.search" => { + #[derive(Deserialize)] + struct A { + doc: u32, + query: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"hits": pictor_pdf::search(engine, &d.bytes, d.password.as_deref(), &a.query, 2000)?})) + } + "pdf.form" => { + #[derive(Deserialize)] + struct A { + doc: u32, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + Ok(json!({"fields": pictor_pdf::form_fields(engine, &d.bytes, d.password.as_deref())?})) + } + "pdf.save" => { + #[derive(Deserialize)] + struct A { + doc: u32, + edits: Edits, + output: String, + mode: SaveMode, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let applied = pictor_pdf::apply(engine, &d.bytes, d.password.as_deref(), &a.edits)?; + let mut out = write_out(&a.output, &applied.bytes, a.mode)?; + out["warnings"] = json!(applied.warnings); + Ok(out) + } + "pdf.extract" => { + #[derive(Deserialize)] + struct A { + doc: u32, + pages: Vec, + output: String, + } + let a: A = args(a)?; + let d = state.doc(a.doc)?; + let specs: Vec = a.pages.iter().map(|&index| PageSpec::Existing { index, rotate: 0 }).collect(); + let bytes = pictor_pdf::reorganise(&d.bytes, d.password.as_deref(), &specs)?; + write_out(&a.output, &bytes, SaveMode::New) + } + "pdf.to_images" => { + #[derive(Deserialize)] + struct A { + doc: u32, + pages: Vec, + dpi: u32, + format: String, + /// Output path pattern with `{n}` for the 1-based page number. + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let d = state.doc(a.doc)?; + let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose PNG or JPG."))?; + let mut paths = Vec::new(); + for &p in &a.pages { + let img = pictor_pdf::pages_to_images(engine, &d.bytes, d.password.as_deref(), &[p], a.dpi)?.remove(0); + let bytes = pictor_raster::encode(&img, format, &Default::default())?; + let path = a.output.replace("{n}", &(p + 1).to_string()); + pictor_save::save_new(Path::new(&path), &bytes)?; + paths.push(path); + } + Ok(json!({"paths": paths})) + } + // ---- PDF files ---------------------------------------------------------------------------------------- + "pdf.merge" => { + #[derive(Deserialize)] + struct Input { + path: String, + password: Option, + } + #[derive(Deserialize)] + struct A { + inputs: Vec, + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let files: Vec<(Vec, Option)> = + a.inputs.iter().map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))).collect::>()?; + let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect(); + let bytes = pictor_pdf::merge(engine, &refs)?; + write_out(&a.output, &bytes, SaveMode::New) + } + "pdf.split" => { + #[derive(Deserialize)] + struct A { + path: String, + password: Option, + ranges: String, + /// Output path pattern with `{n}` for the part number. + output: String, + } + let a: A = args(a)?; + let engine = state.engine()?; + let bytes = read_file(&a.path)?; + let pages = pictor_pdf::page_sizes(engine, &bytes, a.password.as_deref())?.len(); + let ranges = pictor_pdf::parse_ranges(&a.ranges, pages)?; + let parts = pictor_pdf::split(&bytes, a.password.as_deref(), &ranges)?; + let mut paths = Vec::new(); + for (i, part) in parts.iter().enumerate() { + let path = a.output.replace("{n}", &(i + 1).to_string()); + pictor_save::save_new(Path::new(&path), part)?; + paths.push(path); + } + Ok(json!({"paths": paths})) + } + "pdf.from_images" => { + #[derive(Deserialize)] + struct A { + inputs: Vec, + output: String, + fit: PageFit, + #[serde(default)] + margin: f32, + } + let a: A = args(a)?; + let limits = Limits::default(); + let mut images = Vec::new(); + for p in &a.inputs { + let bytes = read_file(p)?; + let img = pictor_raster::decode(&bytes, &limits)?; + images.push((bytes, img)); + } + let bytes = pictor_pdf::images_to_pdf(&images, a.fit, a.margin)?; + write_out(&a.output, &bytes, SaveMode::New) + } + // ---- Images ------------------------------------------------------------------------------------------- + "image.probe" => { + #[derive(Deserialize)] + struct A { + path: String, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let p = pictor_raster::probe(&bytes, &Limits::default())?; + Ok(json!({"format": p.format, "width": p.width, "height": p.height, "has_alpha": p.has_alpha, + "frames": p.frames, "bytes": bytes.len()})) + } + "image.thumb" => { + #[derive(Deserialize)] + struct A { + path: String, + max: u32, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let img = pictor_raster::decode(&bytes, &Limits::default())?; + let (w, h) = (img.width(), img.height()); + let t = pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?; + Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h})) + } + "image.convert" => { + #[derive(Deserialize)] + struct A { + input: String, + output: String, + format: String, + #[serde(default)] + quality: Option, + #[serde(default)] + crop: Option, + #[serde(default)] + rotate: Option, + #[serde(default)] + resize: Option, + #[serde(default)] + preset: Option, + #[serde(default)] + target_bytes: Option, + #[serde(default)] + overwrite: bool, + } + let a: A = args(a)?; + let limits = Limits::default(); + let src = read_file(&a.input)?; + let src_format = pictor_raster::probe(&src, &limits)?.format; + let mut img = pictor_raster::decode(&src, &limits)?; + if let Some(c) = a.crop { + img = pictor_raster::crop(&img, c)?; + } + if let Some(r) = a.rotate { + img = pictor_raster::rotate(&img, r); + } + if let Some(f) = a.resize { + img = pictor_raster::resize(&img, f, &limits)?; + } + let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?; + let (bytes, format) = if let Some(target) = a.target_bytes { + let c = pictor_raster::compress_to(&img, format, target, &limits)?; + (c.bytes, c.format) + } else if let Some(p) = a.preset { + let _ = src_format; + pictor_raster::apply_preset(&img, format, p)? + } else { + let mut o = pictor_raster::EncodeOptions::default(); + if let Some(q) = a.quality { + o.jpeg_quality = q.clamp(10, 100); + } + (pictor_raster::encode(&img, format, &o)?, format) + }; + let mut out = write_out(&a.output, &bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?; + out["format"] = json!(format); + out["width"] = json!(img.width()); + out["height"] = json!(img.height()); + Ok(out) + } + "image.heif_support" => Ok(json!({"support": pictor_raster::heif_support()})), + // ---- Metadata ----------------------------------------------------------------------------------------- + "meta.read" => { + #[derive(Deserialize)] + struct A { + path: String, + } + let a: A = args(a)?; + let bytes = read_file(&a.path)?; + let report = pictor_meta::read(&bytes)?; + let groups: Vec<_> = report.groups().into_iter().map(|g| json!({"group": g, "label": g.label()})).collect(); + Ok(json!({"report": report, "groups": groups})) + } + "meta.strip" => { + #[derive(Deserialize)] + struct A { + input: String, + output: String, + #[serde(default)] + overwrite: bool, + } + let a: A = args(a)?; + let bytes = read_file(&a.input)?; + let stripped = pictor_meta::strip(&bytes)?; + let mut out = write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?; + out["removed"] = json!(stripped.removed); + Ok(out) + } + // ---- QR ----------------------------------------------------------------------------------------------- + "qr.render" => { + #[derive(Deserialize)] + struct A { + payload: pictor_qr::Payload, + #[serde(default)] + level: pictor_qr::Level, + style: pictor_qr::Style, + #[serde(default)] + logo: Option, + } + let a: A = args(a)?; + let text = pictor_qr::payload_string(&a.payload)?; + let logo_bytes = match &a.logo { + Some(p) => Some(read_file(p)?), + None => None, + }; + let logo = match &logo_bytes { + Some(b) => Some(pictor_raster::decode(b, &Limits::default())?.to_rgba8()), + None => None, + }; + let r = pictor_qr::render_rgba(&text, a.level, &a.style, logo.as_ref())?; + let png = pictor_qr::encode_png(&r.image)?; + let logo_png = match &logo { + Some(l) => Some(pictor_qr::encode_png(l)?), + None => None, + }; + let svg = pictor_qr::render_svg(&text, a.level, &a.style, logo_png.as_deref())?; + Ok(json!({"png": b64(&png), "svg": svg, "level_used": r.level_used, "size": r.size_px, "text": text})) + } + // ---- Tests only (PICTOR_WORKER_DEBUG=1) --------------------------------------------------------------- + "debug.crash" if state.debug => std::process::abort(), + "debug.sleep" if state.debug => { + std::thread::sleep(std::time::Duration::from_secs(a["secs"].as_u64().unwrap_or(60))); + Ok(json!({})) + } + "debug.alloc" if state.debug => { + let mb = a["mb"].as_u64().unwrap_or(4096) as usize; + let mut v: Vec = Vec::new(); + v.try_reserve_exact(mb << 20).map_err(|_| OpError::new("too_large", "out of memory"))?; + v.resize(mb << 20, 1); + Ok(json!({"len": v.len()})) + } + _ => Err(OpError::new("invalid", format!("unknown operation {op}"))), + } +} diff --git a/crates/worker/tests/hostile_pdf.rs b/crates/worker/tests/hostile_pdf.rs new file mode 100644 index 0000000..98e2d9a --- /dev/null +++ b/crates/worker/tests/hostile_pdf.rs @@ -0,0 +1,294 @@ +//! Mandatory test 2: hostile PDFs. Each fixture goes through the real worker process (open, render page 1, text, +//! metadata, a save with an annotation). Every step either works or fails with a typed error within its time cap; +//! a worker that crashes, hangs or runs out of memory is reported as such and replaced. This test process plays the +//! tray: it must never crash, and the next request after a bad file must work. +//! Fixtures are generated here; fixtures-fetch/fetch.ps1 adds real-world corpora under fixtures/fetched/ (optional). +use flate2::{Compression, write::ZlibEncoder}; +use lopdf::{Document, Object, Stream, dictionary}; +use pictor_worker::client::{Worker, WorkerError, WorkerOptions}; +use serde_json::json; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +const CAP: Duration = Duration::from_secs(15); + +fn worker() -> Worker { + let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker")); + o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin")); + o.memory_mb = 1024; + o.debug = true; + Worker::new(o) +} + +fn base_doc(content: &[u8]) -> Document { + let mut doc = Document::with_version("1.7"); + let pages = doc.new_object_id(); + let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); + let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec())); + let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c, + "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}}); + doc.objects.insert(pages, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1, + "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]})); + let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages}); + doc.trailer.set("Root", cat); + doc +} + +fn save(mut doc: Document) -> Vec { + let mut v = Vec::new(); + doc.save_to(&mut v).unwrap(); + v +} + +fn valid() -> Vec { + save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET")) +} + +fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec { + let i = hay.windows(from.len()).position(|w| w == from).expect("pattern"); + [&hay[..i], to, &hay[i + from.len()..]].concat() +} + +fn font_doc(font_key: &str, font_bytes: Vec) -> Vec { + let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET"); + let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes)); + let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32, + "FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800, + "Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff}); + let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" }, + "BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc}); + let page = *doc.get_pages().values().next().unwrap(); + doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}}); + save(doc) +} + +fn fixtures() -> Vec<(&'static str, Vec)> { + let v = valid(); + let mut out: Vec<(&str, Vec)> = vec![ + ("empty file", Vec::new()), + ("header only", b"%PDF-1.7\n".to_vec()), + ("truncated at 10%", v[..v.len() / 10].to_vec()), + ("truncated at 50%", v[..v.len() / 2].to_vec()), + ("truncated before the trailer", v[..v.len() - 40].to_vec()), + ("random bytes after a header", { + let mut x = b"%PDF-1.7\n".to_vec(); + let mut s = 0x2545_4446u32; + for _ in 0..20_000 { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + x.push(s as u8); + } + x + }), + ]; + // Broken xref: startxref points nowhere, then the table itself is garbage. + let sx = v.windows(9).rposition(|w| w == b"startxref").unwrap(); + out.push(("startxref beyond the end", [&v[..sx], b"startxref\n99999999\n%%EOF\n"].concat())); + // lopdf writes a cross-reference stream: garble its binary table, or cut it off and leave a bare trailer. + let xr = v.windows(10).rposition(|w| w == b"/Type/XRef").unwrap(); + let obj_kw = v[..xr].windows(4).rposition(|w| w == b"obj\n").unwrap(); + let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0); + let mut garbled = v.clone(); + let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7; + let end = (data + 40).min(garbled.len()); + for b in garbled[data..end].iter_mut() { + *b = b.wrapping_mul(31).wrapping_add(7); + } + out.push(("garbled xref table", garbled)); + out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat())); + // Recursive references. + { + let mut doc = base_doc(b""); + let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap(); + doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]); + out.push(("page tree that contains itself", save(doc))); + } + { + let mut doc = base_doc(b""); + let page = *doc.get_pages().values().next().unwrap(); + let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap(); + doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page)); + out.push(("parent loop", save(doc))); + } + out.push(("object that is a reference to itself", replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R").into_iter().chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied()).collect())); + out.push(("deeply nested arrays", { + let mut deep = vec![b'['; 200_000]; + deep.extend(vec![b']'; 200_000]); + replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat()) + })); + out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647"))); + out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]"))); + // A 1 GB declared stream, and a deflate bomb that expands to 1 GiB. + { + let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET"); + let bytes = save(doc); + let i = bytes.windows(7).position(|w| w == b"/Length").unwrap(); + let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap(); + out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat())); + } + { + let mut z = ZlibEncoder::new(Vec::new(), Compression::best()); + let zeros = vec![b' '; 1 << 20]; + for _ in 0..1024 { + z.write_all(&zeros).unwrap(); + } + let bomb = z.finish().unwrap(); + let mut doc = base_doc(b""); + let page = *doc.get_pages().values().next().unwrap(); + let c = doc.add_object(Stream::new(dictionary! {"Filter" => "FlateDecode"}, bomb).with_compression(false)); + doc.get_dictionary_mut(page).unwrap().set("Contents", c); + out.push(("content stream that inflates to 1 GiB", save(doc))); + } + // Malformed fonts. + out.push(("TrueType font of garbage", font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect()))); + out.push(("TrueType claiming 65535 tables", font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat()))); + out.push(("truncated Type 1 font", font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec()))); + // Encryption with a handler that does not exist. + out.push(("unknown security handler", replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>"))); + out +} + +fn fetched() -> Vec<(String, Vec)> { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched"); + let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() }; + let mut v: Vec<(String, Vec)> = rd + .filter_map(|e| e.ok()) + .filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf"))) + .map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap())) + .collect(); + v.sort(); + v +} + +#[derive(Default, Debug)] +struct Tally { + ok: usize, + typed_error: usize, + timed_out: usize, + out_of_memory: usize, + crashed: usize, +} + +fn run(w: &mut Worker, tally: &mut Tally, name: &str, op: &str, args: serde_json::Value) { + let start = Instant::now(); + let r = w.call(op, args, CAP); + let took = start.elapsed(); + assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap"); + let outcome = match &r { + Ok(_) => { + tally.ok += 1; + "ok".to_string() + } + Err(WorkerError::Op(e)) => { + assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}"); + tally.typed_error += 1; + format!("{} ({})", e.kind, e.message) + } + Err(WorkerError::TimedOut(_)) => { + tally.timed_out += 1; + "timed out".into() + } + Err(WorkerError::OutOfMemory) => { + tally.out_of_memory += 1; + "out of memory".into() + } + Err(WorkerError::Crashed(m)) => { + tally.crashed += 1; + format!("crashed: {m}") + } + Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"), + }; + println!("{name:40} {op:10} {took:>8.2?} {outcome}"); +} + +#[test] +fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() { + let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap(); + let mut w = worker(); + let mut tally = Tally::default(); + let mut all: Vec<(String, Vec)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect(); + all.extend(fetched()); + let annotation = json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]}); + for (i, (name, bytes)) in all.iter().enumerate() { + let path = dir.path().join(format!("f{i}.pdf")); + std::fs::write(&path, bytes).unwrap(); + let p = path.to_string_lossy().to_string(); + let start = Instant::now(); + let opened = w.call("pdf.open", json!({"path": p}), CAP); + let took = start.elapsed(); + let doc = match &opened { + Ok(v) => { + tally.ok += 1; + println!("{name:40} {:10} {took:>8.2?} ok, {} pages", "open", v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0)); + v["doc"].as_u64() + } + Err(e) => { + match e { + WorkerError::Op(_) => tally.typed_error += 1, + WorkerError::TimedOut(_) => tally.timed_out += 1, + WorkerError::OutOfMemory => tally.out_of_memory += 1, + WorkerError::Crashed(_) => tally.crashed += 1, + WorkerError::Spawn(e) => panic!("{e}"), + } + println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind()); + None + } + }; + if let Some(doc) = doc { + run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800})); + if w.take_restarted() { + continue; + } + run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc})); + if w.take_restarted() { + continue; + } + let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string(); + run(&mut w, &mut tally, name, "pdf.save", json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"})); + } + run(&mut w, &mut tally, name, "meta.read", json!({"path": p})); + w.take_restarted(); + // The tray carries on: a normal request right after works. + let good = dir.path().join("good.pdf"); + std::fs::write(&good, valid()).unwrap(); + let r = w.call("pdf.open", json!({"path": good.to_string_lossy()}), CAP).expect("a good PDF after a bad one"); + w.call("pdf.close", json!({"doc": r["doc"]}), CAP).unwrap(); + } + println!("{} fixtures: {tally:?}", all.len()); + assert!(all.len() >= 21); + assert_eq!(tally.timed_out, 0, "a fixture hung"); + assert_eq!(tally.crashed, 0, "a worker died without a known cause"); +} + +#[test] +fn the_client_survives_crash_hang_and_memory_blowup() { + let mut w = worker(); + let crash = w.call("debug.crash", json!({}), CAP); + assert!(matches!(crash, Err(WorkerError::Crashed(_))), "{crash:?}"); + assert!(w.take_restarted()); + let start = Instant::now(); + let hang = w.call("debug.sleep", json!({"secs": 120}), Duration::from_secs(2)); + assert!(matches!(hang, Err(WorkerError::TimedOut(_))), "{hang:?}"); + assert!(start.elapsed() < Duration::from_secs(10)); + let oom = w.call("debug.alloc", json!({"mb": 3000}), CAP); + // try_reserve fails cleanly under the cap (a typed error); a hard allocation would be OutOfMemory. + assert!(matches!(&oom, Err(WorkerError::OutOfMemory) | Err(WorkerError::Op(_))), "the 1 GB memory cap did not hold: {oom:?}"); + // And it works again. + let ok = w.call("image.heif_support", json!({}), CAP).unwrap(); + assert!(ok["support"].is_string()); +} + +#[test] +fn unknown_operations_and_bad_arguments_are_typed_errors() { + let mut w = worker(); + for (op, args) in [("nope", json!({})), ("pdf.open", json!({"wrong": 1})), ("pdf.render", json!({"doc": 77, "page": 0, "width": 10}))] { + match w.call(op, args, CAP) { + Err(WorkerError::Op(e)) => assert!(["invalid", "not_open"].contains(&e.kind.as_str()), "{e:?}"), + other => panic!("{op}: {other:?}"), + } + } + let missing = w.call("pdf.open", json!({"path": "F:/definitely/not/here.pdf"}), CAP); + assert!(matches!(missing, Err(WorkerError::Op(ref e)) if e.kind == "io"), "{missing:?}"); +}