diff --git a/.gitmodules b/.gitmodules index e98360d6..a895297f 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,9 +1,6 @@ [submodule "wiki"] path = wiki url = https://github.com/tinyhumansai/tinyjuice.wiki.git -[submodule "vendor/tinybus"] - path = vendor/tinybus - url = https://github.com/tinyhumansai/tinybus.git [submodule "vendor/tinyagents"] path = vendor/tinyagents url = https://github.com/tinyhumansai/tinyagents diff --git a/Cargo.lock b/Cargo.lock index 9064a091..850aab01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,16 +8,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" -[[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" -dependencies = [ - "crypto-common 0.1.7", - "generic-array", -] - [[package]] name = "aho-corasick" version = "1.1.4" @@ -54,15 +44,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "async-trait" version = "0.1.92" @@ -74,17 +55,6 @@ dependencies = [ "syn 3.0.0", ] -[[package]] -name = "atomicwrites" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ef1bb8d1b645fe38d51dfc331d720fb5fc2c94b440c76cc79c80ff265ca33e3" -dependencies = [ - "rustix 0.38.44", - "tempfile", - "windows-sys 0.52.0", -] - [[package]] name = "autocfg" version = "1.5.1" @@ -181,28 +151,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] -name = "chacha20" -version = "0.9.1" +name = "cfg_aliases" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", -] - -[[package]] -name = "chacha20poly1305" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" -dependencies = [ - "aead", - "chacha20", - "cipher", - "poly1305", - "zeroize", -] +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "ciborium" @@ -231,26 +183,6 @@ dependencies = [ "half", ] -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common 0.1.7", - "inout", - "zeroize", -] - -[[package]] -name = "clack-private-fs" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fcca21d8096fca7f1c3a22c3109e38927c9b587007c9c7a13b327e5a955baba" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "clap" version = "4.6.1" @@ -382,7 +314,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] @@ -432,17 +363,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - [[package]] name = "digest" version = "0.10.7" @@ -451,7 +371,6 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", - "subtle", ] [[package]] @@ -486,17 +405,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "displaydoc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.0", -] - [[package]] name = "dyn-clone" version = "1.0.20" @@ -525,6 +433,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.4.1" @@ -564,14 +484,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] -name = "fs4" -version = "1.1.0" +name = "foldhash" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" -dependencies = [ - "rustix 1.1.4", - "windows-sys 0.61.2", -] +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "futures-core" @@ -579,6 +495,17 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "futures-task" version = "0.3.32" @@ -592,6 +519,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ "futures-core", + "futures-macro", "futures-task", "pin-project-lite", "slab", @@ -652,11 +580,32 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash 0.2.0", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.1", +] [[package]] name = "hex" @@ -670,24 +619,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "242402749acf71e6f32f5857598b7002c4058a4e3c3b22b4c7d51cab9aea754e" -[[package]] -name = "hkdf" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - [[package]] name = "http" version = "1.5.0" @@ -720,16 +651,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", - "hashbrown", -] - -[[package]] -name = "inout" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" -dependencies = [ - "generic-array", + "hashbrown 0.17.1", ] [[package]] @@ -766,7 +688,7 @@ checksum = "4be2f53207ffb1313a2d2ad819cfa8bfaa7936cb85a110eda10fd5da822cec94" dependencies = [ "bstr", "bytes", - "foldhash", + "foldhash 0.1.5", "hifijson", "indexmap", "jaq-core", @@ -891,10 +813,15 @@ dependencies = [ ] [[package]] -name = "linux-raw-sys" -version = "0.4.15" +name = "libsqlite3-sys" +version = "0.38.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] [[package]] name = "linux-raw-sys" @@ -924,6 +851,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.0", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -964,12 +903,6 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "option-ext" version = "0.2.0" @@ -1032,17 +965,6 @@ dependencies = [ "plotters-backend", ] -[[package]] -name = "poly1305" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" -dependencies = [ - "cpufeatures 0.2.17", - "opaque-debug", - "universal-hash", -] - [[package]] name = "portable-atomic" version = "1.15.0" @@ -1104,7 +1026,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha", - "rand_core 0.9.5", + "rand_core", ] [[package]] @@ -1114,16 +1036,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", + "rand_core", ] [[package]] @@ -1216,16 +1129,28 @@ dependencies = [ ] [[package]] -name = "rustix" -version = "0.38.44" +name = "rsqlite-vfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.40.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" dependencies = [ "bitflags 2.13.0", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", ] [[package]] @@ -1237,15 +1162,15 @@ dependencies = [ "bitflags 2.13.0", "errno", "libc", - "linux-raw-sys 0.12.1", + "linux-raw-sys", "windows-sys 0.61.2", ] [[package]] name = "rustls" -version = "0.23.43" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", @@ -1267,9 +1192,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.14" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -1396,6 +1321,24 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "sqlite-wasm-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75" +dependencies = [ + "cc", + "js-sys", + "rsqlite-vfs", + "wasm-bindgen", +] + [[package]] name = "streaming-iterator" version = "0.1.9" @@ -1448,9 +1391,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", - "rustix 1.1.4", + "rustix", "windows-sys 0.61.2", ] @@ -1476,7 +1419,8 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.1.5" +version = "0.1.6" +source = "git+https://github.com/tinyhumansai/tinybus?rev=0de2d283f35cbbff08efad6fbe05537ffb74611b#0de2d283f35cbbff08efad6fbe05537ffb74611b" dependencies = [ "async-trait", "flate2", @@ -1497,7 +1441,8 @@ dependencies = [ [[package]] name = "tinybus-macros" -version = "0.1.5" +version = "0.1.6" +source = "git+https://github.com/tinyhumansai/tinybus?rev=0de2d283f35cbbff08efad6fbe05537ffb74611b#0de2d283f35cbbff08efad6fbe05537ffb74611b" dependencies = [ "proc-macro2", "quote", @@ -1506,7 +1451,8 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.1.5" +version = "0.1.6" +source = "git+https://github.com/tinyhumansai/tinybus?rev=0de2d283f35cbbff08efad6fbe05537ffb74611b#0de2d283f35cbbff08efad6fbe05537ffb74611b" dependencies = [ "async-trait", "serde", @@ -1554,7 +1500,25 @@ dependencies = [ "serde", "serde_json", "thiserror", - "tinystoragedrivers-core", + "tinystoragedrivers-types", + "tokio", +] + +[[package]] +name = "tinyjuice-cli" +version = "0.11.0" +dependencies = [ + "async-trait", + "dirs", + "log", + "serde_json", + "tempfile", + "tinyjuice", + "tinyjuice-drivers", + "tinystoragedrivers", + "tinystoragedrivers-api", + "tinystoragedrivers-testkit", + "tinystoragedrivers-types", "tokio", ] @@ -1566,7 +1530,10 @@ dependencies = [ "log", "tinyjuice", "tinyjuice-bus", - "tinystoragedrivers-core", + "tinystoragedrivers-api", + "tinystoragedrivers-blob", + "tinystoragedrivers-testkit", + "tinystoragedrivers-types", "tokio", ] @@ -1598,90 +1565,189 @@ dependencies = [ "tinyjuice", "tinyjuice-bus", "tinyjuice-drivers", + "tinystoragedrivers-api", "tinystoragedrivers-busproxy", - "tinystoragedrivers-client", - "tinystoragedrivers-core", + "tinystoragedrivers-testkit", + "tinystoragedrivers-types", "tokio", ] +[[package]] +name = "tinystoragedrivers" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "tinystoragedrivers-api", + "tinystoragedrivers-blob", + "tinystoragedrivers-connect", + "tinystoragedrivers-document", + "tinystoragedrivers-kv", + "tinystoragedrivers-queue", + "tinystoragedrivers-secrets", + "tinystoragedrivers-types", +] + +[[package]] +name = "tinystoragedrivers-api" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "async-trait", + "bytes", + "futures-core", + "serde", + "serde_json", + "tinystoragedrivers-types", + "zeroize", +] + +[[package]] +name = "tinystoragedrivers-blob" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "async-trait", + "bytes", + "futures-core", + "serde", + "serde_json", + "tinystoragedrivers-api", + "tinystoragedrivers-connect", + "tinystoragedrivers-types", +] + [[package]] name = "tinystoragedrivers-bus" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "serde", "serde_json", "tinybus", + "tinystoragedrivers-types", ] [[package]] name = "tinystoragedrivers-busproxy" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", + "bytes", + "futures-core", "serde", "serde_json", "tinybus", + "tinystoragedrivers-api", "tinystoragedrivers-bus", - "tinystoragedrivers-client", - "tinystoragedrivers-core", + "tinystoragedrivers-types", "tokio", + "zeroize", ] [[package]] -name = "tinystoragedrivers-client" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +name = "tinystoragedrivers-connect" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "rusqlite", + "serde_json", + "tinystoragedrivers-types", + "tokio", + "zstd", +] + +[[package]] +name = "tinystoragedrivers-document" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", + "data-encoding", + "libc", + "rusqlite", "serde", "serde_json", - "tinystoragedrivers-bus", - "tinystoragedrivers-core", - "tinystoragedrivers-secrets", + "sha2 0.11.0", + "tinystoragedrivers-api", + "tinystoragedrivers-connect", + "tinystoragedrivers-types", "tokio", + "zstd", ] [[package]] -name = "tinystoragedrivers-core" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +name = "tinystoragedrivers-kv" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "async-trait", + "libc", + "serde", + "serde_json", + "tinystoragedrivers-api", + "tinystoragedrivers-connect", + "tinystoragedrivers-types", +] + +[[package]] +name = "tinystoragedrivers-queue" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", "data-encoding", "serde", "serde_json", - "sha2 0.10.9", - "thiserror", + "sha2 0.11.0", + "tinystoragedrivers-api", + "tinystoragedrivers-types", "tokio", "ulid", - "zstd", ] [[package]] name = "tinystoragedrivers-secrets" -version = "1.0.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" dependencies = [ "async-trait", - "atomicwrites", - "chacha20poly1305", - "clack-private-fs", - "fs4", - "hkdf", - "rustix 1.1.4", - "serde", + "tinystoragedrivers-api", + "tinystoragedrivers-types", + "zeroize", +] + +[[package]] +name = "tinystoragedrivers-testkit" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "async-trait", + "bytes", + "futures-util", "serde_json", - "sha2 0.10.9", - "tinystoragedrivers-core", + "tinystoragedrivers-api", + "tinystoragedrivers-blob", + "tinystoragedrivers-document", + "tinystoragedrivers-kv", + "tinystoragedrivers-queue", + "tinystoragedrivers-secrets", + "tinystoragedrivers-types", "tokio", - "winapi-util", - "windows-permissions", - "winsafe", + "ulid", "zeroize", ] +[[package]] +name = "tinystoragedrivers-types" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "tinytemplate" version = "1.2.1" @@ -1850,6 +1916,12 @@ version = "2.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" +[[package]] +name = "typed-path" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" + [[package]] name = "typenum" version = "1.20.1" @@ -1884,16 +1956,6 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" -[[package]] -name = "universal-hash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common 0.1.7", - "subtle", -] - [[package]] name = "untrusted" version = "0.9.0" @@ -1952,6 +2014,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -2050,9 +2118,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -2094,16 +2162,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-permissions" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e2ccdc3c6bf4d4a094e031b63fadd08d8e42abd259940eb8aa5fdc09d4bf9be" -dependencies = [ - "bitflags 1.3.2", - "winapi", -] - [[package]] name = "windows-sys" version = "0.52.0" @@ -2192,12 +2250,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" -[[package]] -name = "winsafe" -version = "0.0.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" - [[package]] name = "wit-bindgen" version = "0.57.1" @@ -2211,7 +2263,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.4", + "rustix", ] [[package]] @@ -2242,19 +2294,16 @@ checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" [[package]] name = "zip" -version = "2.4.2" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror", - "zopfli", + "nix", + "typed-path", ] [[package]] @@ -2263,18 +2312,6 @@ version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" -[[package]] -name = "zopfli" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] - [[package]] name = "zstd" version = "0.13.3" diff --git a/Cargo.toml b/Cargo.toml index c3b2037f..c94dace3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [package] -rust-version = "1.88" +rust-version = "1.90" name = "tinyjuice" version = "0.11.0" edition = "2024" @@ -14,15 +14,14 @@ exclude = [ ".github/", ".gitmodules", "docs/", - "vendor/tinybus/", "vendor/tinyagents/", "crates/tinyjuice-examples/", "wiki/", ] [workspace] -members = ["crates/tinyjuice-bus", "crates/tinyjuice-module", "crates/tinyjuice-drivers", "crates/tinyjuice-host"] -default-members = [".", "crates/tinyjuice-bus", "crates/tinyjuice-module", "crates/tinyjuice-drivers", "crates/tinyjuice-host"] +members = ["crates/tinyjuice-bus", "crates/tinyjuice-module", "crates/tinyjuice-drivers", "crates/tinyjuice-cli", "crates/tinyjuice-host"] +default-members = [".", "crates/tinyjuice-bus", "crates/tinyjuice-module", "crates/tinyjuice-drivers", "crates/tinyjuice-cli", "crates/tinyjuice-host"] exclude = ["vendor/tinybus", "vendor/tinyagents", "crates/tinyjuice-examples"] resolver = "3" @@ -72,28 +71,6 @@ criterion = "0.8" tempfile = "3" tokio = { version = "1", features = ["macros", "rt", "test-util"] } -[[bin]] -name = "tinyjuice" -path = "src/bin/tinyjuice.rs" -required-features = ["cli-disk-tier"] - -[[bin]] -name = "tinyjuice-reduce" -path = "src/main.rs" -required-features = ["cli-disk-tier"] - -# These integration suites launch the CLI binaries, which are unavailable in -# the default host build without the standalone CLI disk-tier feature. -[[test]] -name = "cli" -path = "tests/cli.rs" -required-features = ["cli-disk-tier"] - -[[test]] -name = "host_cli" -path = "tests/host_cli.rs" -required-features = ["cli-disk-tier"] - [[bench]] name = "compression" harness = false @@ -102,9 +79,6 @@ harness = false default = ["tinyjuice-treesitter"] # Exposes the REPL ops as `tinytools::Tool` impls (see src/repl/tools.rs). tinytools = ["dep:tinytools", "dep:anyhow", "jq"] -# File-backed CCR cache commands for the standalone CLI only. Hosts use their -# own durable CcrStore implementation through the storage bus. -cli-disk-tier = [] # jq-style queries over JSON outputs (the `jq` REPL op and `juice_jq` tool). jq = ["dep:jaq-core", "dep:jaq-std", "dep:jaq-json"] tinyjuice-treesitter = [ @@ -122,15 +96,3 @@ strip = "debuginfo" [[example]] name = "repl_tool_schema" required-features = ["tinytools"] - -# tinystoragedrivers names tinybus by git rev; point that source at the same -# vendored checkout so the module and the storage proxy share one `Connection`. -[patch."https://github.com/tinyhumansai/tinybus"] -tinybus = { path = "vendor/tinybus/crates/tinybus" } - -# tinybus is not on crates.io; modules name it by version range so a host can -# unify it, and standalone builds resolve it to the nested checkout. -[patch.crates-io] -tinybus = { path = "vendor/tinybus/crates/tinybus" } -tinybus-module = { path = "vendor/tinybus/crates/tinybus-module" } -tinybus-macros = { path = "vendor/tinybus/crates/tinybus-macros" } diff --git a/README.md b/README.md index 7aa31fd5..05f80d3a 100644 --- a/README.md +++ b/README.md @@ -230,25 +230,25 @@ tool-output adapter leaves the output unchanged and reports Install the CLI: ```sh -cargo install tinyjuice --features cli-disk-tier --locked +cargo install --path crates/tinyjuice-cli --locked --bin tinyjuice ``` Run the minimal reducer CLI: ```sh -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- reduce --tool-name bash --command "git status" status.txt -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- reduce-json payload.json -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- verify --rules --fixtures -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- discover executions.ndjson -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- wrap -- cargo test -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- ls --store-dir .tokenjuice/ccr -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- cat --store-dir .tokenjuice/ccr -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- stats --store-dir .tokenjuice/ccr -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- doctor --store-dir .tokenjuice/ccr -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- doctor codex -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- doctor hooks -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- install codex --local target/debug/tinyjuice -cargo run --features cli-disk-tier --bin tinyjuice-reduce -- uninstall codex +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- reduce --tool-name bash --command "git status" status.txt +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- reduce-json payload.json +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- verify --rules --fixtures +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- discover executions.ndjson +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- wrap -- cargo test +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- ls --store-dir .tokenjuice/ccr +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- cat --store-dir .tokenjuice/ccr +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- stats --store-dir .tokenjuice/ccr +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- doctor --store-dir .tokenjuice/ccr +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- doctor codex +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- doctor hooks +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- install codex --local target/debug/tinyjuice +cargo run --manifest-path crates/tinyjuice-cli/Cargo.toml --bin tinyjuice-reduce -- uninstall codex ``` Run hot-path benchmarks: @@ -280,18 +280,17 @@ helpers still use the process-global `GlobalCcrStore` for compatibility. New tests and host adapters can use `MemoryCcrStore` to assert CCR behavior without touching the global cache. -The standalone CLI's `ls`, `cat`, `stats`, and `gc` commands are compiled with -the opt-in `cli-disk-tier` feature; `ls`, `cat`, and `stats` can inspect an -explicit directory with `--store-dir`. `gc` and normal CLI or hook compression -runs use `TINYJUICE_CCR_DIR`, falling back to the platform cache directory. -Library and hosted module builds do not contain this tier. It is a disposable -recovery cache, not durable user data. Hosted persistence is owned by the host's -BlobCcrStore. Existing standalone cache files are not imported into hosted -storage. The REPL's former `repl_save_dir` text snapshots are no longer written; -the CCR token and its configured store are authoritative. TinyBus contract 3.0 -rejects 2.x hosts because the old disk-path request cannot express host -durability. These commands do not imply access to another process's in-memory -cache. `cat` supports +The standalone CLI lives in the separate `tinyjuice-cli` package and uses a +host-composed file blob store for `ls`, `cat`, `stats`, and `gc`; the library +and hosted module contain no file-backed persistence tier. These commands can +inspect an explicit directory with `--store-dir`, while normal CLI and hook +compression runs use `TINYJUICE_CCR_DIR` or the platform cache directory. It is +a disposable recovery cache, not durable user data. Hosted persistence is +owned by the host's BlobCcrStore. Existing standalone cache files are imported +by the CLI into its configured store. The REPL's former `repl_save_dir` text +snapshots are no longer written; the CCR token and its configured store are +authoritative. These commands do not imply access to another process's +in-memory cache. `cat` supports `--lines START:END` and `--bytes START:END` ranges. `stats` reports metadata-only counts and byte totals without reading token content. diff --git a/crates/tinyjuice-bus/Cargo.toml b/crates/tinyjuice-bus/Cargo.toml index 113eec81..d4ddea9d 100644 --- a/crates/tinyjuice-bus/Cargo.toml +++ b/crates/tinyjuice-bus/Cargo.toml @@ -1,5 +1,5 @@ [package] -rust-version = "1.88" +rust-version = "1.90" name = "tinyjuice-bus" version = "0.11.0" edition = "2024" @@ -19,14 +19,10 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" # Shared REPL error vocabulary; no execution dependencies. thiserror = "2" -# Optional (`storage` feature, off by default). Storage ports only (no I/O or runtime of its own): the schema the host composes -# lives in the contract so the host never links the implementation crate. -tinystoragedrivers-core = { version = "1.0.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, optional = true } +tinystoragedrivers-types = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } [features] default = [] -# `storage_schema()` for the host's schema composition. Hosts enable this. -storage = ["dep:tinystoragedrivers-core"] [dev-dependencies] # The migration tests run the schema over the in-memory backend. diff --git a/crates/tinyjuice-bus/src/lib.rs b/crates/tinyjuice-bus/src/lib.rs index 89a0fbec..e35a6173 100644 --- a/crates/tinyjuice-bus/src/lib.rs +++ b/crates/tinyjuice-bus/src/lib.rs @@ -15,7 +15,6 @@ pub mod handle; pub mod names; pub mod repl; pub mod savings; -#[cfg(feature = "storage")] pub mod storage; pub mod summary; pub mod tools; diff --git a/crates/tinyjuice-bus/src/lib_tests.rs b/crates/tinyjuice-bus/src/lib_tests.rs index 2940a342..fa34535e 100644 --- a/crates/tinyjuice-bus/src/lib_tests.rs +++ b/crates/tinyjuice-bus/src/lib_tests.rs @@ -4,7 +4,7 @@ use super::*; #[test] fn the_contract_accepts_newer_minors_and_rejects_the_breaking_v2_contract() { - assert_eq!(CONTRACT_VERSION, (3, 0)); + assert_eq!(CONTRACT_VERSION, (3, 1)); assert!(is_compatible(CONTRACT_VERSION)); assert!(is_compatible((3, 1))); assert!( @@ -73,6 +73,39 @@ fn the_wire_envelopes_keep_their_json_contract() { ); } +#[test] +fn request_local_savings_import_address_is_a_transport_only_descriptor() { + use savings::{ImportSavingsAtRequest, SavingsAggregate, StorageCallbackAddress}; + + let request = ImportSavingsAtRequest { + aggregate: SavingsAggregate::default(), + callback: StorageCallbackAddress { + host: ":1.42".to_owned(), + object_root: "/ai/tinyhumans/tinystorage/Invocation/abc".to_owned(), + }, + }; + let encoded = serde_json::to_value(&request).unwrap(); + assert_eq!(encoded["callback"]["host"], ":1.42"); + assert_eq!( + encoded["callback"]["object_root"], + "/ai/tinyhumans/tinystorage/Invocation/abc" + ); + let decoded: ImportSavingsAtRequest = serde_json::from_value(encoded.clone()).unwrap(); + assert_eq!(decoded.callback.host, ":1.42"); + assert_eq!( + decoded.callback.object_root, + "/ai/tinyhumans/tinystorage/Invocation/abc" + ); + assert!( + serde_json::from_value::({ + let mut value = encoded; + value["callback"]["write_condition"] = serde_json::json!("must-not-cross-the-bus"); + value + }) + .is_err() + ); +} + #[test] fn compress_options_round_trip_through_their_defaults() { // `CompressOptions` is `#[serde(default)]`, which is what lets a host send diff --git a/crates/tinyjuice-bus/src/names.rs b/crates/tinyjuice-bus/src/names.rs index 13de1295..e554f054 100644 --- a/crates/tinyjuice-bus/src/names.rs +++ b/crates/tinyjuice-bus/src/names.rs @@ -52,6 +52,9 @@ pub mod methods { /// when the module has recorded nothing yet; answers whether it took it. /// Added in contract 2.3. pub const IMPORT_SAVINGS: &str = "ImportSavings"; + /// Adopts legacy totals through an invocation-scoped host storage callback. + /// Added in contract 3.1. + pub const IMPORT_SAVINGS_AT: &str = "ImportSavingsAt"; /// Reports what the cache is holding. pub const CACHE_STATS: &str = "CacheStats"; } @@ -83,4 +86,5 @@ pub const METHODS: &[&str] = &[ methods::SAVINGS_STATS, methods::RESET_SAVINGS, methods::IMPORT_SAVINGS, + methods::IMPORT_SAVINGS_AT, ]; diff --git a/crates/tinyjuice-bus/src/savings.rs b/crates/tinyjuice-bus/src/savings.rs index 6b6dcb9e..09c07674 100644 --- a/crates/tinyjuice-bus/src/savings.rs +++ b/crates/tinyjuice-bus/src/savings.rs @@ -31,6 +31,30 @@ pub struct SavingsAggregate { pub by_compressor: HashMap, } +/// A callback storage endpoint that a host grants for one import invocation. +/// +/// The host name must be the unique name of the attested callback connection; +/// `object_root` must identify that invocation's isolated object subtree. The +/// address contains no storage policy or write condition. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StorageCallbackAddress { + /// Unique TinyBus name serving this callback. + pub host: String, + /// Per-invocation TinyBus object root served by `host`. + pub object_root: String, +} + +/// A savings snapshot plus a temporary callback destination for adoption. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ImportSavingsAtRequest { + /// The legacy savings snapshot to adopt if the destination has no totals. + pub aggregate: SavingsAggregate, + /// Host-created callback authority, valid only while the import call runs. + pub callback: StorageCallbackAddress, +} + /// One compaction attributed to the model that would consume its output. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/tinyjuice-bus/src/storage.rs b/crates/tinyjuice-bus/src/storage.rs index 3540c589..362f33e3 100644 --- a/crates/tinyjuice-bus/src/storage.rs +++ b/crates/tinyjuice-bus/src/storage.rs @@ -1,65 +1,20 @@ -//! What TinyJuice stores, as a schema the host composes. -//! -//! The savings totals are one document in `juice.savings`. -//! -//! The CCR store's originals are blobs under `juice/ccr/`. The module -//! runs for one tenant at a time, so they live at [`ScopeClass::Module`], and a -//! host derives the module's storage grant from this schema rather than -//! spelling the prefix out a second time. -//! -//! Before schema v2 the same blobs lived under `tinyjuice_ccr/`. One -//! blob step moves them; the bytes and content type are untouched. The steps -//! are pure: no I/O happens until the host's registry runs them. +//! TinyJuice's storage vocabulary for hosts composing its owner ports. -use tinystoragedrivers_core::Result; -use tinystoragedrivers_core::schema::{BlobOutput, Owner, Schema, ScopeClass, Step}; +use tinystoragedrivers_types::CollectionSpec; -/// Where the CCR store keeps originals, `juice/ccr/` (no trailing slash). -pub const CCR_PREFIX: &str = "juice/ccr"; +/// CCR originals retain the released `tinyjuice_ccr/` blob keys. +pub const CCR_PREFIX: &str = "tinyjuice_ccr"; -/// The savings totals: one document (`savings::SAVINGS_DOC_ID`) per module -/// scope, a snake_case body with `updated_ms`. Schema v2 introduced it; before -/// that the host kept `state/tokenjuice_savings.json`. +/// The owner-scoped savings totals document collection. pub const SAVINGS_COLLECTION: &str = "juice.savings"; -/// Where schema v1 kept the originals, `tinyjuice_ccr/`. -const LEGACY_PREFIX: &str = "tinyjuice_ccr/"; - -/// The schema owner, and the first path segment of every blob key. -const OWNER: &str = "juice"; - -/// Everything TinyJuice stores, for the host's `Registry::compose`. +/// Collections a host should provision when it composes TinyJuice storage. /// -/// # Panics -/// -/// Never in practice: the owner name is a constant that satisfies the owner -/// grammar, which the tests pin. +/// Blob prefixes are provisioned by the blob engine itself; only document +/// collections need a declaration in this vocabulary. #[must_use] -pub fn storage_schema() -> Schema { - let prefix = format!("{CCR_PREFIX}/"); - Schema::new(Owner::new(OWNER).expect("`juice` is a valid schema owner")) - .blobs(&prefix, ScopeClass::Module) - .collection(SAVINGS_COLLECTION, 1, ScopeClass::Module) - .step(ccr_prefix_step()) -} - -/// v1 to v2: `tinyjuice_ccr/` becomes `juice/ccr/`. -fn ccr_prefix_step() -> Step { - Step::blobs("ccr_prefix_v2", "juice/ccr/", 1, 2, move_ccr_blob).source_prefix(LEGACY_PREFIX) -} - -/// One blob of the v1 prefix, re-keyed. Bytes and content type are untouched. -fn move_ccr_blob( - key: String, - content_type: Option, - bytes: Vec, -) -> Result> { - // The runner lists by the legacy prefix, so every key carries it; a key - // that somehow does not has nothing to move. - let Some(rest) = key.strip_prefix(LEGACY_PREFIX) else { - return Ok(None); - }; - Ok(Some((format!("{CCR_PREFIX}/{rest}"), content_type, bytes))) +pub fn collections() -> Vec { + vec![CollectionSpec::new(SAVINGS_COLLECTION)] } #[cfg(test)] diff --git a/crates/tinyjuice-bus/src/storage_tests.rs b/crates/tinyjuice-bus/src/storage_tests.rs index 40cbf167..236f840d 100644 --- a/crates/tinyjuice-bus/src/storage_tests.rs +++ b/crates/tinyjuice-bus/src/storage_tests.rs @@ -1,111 +1,9 @@ use super::*; -use tinystoragedrivers_core::schema::{Item, MigrateOptions, Registry, ScopeClass}; -use tinystoragedrivers_core::{MemoryStorage, Scope, StorageBackend}; - -const LEGACY: &str = "tinyjuice_ccr/"; - -#[test] -fn the_schema_declares_the_ccr_blobs_and_the_savings_collection_at_module_scope() { - let schema = storage_schema(); - let items: Vec<_> = schema.items.iter().collect(); - assert_eq!(items.len(), 2, "CCR blobs and savings are all juice stores"); - match items[0] { - Item::Blobs { prefix, scope } => { - assert_eq!(prefix, "juice/ccr/"); - assert_eq!(*scope, ScopeClass::Module); - } - other => panic!("expected a blob prefix, got {other:?}"), - } - match items[1] { - Item::Collection { - name, - version, - scope, - .. - } => { - assert_eq!(name, "juice.savings"); - assert_eq!(*version, 1); - assert_eq!(*scope, ScopeClass::Module); - } - other => panic!("expected the savings collection, got {other:?}"), - } - assert!( - format!("{CCR_PREFIX}/token").starts_with("juice/ccr/"), - "keys the store writes sit under the declared prefix" - ); - Registry::compose([schema]).expect("the schema composes"); -} - -#[tokio::test] -async fn migration_moves_v1_ccr_blobs_under_the_v2_prefix() { - let backend = MemoryStorage::new(); - let storage = backend.for_scope(&Scope::local()).unwrap(); - let blobs = storage.blobs(); - blobs - .put( - "tinyjuice_ccr/0123456789abcdef", - b"original text".to_vec(), - Some("text/plain; charset=utf-8"), - ) - .await - .unwrap(); - blobs - .put("tinyjuice_ccr/fedcba9876543210", b"two".to_vec(), None) - .await - .unwrap(); - // Not ours: must be left alone. - blobs - .put("other/keep", b"keep".to_vec(), None) - .await - .unwrap(); - - let registry = Registry::compose([storage_schema()]).unwrap(); - let report = registry - .migrate(&storage, &MigrateOptions::new()) - .await - .unwrap(); - assert_eq!(report.ran[0].written, 2); - - assert!(blobs.list(LEGACY).await.unwrap().is_empty()); - let moved = blobs - .get("juice/ccr/0123456789abcdef") - .await - .unwrap() - .unwrap(); - assert_eq!(moved.bytes, b"original text"); - assert_eq!( - moved.meta.content_type.as_deref(), - Some("text/plain; charset=utf-8") - ); - let moved = blobs - .get("juice/ccr/fedcba9876543210") - .await - .unwrap() - .unwrap(); - assert_eq!(moved.meta.content_type, None); - assert!(blobs.get("other/keep").await.unwrap().is_some()); - - let again = registry - .migrate(&storage, &MigrateOptions::new()) - .await - .unwrap(); - assert!(again.ran.is_empty(), "a finished step does not run again"); -} #[test] -fn a_key_outside_the_legacy_prefix_has_nothing_to_move() { - let moved = move_ccr_blob("elsewhere/x".into(), None, b"x".to_vec()).unwrap(); - assert!(moved.is_none()); - let (key, content_type, bytes) = move_ccr_blob( - "tinyjuice_ccr/ab".into(), - Some("text/plain".into()), - b"x".to_vec(), - ) - .unwrap() - .unwrap(); - assert_eq!(key, "juice/ccr/ab"); - assert_eq!(content_type.as_deref(), Some("text/plain")); - assert_eq!(bytes, b"x"); +fn owner_collections_declare_savings_without_engine_or_migration_policy() { + assert_eq!(collections(), vec![CollectionSpec::new("juice.savings")]); + assert_eq!(CCR_PREFIX, "tinyjuice_ccr"); } #[test] diff --git a/crates/tinyjuice-bus/src/version.rs b/crates/tinyjuice-bus/src/version.rs index 6b63d954..f01cdad0 100644 --- a/crates/tinyjuice-bus/src/version.rs +++ b/crates/tinyjuice-bus/src/version.rs @@ -2,9 +2,11 @@ /// The wire contract version this crate defines. /// Version 3 removes the host-provided disk path and replaces it with an -/// explicit host-durability capability. Version 2 hosts must be rejected so -/// their old `diskTierRoot` request cannot silently lose its persistence. -pub const CONTRACT_VERSION: (u32, u32) = (3, 0); +/// explicit host-durability capability. Minor version 1 adds the +/// invocation-scoped savings-import callback while retaining the old import +/// method. Version 2 hosts must be rejected so their old `diskTierRoot` +/// request cannot silently lose its persistence. +pub const CONTRACT_VERSION: (u32, u32) = (3, 1); /// Returns whether a host using [`CONTRACT_VERSION`] can bind to `module`. /// diff --git a/crates/tinyjuice-cli/Cargo.toml b/crates/tinyjuice-cli/Cargo.toml new file mode 100644 index 00000000..c6c00b22 --- /dev/null +++ b/crates/tinyjuice-cli/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "tinyjuice-cli" +version = "0.11.0" +edition = "2024" +rust-version = "1.90" +publish = false +license = "GPL-3.0-only" +description = "Standalone TinyJuice command-line tools." +repository = "https://github.com/tinyhumansai/tinyjuice" + +[dependencies] +tinyjuice = { path = "../.." } +tinyjuice-drivers = { path = "../tinyjuice-drivers" } +tinystoragedrivers = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456", features = ["file"] } +tinystoragedrivers-api = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +tinystoragedrivers-types = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +dirs = "7" +log = "0.4" +serde_json = "1" +tokio = { version = "1", features = ["rt-multi-thread"] } + +[dev-dependencies] +async-trait = "0.1" +tempfile = "3" +tinystoragedrivers-testkit = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } + +[[bin]] +name = "tinyjuice" +path = "src/bin/tinyjuice.rs" +doc = false + +[[bin]] +name = "tinyjuice-reduce" +path = "src/bin/tinyjuice-reduce.rs" diff --git a/src/main.rs b/crates/tinyjuice-cli/src/bin/tinyjuice-reduce.rs similarity index 97% rename from src/main.rs rename to crates/tinyjuice-cli/src/bin/tinyjuice-reduce.rs index cc47989c..33b64633 100644 --- a/src/main.rs +++ b/crates/tinyjuice-cli/src/bin/tinyjuice-reduce.rs @@ -10,6 +10,10 @@ use tinyjuice::{ load_builtin_rules, reduce_execution_with_rules, reduce_json_str, verify_rule_fixtures, verify_rules, }; +use tinyjuice_drivers::CCR_PREFIX; + +#[path = "../storage.rs"] +mod storage; const TINYJUICE_MANAGED_BEGIN: &str = ""; const TINYJUICE_MANAGED_END: &str = ""; @@ -747,7 +751,12 @@ fn run_cat(args: &[String]) -> Result<(), String> { return Err("cat token must be a 32-character hex CCR token".to_owned()); } - tinyjuice::cache::enable_disk_tier(store_dir); + tinyjuice::cache::configure( + tinyjuice::cache::DEFAULT_MAX_ENTRIES, + tinyjuice::cache::DEFAULT_MAX_BYTES, + None, + ); + storage::configure(&store_dir, storage::configured_ttl(), None)?; let content = match range { Some((unit, (start, end))) => tinyjuice::cache::retrieve_range(&token, start, end, unit), None => tinyjuice::cache::retrieve(&token), @@ -809,37 +818,24 @@ struct CcrStoreEntry { } fn read_ccr_store_inventory(store_dir: &Path) -> Result { - let mut entries = Vec::new(); - let mut ignored_entries = 0; - - for entry in fs::read_dir(store_dir) - .map_err(|error| format!("failed to read {}: {error}", store_dir.display()))? - { - let entry = entry.map_err(|error| format!("failed to read store entry: {error}"))?; - if !entry - .file_type() - .map_err(|error| format!("failed to inspect store entry: {error}"))? - .is_file() - { - ignored_entries += 1; - continue; - } - let name = entry.file_name().to_string_lossy().into_owned(); - if is_cli_ccr_token(&name) { - let bytes = entry - .metadata() - .map_err(|error| format!("failed to inspect store entry {name}: {error}"))? - .len(); - entries.push(CcrStoreEntry { token: name, bytes }); - } else { - ignored_entries += 1; - } - } - - entries.sort_by(|left, right| left.token.cmp(&right.token)); + let inventory = storage::inventory(store_dir, storage::configured_ttl())?; + let entries = inventory + .entries + .into_iter() + .filter_map(|entry| { + let token = entry + .key + .strip_prefix(&format!("{CCR_PREFIX}/"))? + .to_owned(); + is_cli_ccr_token(&token).then_some(CcrStoreEntry { + token, + bytes: entry.len, + }) + }) + .collect(); Ok(CcrStoreInventory { entries, - ignored_entries, + ignored_entries: inventory.ignored_entries, }) } @@ -1305,5 +1301,5 @@ fn print_uninstall_usage() { } #[cfg(test)] -#[path = "main_tests.rs"] +#[path = "tinyjuice-reduce/tinyjuice_reduce_tests.rs"] mod tests; diff --git a/src/main_tests.rs b/crates/tinyjuice-cli/src/bin/tinyjuice-reduce/tinyjuice_reduce_tests.rs similarity index 98% rename from src/main_tests.rs rename to crates/tinyjuice-cli/src/bin/tinyjuice-reduce/tinyjuice_reduce_tests.rs index f1897799..e8be2104 100644 --- a/src/main_tests.rs +++ b/crates/tinyjuice-cli/src/bin/tinyjuice-reduce/tinyjuice_reduce_tests.rs @@ -225,7 +225,9 @@ fn install_and_uninstall_dispatch_with_explicit_host_paths() { #[test] fn store_inventory_counts_only_tokens_and_stats_formats_both_modes() { let dir = tempfile::tempdir().unwrap(); - fs::write(dir.path().join("a".repeat(32)), "original").unwrap(); + let content = "original"; + let token = tinyjuice::cache::short_hash(content); + fs::write(dir.path().join(token), content).unwrap(); fs::write(dir.path().join("notes"), "unrelated").unwrap(); fs::create_dir(dir.path().join("nested")).unwrap(); let inventory = read_ccr_store_inventory(dir.path()).unwrap(); diff --git a/src/bin/tinyjuice.rs b/crates/tinyjuice-cli/src/bin/tinyjuice.rs similarity index 97% rename from src/bin/tinyjuice.rs rename to crates/tinyjuice-cli/src/bin/tinyjuice.rs index ad5a24f9..38fbcd59 100644 --- a/src/bin/tinyjuice.rs +++ b/crates/tinyjuice-cli/src/bin/tinyjuice.rs @@ -11,6 +11,9 @@ use tinyjuice::{ host_install_specs, host_template, request_from_json_value, }; +#[path = "../storage.rs"] +mod storage; + const SUPPORT_GIT_TRAILER: &str = "Co-Authored-By: TinyJuice "; const CODEX_SUPPORT_ATTRIBUTION: &str = "TinyJuice "; const CLAUDE_DEFAULT_COMMIT_ATTRIBUTION: &str = @@ -75,7 +78,6 @@ fn run() -> Result<(), String> { } fn reduce_json(args: Vec) -> Result<(), String> { - configure_cli_cache(); let mut host_override = None; let mut path = None; let mut index = 0; @@ -108,6 +110,7 @@ fn reduce_json(args: Vec) -> Result<(), String> { } } + configure_cli_cache()?; let input = read_input(path.as_deref())?; let value = serde_json::from_str(&input).map_err(|error| format!("invalid JSON: {error}"))?; let mut request = request_from_json_value(value).map_err(|error| error.to_string())?; @@ -128,8 +131,13 @@ fn reduce_json(args: Vec) -> Result<(), String> { } fn post_tool_use_hook(host: TinyJuiceHost) -> Result<(), String> { - configure_cli_cache(); let input = read_input(None)?; + if configure_cli_cache().is_err() { + // A hook runs as a short-lived process, so its in-memory CCR entries + // would disappear before the host can retrieve them. Preserve the + // original tool output when durable recovery is unavailable. + return Ok(()); + } let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -524,13 +532,13 @@ fn finish_toml_lines(lines: Vec) -> String { } fn retrieve_command(args: Vec) -> Result<(), String> { - configure_cli_cache(); let token = args .first() .ok_or_else(|| "retrieve requires a CCR token".to_string())?; if args.len() > 1 { return Err("retrieve accepts exactly one CCR token".to_string()); } + configure_cli_cache()?; let Some(original) = tinyjuice::cache::retrieve(token) else { return Err(format!("no original found for token {token}")); }; @@ -592,16 +600,15 @@ fn gc_command(args: Vec) -> Result<(), String> { }; let root = cli_cache_root(); - let stats = - tinyjuice::cache::gc_disk_dir(&root, ttl.map(std::time::Duration::from_secs), budget) - .map_err(|error| error.to_string())?; + let (removed, freed_bytes, kept, kept_bytes) = + storage::collect(&root, ttl.map(std::time::Duration::from_secs), budget)?; println!( "gc {}: removed {} entries, freed {} bytes, kept {} ({} bytes)", root.display(), - stats.removed, - stats.freed_bytes, - stats.kept, - stats.kept_bytes + removed, + freed_bytes, + kept, + kept_bytes ); Ok(()) } @@ -693,11 +700,14 @@ fn cli_cache_limits_from_env() -> (usize, usize, Option) { ) } -fn configure_cli_cache() { +fn configure_cli_cache() -> Result<(), String> { let (max_entries, max_bytes, ttl_secs) = cli_cache_limits_from_env(); tinyjuice::cache::configure(max_entries, max_bytes, ttl_secs); - tinyjuice::cache::configure_disk_cap(Some(max_bytes as u64)); - tinyjuice::cache::enable_disk_tier(cli_cache_root()); + storage::configure( + &cli_cache_root(), + ttl_secs.map(std::time::Duration::from_secs), + Some(max_bytes as u64), + ) } fn cli_cache_root() -> PathBuf { diff --git a/src/bin/tinyjuice/tinyjuice_tests.rs b/crates/tinyjuice-cli/src/bin/tinyjuice/tinyjuice_tests.rs similarity index 100% rename from src/bin/tinyjuice/tinyjuice_tests.rs rename to crates/tinyjuice-cli/src/bin/tinyjuice/tinyjuice_tests.rs diff --git a/crates/tinyjuice-cli/src/storage.rs b/crates/tinyjuice-cli/src/storage.rs new file mode 100644 index 00000000..585baf7a --- /dev/null +++ b/crates/tinyjuice-cli/src/storage.rs @@ -0,0 +1,1093 @@ +//! CLI-owned composition of CCR over Tiny Storage Drivers' file backend. + +use std::collections::{HashMap, HashSet}; +use std::fs::{File, OpenOptions}; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use tinyjuice::cache::{CcrPutResult, CcrStore, set_durable_tier}; +use tinyjuice_drivers::{BlobCcrStore, CCR_PREFIX}; +use tinystoragedrivers::{Scope, StorageConfig, open}; +use tinystoragedrivers_api::BlobStore; +use tinystoragedrivers_types::BlobMeta; + +const PAGE_SIZE: usize = 1000; +const DEFAULT_CLI_CCR_TTL_SECS: u64 = 7 * 24 * 60 * 60; +// The blob port has no caller metadata field. Keep legacy/file write chronology +// in a sibling key so the raw CCR body and its content token remain unchanged. +const CCR_METADATA_PREFIX: &str = "tinyjuice/ccr-metadata/"; +const CCR_METADATA_CONTENT_TYPE: &str = "application/vnd.tinyjuice.ccr-metadata"; +const CCR_IMPORT_PREFIX: &str = "tinyjuice/ccr-import-intent/"; +const CCR_STORAGE_CONFIGURATION_KEY: &str = "tinyjuice/ccr-config/applied-storage"; + +#[allow(dead_code)] // The reducer binary uses inventory; the hook binary shares this module. +pub(crate) struct Inventory { + pub entries: Vec, + pub ignored_entries: usize, +} + +struct PruneReport { + removed: usize, + bytes_freed: u64, + kept: usize, + kept_bytes: u64, +} + +struct ConfigureReport { + legacy_removed: usize, + legacy_bytes: u64, + pruned: PruneReport, +} + +pub(crate) fn configure( + root: &Path, + ttl: Option, + max_bytes: Option, +) -> Result<(), String> { + configure_with_report(root, ttl, max_bytes).map(|_| ()) +} + +fn configure_with_report( + root: &Path, + ttl: Option, + max_bytes: Option, +) -> Result { + std::fs::create_dir_all(root).map_err(|error| { + format!( + "cannot create CCR storage directory {}: {error}", + root.display() + ) + })?; + let blobs = open_file_blobs(root)?; + let _lock = acquire_process_lock(&process_lock_path(root))?; + let discarded_legacy = import_legacy_files(root, &blobs, ttl)?; + let store = BlobCcrStore::new(Arc::clone(&blobs), ttl).map_err(|error| error.to_string())?; + reapply_existing_blob_ttl_if_changed(&blobs, ttl, max_bytes)?; + let capped = CappedCcrStore { + store, + blobs: Arc::clone(&blobs), + lock_path: process_lock_path(root), + ttl, + max_bytes, + }; + let pruned = if ttl.is_some() || max_bytes.is_some() { + let (removed, bytes_freed, kept, kept_bytes) = prune(&blobs, ttl, max_bytes, None)?; + PruneReport { + removed, + bytes_freed, + kept, + kept_bytes, + } + } else { + PruneReport { + removed: 0, + bytes_freed: 0, + kept: 0, + kept_bytes: 0, + } + }; + set_durable_tier(Some(Arc::new(capped))); + Ok(ConfigureReport { + legacy_removed: discarded_legacy.0, + legacy_bytes: discarded_legacy.1, + pruned, + }) +} + +#[allow(dead_code)] // The reducer binary uses inventory; the hook binary shares this module. +pub(crate) fn inventory(root: &Path, ttl: Option) -> Result { + if !root.is_dir() { + return Err(format!( + "CCR storage directory does not exist: {}", + root.display() + )); + } + let mut ignored_entries = 0; + for entry in std::fs::read_dir(root).map_err(|error| { + format!( + "failed to inspect CCR storage directory {}: {error}", + root.display() + ) + })? { + let entry = entry.map_err(|error| format!("failed to inspect CCR entry: {error}"))?; + if entry.file_name() == "scopes" { + continue; + } + if !entry + .file_type() + .map_err(|error| format!("failed to inspect CCR entry type: {error}"))? + .is_file() + || !is_token(&entry.file_name().to_string_lossy()) + { + ignored_entries += 1; + } + } + configure(root, ttl, None)?; + let blobs = open_file_blobs(root)?; + let mut entries = Vec::new(); + let mut after = None; + loop { + let page = run_blob({ + let after = after.clone(); + let blobs = Arc::clone(&blobs); + async move { + blobs + .list_page(&format!("{CCR_PREFIX}/"), after.as_deref(), PAGE_SIZE) + .await + } + })?; + entries.extend(page.items.into_iter().map(|item| item.meta)); + after = page.next_after; + if after.is_none() { + break; + } + } + Ok(Inventory { + entries, + ignored_entries, + }) +} + +#[allow(dead_code)] // The reducer binary shares this storage module. +pub(crate) fn configured_ttl() -> Option { + let seconds = std::env::var("TINYJUICE_CCR_TTL_SECS") + .ok() + .and_then(|value| value.trim().parse::().ok()) + .unwrap_or(DEFAULT_CLI_CCR_TTL_SECS); + (seconds > 0).then(|| Duration::from_secs(seconds)) +} + +#[allow(dead_code)] // The hook binary shares this CLI-only collector. +pub(crate) fn collect( + root: &Path, + ttl: Option, + max_bytes: Option, +) -> Result<(usize, u64, usize, u64), String> { + let report = configure_with_report(root, ttl, max_bytes)?; + let pruned = if ttl.is_some() || max_bytes.is_some() { + report.pruned + } else { + let blobs = open_file_blobs(root)?; + let remaining = list_all(blobs)?; + PruneReport { + removed: 0, + bytes_freed: 0, + kept: remaining.len(), + kept_bytes: remaining.iter().map(|entry| entry.meta.len).sum(), + } + }; + Ok(( + report.legacy_removed.saturating_add(pruned.removed), + report.legacy_bytes.saturating_add(pruned.bytes_freed), + pruned.kept, + pruned.kept_bytes, + )) +} + +fn prune( + blobs: &Arc, + ttl: Option, + max_bytes: Option, + protect: Option<&str>, +) -> Result<(usize, u64, usize, u64), String> { + run_blob({ + let blobs = Arc::clone(blobs); + let protect = protect.map(str::to_owned); + async move { prune_async(blobs, ttl, max_bytes, protect.as_deref()).await } + }) +} + +fn reapply_existing_blob_ttl_if_changed( + blobs: &Arc, + ttl: Option, + max_bytes: Option, +) -> Result<(), String> { + let ttl_signature = ttl_signature(ttl); + let signature = storage_configuration_signature(ttl, max_bytes); + let key = CCR_STORAGE_CONFIGURATION_KEY.to_owned(); + let existing = run_blob({ + let blobs = Arc::clone(blobs); + let key = key.clone(); + async move { blobs.get(&key).await } + })?; + let existing_signature = existing.map(|blob| String::from_utf8_lossy(&blob.bytes).into_owned()); + let existing_ttl_signature = existing_signature + .as_deref() + .map(|value| value.split('|').next().unwrap_or(value)); + if existing_ttl_signature != Some(ttl_signature.as_str()) { + reapply_existing_blob_ttl(blobs, ttl)?; + } + + if existing_signature.as_deref() == Some(signature.as_str()) { + return Ok(()); + } + run_blob({ + let blobs = Arc::clone(blobs); + async move { + blobs + .put(&key, signature.into_bytes(), None) + .await + .map(|_| ()) + } + }) +} + +fn ttl_signature(ttl: Option) -> String { + match ttl { + Some(ttl) => format!("{}.{:09}", ttl.as_secs(), ttl.subsec_nanos()), + None => "disabled".to_owned(), + } +} + +fn storage_configuration_signature(ttl: Option, max_bytes: Option) -> String { + let max_bytes = max_bytes.map_or_else(|| "unlimited".to_owned(), |value| value.to_string()); + format!("{}|{max_bytes}", ttl_signature(ttl)) +} + +fn stored_configuration_matches( + blobs: &Arc, + ttl: Option, + max_bytes: Option, +) -> Result { + let key = CCR_STORAGE_CONFIGURATION_KEY.to_owned(); + let signature = storage_configuration_signature(ttl, max_bytes); + let existing = run_blob({ + let blobs = Arc::clone(blobs); + async move { blobs.get(&key).await } + })?; + Ok(existing.is_none_or(|blob| blob.bytes == signature.as_bytes())) +} + +fn reapply_existing_blob_ttl( + blobs: &Arc, + ttl: Option, +) -> Result<(), String> { + run_blob({ + let blobs = Arc::clone(blobs); + async move { + let body_prefix = format!("{CCR_PREFIX}/"); + let bodies = list_all_prefix_async(Arc::clone(&blobs), &body_prefix).await?; + let semantic_times = + list_timestamps_async(Arc::clone(&blobs), CCR_METADATA_PREFIX).await?; + let now = SystemTime::now(); + + for entry in bodies { + let Some(token) = entry.meta.key.strip_prefix(&body_prefix) else { + continue; + }; + let Some(body) = blobs + .get(&entry.meta.key) + .await + .map_err(|error| error.to_string())? + else { + continue; + }; + let written_at_ms = semantic_times + .get(token) + .copied() + .or(entry.written_at_ms) + .unwrap_or_else(|| unix_epoch_ms(now)); + if !semantic_times.contains_key(token) { + refresh_blob_expiry_async( + Arc::clone(&blobs), + &format!("{CCR_METADATA_PREFIX}{token}"), + written_at_ms.to_string().into_bytes(), + Some(CCR_METADATA_CONTENT_TYPE), + Some(written_at_ms), + ttl, + now, + ) + .await?; + } + refresh_blob_expiry_async( + Arc::clone(&blobs), + &entry.meta.key, + body.bytes, + body.meta.content_type.as_deref(), + Some(written_at_ms), + ttl, + now, + ) + .await?; + } + + for prefix in [CCR_METADATA_PREFIX, CCR_IMPORT_PREFIX] { + let entries = list_all_prefix_async(Arc::clone(&blobs), prefix).await?; + for entry in entries { + let Some(token) = entry.meta.key.strip_prefix(prefix) else { + continue; + }; + if !is_token(token) { + continue; + } + let Some(sidecar) = blobs + .get(&entry.meta.key) + .await + .map_err(|error| error.to_string())? + else { + continue; + }; + let Ok(written_at_ms) = parse_timestamp(&sidecar.bytes) else { + continue; + }; + refresh_blob_expiry_async( + Arc::clone(&blobs), + &entry.meta.key, + sidecar.bytes, + sidecar.meta.content_type.as_deref(), + Some(written_at_ms), + ttl, + now, + ) + .await?; + } + } + Ok::<(), String>(()) + } + }) +} + +async fn refresh_blob_expiry_async( + blobs: Arc, + key: &str, + bytes: Vec, + content_type: Option<&str>, + written_at_ms: Option, + ttl: Option, + now: SystemTime, +) -> Result<(), String> { + match ttl { + None => blobs + .put(key, bytes, content_type) + .await + .map(|_| ()) + .map_err(|error| error.to_string()), + Some(ttl) => { + let remaining = match written_at_ms { + Some(written) => remaining_ttl_from_epoch_ms(written, now, ttl), + None => Some(ttl), + }; + let Some(remaining) = remaining else { + return Ok(()); + }; + if remaining.is_zero() { + return Ok(()); + } + blobs + .put_expiring(key, bytes, content_type, remaining) + .await + .map(|_| ()) + .map_err(|error| error.to_string()) + } + } +} + +async fn prune_async( + blobs: Arc, + ttl: Option, + max_bytes: Option, + protect: Option<&str>, +) -> Result<(usize, u64, usize, u64), String> { + let mut entries = list_all_prefix_async(Arc::clone(&blobs), &format!("{CCR_PREFIX}/")).await?; + let semantic_times = list_timestamps_async(Arc::clone(&blobs), CCR_METADATA_PREFIX).await?; + for entry in &mut entries { + if let Some(token) = entry.meta.key.strip_prefix(&format!("{CCR_PREFIX}/")) + && let Some(written_at_ms) = semantic_times.get(token) + { + entry.written_at_ms = Some(*written_at_ms); + } + } + let now_ms = SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64; + let ttl_ms = ttl.map(|ttl| ttl.as_millis().min(u64::MAX as u128) as u64); + let mut remove = Vec::new(); + let mut removed_bytes = 0_u64; + for entry in &entries { + if ttl_ms.is_some_and(|ttl| { + entry + .written_at_ms + .is_some_and(|written| now_ms.saturating_sub(written) >= ttl) + }) { + remove.push(entry.meta.key.clone()); + } + } + for key in &remove { + if let Some(entry) = entries.iter().find(|entry| &entry.meta.key == key) { + removed_bytes = removed_bytes.saturating_add(entry.meta.len); + } + delete_blob_and_metadata_async(Arc::clone(&blobs), key).await?; + } + entries.retain(|entry| !remove.contains(&entry.meta.key)); + let mut total = entries.iter().map(|entry| entry.meta.len).sum::(); + if let Some(budget) = max_bytes { + entries.sort_by_key(|entry| entry.written_at_ms.unwrap_or(0)); + for entry in entries { + if total <= budget { + break; + } + if protect.is_some_and(|token| entry.meta.key == format!("{CCR_PREFIX}/{token}")) { + continue; + } + delete_blob_and_metadata_async(Arc::clone(&blobs), &entry.meta.key).await?; + removed_bytes = removed_bytes.saturating_add(entry.meta.len); + total = total.saturating_sub(entry.meta.len); + remove.push(entry.meta.key); + } + } + let remaining = list_all_prefix_async(Arc::clone(&blobs), &format!("{CCR_PREFIX}/")).await?; + let remaining_bytes = remaining.iter().map(|entry| entry.meta.len).sum(); + let remaining_tokens = remaining + .iter() + .filter_map(|entry| entry.meta.key.strip_prefix(&format!("{CCR_PREFIX}/"))) + .collect::>(); + for token in semantic_times.keys() { + if !remaining_tokens.contains(token.as_str()) { + delete_metadata_async(Arc::clone(&blobs), token).await?; + } + } + for token in list_timestamps_async(Arc::clone(&blobs), CCR_IMPORT_PREFIX) + .await? + .keys() + { + if !remaining_tokens.contains(token.as_str()) { + delete_import_intent_async(Arc::clone(&blobs), token).await?; + } + } + Ok(( + remove.len(), + removed_bytes, + remaining.len(), + remaining_bytes, + )) +} + +fn open_file_blobs(root: &Path) -> Result, String> { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| format!("cannot start storage runtime: {error}"))?; + let url = format!("file:{}", root.display()); + let config = StorageConfig::parse(&url).map_err(|error| error.to_string())?; + let backend = runtime + .block_on(open(&config)) + .map_err(|error| error.to_string())?; + let scope = Scope::new("tinyjuice-cli").map_err(|error| error.to_string())?; + let storage = backend + .for_scope(&scope) + .map_err(|error| error.to_string())?; + let blobs = Arc::clone(storage.blobs()); + drop(runtime); + Ok(blobs) +} + +fn import_legacy_files( + root: &Path, + blobs: &Arc, + ttl: Option, +) -> Result<(usize, u64), String> { + let mut removed_legacy = 0_usize; + let mut removed_legacy_bytes = 0_u64; + let entries = std::fs::read_dir(root).map_err(|error| { + format!( + "failed to inspect legacy CCR directory {}: {error}", + root.display() + ) + })?; + for entry in entries { + let entry = + entry.map_err(|error| format!("failed to inspect legacy CCR entry: {error}"))?; + if !entry + .file_type() + .map_err(|error| error.to_string())? + .is_file() + { + continue; + } + let token = entry.file_name().to_string_lossy().into_owned(); + if !is_token(&token) { + continue; + } + let content = match std::fs::read_to_string(entry.path()) { + Ok(content) => content, + Err(error) if error.kind() == std::io::ErrorKind::InvalidData => { + log::warn!( + "[tinyjuice_cli] discarding non-UTF-8 legacy CCR entry {token}: {error}" + ); + if let Some(size) = remove_legacy_entry(&entry.path(), &token, "non-UTF-8")? { + removed_legacy = removed_legacy.saturating_add(1); + removed_legacy_bytes = removed_legacy_bytes.saturating_add(size); + } + continue; + } + Err(error) => { + log::warn!("[tinyjuice_cli] skipping unreadable legacy CCR entry {token}: {error}"); + continue; + } + }; + if tinyjuice::cache::short_hash(&content) != token { + log::warn!("[tinyjuice_cli] skipping legacy CCR entry {token}: content hash mismatch"); + if let Some(size) = remove_legacy_entry(&entry.path(), &token, "corrupt")? { + removed_legacy = removed_legacy.saturating_add(1); + removed_legacy_bytes = removed_legacy_bytes.saturating_add(size); + } + continue; + } + let modified = entry + .metadata() + .and_then(|metadata| metadata.modified()) + .map_err(|error| { + format!("cannot read modification time for legacy CCR entry {token}: {error}") + })?; + let source_written_at_ms = unix_epoch_ms(modified); + let import_ttl = match ttl { + Some(ttl) => { + let remaining = remaining_ttl(modified, SystemTime::now(), ttl); + if remaining.is_none() { + if let Some(size) = remove_legacy_entry(&entry.path(), &token, "expired")? { + removed_legacy = removed_legacy.saturating_add(1); + removed_legacy_bytes = removed_legacy_bytes.saturating_add(size); + } + continue; + } + remaining + } + None => None, + }; + let store = + BlobCcrStore::new(Arc::clone(blobs), import_ttl).map_err(|error| error.to_string())?; + let existing = store.get(&token); + if existing + .as_deref() + .is_some_and(|existing| existing != content) + { + return Err(format!( + "legacy CCR entry {token} conflicts with different stored content" + )); + } + let recorded_time = read_semantic_time(Arc::clone(blobs), &token)?; + let import_intent = read_import_intent(Arc::clone(blobs), &token)?; + let existing_written_at_ms = if existing.is_some() { + recorded_time.or(import_intent).or(backend_written_at( + Arc::clone(blobs), + &format!("{CCR_PREFIX}/{token}"), + )?) + } else { + import_intent + }; + let semantic_written_at_ms = existing_written_at_ms + .filter(|existing| *existing >= source_written_at_ms) + .unwrap_or(source_written_at_ms); + if existing.is_none() && import_intent.is_none() { + // Mark source chronology before publishing its body. If the body + // succeeds but the timestamp write is interrupted, retry can + // distinguish this partial import from a newer normal store write. + write_import_intent(Arc::clone(blobs), &token, source_written_at_ms, import_ttl)?; + } + if existing.is_none() || semantic_written_at_ms == source_written_at_ms { + let put = store.put(&content); + if put.token() != token || !put.retained() { + return Err(format!("legacy CCR entry {token} was not durably retained")); + } + } + if store.get(&token).as_deref() != Some(content.as_str()) { + return Err(format!("legacy CCR entry {token} failed content readback")); + } + let metadata_ttl = ttl.and_then(|ttl| { + remaining_ttl_from_epoch_ms(semantic_written_at_ms, SystemTime::now(), ttl) + }); + write_semantic_time( + Arc::clone(blobs), + &token, + semantic_written_at_ms, + metadata_ttl, + )?; + if read_semantic_time(Arc::clone(blobs), &token)? != Some(semantic_written_at_ms) { + return Err(format!( + "legacy CCR entry {token} failed timestamp readback" + )); + } + delete_import_intent(Arc::clone(blobs), &token)?; + remove_imported_legacy_entry(&entry.path(), &token)?; + } + Ok((removed_legacy, removed_legacy_bytes)) +} + +fn remove_imported_legacy_entry(path: &Path, token: &str) -> Result<(), String> { + remove_imported_legacy_entry_with(path, token, |path| std::fs::remove_file(path)) +} + +fn remove_imported_legacy_entry_with( + path: &Path, + token: &str, + remove_file: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result<(), String> { + match remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(format!("cannot remove imported CCR entry {token}: {error}")), + } +} + +fn remove_legacy_entry(path: &Path, token: &str, reason: &str) -> Result, String> { + remove_legacy_entry_with(path, token, reason, |path| std::fs::remove_file(path)) +} + +fn remove_legacy_entry_with( + path: &Path, + token: &str, + reason: &str, + remove_file: impl FnOnce(&Path) -> std::io::Result<()>, +) -> Result, String> { + let size = match std::fs::metadata(path) { + Ok(metadata) => metadata.len(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => { + return Err(format!( + "cannot inspect {reason} legacy CCR entry {token}: {error}" + )); + } + }; + match remove_file(path) { + Ok(()) => Ok(Some(size)), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(format!( + "cannot remove {reason} legacy CCR entry {token}: {error}" + )), + } +} + +fn remaining_ttl(modified: SystemTime, now: SystemTime, ttl: Duration) -> Option { + let elapsed = now.duration_since(modified).unwrap_or_default(); + let remaining = ttl.saturating_sub(elapsed); + (!remaining.is_zero()).then_some(remaining) +} + +fn remaining_ttl_from_epoch_ms( + written_at_ms: u64, + now: SystemTime, + ttl: Duration, +) -> Option { + let written_at = std::time::UNIX_EPOCH.checked_add(Duration::from_millis(written_at_ms))?; + remaining_ttl(written_at, now, ttl) +} + +struct CappedCcrStore { + store: BlobCcrStore, + blobs: Arc, + lock_path: PathBuf, + ttl: Option, + max_bytes: Option, +} + +fn process_lock_path(root: &Path) -> PathBuf { + root.join("scopes/tinyjuice-cli/.tinyjuice-ccr.lock") +} + +fn acquire_process_lock(path: &Path) -> Result { + let parent = path + .parent() + .ok_or_else(|| "CCR process lock has no parent directory".to_owned())?; + std::fs::create_dir_all(parent) + .map_err(|error| format!("cannot create CCR process-lock directory: {error}"))?; + let lock = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(path) + .map_err(|error| format!("cannot open CCR process lock: {error}"))?; + lock.lock() + .map_err(|error| format!("cannot acquire CCR process lock: {error}"))?; + Ok(lock) +} + +impl CcrStore for CappedCcrStore { + fn put(&self, content: &str) -> CcrPutResult { + let token = tinyjuice::cache::short_hash(content); + let _lock = match acquire_process_lock(&self.lock_path) { + Ok(lock) => lock, + Err(error) => { + log::debug!("[tinyjuice_cli] CCR process lock failed: {error}"); + return CcrPutResult::new(token, false); + } + }; + match stored_configuration_matches(&self.blobs, self.ttl, self.max_bytes) { + Ok(true) => {} + Ok(false) => { + log::debug!( + "[tinyjuice_cli] CCR write skipped because store configuration is stale" + ); + return CcrPutResult::new(token, false); + } + Err(error) => { + log::debug!("[tinyjuice_cli] CCR configuration check failed: {error}"); + return CcrPutResult::new(token, false); + } + } + if let Err(error) = delete_import_intent(Arc::clone(&self.blobs), &token) { + log::debug!( + "[tinyjuice_cli] stale CCR import intent cleanup failed before write: {error}" + ); + // Do not publish a newer body while stale import chronology could + // still override its backend write time after an interrupted write. + return CcrPutResult::new(token, false); + } + let result = self.store.put(content); + if result.retained() { + if let Err(error) = write_semantic_time( + Arc::clone(&self.blobs), + result.token(), + unix_epoch_ms(SystemTime::now()), + self.ttl, + ) { + log::debug!("[tinyjuice_cli] CCR timestamp write failed: {error}"); + let mut stale_time_cleanup_failed = false; + if let Err(error) = delete_metadata(Arc::clone(&self.blobs), result.token()) { + log::debug!("[tinyjuice_cli] stale CCR timestamp cleanup failed: {error}"); + stale_time_cleanup_failed = true; + } + if let Err(error) = delete_import_intent(Arc::clone(&self.blobs), result.token()) { + log::debug!("[tinyjuice_cli] stale CCR import intent cleanup failed: {error}"); + stale_time_cleanup_failed = true; + } + if stale_time_cleanup_failed { + return CcrPutResult::new(result.token().to_owned(), false); + } + } else if let Err(error) = delete_import_intent(Arc::clone(&self.blobs), result.token()) + { + log::debug!("[tinyjuice_cli] CCR import intent cleanup failed: {error}"); + } + } + if result.retained() + && (self.ttl.is_some() || self.max_bytes.is_some()) + && let Err(error) = prune(&self.blobs, self.ttl, self.max_bytes, Some(result.token())) + { + log::debug!("[tinyjuice_cli] CCR sweep failed: {error}"); + } + result + } + + fn get(&self, token: &str) -> Option { + self.store.get(token) + } + + fn get_range( + &self, + token: &str, + start: usize, + end: usize, + unit: tinyjuice::cache::RangeUnit, + ) -> Option { + self.store.get_range(token, start, end, unit) + } +} + +fn list_all( + blobs: Arc, +) -> Result, String> { + list_all_prefix(blobs, &format!("{CCR_PREFIX}/")) +} + +fn list_all_prefix( + blobs: Arc, + prefix: &str, +) -> Result, String> { + let mut entries = Vec::new(); + let mut after = None; + loop { + let page = run_blob({ + let after = after.clone(); + let blobs = Arc::clone(&blobs); + let prefix = prefix.to_owned(); + async move { blobs.list_page(&prefix, after.as_deref(), PAGE_SIZE).await } + })?; + entries.extend(page.items); + after = page.next_after; + if after.is_none() { + return Ok(entries); + } + } +} + +async fn list_all_prefix_async( + blobs: Arc, + prefix: &str, +) -> Result, String> { + let mut entries = Vec::new(); + let mut after = None; + loop { + let page = blobs + .list_page(prefix, after.as_deref(), PAGE_SIZE) + .await + .map_err(|error| error.to_string())?; + entries.extend(page.items); + after = page.next_after; + if after.is_none() { + return Ok(entries); + } + } +} + +#[cfg(test)] +fn delete_blob(blobs: Arc, key: &str) -> Result<(), String> { + let key = key.to_owned(); + let handle = Arc::clone(&blobs); + run_blob(async move { handle.delete(&key).await }).map(|_| ()) +} + +#[cfg(test)] +fn delete_blob_and_metadata(blobs: Arc, key: &str) -> Result<(), String> { + delete_blob(Arc::clone(&blobs), key)?; + let Some(token) = key.strip_prefix(&format!("{CCR_PREFIX}/")) else { + return Ok(()); + }; + delete_metadata(blobs, token) +} + +async fn delete_blob_and_metadata_async( + blobs: Arc, + key: &str, +) -> Result<(), String> { + blobs.delete(key).await.map_err(|error| error.to_string())?; + let Some(token) = key.strip_prefix(&format!("{CCR_PREFIX}/")) else { + return Ok(()); + }; + delete_metadata_async(blobs, token).await +} + +fn delete_metadata(blobs: Arc, token: &str) -> Result<(), String> { + let key = format!("{CCR_METADATA_PREFIX}{token}"); + let handle = Arc::clone(&blobs); + run_blob(async move { handle.delete(&key).await }).map(|_| ()) +} + +async fn delete_metadata_async(blobs: Arc, token: &str) -> Result<(), String> { + let key = format!("{CCR_METADATA_PREFIX}{token}"); + blobs + .delete(&key) + .await + .map(|_| ()) + .map_err(|error| error.to_string()) +} + +fn write_semantic_time( + blobs: Arc, + token: &str, + written_at_ms: u64, + ttl: Option, +) -> Result<(), String> { + write_timestamp(blobs, CCR_METADATA_PREFIX, token, written_at_ms, ttl) +} + +fn write_import_intent( + blobs: Arc, + token: &str, + written_at_ms: u64, + ttl: Option, +) -> Result<(), String> { + write_timestamp(blobs, CCR_IMPORT_PREFIX, token, written_at_ms, ttl) +} + +fn read_import_intent(blobs: Arc, token: &str) -> Result, String> { + read_timestamp(blobs, CCR_IMPORT_PREFIX, token) +} + +fn delete_import_intent(blobs: Arc, token: &str) -> Result<(), String> { + let key = format!("{CCR_IMPORT_PREFIX}{token}"); + run_blob(async move { blobs.delete(&key).await }).map(|_| ()) +} + +async fn delete_import_intent_async(blobs: Arc, token: &str) -> Result<(), String> { + let key = format!("{CCR_IMPORT_PREFIX}{token}"); + blobs + .delete(&key) + .await + .map(|_| ()) + .map_err(|error| error.to_string()) +} + +fn write_timestamp( + blobs: Arc, + prefix: &str, + token: &str, + written_at_ms: u64, + ttl: Option, +) -> Result<(), String> { + let key = format!("{prefix}{token}"); + let bytes = written_at_ms.to_string().into_bytes(); + run_blob(async move { + // The port accepts relative TTLs, not absolute expiration timestamps. + // This sibling write uses the same remaining TTL as the CCR body, with + // only the small skew between the two backend writes. + match ttl { + Some(ttl) => { + blobs + .put_expiring(&key, bytes, Some(CCR_METADATA_CONTENT_TYPE), ttl) + .await + } + None => { + blobs + .put(&key, bytes, Some(CCR_METADATA_CONTENT_TYPE)) + .await + } + } + }) + .map(|_| ()) +} + +fn read_semantic_time(blobs: Arc, token: &str) -> Result, String> { + read_timestamp(blobs, CCR_METADATA_PREFIX, token) +} + +fn read_timestamp( + blobs: Arc, + prefix: &str, + token: &str, +) -> Result, String> { + let key = format!("{prefix}{token}"); + let lookup_key = key.clone(); + let Some(blob) = run_blob({ + let blobs = Arc::clone(&blobs); + async move { blobs.get(&lookup_key).await } + })? + else { + return Ok(None); + }; + match parse_timestamp(&blob.bytes) { + Ok(timestamp) => Ok(Some(timestamp)), + Err(error) => { + log::warn!("[tinyjuice_cli] discarding malformed CCR timestamp sidecar {key}: {error}"); + run_blob(async move { blobs.delete(&key).await }) + .map(|_| ()) + .map_err(|error| { + format!("cannot remove malformed CCR timestamp sidecar: {error}") + })?; + Ok(None) + } + } +} + +async fn read_timestamp_async( + blobs: Arc, + prefix: &str, + token: &str, +) -> Result, String> { + let key = format!("{prefix}{token}"); + let Some(blob) = blobs.get(&key).await.map_err(|error| error.to_string())? else { + return Ok(None); + }; + match parse_timestamp(&blob.bytes) { + Ok(timestamp) => Ok(Some(timestamp)), + Err(error) => { + log::warn!("[tinyjuice_cli] discarding malformed CCR timestamp sidecar {key}: {error}"); + blobs.delete(&key).await.map(|_| ()).map_err(|error| { + format!("cannot remove malformed CCR timestamp sidecar: {error}") + })?; + Ok(None) + } + } +} + +fn parse_timestamp(bytes: &[u8]) -> Result { + std::str::from_utf8(bytes) + .map_err(|error| format!("invalid CCR timestamp metadata: {error}"))? + .parse::() + .map_err(|error| format!("invalid CCR timestamp metadata: {error}")) +} + +fn backend_written_at(blobs: Arc, key: &str) -> Result, String> { + let key = key.to_owned(); + let lookup_key = key.clone(); + let page = run_blob(async move { blobs.list_page(&lookup_key, None, 1).await })?; + Ok(page + .items + .into_iter() + .find(|entry| entry.meta.key == key) + .and_then(|entry| entry.written_at_ms)) +} + +#[cfg(test)] +fn list_semantic_times(blobs: Arc) -> Result, String> { + list_timestamps(blobs, CCR_METADATA_PREFIX) +} + +#[cfg(test)] +fn list_timestamps( + blobs: Arc, + prefix: &str, +) -> Result, String> { + let entries = list_all_prefix(Arc::clone(&blobs), prefix)?; + let mut times = HashMap::new(); + for entry in entries { + let Some(token) = entry.meta.key.strip_prefix(prefix) else { + continue; + }; + if !is_token(token) { + continue; + } + if let Some(timestamp) = read_timestamp(Arc::clone(&blobs), prefix, token)? { + times.insert(token.to_owned(), timestamp); + } + } + Ok(times) +} + +async fn list_timestamps_async( + blobs: Arc, + prefix: &str, +) -> Result, String> { + let entries = list_all_prefix_async(Arc::clone(&blobs), prefix).await?; + let mut times = HashMap::new(); + for entry in entries { + let Some(token) = entry.meta.key.strip_prefix(prefix) else { + continue; + }; + if !is_token(token) { + continue; + } + if let Some(timestamp) = read_timestamp_async(Arc::clone(&blobs), prefix, token).await? { + times.insert(token.to_owned(), timestamp); + } + } + Ok(times) +} + +fn run_blob( + future: impl std::future::Future> + Send + 'static, +) -> Result +where + T: Send + 'static, + E: std::fmt::Display + Send + 'static, +{ + // Blob engines in this CLI are self-contained and do not depend on work + // from another runtime. Run the synchronous entry point on one dedicated + // thread so it remains safe inside a current-thread Tokio runtime. + std::thread::spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| format!("cannot start storage runtime: {error}"))?; + runtime.block_on(future).map_err(|error| error.to_string()) + }) + .join() + .map_err(|_| "storage worker thread panicked".to_owned())? +} + +fn is_token(token: &str) -> bool { + token.len() == 32 && token.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn unix_epoch_ms(time: SystemTime) -> u64 { + time.duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .min(u64::MAX as u128) as u64 +} + +#[cfg(test)] +#[path = "storage_tests.rs"] +mod tests; diff --git a/crates/tinyjuice-cli/src/storage_tests.rs b/crates/tinyjuice-cli/src/storage_tests.rs new file mode 100644 index 00000000..b74665c0 --- /dev/null +++ b/crates/tinyjuice-cli/src/storage_tests.rs @@ -0,0 +1,1229 @@ +use super::*; +use tinyjuice::cache::{CcrStore, RangeUnit}; +use tinystoragedrivers_api::BlobStore; +use tinystoragedrivers_testkit::FaultPlan; +use tinystoragedrivers_types::{ + Blob, BlobListPage, BlobMeta, Capabilities, ErrorKind, Result as StorageResult, StorageError, +}; + +#[derive(Debug)] +struct FailMetadataOperations { + inner: Arc, + faults: FaultPlan, +} + +#[async_trait::async_trait] +impl BlobStore for FailMetadataOperations { + fn capabilities(&self) -> Capabilities { + self.inner.capabilities() + } + + fn max_key_len(&self) -> usize { + self.inner.max_key_len() + } + + async fn put( + &self, + key: &str, + bytes: Vec, + content_type: Option<&str>, + ) -> StorageResult { + let fail_after_body_write = key.starts_with(&format!("{CCR_PREFIX}/")) + && self.faults.check("body_put_after_commit").is_err(); + if key.starts_with(CCR_METADATA_PREFIX) { + self.faults.check("metadata_put")?; + } + let metadata = self.inner.put(key, bytes, content_type).await?; + if fail_after_body_write { + Err(StorageError::new( + ErrorKind::Backend, + "simulated lost body-write acknowledgement", + )) + } else { + Ok(metadata) + } + } + + async fn get(&self, key: &str) -> StorageResult> { + if key.starts_with(CCR_METADATA_PREFIX) || key.starts_with(CCR_IMPORT_PREFIX) { + self.faults.check("metadata_get")?; + } + self.inner.get(key).await + } + + async fn get_range( + &self, + key: &str, + range: std::ops::Range, + ) -> StorageResult>> { + self.inner.get_range(key, range).await + } + + async fn head(&self, key: &str) -> StorageResult> { + self.inner.head(key).await + } + + async fn delete(&self, key: &str) -> StorageResult { + if key.starts_with(CCR_METADATA_PREFIX) { + self.faults.check("semantic_metadata_delete")?; + } + self.inner.delete(key).await + } + + async fn list(&self, prefix: &str) -> StorageResult> { + self.inner.list(prefix).await + } + + async fn list_page( + &self, + prefix: &str, + after: Option<&str>, + limit: usize, + ) -> StorageResult { + self.inner.list_page(prefix, after, limit).await + } +} + +#[derive(Debug)] +struct SynchronizeConcurrentPuts { + inner: Arc, + body_writes: Arc, + prune_reads: Arc, +} + +#[async_trait::async_trait] +impl BlobStore for SynchronizeConcurrentPuts { + fn capabilities(&self) -> Capabilities { + self.inner.capabilities() + } + + fn max_key_len(&self) -> usize { + self.inner.max_key_len() + } + + async fn put( + &self, + key: &str, + bytes: Vec, + content_type: Option<&str>, + ) -> StorageResult { + let metadata = self.inner.put(key, bytes, content_type).await?; + if key.starts_with(&format!("{CCR_PREFIX}/")) { + let _ = tokio::time::timeout(Duration::from_millis(500), self.body_writes.wait()).await; + } + Ok(metadata) + } + + async fn get(&self, key: &str) -> StorageResult> { + self.inner.get(key).await + } + + async fn get_range( + &self, + key: &str, + range: std::ops::Range, + ) -> StorageResult>> { + self.inner.get_range(key, range).await + } + + async fn head(&self, key: &str) -> StorageResult> { + self.inner.head(key).await + } + + async fn delete(&self, key: &str) -> StorageResult { + self.inner.delete(key).await + } + + async fn list(&self, prefix: &str) -> StorageResult> { + self.inner.list(prefix).await + } + + async fn list_page( + &self, + prefix: &str, + after: Option<&str>, + limit: usize, + ) -> StorageResult { + let page = self.inner.list_page(prefix, after, limit).await?; + if prefix == format!("{CCR_PREFIX}/") { + let _ = tokio::time::timeout(Duration::from_millis(500), self.prune_reads.wait()).await; + } + Ok(page) + } +} + +#[test] +fn collection_reports_bytes_removed_by_the_budget() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let store = BlobCcrStore::new(blobs, None).unwrap(); + assert!(store.put("first").retained()); + assert!(store.put("second").retained()); + + assert_eq!(collect(dir.path(), None, Some(0)).unwrap(), (2, 11, 0, 0)); +} + +#[test] +fn collection_removes_and_reports_corrupt_legacy_entries() { + let dir = tempfile::tempdir().unwrap(); + let token = "0123456789abcdef0123456789abcdef"; + let path = dir.path().join(token); + let corrupt_content = "content does not match its token"; + std::fs::write(&path, corrupt_content).unwrap(); + + let result = collect(dir.path(), None, Some(0)).unwrap(); + + assert_eq!(result, (1, corrupt_content.len() as u64, 0, 0)); + assert!( + !path.exists(), + "garbage collection removes the corrupt file" + ); +} + +#[test] +fn collection_reports_expired_legacy_entries() { + let dir = tempfile::tempdir().unwrap(); + let content = "valid but expired legacy entry"; + let token = tinyjuice::cache::short_hash(content); + let path = dir.path().join(token); + std::fs::write(&path, content).unwrap(); + std::fs::OpenOptions::new() + .write(true) + .open(&path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH)) + .unwrap(); + + let result = collect(dir.path(), Some(Duration::from_secs(1)), None).unwrap(); + + assert_eq!(result, (1, content.len() as u64, 0, 0)); + assert!( + !path.exists(), + "garbage collection removes expired legacy files" + ); +} + +#[test] +fn collection_reports_expired_backend_blobs_pruned_during_configuration() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let content = "expired backend content swept during configuration"; + let store = BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(); + let put = store.put(content); + assert!(put.retained()); + write_semantic_time( + Arc::clone(&blobs), + put.token(), + unix_epoch_ms(SystemTime::now() - Duration::from_secs(60)), + None, + ) + .unwrap(); + + assert_eq!( + collect(dir.path(), Some(Duration::from_secs(1)), None).unwrap(), + (1, content.len() as u64, 0, 0) + ); +} + +#[test] +fn collection_removes_and_reports_non_utf8_legacy_entries() { + let dir = tempfile::tempdir().unwrap(); + let token = "fedcba9876543210fedcba9876543210"; + let path = dir.path().join(token); + let corrupt_content = [0xff, 0xfe]; + std::fs::write(&path, corrupt_content).unwrap(); + + let result = collect(dir.path(), None, Some(0)).unwrap(); + + assert_eq!(result, (1, corrupt_content.len() as u64, 0, 0)); + assert!( + !path.exists(), + "garbage collection removes non-UTF-8 legacy files" + ); +} + +#[test] +fn startup_prunes_expired_blobs_with_ttl_without_a_byte_cap() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let content = "expired before a TTL-only restart"; + let store = BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(); + let put = store.put(content); + assert!(put.retained()); + write_semantic_time( + Arc::clone(&blobs), + put.token(), + unix_epoch_ms(SystemTime::now() - Duration::from_secs(60)), + None, + ) + .unwrap(); + + configure_with_report(dir.path(), Some(Duration::from_secs(1)), None).unwrap(); + + assert!( + BlobCcrStore::new(open_file_blobs(dir.path()).unwrap(), None) + .unwrap() + .get(put.token()) + .is_none(), + "a TTL-only startup sweep removes previously stored expired content" + ); +} + +#[test] +fn configuration_reapplies_changed_ttl_to_existing_blobs() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let blobs = open_file_blobs(root).unwrap(); + let content = "an existing cache entry whose configured TTL changes"; + let token = tinyjuice::cache::short_hash(content); + assert!( + BlobCcrStore::new(Arc::clone(&blobs), Some(Duration::from_secs(3_600))) + .unwrap() + .put(content) + .retained() + ); + + let body_sidecar = || { + std::fs::read_dir(root.join("scopes/tinyjuice-cli/blobs")) + .unwrap() + .map(|entry| std::fs::read(entry.unwrap().path()).unwrap()) + .filter_map(|bytes| serde_json::from_slice::(&bytes).ok()) + .find(|sidecar| sidecar["key"] == format!("{CCR_PREFIX}/{token}")) + .expect("CCR body metadata sidecar exists") + }; + let original_expiry = body_sidecar()["expires_at_ms"] + .as_u64() + .expect("the initial TTL is recorded in the backend sidecar"); + + configure(root, Some(Duration::from_secs(7_200)), None).unwrap(); + + let extended_expiry = body_sidecar()["expires_at_ms"] + .as_u64() + .expect("the updated TTL is recorded in the backend sidecar"); + assert!( + extended_expiry > original_expiry, + "a longer configured TTL must replace the old physical expiry" + ); + + configure(root, None, None).unwrap(); + + assert!(body_sidecar()["expires_at_ms"].is_null()); + assert_eq!( + BlobCcrStore::new(open_file_blobs(root).unwrap(), None) + .unwrap() + .get(&token) + .as_deref(), + Some(content) + ); +} + +#[test] +fn configuration_preserves_backend_write_time_when_semantic_time_is_missing() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let blobs = open_file_blobs(root).unwrap(); + let content = "existing body without a semantic timestamp"; + let token = tinyjuice::cache::short_hash(content); + assert!( + BlobCcrStore::new(Arc::clone(&blobs), Some(Duration::from_secs(3_600))) + .unwrap() + .put(content) + .retained() + ); + let written_at_ms = list_all(Arc::clone(&blobs)) + .unwrap() + .into_iter() + .find(|entry| entry.meta.key == format!("{CCR_PREFIX}/{token}")) + .and_then(|entry| entry.written_at_ms) + .expect("file backend records the original body write time"); + + configure(root, Some(Duration::from_secs(7_200)), None).unwrap(); + + assert_eq!( + read_semantic_time(open_file_blobs(root).unwrap(), &token).unwrap(), + Some(written_at_ms), + "reapplying expiry must preserve the original age for later pruning" + ); +} + +#[test] +fn configuration_does_not_rewrite_cache_when_ttl_is_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let blobs = open_file_blobs(root).unwrap(); + let content = "cache body used to check unchanged TTL configuration"; + let token = tinyjuice::cache::short_hash(content); + let ttl = Some(Duration::from_secs(3_600)); + assert!( + BlobCcrStore::new(Arc::clone(&blobs), ttl) + .unwrap() + .put(content) + .retained() + ); + configure(root, ttl, None).unwrap(); + + let body_sidecar = std::fs::read_dir(root.join("scopes/tinyjuice-cli/blobs")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| { + path.extension() + .is_some_and(|extension| extension == "json") + && std::fs::read(path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .is_some_and(|sidecar| sidecar["key"] == format!("{CCR_PREFIX}/{token}")) + }) + .expect("CCR body metadata sidecar exists"); + std::fs::OpenOptions::new() + .write(true) + .open(&body_sidecar) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH)) + .unwrap(); + + configure(root, ttl, None).unwrap(); + + assert_eq!( + std::fs::metadata(body_sidecar).unwrap().modified().unwrap(), + SystemTime::UNIX_EPOCH, + "an unchanged TTL must not rewrite each cached body's metadata" + ); +} + +#[test] +fn stale_capped_store_does_not_write_after_configuration_changes() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let blobs = open_file_blobs(root).unwrap(); + let old_ttl = Some(Duration::from_secs(3_600)); + let new_ttl = Some(Duration::from_secs(7_200)); + configure(root, old_ttl, None).unwrap(); + let stale = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&blobs), old_ttl).unwrap(), + blobs: Arc::clone(&blobs), + lock_path: process_lock_path(root), + ttl: old_ttl, + max_bytes: None, + }; + configure(root, new_ttl, None).unwrap(); + + let result = stale.put("stale process must not write with an old TTL"); + + assert!(!result.retained()); + assert!( + run_blob(async move { blobs.list(&format!("{CCR_PREFIX}/")).await }) + .unwrap() + .is_empty(), + "a store configured with a superseded TTL must not publish a body" + ); +} + +#[test] +fn removing_legacy_entries_reports_inspection_and_removal_errors() { + let dir = tempfile::tempdir().unwrap(); + let token = "0123456789abcdef0123456789abcdef"; + let missing_path = dir.path().join(token); + assert_eq!( + remove_legacy_entry(&missing_path, token, "corrupt").unwrap(), + None + ); + + let raced_path = dir.path().join("raced"); + std::fs::write(&raced_path, "legacy").unwrap(); + let removed = remove_legacy_entry_with(&raced_path, token, "corrupt", |path| { + std::fs::remove_file(path)?; + Err(std::io::Error::from(std::io::ErrorKind::NotFound)) + }) + .unwrap(); + assert_eq!(removed, None); + assert!(!raced_path.exists()); + + let directory_path = dir.path().join(token); + std::fs::create_dir(&directory_path).unwrap(); + let remove_error = remove_legacy_entry(&directory_path, token, "expired").unwrap_err(); + assert!(remove_error.contains("cannot remove expired legacy CCR entry")); + assert!(directory_path.is_dir()); +} + +#[test] +fn imported_legacy_removal_tolerates_a_concurrent_not_found() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("imported"); + std::fs::write(&path, "legacy").unwrap(); + + remove_imported_legacy_entry_with(&path, "0123456789abcdef0123456789abcdef", |path| { + std::fs::remove_file(path)?; + Err(std::io::Error::from(std::io::ErrorKind::NotFound)) + }) + .unwrap(); + + assert!(!path.exists()); +} + +#[test] +fn configure_and_inventory_report_invalid_storage_paths() { + let dir = tempfile::tempdir().unwrap(); + let missing = dir.path().join("missing"); + let inventory_error = match inventory(&missing, None) { + Err(error) => error, + Ok(_) => panic!("missing storage directory unexpectedly inventoried"), + }; + assert!(inventory_error.contains("does not exist")); + + let file_path = dir.path().join("not-a-directory"); + std::fs::write(&file_path, "file").unwrap(); + let configure_error = configure(&file_path, None, None).unwrap_err(); + assert!(configure_error.contains("cannot create CCR storage directory")); + let import_error = + import_legacy_files(&file_path, &open_file_blobs(dir.path()).unwrap(), None).unwrap_err(); + assert!(import_error.contains("failed to inspect legacy CCR directory")); +} + +#[test] +fn legacy_import_skips_corrupt_entries_and_continues_importing_valid_files() { + let dir = tempfile::tempdir().unwrap(); + let valid_content = "valid legacy entry still imports"; + let valid_token = tinyjuice::cache::short_hash(valid_content); + let mismatch_token = "0123456789abcdef0123456789abcdef"; + let unreadable_token = "fedcba9876543210fedcba9876543210"; + let valid_path = dir.path().join(&valid_token); + let mismatch_path = dir.path().join(mismatch_token); + let unreadable_path = dir.path().join(unreadable_token); + std::fs::write(&valid_path, valid_content).unwrap(); + std::fs::write(&mismatch_path, "content does not match its token").unwrap(); + std::fs::write(&unreadable_path, [0xff, 0xfe]).unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + + import_legacy_files(dir.path(), &blobs, None).unwrap(); + + assert!(!valid_path.exists(), "the valid legacy file is imported"); + assert!( + !mismatch_path.exists(), + "the corrupt source is discarded rather than retried forever" + ); + assert!( + !unreadable_path.exists(), + "the non-UTF-8 source is discarded" + ); + assert_eq!( + BlobCcrStore::new(blobs, None) + .unwrap() + .get(&valid_token) + .as_deref(), + Some(valid_content) + ); +} + +#[test] +fn inventory_counts_ignored_entries_and_returns_imported_blobs() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("not-a-token"), "ignored").unwrap(); + std::fs::create_dir(dir.path().join("nested")).unwrap(); + let content = "inventory imports the valid legacy entry"; + let token = tinyjuice::cache::short_hash(content); + std::fs::write(dir.path().join(&token), content).unwrap(); + + let result = inventory(dir.path(), None).unwrap(); + + assert_eq!(result.ignored_entries, 2); + assert_eq!(result.entries.len(), 1); + assert_eq!(result.entries[0].key, format!("{CCR_PREFIX}/{token}")); + assert_eq!( + BlobCcrStore::new(open_file_blobs(dir.path()).unwrap(), None) + .unwrap() + .get(&token) + .as_deref(), + Some(content) + ); +} + +#[test] +fn inventory_does_not_count_backend_storage_after_a_blob_write() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let store = BlobCcrStore::new(blobs, None).unwrap(); + assert!(store.put("inventory backend entry").retained()); + + let first = inventory(dir.path(), None).unwrap(); + let second = inventory(dir.path(), None).unwrap(); + + assert_eq!(first.ignored_entries, second.ignored_entries); +} + +#[test] +fn concurrent_capped_writes_do_not_prune_each_other_into_an_empty_cache() { + let dir = tempfile::tempdir().unwrap(); + let inner = open_file_blobs(dir.path()).unwrap(); + let body_writes = Arc::new(tokio::sync::Barrier::new(2)); + let prune_reads = Arc::new(tokio::sync::Barrier::new(2)); + let blobs: Arc = Arc::new(SynchronizeConcurrentPuts { + inner: Arc::clone(&inner), + body_writes, + prune_reads, + }); + let lock_path = dir.path().join("scopes/tinyjuice-cli/.tinyjuice-ccr.lock"); + let make_store = || CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(), + blobs: Arc::clone(&blobs), + lock_path: lock_path.clone(), + ttl: None, + max_bytes: Some(5), + }; + let first = make_store(); + let second = make_store(); + let first_put = std::thread::spawn(move || first.put("first")); + let second_put = std::thread::spawn(move || second.put("other")); + + let first_put = first_put.join().unwrap(); + let second_put = second_put.join().unwrap(); + assert!(first_put.retained()); + assert!(second_put.retained()); + let entries = run_blob(async move { inner.list(&format!("{CCR_PREFIX}/")).await }).unwrap(); + + assert_eq!( + entries.len(), + 1, + "a capped concurrent write must retain one blob" + ); +} + +#[test] +fn capped_write_fails_closed_when_process_lock_directory_cannot_be_created() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let blocker = dir.path().join("not-a-directory"); + std::fs::write(&blocker, b"file blocks lock directory creation").unwrap(); + let store = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(), + blobs: Arc::clone(&blobs), + lock_path: blocker.join(".tinyjuice-ccr.lock"), + ttl: None, + max_bytes: Some(1024), + }; + + let result = store.put("must not be written without the process lock"); + + assert!(!result.retained()); + assert!( + run_blob(async move { blobs.list(&format!("{CCR_PREFIX}/")).await }) + .unwrap() + .is_empty(), + "the write must not proceed after process-lock acquisition fails" + ); +} + +#[test] +fn import_skips_directories_and_unrecognized_names_and_removes_expired_files() { + let dir = tempfile::tempdir().unwrap(); + let nested = dir.path().join("nested"); + std::fs::create_dir(&nested).unwrap(); + std::fs::write(nested.join("entry"), "not a top-level CCR").unwrap(); + let unrecognized = dir.path().join("not-a-token"); + std::fs::write(&unrecognized, "unrecognized").unwrap(); + + let content = "already expired legacy content"; + let token = tinyjuice::cache::short_hash(content); + let expired = dir.path().join(&token); + std::fs::write(&expired, content).unwrap(); + std::fs::OpenOptions::new() + .write(true) + .open(&expired) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(SystemTime::UNIX_EPOCH)) + .unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + + import_legacy_files(dir.path(), &blobs, Some(Duration::from_secs(1))).unwrap(); + + assert!(!expired.exists()); + assert!(unrecognized.exists()); + assert!(nested.join("entry").exists()); + assert!( + BlobCcrStore::new(blobs, None) + .unwrap() + .get(&token) + .is_none() + ); +} + +#[test] +fn import_uses_an_existing_backend_write_time_without_sidecars() { + let dir = tempfile::tempdir().unwrap(); + let content = "the already published backend body is newer"; + let token = tinyjuice::cache::short_hash(content); + let source = dir.path().join(&token); + std::fs::write(&source, content).unwrap(); + let source_time = SystemTime::now() - Duration::from_secs(60); + std::fs::OpenOptions::new() + .write(true) + .open(&source) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(source_time)) + .unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let existing = BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(); + assert!(existing.put(content).retained()); + let backend_time = backend_written_at(Arc::clone(&blobs), &format!("{CCR_PREFIX}/{token}")) + .unwrap() + .unwrap(); + + import_legacy_files(dir.path(), &blobs, None).unwrap(); + + assert!(!source.exists()); + assert_eq!( + read_semantic_time(blobs, &token).unwrap(), + Some(backend_time.max(unix_epoch_ms(source_time))) + ); +} + +#[test] +fn capped_store_delegates_byte_ranges_to_the_durable_store() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let store = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(), + blobs, + lock_path: process_lock_path(dir.path()), + ttl: None, + max_bytes: None, + }; + let put = store.put("abcdefgh"); + + assert_eq!( + store + .get_range(put.token(), 2, 5, RangeUnit::Bytes) + .as_deref(), + Some("cde") + ); +} + +#[test] +fn timestamp_listing_ignores_non_tokens_and_discards_malformed_values() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + run_blob({ + let blobs = Arc::clone(&blobs); + async move { + blobs + .put( + &format!("{CCR_METADATA_PREFIX}not-a-token"), + b"not a timestamp".to_vec(), + None, + ) + .await + } + }) + .unwrap(); + assert!(list_semantic_times(Arc::clone(&blobs)).unwrap().is_empty()); + + let token = "0123456789abcdef0123456789abcdef"; + run_blob({ + let blobs = Arc::clone(&blobs); + async move { + blobs + .put(&format!("{CCR_METADATA_PREFIX}{token}"), vec![0xff], None) + .await + } + }) + .unwrap(); + assert_eq!(read_semantic_time(blobs, token).unwrap(), None); +} + +#[test] +fn malformed_timestamp_sidecars_do_not_abort_pruning_or_hide_backend_write_time() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let store = BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(); + let content = "recent content with malformed timestamp sidecars"; + let body_token = tinyjuice::cache::short_hash(content); + assert!(store.put(content).retained()); + let body_token_for_sidecar = body_token.clone(); + let intent_token = "0123456789abcdef0123456789abcdef"; + run_blob({ + let blobs = Arc::clone(&blobs); + async move { + blobs + .put( + &format!("{CCR_METADATA_PREFIX}{body_token_for_sidecar}"), + b"not-a-number".to_vec(), + None, + ) + .await?; + blobs + .put( + &format!("{CCR_IMPORT_PREFIX}{intent_token}"), + vec![0xff], + None, + ) + .await + } + }) + .unwrap(); + + assert_eq!( + prune(&blobs, Some(Duration::from_secs(3600)), None, None).unwrap(), + (0, 0, 1, content.len() as u64) + ); + assert_eq!(store.get(&body_token).as_deref(), Some(content)); + assert_eq!( + read_semantic_time(Arc::clone(&blobs), &body_token).unwrap(), + None + ); + assert_eq!(read_import_intent(blobs, intent_token).unwrap(), None); +} + +#[test] +fn malformed_timestamp_cleanup_failure_aborts_pruning() { + let dir = tempfile::tempdir().unwrap(); + let inner = open_file_blobs(dir.path()).unwrap(); + let content = "body with an unreadable timestamp sidecar"; + let token = tinyjuice::cache::short_hash(content); + assert!( + BlobCcrStore::new(Arc::clone(&inner), None) + .unwrap() + .put(content) + .retained() + ); + let token_for_sidecar = token.clone(); + run_blob({ + let inner = Arc::clone(&inner); + async move { + inner + .put( + &format!("{CCR_METADATA_PREFIX}{token_for_sidecar}"), + b"not-a-number".to_vec(), + None, + ) + .await + } + }) + .unwrap(); + let faults = FaultPlan::new(); + faults.fail_operation_nth("semantic_metadata_delete", 1, ErrorKind::Backend); + let failing: Arc = Arc::new(FailMetadataOperations { + inner: Arc::clone(&inner), + faults, + }); + + let error = prune(&failing, None, None, None).unwrap_err(); + + assert!(error.contains("cannot remove malformed CCR timestamp sidecar")); + assert!( + run_blob(async move { inner.get(&format!("{CCR_METADATA_PREFIX}{token}")).await }) + .unwrap() + .is_some() + ); +} + +#[test] +fn timestamp_backend_read_errors_still_abort_pruning() { + let dir = tempfile::tempdir().unwrap(); + let inner = open_file_blobs(dir.path()).unwrap(); + let token = "0123456789abcdef0123456789abcdef"; + write_semantic_time( + Arc::clone(&inner), + token, + unix_epoch_ms(SystemTime::now()), + None, + ) + .unwrap(); + let faults = FaultPlan::new(); + faults.fail_operation_nth("metadata_get", 1, ErrorKind::Backend); + let failing: Arc = Arc::new(FailMetadataOperations { inner, faults }); + + let error = prune(&failing, None, None, None).unwrap_err(); + + assert!(error.contains("injected failure for metadata_get")); +} + +#[test] +fn deleting_a_non_ccr_blob_does_not_touch_ccr_metadata() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let key = "unrelated/object"; + run_blob({ + let blobs = Arc::clone(&blobs); + async move { blobs.put(key, b"data".to_vec(), None).await } + }) + .unwrap(); + + delete_blob_and_metadata(Arc::clone(&blobs), key).unwrap(); + + assert!( + run_blob(async move { blobs.get(key).await }) + .unwrap() + .is_none() + ); +} + +#[test] +fn durable_cli_writes_enforce_the_configured_byte_budget() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let store = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(), + blobs: Arc::clone(&blobs), + lock_path: process_lock_path(dir.path()), + ttl: None, + max_bytes: Some(9), + }; + + assert!(store.put("first").retained()); + assert!(store.put("second").retained()); + let current = store.put("tri"); + assert!(current.retained()); + + let entries = run_blob({ + let blobs = Arc::clone(&blobs); + async move { blobs.list(&format!("{CCR_PREFIX}/")).await } + }) + .unwrap(); + assert_eq!(entries.iter().map(|entry| entry.len).sum::(), 9); + assert!(store.get(current.token()).is_some()); +} + +#[test] +fn migration_ttl_uses_the_source_file_age() { + let now = SystemTime::UNIX_EPOCH + Duration::from_secs(100); + let modified = SystemTime::UNIX_EPOCH + Duration::from_secs(95); + assert_eq!( + remaining_ttl(modified, now, Duration::from_secs(10)), + Some(Duration::from_secs(5)) + ); + assert_eq!(remaining_ttl(modified, now, Duration::from_secs(5)), None); + assert_eq!( + remaining_ttl(now + Duration::from_secs(1), now, Duration::from_secs(5)), + Some(Duration::from_secs(5)) + ); +} + +#[test] +fn collection_uses_imported_write_time_for_ttl() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let content = "legacy ccr with an old semantic timestamp"; + let store = BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(); + let put = store.put(content); + assert!(put.retained()); + let old_time = unix_epoch_ms(SystemTime::UNIX_EPOCH + Duration::from_secs(1)); + write_semantic_time(Arc::clone(&blobs), put.token(), old_time, None).unwrap(); + + assert_eq!( + prune(&blobs, Some(Duration::from_secs(1)), None, None).unwrap(), + (1, content.len() as u64, 0, 0) + ); + assert!(store.get(put.token()).is_none()); + assert_eq!( + read_semantic_time(Arc::clone(&blobs), put.token()).unwrap(), + None + ); +} + +#[test] +fn collection_orders_by_imported_write_time_under_the_byte_budget() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let store = BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(); + let older = "older legacy ccr"; + let newer = "newer legacy ccr body"; + let older_put = store.put(older); + let newer_put = store.put(newer); + assert!(older_put.retained() && newer_put.retained()); + write_semantic_time( + Arc::clone(&blobs), + older_put.token(), + unix_epoch_ms(SystemTime::UNIX_EPOCH + Duration::from_secs(1)), + None, + ) + .unwrap(); + write_semantic_time( + Arc::clone(&blobs), + newer_put.token(), + unix_epoch_ms(SystemTime::UNIX_EPOCH + Duration::from_secs(2)), + None, + ) + .unwrap(); + + assert_eq!( + prune(&blobs, None, Some(newer.len() as u64), None).unwrap(), + (1, older.len() as u64, 1, newer.len() as u64) + ); + assert!(store.get(older_put.token()).is_none()); + assert_eq!(store.get(newer_put.token()).as_deref(), Some(newer)); +} + +#[test] +fn gc_removes_import_intents_that_have_no_ccr_body() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let token = "0123456789abcdef0123456789abcdef"; + write_import_intent( + Arc::clone(&blobs), + token, + unix_epoch_ms(SystemTime::now()), + None, + ) + .unwrap(); + + assert_eq!(prune(&blobs, None, None, None).unwrap(), (0, 0, 0, 0)); + assert_eq!(read_import_intent(blobs, token).unwrap(), None); +} + +#[test] +fn failed_timestamp_refresh_does_not_leave_an_old_age_for_gc() { + let dir = tempfile::tempdir().unwrap(); + let content = "a normal re-offload of imported content"; + let token = tinyjuice::cache::short_hash(content); + let inner = open_file_blobs(dir.path()).unwrap(); + let original = BlobCcrStore::new(Arc::clone(&inner), None).unwrap(); + assert!(original.put(content).retained()); + let old_time = unix_epoch_ms(SystemTime::now() - Duration::from_secs(86_400)); + write_semantic_time(Arc::clone(&inner), &token, old_time, None).unwrap(); + + let faults = FaultPlan::new(); + faults.fail_operation_nth("metadata_put", 1, ErrorKind::Backend); + let failing: Arc = Arc::new(FailMetadataOperations { + inner: Arc::clone(&inner), + faults, + }); + let refreshed = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&failing), None).unwrap(), + blobs: failing, + lock_path: process_lock_path(dir.path()), + ttl: None, + max_bytes: None, + }; + + assert!(refreshed.put(content).retained()); + assert_eq!( + read_semantic_time(Arc::clone(&inner), &token).unwrap(), + None + ); + assert_eq!( + read_import_intent(Arc::clone(&inner), &token).unwrap(), + None + ); + assert_eq!( + prune(&inner, Some(Duration::from_secs(3_600)), None, None).unwrap(), + (0, 0, 1, content.len() as u64), + "the physical write time must replace stale imported age when timestamp refresh fails" + ); + assert_eq!(original.get(&token).as_deref(), Some(content)); +} + +#[test] +fn failed_stale_timestamp_cleanup_does_not_advertise_or_prune_the_new_body() { + let dir = tempfile::tempdir().unwrap(); + let content = "fresh body whose stale semantic age cannot be cleared"; + let token = tinyjuice::cache::short_hash(content); + let inner = open_file_blobs(dir.path()).unwrap(); + let original = BlobCcrStore::new(Arc::clone(&inner), None).unwrap(); + assert!(original.put(content).retained()); + let old_time = unix_epoch_ms(SystemTime::now() - Duration::from_secs(86_400)); + write_semantic_time(Arc::clone(&inner), &token, old_time, None).unwrap(); + + let faults = FaultPlan::new(); + faults.fail_operation_nth("metadata_put", 1, ErrorKind::Backend); + faults.fail_operation_nth("semantic_metadata_delete", 1, ErrorKind::Backend); + let failing: Arc = Arc::new(FailMetadataOperations { + inner: Arc::clone(&inner), + faults, + }); + let capped = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&failing), None).unwrap(), + blobs: failing, + lock_path: process_lock_path(dir.path()), + ttl: Some(Duration::from_secs(3_600)), + max_bytes: None, + }; + + assert!(!capped.put(content).retained()); + assert_eq!( + read_semantic_time(Arc::clone(&inner), &token).unwrap(), + Some(old_time) + ); + assert_eq!(original.get(&token).as_deref(), Some(content)); +} + +#[test] +fn stale_import_intent_does_not_hide_a_newer_body_write() { + let dir = tempfile::tempdir().unwrap(); + let content = "a later normal re-offload after an interrupted import"; + let token = tinyjuice::cache::short_hash(content); + let source_path = dir.path().join(&token); + std::fs::write(&source_path, content).unwrap(); + let old_time = SystemTime::now() - Duration::from_secs(60); + std::fs::OpenOptions::new() + .write(true) + .open(&source_path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(old_time)) + .unwrap(); + + let inner = open_file_blobs(dir.path()).unwrap(); + let initial = BlobCcrStore::new(Arc::clone(&inner), None).unwrap(); + assert!(initial.put(content).retained()); + write_import_intent(Arc::clone(&inner), &token, unix_epoch_ms(old_time), None).unwrap(); + + let faults = FaultPlan::new(); + faults.fail_operation_nth("body_put_after_commit", 1, ErrorKind::Backend); + let flaky: Arc = Arc::new(FailMetadataOperations { + inner: Arc::clone(&inner), + faults, + }); + let reoffloaded = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&flaky), None).unwrap(), + blobs: flaky.clone(), + lock_path: process_lock_path(dir.path()), + ttl: None, + max_bytes: None, + }; + assert!(!reoffloaded.put(content).retained()); + let backend_time = backend_written_at(Arc::clone(&inner), &format!("{CCR_PREFIX}/{token}")) + .unwrap() + .unwrap(); + assert!(backend_time > unix_epoch_ms(old_time)); + + import_legacy_files(dir.path(), &flaky, None).unwrap(); + + assert_eq!( + read_semantic_time(inner, &token).unwrap(), + Some(backend_time) + ); +} + +#[test] +fn capped_store_put_works_inside_a_current_thread_runtime() { + let dir = tempfile::tempdir().unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let capped = CappedCcrStore { + store: BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(), + blobs, + lock_path: process_lock_path(dir.path()), + ttl: Some(Duration::from_secs(600)), + max_bytes: Some(1024), + }; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + + let result = runtime.block_on(async { capped.put("retained from an active runtime") }); + + assert!(result.retained()); +} + +#[test] +fn import_refuses_to_replace_different_content_at_a_legacy_token() { + let dir = tempfile::tempdir().unwrap(); + let content = "source legacy content"; + let token = tinyjuice::cache::short_hash(content); + let source_path = dir.path().join(&token); + std::fs::write(&source_path, content).unwrap(); + let blobs = open_file_blobs(dir.path()).unwrap(); + let key = format!("{CCR_PREFIX}/{token}"); + run_blob({ + let blobs = Arc::clone(&blobs); + let key = key.clone(); + async move { + blobs + .put(&key, b"different target content".to_vec(), None) + .await + } + }) + .unwrap(); + + let error = import_legacy_files(dir.path(), &blobs, None).unwrap_err(); + assert!(error.contains("conflicts with different stored content")); + assert!(source_path.exists(), "the unimported source is retained"); + let existing = run_blob({ + let blobs = Arc::clone(&blobs); + async move { blobs.get(&key).await } + }) + .unwrap() + .unwrap(); + assert_eq!(existing.bytes, b"different target content"); +} + +#[test] +fn retry_after_timestamp_write_failure_preserves_the_source_file_age() { + let dir = tempfile::tempdir().unwrap(); + let content = "legacy ccr whose age must survive an interrupted import"; + let token = tinyjuice::cache::short_hash(content); + let source_path = dir.path().join(&token); + std::fs::write(&source_path, content).unwrap(); + let source_time = SystemTime::now() - Duration::from_secs(20); + std::fs::OpenOptions::new() + .write(true) + .open(&source_path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(source_time)) + .unwrap(); + + let inner = open_file_blobs(dir.path()).unwrap(); + let faults = FaultPlan::new(); + faults.fail_operation_nth("metadata_put", 1, ErrorKind::Backend); + let failing: Arc = Arc::new(FailMetadataOperations { + inner: Arc::clone(&inner), + faults: faults.clone(), + }); + + assert!(import_legacy_files(dir.path(), &failing, None).is_err()); + assert!(source_path.exists(), "failed import must retain its source"); + let body_key = format!("{CCR_PREFIX}/{token}"); + assert!( + run_blob({ + let inner = Arc::clone(&inner); + let body_key = body_key.clone(); + async move { inner.get(&body_key).await } + }) + .unwrap() + .is_some(), + "the fault occurs after the body has been stored" + ); + + faults.clear(); + import_legacy_files(dir.path(), &failing, None).unwrap(); + assert!( + !source_path.exists(), + "retry completes and retires the source" + ); + assert_eq!( + read_semantic_time(Arc::clone(&inner), &token).unwrap(), + Some(unix_epoch_ms(source_time)) + ); + assert_eq!( + read_import_intent(Arc::clone(&inner), &token).unwrap(), + None + ); +} + +#[test] +fn imports_released_v01010_disk_tier_file_and_preserves_its_age() { + const TOKEN: &str = "1e66b4cff1835002102d821ffee64f75"; + const CONTENT: &str = + include_str!("../tests/fixtures/legacy-ccr/v0.10.10/1e66b4cff1835002102d821ffee64f75"); + + let dir = tempfile::tempdir().unwrap(); + let source_path = dir.path().join(TOKEN); + std::fs::write(&source_path, CONTENT).unwrap(); + let source_time = SystemTime::now() - Duration::from_secs(5); + std::fs::OpenOptions::new() + .write(true) + .open(&source_path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(source_time)) + .unwrap(); + + assert_eq!(tinyjuice::cache::short_hash(CONTENT), TOKEN); + let blobs = open_file_blobs(dir.path()).unwrap(); + import_legacy_files(dir.path(), &blobs, Some(Duration::from_secs(3600))).unwrap(); + + assert!(!source_path.exists(), "the verified legacy file is retired"); + let store = BlobCcrStore::new(Arc::clone(&blobs), None).unwrap(); + assert_eq!(store.get(TOKEN).as_deref(), Some(CONTENT)); + assert_eq!( + read_semantic_time(Arc::clone(&blobs), TOKEN).unwrap(), + Some(unix_epoch_ms(source_time)) + ); +} diff --git a/tests/cli.rs b/crates/tinyjuice-cli/tests/cli.rs similarity index 94% rename from tests/cli.rs rename to crates/tinyjuice-cli/tests/cli.rs index 6934fb2b..7398ac23 100644 --- a/tests/cli.rs +++ b/crates/tinyjuice-cli/tests/cli.rs @@ -3,7 +3,15 @@ use std::io::Write; use std::process::{Command, Stdio}; fn tinyjuice() -> Command { - Command::new(env!("CARGO_BIN_EXE_tinyjuice-reduce")) + let mut command = Command::new(env!("CARGO_BIN_EXE_tinyjuice-reduce")); + command.current_dir(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")); + command +} + +fn write_legacy_entry(directory: &std::path::Path, content: &str) -> String { + let token = tinyjuice::cache::short_hash(content); + fs::write(directory.join(&token), content).expect("write legacy CCR entry"); + token } #[test] @@ -183,7 +191,7 @@ fn wrap_preserves_wrapped_exit_code() { #[test] fn ls_lists_only_token_shaped_store_entries() { let dir = tempfile::tempdir().expect("temp store"); - fs::write(dir.path().join("0123456789abcdef0123456789abcdef"), "one").expect("write token"); + let token = write_legacy_entry(dir.path(), "one"); fs::write(dir.path().join("not-a-token"), "ignored").expect("write ignored"); let output = tinyjuice() @@ -194,18 +202,22 @@ fn ls_lists_only_token_shaped_store_entries() { assert!(output.status.success(), "{output:#?}"); assert_eq!( String::from_utf8(output.stdout).expect("utf8 stdout"), - "0123456789abcdef0123456789abcdef\n" + format!("{token}\n") ); } #[test] fn cat_reads_token_from_explicit_store_dir() { let dir = tempfile::tempdir().expect("temp store"); - let token = "0123456789abcdef0123456789abcdef"; - fs::write(dir.path().join(token), "alpha\nbeta\ngamma\n").expect("write token"); + let token = write_legacy_entry(dir.path(), "alpha\nbeta\ngamma\n"); let output = tinyjuice() - .args(["cat", "--store-dir", &dir.path().to_string_lossy(), token]) + .args([ + "cat", + "--store-dir", + &dir.path().to_string_lossy(), + token.as_str(), + ]) .output() .expect("run tinyjuice cat"); @@ -219,8 +231,7 @@ fn cat_reads_token_from_explicit_store_dir() { #[test] fn cat_reads_line_range_from_explicit_store_dir() { let dir = tempfile::tempdir().expect("temp store"); - let token = "0123456789abcdef0123456789abcdef"; - fs::write(dir.path().join(token), "alpha\nbeta\ngamma\ndelta\n").expect("write token"); + let token = write_legacy_entry(dir.path(), "alpha\nbeta\ngamma\ndelta\n"); let output = tinyjuice() .args([ @@ -229,7 +240,7 @@ fn cat_reads_line_range_from_explicit_store_dir() { &dir.path().to_string_lossy(), "--lines", "1:3", - token, + token.as_str(), ]) .output() .expect("run tinyjuice cat lines"); @@ -244,8 +255,7 @@ fn cat_reads_line_range_from_explicit_store_dir() { #[test] fn cat_reads_byte_range_from_explicit_store_dir() { let dir = tempfile::tempdir().expect("temp store"); - let token = "0123456789abcdef0123456789abcdef"; - fs::write(dir.path().join(token), "alpha beta gamma").expect("write token"); + let token = write_legacy_entry(dir.path(), "alpha beta gamma"); let output = tinyjuice() .args([ @@ -254,7 +264,7 @@ fn cat_reads_byte_range_from_explicit_store_dir() { &dir.path().to_string_lossy(), "--bytes", "6:10", - token, + token.as_str(), ]) .output() .expect("run tinyjuice cat bytes"); @@ -269,8 +279,7 @@ fn cat_reads_byte_range_from_explicit_store_dir() { #[test] fn cat_rejects_multiple_range_flags() { let dir = tempfile::tempdir().expect("temp store"); - let token = "0123456789abcdef0123456789abcdef"; - fs::write(dir.path().join(token), "alpha\nbeta\n").expect("write token"); + let token = write_legacy_entry(dir.path(), "alpha\nbeta\n"); let output = tinyjuice() .args([ @@ -281,7 +290,7 @@ fn cat_rejects_multiple_range_flags() { "0:1", "--bytes", "0:5", - token, + token.as_str(), ]) .output() .expect("run tinyjuice cat conflicting ranges"); @@ -297,9 +306,8 @@ fn cat_rejects_multiple_range_flags() { #[test] fn stats_reports_metadata_for_explicit_store_dir() { let dir = tempfile::tempdir().expect("temp store"); - fs::write(dir.path().join("0123456789abcdef0123456789abcdef"), "one").expect("write token"); - fs::write(dir.path().join("fedcba9876543210fedcba9876543210"), "three") - .expect("write second token"); + write_legacy_entry(dir.path(), "one"); + write_legacy_entry(dir.path(), "three"); fs::write(dir.path().join("not-a-token"), "ignored raw content").expect("write ignored"); fs::create_dir(dir.path().join("subdir")).expect("create ignored dir"); diff --git a/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/1e66b4cff1835002102d821ffee64f75 b/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/1e66b4cff1835002102d821ffee64f75 new file mode 100644 index 00000000..85425b7c --- /dev/null +++ b/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/1e66b4cff1835002102d821ffee64f75 @@ -0,0 +1 @@ +Fixture written by TinyJuice v0.10.10 public disk-tier API. \ No newline at end of file diff --git a/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/README.md b/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/README.md new file mode 100644 index 00000000..7f63d2a3 --- /dev/null +++ b/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/README.md @@ -0,0 +1,35 @@ +# TinyJuice v0.10.10 disk-tier CCR fixture + +This file was produced by the public CCR writer in released TinyJuice `v0.10.10`, +not reconstructed from the current implementation. The tag resolves to +`4db24354d0e883f6a0aefe96e5cc0c76073fd76e`. Its root `Cargo.toml` and +`Cargo.lock` hashes are respectively +`689e3b78858fbf65a33b8b56e01134a49698bb835f00c2f0b5e05b93e6a9eb95` and +`62b38e108654d0b4b97009c6cd6cd412e954a5d9dc46bedc24b1767f3a51ba4c`. + +The archived writer was injected with `examples/write_ccr_fixture.rs` +(`ab050f31a019797b5e5d05aa33ad315a61b5ffa6ec3b3b465644f1caaa5ee2bc`). It +calls `tinyjuice::cache::{configure, configure_disk_cap, enable_disk_tier, +offload_checked}`. The recorded TinyBus and TinyAgents gitlinks were restored +at `207a9a7df15e44fdba00a807d0f7eaf21904ba0e` and +`aa5476fa48092d9bf051fbd2d1bf07f14cc9f331`; neither archived manifest nor +lockfile was changed. Reproduce from the native repository root with: + +```sh +mkdir -p target/legacy-writer-v0.10.10 +git archive --format=tar 4db24354d0e883f6a0aefe96e5cc0c76073fd76e | tar -x -C target/legacy-writer-v0.10.10 +mkdir -p target/legacy-writer-v0.10.10/vendor/tinybus target/legacy-writer-v0.10.10/vendor/tinyagents target/legacy-writer-v0.10.10/examples target/legacy-writer-v0.10.10/legacy-output target/legacy-source-cache/tinybus +git -C target/legacy-source-cache/tinybus init +git -C target/legacy-source-cache/tinybus fetch --depth=1 https://github.com/tinyhumansai/tinybus.git 207a9a7df15e44fdba00a807d0f7eaf21904ba0e +git -C target/legacy-source-cache/tinybus checkout --detach FETCH_HEAD +git -C target/legacy-source-cache/tinybus archive 207a9a7df15e44fdba00a807d0f7eaf21904ba0e | tar -x -C target/legacy-writer-v0.10.10/vendor/tinybus +git -C vendor/tinyagents archive aa5476fa48092d9bf051fbd2d1bf07f14cc9f331 | tar -x -C target/legacy-writer-v0.10.10/vendor/tinyagents +cp crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/write_ccr_fixture.rs target/legacy-writer-v0.10.10/examples/ +cargo run --locked --manifest-path target/legacy-writer-v0.10.10/Cargo.toml -p tinyjuice --example write_ccr_fixture -- target/legacy-writer-v0.10.10/legacy-output "Fixture written by TinyJuice v0.10.10 public disk-tier API." +``` + +The writer emitted token `1e66b4cff1835002102d821ffee64f75`. The checked-in +raw body is 59 bytes with SHA-256 +`1e66b4cff1835002102d821ffee64f751d1c89efe286027d815bfdd8c25827b5`. Its timestamp is set by the import test +on a temporary copy so the test can check preserved semantic age without +changing the writer-produced bytes. diff --git a/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/write_ccr_fixture.rs b/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/write_ccr_fixture.rs new file mode 100644 index 00000000..5892a787 --- /dev/null +++ b/crates/tinyjuice-cli/tests/fixtures/legacy-ccr/v0.10.10/write_ccr_fixture.rs @@ -0,0 +1,12 @@ +use std::{env, path::PathBuf}; +fn main() { + let mut args = env::args().skip(1); + let root = PathBuf::from(args.next().expect("output directory")); + let content = args.next().expect("fixture content"); + tinyjuice::cache::configure(256, 1024 * 1024, Some(604800)); + tinyjuice::cache::configure_disk_cap(Some(1024 * 1024)); + tinyjuice::cache::enable_disk_tier(root); + let (token, retained) = tinyjuice::cache::offload_checked(&content); + assert!(retained, "released CCR writer must retain its original"); + println!("{token}"); +} diff --git a/tests/host_cli.rs b/crates/tinyjuice-cli/tests/host_cli.rs similarity index 73% rename from tests/host_cli.rs rename to crates/tinyjuice-cli/tests/host_cli.rs index 154becdd..67f61d93 100644 --- a/tests/host_cli.rs +++ b/crates/tinyjuice-cli/tests/host_cli.rs @@ -118,6 +118,67 @@ fn host_cli_help_templates_and_gc_are_usable() { } } +#[test] +fn reduce_json_help_and_argument_errors_do_not_open_cache() { + let dir = tempfile::tempdir().unwrap(); + let cache_path = dir.path().join("not-a-directory"); + std::fs::write(&cache_path, "not a directory").unwrap(); + + for (args, expected_success, expected_output) in [ + (&["reduce-json", "--help"][..], true, "Usage:"), + ( + &["reduce-json", "--unknown"][..], + false, + "unknown reduce-json flag", + ), + ] { + let out = Command::new(env!("CARGO_BIN_EXE_tinyjuice")) + .args(args) + .env("TINYJUICE_CCR_DIR", &cache_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .unwrap(); + assert_eq!(out.status.success(), expected_success, "{args:?}: {out:?}"); + let output = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!(output.contains(expected_output), "{args:?}: {output}"); + assert!(!output.contains("not a directory"), "{args:?}: {output}"); + } +} + +#[test] +fn retrieve_argument_errors_do_not_open_cache() { + let dir = tempfile::tempdir().unwrap(); + let cache_path = dir.path().join("not-a-directory"); + std::fs::write(&cache_path, "not a directory").unwrap(); + + for (args, expected_error) in [ + (&["retrieve"][..], "retrieve requires a CCR token"), + ( + &["retrieve", "one", "two"][..], + "retrieve accepts exactly one CCR token", + ), + ] { + let out = Command::new(env!("CARGO_BIN_EXE_tinyjuice")) + .args(args) + .env("TINYJUICE_CCR_DIR", &cache_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .unwrap(); + assert!(!out.status.success(), "{args:?}: {out:?}"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains(expected_error), "{args:?}: {stderr}"); + assert!(!stderr.contains("not a directory"), "{args:?}: {stderr}"); + } +} + #[test] fn host_cli_install_update_and_uninstall_preserve_settings() { let dir = tempfile::tempdir().unwrap(); @@ -212,6 +273,34 @@ fn host_cli_reads_json_files_and_accepts_hooks_without_output() { } } +#[test] +fn post_tool_hook_skips_compression_when_persistent_cache_storage_cannot_open() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("ccr"), "not a directory").unwrap(); + let output = (0..200) + .map(|index| format!("\tmodified: src/file_{index}.rs")) + .collect::>() + .join("\n"); + let payload = serde_json::json!({ + "hook_event_name": "PostToolUse", + "tool_name": "Bash", + "tool_input": {"command": "git status"}, + "tool_response": {"output": output, "exitCode": 0} + }) + .to_string(); + + let out = invoke(dir.path(), &["codex-post-tool-use"], &payload); + + assert!( + out.status.success(), + "cache setup must not fail the hook: {out:?}" + ); + assert!( + out.stdout.is_empty(), + "without durable recovery, the hook must leave host output unchanged" + ); +} + #[test] fn host_cli_retrieves_original_from_disk_tier() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/tinyjuice-drivers/Cargo.toml b/crates/tinyjuice-drivers/Cargo.toml index b71f6377..cd82a0a4 100644 --- a/crates/tinyjuice-drivers/Cargo.toml +++ b/crates/tinyjuice-drivers/Cargo.toml @@ -1,5 +1,5 @@ [package] -rust-version = "1.88" +rust-version = "1.90" name = "tinyjuice-drivers" version = "0.9.0" edition = "2024" @@ -12,11 +12,15 @@ repository = "https://github.com/tinyhumansai/tinyjuice" publish = false [dependencies] -tinyjuice-bus = { path = "../tinyjuice-bus", features = ["storage"] } +tinyjuice-bus = { path = "../tinyjuice-bus" } tinyjuice = { path = "../..", default-features = false } -tinystoragedrivers-core = { version = "1.0.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", features = ["blocking"] } +tinystoragedrivers-api = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +tinystoragedrivers-types = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } log = "0.4" +tokio = { version = "1", features = ["rt"] } [dev-dependencies] tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } async-trait = "0.1" +tinystoragedrivers-testkit = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +tinystoragedrivers-blob = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } diff --git a/crates/tinyjuice-drivers/src/blob_store.rs b/crates/tinyjuice-drivers/src/blob_store.rs index 8103b887..4f84a54e 100644 --- a/crates/tinyjuice-drivers/src/blob_store.rs +++ b/crates/tinyjuice-drivers/src/blob_store.rs @@ -4,7 +4,10 @@ use std::sync::Arc; use std::time::Duration; use tinyjuice::cache::store::{CcrPutResult, CcrStore, RangeUnit, range_from_original, short_hash}; -use tinystoragedrivers_core::{BlobStore, Blocking, Capability, StorageError}; +use tinystoragedrivers_api::BlobStore; +use tinystoragedrivers_types::{Capability, StorageError}; + +use crate::blocking::Blocking; pub use tinyjuice_bus::storage::CCR_PREFIX; diff --git a/crates/tinyjuice-drivers/src/blob_store_tests.rs b/crates/tinyjuice-drivers/src/blob_store_tests.rs index 9a1cdc0d..54f42360 100644 --- a/crates/tinyjuice-drivers/src/blob_store_tests.rs +++ b/crates/tinyjuice-drivers/src/blob_store_tests.rs @@ -1,26 +1,36 @@ use super::*; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use tinystoragedrivers_core::{Capability, MemoryStorage, Scope, StorageBackend}; +use tinystoragedrivers_api::BlobStore; +use tinystoragedrivers_types::{Capability, ErrorKind, Scope}; use crate::faulty::Faulty; -fn clocked() -> (MemoryStorage, Arc) { - let now = Arc::new(AtomicU64::new(1_000)); - let reading = Arc::clone(&now); +static TEST_NOW: AtomicU64 = AtomicU64::new(1_000); +static CLOCK_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn test_now_ms() -> u64 { + TEST_NOW.load(Ordering::SeqCst) +} + +fn clocked() -> (Arc, &'static AtomicU64) { + let scope = Scope::new("local").unwrap(); ( - MemoryStorage::with_clock(Arc::new(move || reading.load(Ordering::SeqCst))), - now, + Arc::new(tinystoragedrivers_blob::MemoryBlobStore::with_clock( + scope, + test_now_ms, + )), + &TEST_NOW, ) } -fn handle(storage: &MemoryStorage) -> Arc { - Arc::clone(storage.for_scope(&Scope::local()).unwrap().blobs()) +fn handle() -> Arc { + Arc::clone(tinystoragedrivers_testkit::memory_storage(&Scope::new("local").unwrap()).blobs()) } -fn faulty(storage: &MemoryStorage, ttl: bool) -> (Arc, Arc) { +fn faulty(ttl: bool) -> (Arc, Arc) { let fail = Arc::new(AtomicBool::new(false)); let blobs: Arc = Arc::new(Faulty { - inner: handle(storage), + inner: handle(), fail: Arc::clone(&fail), ttl, }); @@ -29,16 +39,16 @@ fn faulty(storage: &MemoryStorage, ttl: bool) -> (Arc, Arc; + +thread_local! { + static ON_BRIDGE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs asynchronous storage operations for the synchronous `CcrStore` trait. +#[derive(Clone)] +pub(crate) struct Blocking { + jobs: Sender, +} + +impl fmt::Debug for Blocking { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Blocking").finish_non_exhaustive() + } +} + +impl Blocking { + pub(crate) fn new() -> Result { + let (jobs, receiver) = mpsc::channel::(); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(runtime_build_error)?; + thread::Builder::new() + .name("tinyjuice-storage-bridge".into()) + .spawn(move || { + ON_BRIDGE.with(|active| active.set(true)); + while let Ok(job) = receiver.recv() { + job(&runtime); + } + }) + .map_err(thread_start_error)?; + Ok(Self { jobs }) + } + + pub(crate) fn run(&self, future: F) -> Result + where + F: Future + Send + 'static, + T: Send + 'static, + { + if ON_BRIDGE.with(std::cell::Cell::get) { + return Err(StorageError::backend("storage bridge re-entered")); + } + let (reply, wait) = mpsc::sync_channel(1); + self.jobs + .send(Box::new(move |runtime| { + let _ = reply.send(runtime.block_on(future)); + })) + .map_err(|_| StorageError::backend("storage bridge stopped"))?; + wait.recv() + .map_err(|_| StorageError::backend("storage bridge dropped a call")) + } +} + +fn runtime_build_error(error: std::io::Error) -> StorageError { + StorageError::backend("cannot build the storage bridge runtime").with_source(error) +} + +fn thread_start_error(error: std::io::Error) -> StorageError { + StorageError::backend("cannot start the storage bridge").with_source(error) +} + +#[cfg(test)] +#[path = "blocking_tests.rs"] +mod tests; diff --git a/crates/tinyjuice-drivers/src/blocking_tests.rs b/crates/tinyjuice-drivers/src/blocking_tests.rs new file mode 100644 index 00000000..df642099 --- /dev/null +++ b/crates/tinyjuice-drivers/src/blocking_tests.rs @@ -0,0 +1,65 @@ +use super::*; + +#[test] +fn debug_output_hides_runtime_implementation() { + let bridge = Blocking::new().unwrap(); + let debug = format!("{bridge:?}"); + + assert_eq!(debug, "Blocking { .. }"); +} + +#[test] +fn bridge_rejects_reentrant_storage_calls() { + let bridge = Blocking::new().unwrap(); + let nested = bridge.clone(); + + let nested_result = bridge.run(async move { nested.run(async {}) }).unwrap(); + + assert!( + nested_result + .unwrap_err() + .to_string() + .contains("re-entered") + ); +} + +#[test] +fn bridge_reports_calls_when_its_worker_has_stopped() { + let (jobs, receiver) = mpsc::channel::(); + drop(receiver); + let bridge = Blocking { jobs }; + + let error = bridge.run(async {}).unwrap_err(); + + assert!(error.to_string().contains("storage bridge stopped")); +} + +#[test] +fn bridge_reports_a_worker_that_drops_a_call_without_replying() { + let (jobs, receiver) = mpsc::channel::(); + thread::spawn(move || drop(receiver.recv().unwrap())); + let bridge = Blocking { jobs }; + + let error = bridge.run(async {}).unwrap_err(); + + assert!(error.to_string().contains("storage bridge dropped a call")); +} + +#[test] +fn startup_errors_keep_their_source_and_backend_context() { + let runtime_error = runtime_build_error(std::io::Error::other("runtime resources unavailable")); + let thread_error = thread_start_error(std::io::Error::other("thread resources unavailable")); + + assert!( + runtime_error + .to_string() + .contains("cannot build the storage bridge runtime") + ); + assert!(std::error::Error::source(&runtime_error).is_some()); + assert!( + thread_error + .to_string() + .contains("cannot start the storage bridge") + ); + assert!(std::error::Error::source(&thread_error).is_some()); +} diff --git a/crates/tinyjuice-drivers/src/faulty_tests.rs b/crates/tinyjuice-drivers/src/faulty_tests.rs index 5b885624..41976a6a 100644 --- a/crates/tinyjuice-drivers/src/faulty_tests.rs +++ b/crates/tinyjuice-drivers/src/faulty_tests.rs @@ -6,7 +6,8 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use async_trait::async_trait; -use tinystoragedrivers_core::{Blob, BlobMeta, BlobStore, Capabilities, Result, StorageError}; +use tinystoragedrivers_api::BlobStore; +use tinystoragedrivers_types::{Blob, BlobMeta, Capabilities, Result, StorageError}; /// Wraps a real handle; `fail` makes every call error, `ttl` toggles whether /// it claims `BlobTtl`. @@ -29,6 +30,9 @@ impl Faulty { #[async_trait] impl BlobStore for Faulty { + fn max_key_len(&self) -> usize { + self.inner.max_key_len() + } async fn put(&self, key: &str, bytes: Vec, ct: Option<&str>) -> Result { self.check()?; self.inner.put(key, bytes, ct).await diff --git a/crates/tinyjuice-drivers/src/lib.rs b/crates/tinyjuice-drivers/src/lib.rs index 07b99801..bc7ab067 100644 --- a/crates/tinyjuice-drivers/src/lib.rs +++ b/crates/tinyjuice-drivers/src/lib.rs @@ -7,17 +7,16 @@ //! host's choice, made when it builds the [`BlobStore`] handle. Nothing here //! names a database. //! -//! [`tinyjuice::cache::CcrStore`] is synchronous, so the store owns a -//! [`Blocking`] bridge that runs the port's futures on a dedicated runtime -//! thread. That works from inside or outside a tokio runtime. +//! [`tinyjuice::cache::CcrStore`] is synchronous, so the store uses a private +//! blocking bridge to run the port's futures on a dedicated runtime thread. +//! That works from inside or outside a tokio runtime. //! -//! [`BlobStore`]: tinystoragedrivers_core::BlobStore -//! [`Blocking`]: tinystoragedrivers_core::Blocking +//! [`BlobStore`]: tinystoragedrivers_api::BlobStore mod blob_store; +mod blocking; pub use blob_store::{BlobCcrStore, CCR_PREFIX}; -pub use tinyjuice_bus::storage::storage_schema; #[cfg(test)] #[path = "faulty_tests.rs"] diff --git a/crates/tinyjuice-examples/Cargo.lock b/crates/tinyjuice-examples/Cargo.lock index 17b7338d..7585b065 100644 --- a/crates/tinyjuice-examples/Cargo.lock +++ b/crates/tinyjuice-examples/Cargo.lock @@ -1689,7 +1689,7 @@ dependencies = [ "async-trait", "serde", "serde_json", - "tinytools", + "tinytools 0.5.0", "toml", "tracing", ] @@ -1716,7 +1716,7 @@ dependencies = [ "tinyinference-embeddings", "tinyinference-llm", "tinystoragedrivers-core", - "tinytools", + "tinytools 0.5.0", "tinytools-agent", "tokio", "tracing", @@ -1789,7 +1789,7 @@ dependencies = [ [[package]] name = "tinyjuice" -version = "0.10.4" +version = "0.11.0" dependencies = [ "anyhow", "async-trait", @@ -1806,7 +1806,7 @@ dependencies = [ "sha2 0.11.0", "thiserror", "tinyjuice-bus", - "tinytools", + "tinytools 0.6.0", "tokio", "tree-sitter", "tree-sitter-python", @@ -1818,11 +1818,12 @@ dependencies = [ [[package]] name = "tinyjuice-bus" -version = "0.10.4" +version = "0.11.0" dependencies = [ "serde", "serde_json", "thiserror", + "tinystoragedrivers-types", ] [[package]] @@ -1835,7 +1836,7 @@ dependencies = [ "tinyagents-harness", "tinyinference-llm", "tinyjuice", - "tinytools", + "tinytools 0.5.0", "tokio", ] @@ -1874,6 +1875,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "tinystoragedrivers-types" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=05eaada962decbab33bafa4763d2bd1a67f6b456#05eaada962decbab33bafa4763d2bd1a67f6b456" +dependencies = [ + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -1894,6 +1905,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tinytools" +version = "0.6.0" +source = "git+https://github.com/tinyhumansai/tinytools?rev=3a01641f8ebd8a55656cd212f9a90638d958a447#3a01641f8ebd8a55656cd212f9a90638d958a447" +dependencies = [ + "anyhow", + "async-trait", + "serde", + "serde_json", +] + [[package]] name = "tinytools-agent" version = "0.5.0" @@ -1901,7 +1923,7 @@ dependencies = [ "regex", "serde", "serde_json", - "tinytools", + "tinytools 0.5.0", ] [[package]] diff --git a/crates/tinyjuice-examples/Cargo.toml b/crates/tinyjuice-examples/Cargo.toml index 46edadde..7d1b8e0c 100644 --- a/crates/tinyjuice-examples/Cargo.toml +++ b/crates/tinyjuice-examples/Cargo.toml @@ -1,5 +1,5 @@ [package] -rust-version = "1.88" +rust-version = "1.90" name = "tinyjuice-examples" version = "0.0.0" edition = "2024" diff --git a/crates/tinyjuice-module/Cargo.toml b/crates/tinyjuice-module/Cargo.toml index 043c5082..7f4e55ec 100644 --- a/crates/tinyjuice-module/Cargo.toml +++ b/crates/tinyjuice-module/Cargo.toml @@ -1,5 +1,5 @@ [package] -rust-version = "1.88" +rust-version = "1.90" name = "tinyjuice-module" version = "0.11.0" edition = "2024" @@ -21,21 +21,22 @@ tinyjuice = { path = "../..", default-features = false, features = ["jq"] } # The interface vocabulary. Shared with hosts, so this adapter cannot drift # from what a caller was compiled against. tinyjuice-bus = { path = "../tinyjuice-bus" } -tinybus = { version = ">=0.1.3, <0.2", default-features = false, features = ["macros", "modules"] } -tinybus-module = ">=0.1.3, <0.2" +tinybus = { version = "=0.1.6", git = "https://github.com/tinyhumansai/tinybus", rev = "0de2d283f35cbbff08efad6fbe05537ffb74611b", default-features = false, features = ["macros", "modules"] } +tinybus-module = { version = "=0.1.6", git = "https://github.com/tinyhumansai/tinybus", rev = "0de2d283f35cbbff08efad6fbe05537ffb74611b" } tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync"] } serde_json = "1" # The CCR store's durable tier is blobs on the host's storage ports, reached # over the storage bus. The module has no storage backend or file of its own. tinyjuice-drivers = { path = "../tinyjuice-drivers" } -tinystoragedrivers-core = { version = "1.0.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" } -tinystoragedrivers-busproxy = { version = "1.0.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" } +tinystoragedrivers-api = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +tinystoragedrivers-types = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +tinystoragedrivers-busproxy = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } log = "0.4" [dev-dependencies] # Tests serve the storage objects on the in-memory broker the module connects to. -tinystoragedrivers-client = { version = "1.0.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" } -tinybus = { version = ">=0.1.3, <0.2", default-features = false, features = ["test-support"] } +tinystoragedrivers-testkit = { version = "2.1.0", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "05eaada962decbab33bafa4763d2bd1a67f6b456" } +tinybus = { version = "=0.1.6", git = "https://github.com/tinyhumansai/tinybus", rev = "0de2d283f35cbbff08efad6fbe05537ffb74611b", default-features = false, features = ["test-support"] } tempfile = "3" async-trait = "0.1" tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } diff --git a/crates/tinyjuice-module/src/lib.rs b/crates/tinyjuice-module/src/lib.rs index 7ff93b86..c7136f59 100644 --- a/crates/tinyjuice-module/src/lib.rs +++ b/crates/tinyjuice-module/src/lib.rs @@ -21,7 +21,5 @@ pub use service::exports::linked_module; pub use service::{BUS_NAME, OBJECT_PATH}; -/// What the module stores. A host composes it into its schema registry and -/// derives the module's storage grant from it, so the grant never repeats the -/// blob prefix by hand. -pub use tinyjuice_drivers::storage_schema; +/// Collections declared by TinyJuice's storage contract. +pub use tinyjuice_bus::storage::collections; diff --git a/crates/tinyjuice-module/src/savings_store.rs b/crates/tinyjuice-module/src/savings_store.rs index ec123021..3f93d81f 100644 --- a/crates/tinyjuice-module/src/savings_store.rs +++ b/crates/tinyjuice-module/src/savings_store.rs @@ -13,7 +13,8 @@ use tinyjuice_bus::savings::{ RecordSavingsRequest, SAVINGS_DOC_ID, SavingsAggregate, StoredSavings, }; use tinyjuice_bus::storage::SAVINGS_COLLECTION; -use tinystoragedrivers_core::{DocumentStore, DocumentStoreExt, Precondition}; +use tinystoragedrivers_api::{DocumentStore, DocumentStoreExt, Storage}; +use tinystoragedrivers_types::Precondition; /// Working state behind one lock, so load, change and write never interleave. #[derive(Default)] @@ -107,6 +108,52 @@ impl Savings { Ok(true) } + /// Adopt a legacy snapshot through a storage handle supplied for this one + /// call. This handle is deliberately not cached in `State`: hosts use it + /// for claim-bound imports, and its authority ends when the call returns. + pub(crate) async fn import_at( + &self, + _connection: Option<&Connection>, + storage: &Storage, + legacy: SavingsAggregate, + ) -> BusResult { + let mut state = self.state.lock().await; + let docs = storage.documents(); + let stored = docs + .get_as::(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await + .map_err(|error| { + tinybus::Error::failed(format!("savings could not be read: {error}")) + })?; + if stored + .as_ref() + .is_some_and(|stored| stored.doc.total.events != 0) + { + log::debug!("[tinyjuice_module][savings] import skipped: totals exist"); + return Ok(false); + } + + // Import is a read-modify-write operation. Preserve the observed + // document version (or absence) so a concurrent normal savings write + // cannot be overwritten by this legacy snapshot. + let precondition = stored.map_or(Precondition::Absent, |stored| { + Precondition::Version(stored.version) + }); + + let body = StoredSavings::from_aggregate(&legacy, now_ms()); + docs.put_as(SAVINGS_COLLECTION, SAVINGS_DOC_ID, &body, precondition) + .await + .map_err(|error| { + tinybus::Error::failed(format!("savings could not be written: {error}")) + })?; + + // The callback port is invocation-scoped and may address a different + // document from the ordinary port. Invalidate the cached ledger so the + // next ordinary operation reloads only through the ordinary port. + state.loaded = false; + Ok(true) + } + /// Reach the document port and reconcile the ledger with its document. /// /// Changes made before the document could be read are kept: they are @@ -116,11 +163,11 @@ impl Savings { if state.loaded { return; } - let Some(connection) = connection else { - state.loaded = true; - return; - }; if state.docs.is_none() { + let Some(connection) = connection else { + state.loaded = true; + return; + }; if state .last_connect_failure .is_some_and(|at| at.elapsed() < self.cooldown) @@ -144,9 +191,11 @@ impl Savings { } }; if let Some(stored) = stored.filter(|_| !state.reset_early) { - let early = self.ledger.stats(); + let early = state.dirty.then(|| self.ledger.stats()); self.ledger.replace(stored); - self.ledger.absorb(&early); + if let Some(early) = early { + self.ledger.absorb(&early); + } } state.loaded = true; if state.dirty { diff --git a/crates/tinyjuice-module/src/savings_store_tests.rs b/crates/tinyjuice-module/src/savings_store_tests.rs index 56dd0968..eb6a0fd1 100644 --- a/crates/tinyjuice-module/src/savings_store_tests.rs +++ b/crates/tinyjuice-module/src/savings_store_tests.rs @@ -1,7 +1,9 @@ use super::*; use crate::storage::tests::rig; use tinyjuice_bus::savings::SavingsBucket; -use tinystoragedrivers_core::{Scope, StorageBackend}; +use tinystoragedrivers_api::{DocumentStore, Storage, StorageBackend}; +use tinystoragedrivers_testkit::{Failing, FaultPlan}; +use tinystoragedrivers_types::{ErrorKind, Scope}; type TestResult = Result<(), Box>; @@ -18,7 +20,7 @@ fn req(original: u64, compacted: u64) -> RecordSavingsRequest { async fn stored( rig: &crate::storage::tests::Rig, ) -> Result, Box> { - let docs = Arc::clone(rig.backend.for_scope(&Scope::local())?.documents()); + let docs = Arc::clone(rig.backend.for_scope(&Scope::new("local")?)?.documents()); Ok(docs .get(SAVINGS_COLLECTION, SAVINGS_DOC_ID) .await? @@ -156,102 +158,18 @@ async fn a_host_without_storage_is_not_asked_again_within_the_cooldown() -> Test Ok(()) } -/// The real document store, except that writes fail while `fail_puts` is set. -#[derive(Debug)] -struct FlakyDocs { - inner: Arc, - fail_puts: std::sync::atomic::AtomicBool, -} - -#[tinystoragedrivers_core::async_trait] -impl DocumentStore for FlakyDocs { - fn capabilities(&self) -> tinystoragedrivers_core::Capabilities { - self.inner.capabilities() - } - async fn ensure_collection( - &self, - spec: &tinystoragedrivers_core::CollectionSpec, - ) -> tinystoragedrivers_core::Result<()> { - self.inner.ensure_collection(spec).await - } - async fn get( - &self, - collection: &str, - id: &str, - ) -> tinystoragedrivers_core::Result< - Option>, - > { - self.inner.get(collection, id).await - } - async fn put( - &self, - collection: &str, - id: &str, - doc: serde_json::Value, - precondition: Precondition, - ) -> tinystoragedrivers_core::Result { - if self.fail_puts.load(std::sync::atomic::Ordering::SeqCst) { - return Err(tinystoragedrivers_core::StorageError::unavailable( - "writes are down", - )); - } - self.inner.put(collection, id, doc, precondition).await - } - async fn delete( - &self, - collection: &str, - id: &str, - precondition: Precondition, - ) -> tinystoragedrivers_core::Result { - self.inner.delete(collection, id, precondition).await - } - async fn query( - &self, - collection: &str, - query: &tinystoragedrivers_core::Query, - ) -> tinystoragedrivers_core::Result< - tinystoragedrivers_core::Page>, - > { - self.inner.query(collection, query).await - } - async fn count( - &self, - collection: &str, - filter: &tinystoragedrivers_core::Filter, - ) -> tinystoragedrivers_core::Result { - self.inner.count(collection, filter).await - } - async fn delete_where( - &self, - collection: &str, - filter: &tinystoragedrivers_core::Filter, - ) -> tinystoragedrivers_core::Result { - self.inner.delete_where(collection, filter).await - } - async fn claim( - &self, - collection: &str, - filter: &tinystoragedrivers_core::Filter, - sort: &[tinystoragedrivers_core::Sort], - patch: &serde_json::Value, - ) -> tinystoragedrivers_core::Result< - Option>, - > { - self.inner.claim(collection, filter, sort, patch).await - } - async fn drop_collection(&self, collection: &str) -> tinystoragedrivers_core::Result<()> { - self.inner.drop_collection(collection).await - } -} - #[tokio::test] async fn an_import_whose_write_fails_is_an_error_leaves_totals_alone_and_can_retry() { - let backend = tinystoragedrivers_core::MemoryStorage::new(); - let inner = Arc::clone(backend.for_scope(&Scope::local()).unwrap().documents()); - let flaky = Arc::new(FlakyDocs { - inner, - fail_puts: std::sync::atomic::AtomicBool::new(true), - }); + let backend = tinystoragedrivers_testkit::memory_backend(); + let inner = Arc::clone( + backend + .for_scope(&Scope::new("local").unwrap()) + .unwrap() + .documents(), + ); + let faults = FaultPlan::new(); + faults.fail_operation_nth("documents.put", 1, ErrorKind::Unavailable); + let flaky = Arc::new(Failing::with_plan(inner, faults)); let savings = Savings::new(); { let mut state = savings.state.lock().await; @@ -277,11 +195,226 @@ async fn an_import_whose_write_fails_is_an_error_leaves_totals_alone_and_can_ret "totals roll back" ); - flaky - .fail_puts - .store(false, std::sync::atomic::Ordering::SeqCst); assert!(savings.import(None, legacy).await.unwrap()); assert_eq!(savings.stats(None).await.total.tokens_saved, 20); let stored = flaky.get(SAVINGS_COLLECTION, SAVINGS_DOC_ID).await.unwrap(); assert_eq!(stored.unwrap().doc["total"]["events"], 3); } + +#[tokio::test] +async fn request_local_import_refusal_leaves_the_cached_ledger_unchanged() { + let backend = tinystoragedrivers_testkit::memory_backend(); + let ordinary = backend.for_scope(&Scope::new("ordinary").unwrap()).unwrap(); + let callback = backend.for_scope(&Scope::new("callback").unwrap()).unwrap(); + let faults = FaultPlan::new(); + faults.fail_operation_nth("documents.put", 1, ErrorKind::Unavailable); + let callback_docs = Arc::new(Failing::with_plan(Arc::clone(callback.documents()), faults)); + let callback_storage = tinystoragedrivers_api::Storage::new( + callback_docs.clone(), + Arc::clone(callback.streams()), + Arc::clone(callback.kv()), + Arc::clone(callback.blobs()), + Arc::clone(callback.queues()), + Arc::clone(callback.secrets()), + ); + let savings = Savings::new(); + { + let mut state = savings.state.lock().await; + state.docs = Some(Arc::clone(ordinary.documents())); + state.loaded = true; + } + let legacy = SavingsAggregate { + total: SavingsBucket { + events: 3, + original_tokens: 30, + compacted_tokens: 10, + tokens_saved: 20, + cost_saved_usd: 0.1, + }, + ..Default::default() + }; + + let failed = savings.import_at(None, &callback_storage, legacy).await; + assert!(failed.is_err()); + assert_eq!(savings.stats(None).await.total.events, 0); + assert!( + ordinary + .documents() + .get(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await + .unwrap() + .is_none() + ); + assert!( + callback + .documents() + .get(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn request_local_import_uses_the_call_storage_without_caching_it() { + let backend = tinystoragedrivers_testkit::memory_backend(); + let ordinary = backend.for_scope(&Scope::new("local").unwrap()).unwrap(); + let ordinary_docs = Arc::clone(ordinary.documents()); + let callback_docs = Arc::new(Failing::with_plan( + Arc::clone(&ordinary_docs), + FaultPlan::new(), + )); + let callback_storage = tinystoragedrivers_api::Storage::new( + callback_docs, + Arc::clone(ordinary.streams()), + Arc::clone(ordinary.kv()), + Arc::clone(ordinary.blobs()), + Arc::clone(ordinary.queues()), + Arc::clone(ordinary.secrets()), + ); + let savings = Savings::new(); + { + let mut state = savings.state.lock().await; + state.docs = Some(Arc::clone(&ordinary_docs)); + state.loaded = true; + } + let legacy = SavingsAggregate { + total: SavingsBucket { + events: 2, + original_tokens: 18, + compacted_tokens: 8, + tokens_saved: 10, + cost_saved_usd: 0.25, + }, + ..Default::default() + }; + + assert!( + savings + .import_at(None, &callback_storage, legacy) + .await + .unwrap() + ); + assert_eq!( + ordinary_docs + .get(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await + .unwrap() + .unwrap() + .doc["total"]["tokens_saved"], + 10 + ); + assert_eq!(savings.stats(None).await.total.events, 2); + let state = savings.state.lock().await; + assert!(Arc::ptr_eq( + state.docs.as_ref().expect("ordinary port remains cached"), + &ordinary_docs, + )); +} + +#[tokio::test] +async fn request_local_import_works_without_an_ordinary_storage_port() -> TestResult { + let rig = rig(false).await?; + let callback = tinystoragedrivers_testkit::memory_backend(); + let callback = callback.for_scope(&Scope::new("callback")?)?; + let callback_storage = Storage::new( + Arc::clone(callback.documents()), + Arc::clone(callback.streams()), + Arc::clone(callback.kv()), + Arc::clone(callback.blobs()), + Arc::clone(callback.queues()), + Arc::clone(callback.secrets()), + ); + let savings = Savings::new(); + let legacy = SavingsAggregate { + total: SavingsBucket { + events: 2, + original_tokens: 20, + compacted_tokens: 10, + tokens_saved: 10, + cost_saved_usd: 0.1, + }, + ..Default::default() + }; + + assert!(savings.import_at(None, &callback_storage, legacy).await?); + assert_eq!(savings.stats(Some(&rig.module)).await.total.events, 0); + assert_eq!( + callback_storage + .documents() + .get_as::(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await? + .unwrap() + .doc + .total + .events, + 2 + ); + Ok(()) +} + +#[tokio::test] +async fn request_local_import_uses_callback_destination_when_ordinary_totals_exist() -> TestResult { + let backend = tinystoragedrivers_testkit::memory_backend(); + let ordinary = backend.for_scope(&Scope::new("ordinary")?)?; + let callback = backend.for_scope(&Scope::new("callback")?)?; + let savings = Savings::new(); + let ordinary_totals = SavingsAggregate { + total: SavingsBucket { + events: 1, + original_tokens: 9, + compacted_tokens: 4, + tokens_saved: 5, + cost_saved_usd: 0.1, + }, + ..Default::default() + }; + ordinary + .documents() + .put_as( + SAVINGS_COLLECTION, + SAVINGS_DOC_ID, + &StoredSavings::from_aggregate(&ordinary_totals, now_ms()), + Precondition::Absent, + ) + .await?; + { + let mut state = savings.state.lock().await; + state.docs = Some(Arc::clone(ordinary.documents())); + state.loaded = true; + savings.ledger.replace(ordinary_totals.clone()); + } + let callback_storage = Storage::new( + Arc::clone(callback.documents()), + Arc::clone(callback.streams()), + Arc::clone(callback.kv()), + Arc::clone(callback.blobs()), + Arc::clone(callback.queues()), + Arc::clone(callback.secrets()), + ); + let legacy = SavingsAggregate { + total: SavingsBucket { + events: 2, + original_tokens: 20, + compacted_tokens: 10, + tokens_saved: 10, + cost_saved_usd: 0.1, + }, + ..Default::default() + }; + + assert!(savings.import_at(None, &callback_storage, legacy).await?); + assert_eq!( + callback_storage + .documents() + .get_as::(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await? + .unwrap() + .doc + .total + .events, + 2 + ); + assert_eq!(savings.stats(None).await.total.events, 1); + Ok(()) +} diff --git a/crates/tinyjuice-module/src/service.rs b/crates/tinyjuice-module/src/service.rs index cfc6fd26..d886b2f9 100644 --- a/crates/tinyjuice-module/src/service.rs +++ b/crates/tinyjuice-module/src/service.rs @@ -11,6 +11,7 @@ use tinyjuice::types::{AgentTokenjuiceCompression, CompressedOutput, ContentHint use tinyjuice::tool_integration::ToolOutputCall; use tinyjuice_bus::names::ml_host; pub use tinyjuice_bus::names::{BUS_NAME, ML_HOST_NAME, ML_HOST_PATH, OBJECT_PATH}; +use tinyjuice_bus::savings::ImportSavingsAtRequest; use tinyjuice_bus::wire::{ CacheStats, CompactRequest, CompactResponse, GenerateRequest, InstallRequest, RangeUnit as WireRangeUnit, RetrieveRange, @@ -220,6 +221,12 @@ impl Compression { ) -> BusResult { savings().import(self.connection.as_ref(), legacy).await } + + /// Adopt legacy totals through a host callback scoped to this invocation. + /// The callback handle is never installed as the module's ordinary store. + async fn import_savings_at(&self, request: ImportSavingsAtRequest) -> BusResult { + import_savings_at(savings(), self.connection.as_ref(), request).await + } } /// Requests may narrow a budget but never expand the module's stock ceilings. @@ -340,7 +347,8 @@ pub(crate) mod exports { "RecordSavings", "SavingsStats", "ResetSavings", - "ImportSavings" + "ImportSavings", + "ImportSavingsAt" ], signals = [], requires = [], @@ -358,3 +366,26 @@ fn savings() -> &'static crate::savings_store::Savings { static SAVINGS: std::sync::OnceLock = std::sync::OnceLock::new(); SAVINGS.get_or_init(crate::savings_store::Savings::new) } + +/// Perform an import through a callback port without caching that port. +async fn import_savings_at( + savings: &crate::savings_store::Savings, + connection: Option<&Connection>, + request: ImportSavingsAtRequest, +) -> BusResult { + let connection = connection + .ok_or_else(|| tinybus::Error::failed("request-scoped savings storage is unavailable"))?; + let host = tinybus::BusName::new(request.callback.host) + .map_err(|error| tinybus::Error::failed(error.to_string()))?; + let object_root = tinybus::ObjectPath::new(request.callback.object_root) + .map_err(|error| tinybus::Error::failed(error.to_string()))?; + let address = tinystoragedrivers_busproxy::StorageAddress::try_new(host, object_root) + .map_err(|error| tinybus::Error::failed(error.to_string()))?; + let storage = + tinystoragedrivers_busproxy::connect_storage_at_address(connection.clone(), address) + .await + .map_err(|error| tinybus::Error::failed(error.to_string()))?; + savings + .import_at(Some(connection), &storage, request.aggregate) + .await +} diff --git a/crates/tinyjuice-module/src/service_tests.rs b/crates/tinyjuice-module/src/service_tests.rs index 230ea314..a4720934 100644 --- a/crates/tinyjuice-module/src/service_tests.rs +++ b/crates/tinyjuice-module/src/service_tests.rs @@ -363,3 +363,152 @@ async fn setup_serves_detection_and_forwards_model_calls_to_the_host() { tinyjuice::llm::configure_callback(None); broker_task.abort(); } + +#[tokio::test] +async fn import_savings_at_uses_only_its_request_scoped_storage_address() { + use tinybus::broker::Broker; + use tinybus::transport::memory::MemoryBus; + use tinyjuice_bus::savings::{ + ImportSavingsAtRequest, SAVINGS_DOC_ID, SavingsAggregate, SavingsBucket, + StorageCallbackAddress, + }; + use tinyjuice_bus::storage::SAVINGS_COLLECTION; + use tinystoragedrivers_api::StorageBackend; + use tinystoragedrivers_busproxy::{ + INVOCATION_OBJECT_ROOT, PerCallerEndpoint, StorageAddress, StorageServer, serve, + serve_at_address, + }; + use tinystoragedrivers_testkit::MemoryBackend; + use tinystoragedrivers_types::Scope; + + let bus = MemoryBus::new(); + let broker_task = Broker::new().spawn(bus.clone()); + let host = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let backend = Arc::new(MemoryBackend::new()); + let ordinary_backend: Arc = backend.clone(); + let ordinary_endpoint = PerCallerEndpoint::new({ + let backend = Arc::clone(&ordinary_backend); + move |_| { + let storage = backend.for_scope(&Scope::new("ordinary").ok()?).ok()?; + Some(StorageServer::new(storage)) + } + }); + let _ordinary_server = serve(&host, Arc::new(ordinary_endpoint)).await.unwrap(); + + let callback_backend: Arc = backend.clone(); + let callback_scope = Scope::new("invocation").unwrap(); + let callback = callback_backend.for_scope(&callback_scope).unwrap(); + let callback_docs = Arc::clone(callback.documents()); + let address = StorageAddress::try_new( + host.unique_name().unwrap(), + tinybus::ObjectPath::new(format!("{INVOCATION_OBJECT_ROOT}/juice_test")).unwrap(), + ) + .unwrap(); + let _callback_server = serve_at_address( + &host, + address.clone(), + Arc::new(PerCallerEndpoint::new(move |_| { + Some(StorageServer::new(callback.clone())) + })), + ) + .await + .unwrap(); + + let module = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let savings = crate::savings_store::Savings::new(); + let initial: SavingsAggregate = savings.stats(Some(&module)).await; + assert_eq!(initial.total.events, 0); + let aggregate = SavingsAggregate { + total: SavingsBucket { + events: 2, + original_tokens: 20, + compacted_tokens: 8, + tokens_saved: 12, + cost_saved_usd: 0.25, + }, + ..Default::default() + }; + let imported = import_savings_at( + &savings, + Some(&module), + ImportSavingsAtRequest { + aggregate, + callback: StorageCallbackAddress { + host: address.host().to_string(), + object_root: address.object_root().to_string(), + }, + }, + ) + .await + .unwrap(); + assert!(imported); + + assert_eq!( + savings.stats(Some(&module)).await.total.events, + 0, + "request-scoped import state must not become ordinary module state" + ); + + let ordinary = backend.for_scope(&Scope::new("ordinary").unwrap()).unwrap(); + let stored = ordinary + .documents() + .get(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await + .unwrap(); + assert!( + stored.is_none(), + "the request port does not replace the normal port" + ); + assert!( + callback_docs + .get(SAVINGS_COLLECTION, SAVINGS_DOC_ID) + .await + .unwrap() + .is_some() + ); + broker_task.abort(); +} + +#[tokio::test] +async fn import_savings_at_rejects_non_unique_hosts_and_non_invocation_roots() { + use tinybus::broker::Broker; + use tinybus::transport::memory::MemoryBus; + use tinyjuice_bus::savings::{ + ImportSavingsAtRequest, SavingsAggregate, StorageCallbackAddress, + }; + + let bus = MemoryBus::new(); + let broker_task = Broker::new().spawn(bus.clone()); + let module = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let savings = crate::savings_store::Savings::new(); + + let invalid_addresses = [ + StorageCallbackAddress { + host: "ai.example.Storage".into(), + object_root: "/ai/tinyhumans/tinystorage/Invocation/import-1".into(), + }, + StorageCallbackAddress { + host: ":1.7".into(), + object_root: "/ai/tinyhumans/tinystorage/Other/import-1".into(), + }, + ]; + for callback in invalid_addresses { + let result = import_savings_at( + &savings, + Some(&module), + ImportSavingsAtRequest { + aggregate: SavingsAggregate::default(), + callback, + }, + ) + .await; + assert!(result.is_err(), "invalid destination must be rejected"); + } + broker_task.abort(); +} diff --git a/crates/tinyjuice-module/src/storage.rs b/crates/tinyjuice-module/src/storage.rs index ef2d4d7a..ff010e1d 100644 --- a/crates/tinyjuice-module/src/storage.rs +++ b/crates/tinyjuice-module/src/storage.rs @@ -10,26 +10,26 @@ use std::sync::Arc; use std::time::Duration; use tinybus::Connection; -use tinyjuice::cache::store::{CcrPutResult, CcrStore, RangeUnit}; +use tinyjuice::cache::store::{CcrPutResult, CcrStore, RangeUnit, short_hash}; use tinyjuice_drivers::BlobCcrStore; -use tinystoragedrivers_core::{BlobStore, DocumentStore, StorageBackend}; +use tinystoragedrivers_api::{BlobStore, DocumentStore, Storage}; /// The host's blob port, connected through `connection`, when it serves one. async fn blobs(connection: Connection) -> Option> { scoped(connection) .await - .map(|scoped| Arc::clone(scoped.blobs())) + .map(|storage| Arc::clone(storage.blobs())) } /// The host's document port, connected through `connection`, when it serves one. pub(crate) async fn documents(connection: Connection) -> Option> { scoped(connection) .await - .map(|scoped| Arc::clone(scoped.documents())) + .map(|storage| Arc::clone(storage.documents())) } /// The module's scope of the host's storage, when the host serves one. -async fn scoped(connection: Connection) -> Option { +async fn scoped(connection: Connection) -> Option { let bus = match tinystoragedrivers_busproxy::connect_storage(connection).await { Ok(bus) => bus, Err(error) => { @@ -37,13 +37,7 @@ async fn scoped(connection: Connection) -> Option Some(scoped), - Err(error) => { - log::warn!("[tinyjuice_module] storage bus scope refused: {error}"); - None - } - } + Some(bus) } /// The CCR durable tier on the host's blob port, or `None` when the host @@ -81,16 +75,18 @@ async fn tier_on(blobs: Arc, ttl: Option) -> Option(S); impl OffWorker { - fn off_worker(call: impl FnOnce() -> T) -> T { + fn off_worker(call: impl FnOnce() -> T) -> Option { match tokio::runtime::Handle::try_current() { Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => { - tokio::task::block_in_place(call) + Some(tokio::task::block_in_place(call)) } - _ => call(), + Ok(_) => None, + Err(_) => Some(call()), } } } @@ -98,14 +94,15 @@ impl OffWorker { impl CcrStore for OffWorker { fn put(&self, content: &str) -> CcrPutResult { Self::off_worker(|| self.0.put(content)) + .unwrap_or_else(|| CcrPutResult::new(short_hash(content), false)) } fn get(&self, token: &str) -> Option { - Self::off_worker(|| self.0.get(token)) + Self::off_worker(|| self.0.get(token)).flatten() } fn get_range(&self, token: &str, start: usize, end: usize, unit: RangeUnit) -> Option { - Self::off_worker(|| self.0.get_range(token, start, end, unit)) + Self::off_worker(|| self.0.get_range(token, start, end, unit)).flatten() } } diff --git a/crates/tinyjuice-module/src/storage_tests.rs b/crates/tinyjuice-module/src/storage_tests.rs index c0ff7713..e8c8b0a0 100644 --- a/crates/tinyjuice-module/src/storage_tests.rs +++ b/crates/tinyjuice-module/src/storage_tests.rs @@ -5,9 +5,12 @@ use super::*; use tinybus::broker::Broker; use tinybus::transport::memory::MemoryBus; use tinyjuice::cache::store::short_hash; -use tinystoragedrivers_busproxy::{PerCallerEndpoint, ServedStorage, serve}; -use tinystoragedrivers_client::StorageServer; -use tinystoragedrivers_core::{MemoryStorage, Scope, ScopedStorage}; +use tinystoragedrivers_api::{BlobStore, StorageBackend}; +use tinystoragedrivers_busproxy::{PerCallerEndpoint, ServedStorage, StorageServer, serve}; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::{ + Blob, BlobMeta, Capabilities, Capability, Result as StorageResult, Scope, +}; /// Serializes the tests that `install`, which reconfigures process-global cache /// state. @@ -17,7 +20,7 @@ type TestResult = Result<(), Box>; pub(crate) struct Rig { pub(crate) module: Connection, - pub(crate) backend: MemoryStorage, + pub(crate) backend: Arc, host: Connection, _served: Option, } @@ -25,9 +28,9 @@ pub(crate) struct Rig { impl Rig { /// Start serving storage on a rig built without it. pub(crate) async fn serve_storage(&mut self) -> Result<(), Box> { - let bound = self.backend.clone(); + let bound = Arc::clone(&self.backend); let endpoint = PerCallerEndpoint::new(move |_sender| { - let scoped: ScopedStorage = bound.for_scope(&Scope::local()).ok()?; + let scoped = bound.for_scope(&Scope::new("local").ok()?).ok()?; Some(StorageServer::new(scoped)) }); self._served = Some(serve(&self.host, Arc::new(endpoint)).await?); @@ -38,12 +41,12 @@ impl Rig { pub(crate) async fn rig(serve_storage: bool) -> Result> { let bus = MemoryBus::new(); Broker::new().spawn(bus.clone()); - let backend = MemoryStorage::new(); + let backend = Arc::new(MemoryBackend::new()); let host = Connection::connect(bus.connect().await?).await?; let served = if serve_storage { - let bound = backend.clone(); + let bound = Arc::clone(&backend); let endpoint = PerCallerEndpoint::new(move |_sender| { - let scoped: ScopedStorage = bound.for_scope(&Scope::local()).ok()?; + let scoped = bound.for_scope(&Scope::new("local").ok()?).ok()?; Some(StorageServer::new(scoped)) }); Some(serve(&host, Arc::new(endpoint)).await?) @@ -69,7 +72,7 @@ async fn originals_land_as_blobs_on_the_host_port() -> TestResult { let put = store.put(content); assert!(put.retained()); - let host_blobs = Arc::clone(rig.backend.for_scope(&Scope::local())?.blobs()); + let host_blobs = Arc::clone(rig.backend.for_scope(&Scope::new("local")?)?.blobs()); let key = format!("{}/{}", tinyjuice_drivers::CCR_PREFIX, short_hash(content)); let blob = host_blobs.get(&key).await?.ok_or("blob is on the host")?; assert_eq!(blob.bytes, content.as_bytes()); @@ -111,6 +114,31 @@ async fn store_calls_on_the_only_worker_do_not_deadlock() -> TestResult { Ok(()) } +#[tokio::test(flavor = "current_thread")] +async fn durable_calls_fail_closed_on_a_current_thread_runtime() -> TestResult { + let rig = rig(true).await?; + let store = durable_tier(rig.module.clone(), None) + .await + .ok_or("host serves storage")?; + let put = store.put("current thread must not block its bus runtime"); + assert!(!put.retained()); + assert!(store.get(put.token()).is_none()); + + let blobs = rig.backend.for_scope(&Scope::new("local")?)?; + assert!( + blobs + .blobs() + .get(&format!( + "{}/{}", + tinyjuice_drivers::CCR_PREFIX, + put.token() + )) + .await? + .is_none() + ); + Ok(()) +} + fn install_request(durable: bool) -> tinyjuice_bus::wire::InstallRequest { tinyjuice_bus::wire::InstallRequest { options: tinyjuice::types::CompressOptions::default(), @@ -129,7 +157,7 @@ async fn install_moves_the_disk_tier_onto_host_blobs_and_off_again() -> TestResu let service = Compression { connection: Some(rig.module.clone()), }; - let host_blobs = Arc::clone(rig.backend.for_scope(&Scope::local())?.blobs()); + let host_blobs = Arc::clone(rig.backend.for_scope(&Scope::new("local")?)?.blobs()); service.install(install_request(true)).await?; let content = "install wired durable tier fixture original"; @@ -151,23 +179,28 @@ async fn install_moves_the_disk_tier_onto_host_blobs_and_off_again() -> TestResu /// A blob handle that reports no optional abilities (no expiry), over memory. #[derive(Debug)] -struct NoExpiry(Arc); +struct NoBlobExpiry(Arc); #[async_trait::async_trait] -impl BlobStore for NoExpiry { +impl BlobStore for NoBlobExpiry { + fn capabilities(&self) -> Capabilities { + self.0.capabilities().without(Capability::BlobTtl) + } + + fn max_key_len(&self) -> usize { + self.0.max_key_len() + } + async fn put( &self, key: &str, bytes: Vec, content_type: Option<&str>, - ) -> tinystoragedrivers_core::Result { + ) -> StorageResult { self.0.put(key, bytes, content_type).await } - async fn get( - &self, - key: &str, - ) -> tinystoragedrivers_core::Result> { + async fn get(&self, key: &str) -> StorageResult> { self.0.get(key).await } @@ -175,34 +208,28 @@ impl BlobStore for NoExpiry { &self, key: &str, range: std::ops::Range, - ) -> tinystoragedrivers_core::Result>> { + ) -> StorageResult>> { self.0.get_range(key, range).await } - async fn head( - &self, - key: &str, - ) -> tinystoragedrivers_core::Result> { + async fn head(&self, key: &str) -> StorageResult> { self.0.head(key).await } - async fn delete(&self, key: &str) -> tinystoragedrivers_core::Result { + async fn delete(&self, key: &str) -> StorageResult { self.0.delete(key).await } - async fn list( - &self, - prefix: &str, - ) -> tinystoragedrivers_core::Result> { + async fn list(&self, prefix: &str) -> StorageResult> { self.0.list(prefix).await } } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_handle_that_cannot_expire_blobs_gets_no_ttl_tier_but_a_keep_forever_one() -> TestResult { - let backend = MemoryStorage::new(); - let blobs: Arc = Arc::new(NoExpiry(Arc::clone( - backend.for_scope(&Scope::local())?.blobs(), + let backend = MemoryBackend::new(); + let blobs: Arc = Arc::new(NoBlobExpiry(Arc::clone( + backend.for_scope(&Scope::new("local")?)?.blobs(), ))); assert!( tier_on(Arc::clone(&blobs), Some(Duration::from_secs(60))) @@ -213,10 +240,10 @@ async fn a_handle_that_cannot_expire_blobs_gets_no_ttl_tier_but_a_keep_forever_o Ok(()) } -/// Off a multi-thread runtime there is no worker to hand off, so the call runs -/// in place. +/// On a current-thread runtime the synchronous bridge cannot safely wait for +/// the same executor to deliver its reply, so it refuses durable calls. #[tokio::test(flavor = "current_thread")] -async fn store_calls_run_in_place_on_a_current_thread_runtime() { +async fn off_worker_refuses_calls_on_a_current_thread_runtime() { struct Fixed; impl CcrStore for Fixed { fn put(&self, content: &str) -> CcrPutResult { @@ -230,32 +257,16 @@ async fn store_calls_run_in_place_on_a_current_thread_runtime() { } } let store = OffWorker(Fixed); - assert!(store.put("x").retained()); - assert_eq!(store.get("t").as_deref(), Some("fixed")); - assert_eq!( - store.get_range("t", 0, 1, RangeUnit::Lines).as_deref(), - Some("range") - ); + assert!(!store.put("x").retained()); + assert_eq!(store.get("t"), None); + assert_eq!(store.get_range("t", 0, 1, RangeUnit::Lines), None); } #[test] -fn the_module_grant_is_its_schema_at_module_scope() { - use tinystoragedrivers_core::schema::{Item, ScopeClass}; - let schema = crate::storage_schema(); - let grant: Vec<(&str, ScopeClass)> = schema - .items - .iter() - .map(|item| match item { - Item::Blobs { prefix, scope } => (prefix.as_str(), *scope), - Item::Collection { name, scope, .. } => (name.as_str(), *scope), - other => panic!("the module stores blobs and collections only, got {other:?}"), - }) - .collect(); +fn declares_document_collection_for_host_provisioning() { + use tinystoragedrivers_types::CollectionSpec; assert_eq!( - grant, - [ - ("juice/ccr/", ScopeClass::Module), - ("juice.savings", ScopeClass::Module) - ] + crate::collections(), + vec![CollectionSpec::new("juice.savings")] ); } diff --git a/crates/tinyjuice-module/tests/module_e2e_tests.rs b/crates/tinyjuice-module/tests/module_e2e_tests.rs index 0074d5b2..0ef00990 100644 --- a/crates/tinyjuice-module/tests/module_e2e_tests.rs +++ b/crates/tinyjuice-module/tests/module_e2e_tests.rs @@ -1,6 +1,7 @@ //! End-to-end proof that the built TinyJuice cdylib is admitted and serves //! compression and CCR retrieval through a real TinyBus broker. +use std::sync::Arc; use std::time::Duration; use tinybus::Connection; @@ -9,6 +10,10 @@ use tinybus::test_support::{admit_module, start_bus, wait_until_serving}; use tinyjuice::types::{AgentTokenjuiceCompression, CompressedOutput, ContentHint, ContentKind}; use tinyjuice_bus::wire::CompactResponse; use tinyjuice_module::{BUS_NAME, OBJECT_PATH}; +use tinystoragedrivers_api::{BlobStore, StorageBackend}; +use tinystoragedrivers_busproxy::{PerCallerEndpoint, StorageServer, serve}; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::Scope; const EXPECTED_METHODS: &[&str] = tinyjuice_bus::METHODS; @@ -16,6 +21,16 @@ const EXPECTED_METHODS: &[&str] = tinyjuice_bus::METHODS; #[ignore = "requires TINYJUICE_TEST_MODULE to point at the built cdylib"] async fn the_built_module_compresses_and_recovers_over_a_real_broker() { let (modules, client, broker_task) = start_bus().await.expect("memory bus should start"); + let storage_backend = Arc::new(MemoryBackend::new()); + let endpoint_backend = Arc::clone(&storage_backend); + let storage_endpoint = PerCallerEndpoint::new(move |_sender| { + let scope = Scope::new("tinyjuice-module-test").ok()?; + let storage = endpoint_backend.for_scope(&scope).ok()?; + Some(StorageServer::new(storage)) + }); + let _served_storage = serve(&client, Arc::new(storage_endpoint)) + .await + .expect("host storage should be served before module setup"); let loaded = admit_module(&modules, "TINYJUICE_TEST_MODULE", "tinyjuice-module") .expect("module should load"); assert_eq!(loaded.name, "tinyjuice-module"); @@ -56,10 +71,10 @@ async fn the_built_module_compresses_and_recovers_over_a_real_broker() { "codeTargetRatio": null, "charsPerToken": 4.0 }, - "maxCacheEntries": 8, + "maxCacheEntries": 1, "maxCacheBytes": 1048576, "ccrTtlSecs": null, - "ccrDurable": false + "ccrDurable": true }),), ) .await @@ -116,6 +131,33 @@ async fn the_built_module_compresses_and_recovers_over_a_real_broker() { .expect("compress should succeed"); assert!(output.applied); let token = output.ccr_token.expect("compression should be recoverable"); + + let scope = Scope::new("tinyjuice-module-test").expect("valid test scope"); + let host_blobs: Arc = + Arc::clone(storage_backend.for_scope(&scope).unwrap().blobs()); + let durable_key = format!("{}/{}", tinyjuice_drivers::CCR_PREFIX, token); + let durable_blob = host_blobs + .get(&durable_key) + .await + .expect("host blob lookup should succeed") + .expect("the module should write its CCR original to host storage"); + assert_eq!(durable_blob.bytes, content.as_bytes()); + + // A second distinct retained original evicts the first from the one-entry + // module cache. Retrieval below must therefore use the host BlobStore. + let eviction_content = (0..200) + .map(|index| format!("WARN independent request queued id={index}\n")) + .collect::(); + let eviction_output: CompressedOutput = proxy + .call( + "Compress", + (eviction_content, serde_json::json!({ "explicit": "log" })), + ) + .await + .expect("second compression should succeed"); + assert!(eviction_output.applied); + assert!(eviction_output.ccr_token.is_some()); + let recovered: Option = proxy .call( "Retrieve", diff --git a/deny.toml b/deny.toml index 501bb205..fa1309b5 100644 --- a/deny.toml +++ b/deny.toml @@ -46,4 +46,5 @@ allow-registry = ["https://github.com/rust-lang/crates.io-index"] allow-git = [ "https://github.com/tinyhumansai/tinytools", "https://github.com/tinyhumansai/tinystoragedrivers", + "https://github.com/tinyhumansai/tinybus", ] diff --git a/docs/agent-hooks/README.md b/docs/agent-hooks/README.md index 320621de..b9e4ed88 100644 --- a/docs/agent-hooks/README.md +++ b/docs/agent-hooks/README.md @@ -12,23 +12,11 @@ Use `tinyjuice update ` to refresh an installed hook and ## Install The CLI -Install from crates.io: +Install the CLI from a local TinyJuice checkout (the CLI package is not +published separately): ```sh -cargo install tinyjuice --features cli-disk-tier --locked -``` - -For development builds, install from Git: - -```sh -cargo install --git https://github.com/tinyhumansai/tinyjuice \ - --features cli-disk-tier --locked --bin tinyjuice -``` - -Or install the exact code in a local checkout: - -```sh -cargo install --path . --features cli-disk-tier --locked --bin tinyjuice +cargo install --path crates/tinyjuice-cli --locked --bin tinyjuice ``` Make sure Cargo's bin directory is on `PATH` before installing hooks: diff --git a/docs/architecture.md b/docs/architecture.md index 73a57e35..7b6e126e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -25,8 +25,14 @@ on whatever backend it has. `tinyjuice-module` uses the host storage bus retaining an original only when it reports success under the content hash that callers advertise as the recovery token. - A memory miss in `retrieve` / `retrieve_range` falls through to the tier. -- The library has no file-backed persistence tier. Standalone CLI cache - commands use their separate `cli-disk-tier` feature. +- The library has no file-backed persistence tier. The separate + `tinyjuice-cli` package composes the file backend for standalone cache + commands. +- The CLI stores the original CCR write time in a sibling metadata blob because + the BlobStore port has no caller-supplied timestamp. TTLs use the remaining + relative duration when the content and metadata blobs are written separately, + so their backend expiration times can differ by a small write-time skew; + collection ordering and age checks use the preserved original timestamp. - Store calls may block, so a host must not call them from a single-threaded runtime that also drives the store's transport. diff --git a/docs/specs/tinybus-module.md b/docs/specs/tinybus-module.md index 5e7b49ba..7e9b5237 100644 --- a/docs/specs/tinybus-module.md +++ b/docs/specs/tinybus-module.md @@ -111,7 +111,7 @@ narrow these values but cannot enlarge the module's stock ceilings. Grep keeps matching lines before allocating remaining context slots. An explicit summary `max_chars` also bounds a model-failure notice combined with its overview. -## Model-attributed savings (contract 2.1) +## Model-attributed savings (contract 3.1) The module owns aggregation and persistence. Since contract 2.3 the totals are one document, `juice.savings/totals` (snake_case body, `updated_ms`), in the @@ -124,6 +124,13 @@ link only `tinyjuice-bus::savings` and call these members: - `ImportSavings(SavingsAggregate) -> bool` (2.3) adopts a legacy camelCase snapshot the host read from its old file, only while nothing has been recorded; `false` means totals already existed and nothing changed. +- `ImportSavingsAt(ImportSavingsAtRequest) -> bool` (3.1) adopts that snapshot + through the request's temporary `StorageCallbackAddress` (`host` plus a + per-invocation `object_root`). The module opens the callback only for this + call and writes `juice.savings/totals` with an absent/version precondition; + an existing total or a concurrent writer wins. The normal module storage + provider and cached handles are unchanged. The host revokes the callback + after the call, so retries must create a new address. - `RecordSavings(RecordSavingsRequest) -> ()` records a positive token saving. The host supplies the attribution model, compressor identifier, pre/post token estimates, and its catalog lookup of the input price per million diff --git a/scripts/check-engine-deps.sh b/scripts/check-engine-deps.sh new file mode 100755 index 00000000..967a738e --- /dev/null +++ b/scripts/check-engine-deps.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +engine_pattern='^(rusqlite|libsqlite3-sys|mongodb|bson|aws-sdk-s3|lapin|amq-protocol|sqlx|redb|sled|rocksdb|tinystoragedrivers-(document|kv|blob|queue|secrets|connect)|tinystoragedrivers)$' + +strip_carriage_return() { + printf '%s' "${1%$'\r'}" +} + +tree_names() { + printf '%s\n' "$1" | tr -d '\r' | awk '{print $1}' +} + +# Cargo metadata may be emitted with CRLF on Windows. Keep this parser +# self-test Bash 3 compatible, as used by the macOS runners. +crlf_packages=$'tinyjuice\r\ntinyjuice-module\r\n' +normalized_packages='' +while IFS= read -r package; do + [[ -n "$package" ]] || continue + package="$(strip_carriage_return "$package")" + normalized_packages="${normalized_packages:+${normalized_packages}$'\n'}${package}" +done <<< "$crlf_packages" +if [[ "$normalized_packages" != $'tinyjuice\ntinyjuice-module' ]]; then + echo "engine gate failed its CRLF package-list self-test" >&2 + exit 1 +fi +if [[ "$(tree_names $'tinyjuice\r\nrusqlite\r\n')" != $'tinyjuice\nrusqlite' ]]; then + echo "engine gate failed its CRLF cargo-tree self-test" >&2 + exit 1 +fi + +# Exact matching must detect backend engines, without rejecting the public +# ports or names that merely contain a forbidden package name. +for name in rusqlite libsqlite3-sys mongodb bson aws-sdk-s3 lapin amq-protocol sqlx redb sled rocksdb tinystoragedrivers-document tinystoragedrivers-kv tinystoragedrivers-blob tinystoragedrivers-queue tinystoragedrivers-secrets tinystoragedrivers-connect tinystoragedrivers; do + if ! printf '%s\n' "$name" | grep -xE "$engine_pattern" >/dev/null; then + echo "engine matcher missed package: $name" >&2 + exit 1 + fi +done +for name in tinyjuice tinyjuice-bus tinyjuice-drivers tinyjuice-module tinystoragedrivers-api tinystoragedrivers-busproxy tinystoragedrivers-testkit tinystoragedrivers-types not-tinystoragedrivers-document tinystoragedrivers-types-extra; do + if printf '%s\n' "$name" | grep -xE "$engine_pattern" >/dev/null; then + echo "engine matcher rejected allowed package name: $name" >&2 + exit 1 + fi +done + +libraries="$(cargo metadata --locked --format-version 1 --no-deps | python3 -c ' +import json, sys +metadata = json.load(sys.stdin) +members = set(metadata["workspace_members"]) +library_kinds = {"lib", "rlib", "cdylib", "dylib", "staticlib", "proc-macro"} +names = sorted({ + package["name"] + for package in metadata["packages"] + if package["id"] in members + and any(library_kinds.intersection(target["kind"]) for target in package["targets"]) +}) +print("\n".join(names)) +')" +if [[ -z "$libraries" ]]; then + echo "Cargo metadata found no workspace library targets" >&2 + exit 1 +fi + +while IFS= read -r package; do + package="$(strip_carriage_return "$package")" + [[ -n "$package" ]] || continue + for features in default all; do + args=(tree --locked -p "$package" -e normal,build --prefix none) + if [[ "$features" == all ]]; then + args+=(--all-features) + fi + tree="$(cargo "${args[@]}")" + names="$(tree_names "$tree")" + if ! printf '%s\n' "$names" | grep -Fx "$package" >/dev/null; then + echo "cargo tree for $package ($features) had no root package entry" >&2 + exit 1 + fi + forbidden="$(printf '%s\n' "$names" | grep -xE "$engine_pattern" || true)" + if [[ -n "$forbidden" ]]; then + printf 'engine dependencies found in %s (%s features):\n%s\n' "$package" "$features" "$forbidden" >&2 + exit 1 + fi + done +done <<< "$libraries" diff --git a/scripts/test-features.sh b/scripts/test-features.sh index 5b72f956..68dd6b02 100755 --- a/scripts/test-features.sh +++ b/scripts/test-features.sh @@ -4,6 +4,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.." python3 scripts/test-e2e-version.py cargo test --locked --workspace cargo test --locked --workspace --all-features +scripts/check-engine-deps.sh case "${RUNNER_OS:-$(uname -s)}" in Windows|MINGW*|MSYS*|CYGWIN*) ;; *) python3 scripts/test-package-layout.py ;; diff --git a/src/cache/disk_tier.rs b/src/cache/disk_tier.rs deleted file mode 100644 index 97268364..00000000 --- a/src/cache/disk_tier.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! Optional filesystem-backed CCR for standalone CLI builds. - -use super::store::{DEFAULT_MAX_BYTES, is_valid_token}; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{OnceLock, RwLock}; -use std::time::{Duration, SystemTime}; - -/// Default total-bytes cap for the CLI disk tier (matches the memory cap). -pub const DEFAULT_DISK_MAX_BYTES: u64 = DEFAULT_MAX_BYTES as u64; -const DISK_CAP_ENFORCE_EVERY: u64 = 128; - -fn root() -> &'static RwLock> { - static ROOT: OnceLock>> = OnceLock::new(); - ROOT.get_or_init(|| RwLock::new(None)) -} - -fn cap() -> &'static RwLock> { - static CAP: OnceLock>> = OnceLock::new(); - CAP.get_or_init(|| RwLock::new(Some(DEFAULT_DISK_MAX_BYTES))) -} - -/// Configure the maximum disk-tier bytes enforced during offload. -pub fn configure_disk_cap(max_bytes: Option) { - *cap().write().unwrap_or_else(|p| p.into_inner()) = max_bytes; -} - -/// Enable the file-backed tier used by standalone CLI commands. -pub fn enable_disk_tier(path: PathBuf) { - if std::fs::create_dir_all(&path).is_ok() { - *root().write().unwrap_or_else(|p| p.into_inner()) = Some(path); - } else { - log::warn!("[tinyjuice][ccr] could not create CLI disk tier at {path:?}"); - } -} - -/// Disable new filesystem writes and lookups for the standalone CLI. -pub fn disable_disk_tier() { - *root().write().unwrap_or_else(|p| p.into_inner()) = None; -} - -/// Disk-tier garbage-collection outcome. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] -pub struct GcStats { - pub removed: usize, - pub freed_bytes: u64, - pub kept: usize, - pub kept_bytes: u64, -} - -/// Store an original in the configured CLI disk tier. -pub(super) fn put(token: &str, content: &str, ttl: Option) -> bool { - let Some(root) = root().read().unwrap_or_else(|p| p.into_inner()).clone() else { - return false; - }; - if std::fs::write(root.join(token), content).is_err() { - return false; - } - static WRITES: AtomicU64 = AtomicU64::new(0); - let n = WRITES.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_multiple_of(DISK_CAP_ENFORCE_EVERY) { - let max_bytes = *cap().read().unwrap_or_else(|p| p.into_inner()); - if (ttl.is_some() || max_bytes.is_some()) - && let Err(error) = gc_dir_protecting(&root, ttl, max_bytes, Some(token)) - { - log::debug!("[tinyjuice][ccr] disk-tier sweep failed: {error}"); - } - } - true -} - -/// Read a token from the CLI disk tier, respecting the configured TTL. -pub(super) fn get(token: &str, ttl: Option) -> Option { - let root = root().read().unwrap_or_else(|p| p.into_inner()).clone()?; - get_from(&root, token, ttl) -} - -fn get_from(root: &Path, token: &str, ttl: Option) -> Option { - let path = root.join(token); - if disk_entry_expired(&path, ttl) { - log::debug!("[tinyjuice][ccr] disk entry expired for {token}"); - let _ = std::fs::remove_file(path); - return None; - } - std::fs::read_to_string(path).ok() -} - -/// Sweep the configured CLI disk tier. -pub fn gc_disk_tier(ttl: Option, max_bytes: Option) -> io::Result { - gc_disk_tier_at( - root().read().unwrap_or_else(|p| p.into_inner()).clone(), - ttl, - max_bytes, - ) -} - -fn gc_disk_tier_at( - path: Option, - ttl: Option, - max_bytes: Option, -) -> io::Result { - let Some(path) = path else { - return Ok(GcStats::default()); - }; - gc_disk_dir(&path, ttl, max_bytes) -} - -/// Sweep one explicit directory, considering files named by valid CCR tokens. -pub fn gc_disk_dir( - path: &Path, - ttl: Option, - max_bytes: Option, -) -> io::Result { - gc_dir_protecting(path, ttl, max_bytes, None) -} - -fn gc_dir_protecting( - root: &Path, - ttl: Option, - max_bytes: Option, - protect: Option<&str>, -) -> io::Result { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(GcStats::default()), - Err(error) => return Err(error), - }; - let mut stats = GcStats::default(); - let mut kept: Vec<(PathBuf, u64, SystemTime)> = Vec::new(); - let now = SystemTime::now(); - for entry in entries { - let entry = entry?; - let name = entry.file_name(); - let Some(name) = name.to_str() else { continue }; - if !is_valid_token(name) { - continue; - } - let Ok(metadata) = entry.metadata() else { - continue; - }; - if !metadata.is_file() { - continue; - } - let bytes = metadata.len(); - let modified = metadata.modified().unwrap_or(now); - let expired = ttl.is_some_and(|ttl| { - now.duration_since(modified) - .is_ok_and(|elapsed| elapsed >= ttl) - }); - if expired && std::fs::remove_file(entry.path()).is_ok() { - stats.removed += 1; - stats.freed_bytes += bytes; - } else { - kept.push((entry.path(), bytes, modified)); - } - } - let mut total: u64 = kept.iter().map(|(_, bytes, _)| bytes).sum(); - if let Some(max_bytes) = max_bytes { - kept.sort_by_key(|(_, _, modified)| *modified); - let mut index = 0; - while total > max_bytes && index < kept.len() { - let (path, bytes, _) = &kept[index]; - let protected = - protect.is_some_and(|token| path.file_name().is_some_and(|name| name == token)); - if !protected && std::fs::remove_file(path).is_ok() { - stats.removed += 1; - stats.freed_bytes += bytes; - total -= bytes; - kept.remove(index); - } else { - index += 1; - } - } - } - stats.kept = kept.len(); - stats.kept_bytes = total; - Ok(stats) -} - -fn disk_entry_expired(path: &Path, ttl: Option) -> bool { - let Some(ttl) = ttl else { return false }; - let Ok(metadata) = std::fs::metadata(path) else { - return false; - }; - let Ok(modified) = metadata.modified() else { - return false; - }; - modified.elapsed().is_ok_and(|elapsed| elapsed >= ttl) -} - -#[cfg(test)] -#[path = "disk_tier_tests.rs"] -mod tests; diff --git a/src/cache/disk_tier_tests.rs b/src/cache/disk_tier_tests.rs deleted file mode 100644 index 7330817c..00000000 --- a/src/cache/disk_tier_tests.rs +++ /dev/null @@ -1,241 +0,0 @@ -use super::*; -use crate::cache::{CcrStore, GlobalCcrStore, RangeUnit, disable_disk_tier, short_hash, stats}; - -/// Write a token-named file with a back-dated mtime. -fn write_aged(dir: &Path, name: &str, bytes: usize, age: Duration) -> PathBuf { - let path = dir.join(name); - std::fs::write(&path, "x".repeat(bytes)).unwrap(); - let file = std::fs::File::options().write(true).open(&path).unwrap(); - file.set_modified(SystemTime::now() - age).unwrap(); - path -} - -fn token(fill: char) -> String { - fill.to_string().repeat(32) -} - -#[test] -fn gc_removes_expired_keeps_fresh() { - let dir = tempfile::tempdir().unwrap(); - let old = write_aged(dir.path(), &token('a'), 10, Duration::from_secs(600)); - let fresh = write_aged(dir.path(), &token('b'), 20, Duration::ZERO); - - let stats = gc_disk_dir(dir.path(), Some(Duration::from_secs(60)), None).unwrap(); - assert_eq!(stats.removed, 1); - assert_eq!(stats.freed_bytes, 10); - assert_eq!(stats.kept, 1); - assert_eq!(stats.kept_bytes, 20); - assert!(!old.exists()); - assert!(fresh.exists()); -} - -#[test] -fn gc_evicts_oldest_over_budget() { - let dir = tempfile::tempdir().unwrap(); - let oldest = write_aged(dir.path(), &token('a'), 100, Duration::from_secs(30)); - let middle = write_aged(dir.path(), &token('b'), 100, Duration::from_secs(20)); - let newest = write_aged(dir.path(), &token('c'), 100, Duration::from_secs(10)); - - let stats = gc_disk_dir(dir.path(), None, Some(250)).unwrap(); - assert_eq!(stats.removed, 1, "one eviction brings 300 under 250"); - assert_eq!(stats.freed_bytes, 100); - assert_eq!(stats.kept, 2); - assert!(!oldest.exists(), "oldest-by-mtime goes first"); - assert!(middle.exists()); - assert!(newest.exists()); -} - -#[test] -fn gc_ignores_non_token_files_and_missing_dir() { - let dir = tempfile::tempdir().unwrap(); - let stray = dir.path().join("README.txt"); - std::fs::write(&stray, "not a ccr entry").unwrap(); - - let stats = gc_disk_dir(dir.path(), Some(Duration::ZERO), Some(0)).unwrap(); - assert_eq!(stats, GcStats::default()); - assert!(stray.exists(), "non-token files are never touched"); - - let missing = dir.path().join("does-not-exist"); - assert_eq!( - gc_disk_dir(&missing, None, None).unwrap(), - GcStats::default() - ); -} - -#[test] -fn gc_protects_named_entry_from_budget_eviction() { - let dir = tempfile::tempdir().unwrap(); - let protected_name = token('a'); - let protected = write_aged(dir.path(), &protected_name, 100, Duration::from_secs(30)); - let newer = write_aged(dir.path(), &token('b'), 100, Duration::from_secs(10)); - - let stats = gc_dir_protecting(dir.path(), None, Some(150), Some(&protected_name)).unwrap(); - assert!( - protected.exists(), - "protected entry survives even when oldest" - ); - assert!(!newer.exists(), "eviction falls through to the next-oldest"); - assert_eq!(stats.removed, 1); - assert_eq!(stats.kept, 1); -} - -#[test] -fn disk_entry_ttl_uses_file_mtime() { - let dir = std::env::temp_dir().join(format!("tj-ccr-ttl-{}", short_hash("disk-ttl"))); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - std::fs::write(&path, "disk ttl payload").unwrap(); - - assert!(!disk_entry_expired(&path, None)); - assert!(!disk_entry_expired(&path, Some(Duration::from_secs(60)))); - assert!(disk_entry_expired(&path, Some(Duration::ZERO))); - - let _ = std::fs::remove_dir_all(&dir); -} - -#[test] -fn configured_tier_reads_entries_expires_them_and_runs_gc() { - let dir = tempfile::tempdir().unwrap(); - let name = token('d'); - let path = dir.path().join(&name); - std::fs::write(&path, "disk-backed payload").unwrap(); - - assert_eq!( - get_from(dir.path(), &name, None).as_deref(), - Some("disk-backed payload") - ); - let sweep = gc_disk_dir(dir.path(), None, None).unwrap(); - assert_eq!(sweep.kept, 1); - - let file = std::fs::File::options().write(true).open(&path).unwrap(); - file.set_modified(SystemTime::now() - Duration::from_secs(5)) - .unwrap(); - assert_eq!( - get_from(dir.path(), &name, Some(Duration::from_secs(1))), - None - ); - assert!(!path.exists(), "expired reads remove the disk entry"); -} - -#[test] -fn configured_gc_sweeps_the_selected_directory() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join(token('a')); - std::fs::write(&path, "remove me").unwrap(); - - let stats = gc_disk_tier_at(Some(dir.path().to_path_buf()), None, Some(0)).unwrap(); - assert_eq!(stats.removed, 1); - assert_eq!(stats.freed_bytes, 9); - assert!(!path.exists()); - assert_eq!( - gc_disk_tier_at(None, None, None).unwrap(), - GcStats::default() - ); -} - -#[test] -fn enabling_tier_with_a_file_as_root_is_best_effort() { - let _guard = crate::cache::DISK_TIER_TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let dir = tempfile::tempdir().unwrap(); - let file = dir.path().join("not-a-directory"); - std::fs::write(&file, "keep this file").unwrap(); - - enable_disk_tier(file.clone()); - - assert_eq!(std::fs::read_to_string(file).unwrap(), "keep this file"); - let memory = crate::cache::MemoryCcrStore::new(4, 1024); - let stored = memory.put("memory remains available"); - assert!(stored.retained()); - assert_eq!( - memory.get(stored.token()).as_deref(), - Some("memory remains available") - ); - disable_disk_tier(); -} - -#[test] -fn periodic_write_sweep_removes_expired_entries() { - let _guard = crate::cache::DISK_TIER_TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let dir = tempfile::tempdir().unwrap(); - enable_disk_tier(dir.path().to_path_buf()); - const TTL_SECS: u64 = 30 * 24 * 60 * 60; - crate::cache::configure(usize::MAX, usize::MAX, Some(TTL_SECS)); - configure_disk_cap(None); - - let expired = write_aged( - dir.path(), - &token('a'), - 10, - Duration::from_secs(TTL_SECS + 60), - ); - // A full interval guarantees that the process-wide write counter reaches a - // sweep regardless of where other tests left it. - for index in 0..DISK_CAP_ENFORCE_EVERY { - let content = format!("fresh original {index}"); - let (_, retained) = crate::cache::offload_checked(&content); - assert!(retained, "fixture write {index} must succeed"); - } - - let expired_remains = expired.exists(); - disable_disk_tier(); - crate::cache::configure( - crate::cache::DEFAULT_MAX_ENTRIES, - crate::cache::DEFAULT_MAX_BYTES, - None, - ); - configure_disk_cap(Some(DEFAULT_DISK_MAX_BYTES)); - assert!( - !expired_remains, - "periodic sweep must enforce the configured TTL" - ); -} - -#[test] -fn garbage_collection_skips_nonentries_and_protects_inflight_original() { - let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join("notes"), "unrelated").unwrap(); - std::fs::create_dir(dir.path().join("a".repeat(32))).unwrap(); - let protected = short_hash("protected"); - std::fs::write(dir.path().join(&protected), "protected").unwrap(); - let removed = short_hash("removed"); - std::fs::write(dir.path().join(&removed), "removed").unwrap(); - let stats = gc_dir_protecting(dir.path(), None, Some(0), Some(&protected)).unwrap(); - assert_eq!(stats.removed, 1); - assert_eq!(stats.kept, 1); - assert_eq!(stats.kept_bytes, 9); - assert!(dir.path().join(&protected).exists()); - assert!(dir.path().join("notes").exists()); - assert_eq!( - gc_disk_dir(&dir.path().join("absent"), None, None).unwrap(), - GcStats::default() - ); - assert!(gc_disk_dir(&dir.path().join("notes"), None, None).is_err()); -} - -#[test] -fn global_adapter_supports_ranges_and_unconfigured_disk_gc() { - let _guard = crate::cache::DISK_TIER_TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let store = GlobalCcrStore; - let put = store.put("global ranged retrieval fixture\nsecond"); - assert!(put.retained()); - assert_eq!( - store - .get_range(put.token(), 1, 2, RangeUnit::Lines) - .as_deref(), - Some("second") - ); - assert!(stats().0 > 0); - disable_disk_tier(); - assert!(gc_disk_tier(None, None).is_ok()); - assert!(!disk_entry_expired( - &PathBuf::from("/nonexistent-tinyjuice-fixture"), - Some(Duration::ZERO) - )); -} diff --git a/src/cache/mod.rs b/src/cache/mod.rs index 336fbadc..2c973665 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -1,10 +1,5 @@ //! CCR (Compress-Cache-Retrieve) — original storage + retrieval markers. -#[cfg(all(test, feature = "cli-disk-tier"))] -pub(crate) static DISK_TIER_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - -#[cfg(feature = "cli-disk-tier")] -mod disk_tier; pub mod marker; pub mod store; @@ -17,9 +12,3 @@ pub use store::{ RangeUnit, configure, offload, offload_checked, offload_checked_with_hash, retrieve, retrieve_range, set_durable_tier, short_hash, stats, }; - -#[cfg(feature = "cli-disk-tier")] -pub use disk_tier::{ - DEFAULT_DISK_MAX_BYTES, GcStats, configure_disk_cap, disable_disk_tier, enable_disk_tier, - gc_disk_dir, gc_disk_tier, -}; diff --git a/src/cache/store.rs b/src/cache/store.rs index b202b4a1..fd0e6e3c 100644 --- a/src/cache/store.rs +++ b/src/cache/store.rs @@ -9,8 +9,7 @@ //! //! Process-global and bounded by **both** an entry count and a total byte cap, //! with an optional TTL. Keyed by content hash, so re-offloading identical -//! content is idempotent. Hosted persistence is supplied through [`CcrStore`]; -//! only standalone CLI builds can opt into a filesystem tier. +//! content is idempotent. Persistence is supplied through [`CcrStore`]. use sha2::{Digest, Sha256}; use std::collections::{HashMap, VecDeque}; @@ -288,12 +287,12 @@ pub fn offload_checked(content: &str) -> (String, bool) { /// Like [`offload_checked`] but takes the precomputed `short_hash(content)` /// so callers that already have it (e.g. the router builds the footer from the /// hash before deciding to store) don't pay for a second SHA-256 pass. -/// Returns whether the original was retained (memory or disk). +/// Returns whether the original was retained (memory or the host's durable store). pub fn offload_checked_with_hash(hash: &str, content: &str) -> bool { debug_assert_eq!(hash, short_hash(content), "hash must match content"); - let (max_entries, max_bytes, ttl) = { + let (max_entries, max_bytes) = { let l = limits().read().unwrap_or_else(|p| p.into_inner()); - (l.max_entries, l.max_bytes, l.ttl) + (l.max_entries, l.max_bytes) }; let mem_retained = global().lock().unwrap_or_else(|p| p.into_inner()).insert( hash.to_string(), @@ -302,16 +301,6 @@ pub fn offload_checked_with_hash(hash: &str, content: &str) -> bool { max_bytes, ); - // Mirror to the standalone CLI disk tier when enabled (best-effort). A successful write - // write keeps the original recoverable even when it was too big for memory. - // Rewriting an existing hash intentionally refreshes the file mtime, which - // is the TTL clock for disk-backed CCR entries. - #[cfg(feature = "cli-disk-tier")] - let disk_retained = crate::cache::disk_tier::put(hash, content, ttl); - #[cfg(not(feature = "cli-disk-tier"))] - let disk_retained = false; - #[cfg(not(feature = "cli-disk-tier"))] - let _ = ttl; // Mirror to the host-provided durable tier (best-effort). let durable = durable_tier() .read() @@ -329,7 +318,7 @@ pub fn offload_checked_with_hash(hash: &str, content: &str) -> bool { } put.retained() && same_token }); - mem_retained || disk_retained || durable_retained + mem_retained || durable_retained } /// True if `hash` is a well-formed CCR token (exactly the generated hex digest). @@ -340,7 +329,7 @@ pub(super) fn is_valid_token(hash: &str) -> bool { } /// Retrieve a previously-offloaded original by hash, if still available -/// (memory first, then a host durable store or the standalone CLI disk tier). +/// (memory first, then a host durable store). /// Honours the in-memory TTL; durable stores own their own expiry. pub fn retrieve(hash: &str) -> Option { // Reject anything that isn't the generated token shape up front. @@ -368,13 +357,6 @@ pub fn retrieve(hash: &str) -> Option { if let Some(found) = durable.and_then(|store| store.get(hash)) { return Some(found); } - // Filesystem fallback, available only to standalone CLI builds. - #[cfg(feature = "cli-disk-tier")] - { - if let Some(found) = crate::cache::disk_tier::get(hash, ttl) { - return Some(found); - } - } None } diff --git a/src/cache/store_tests.rs b/src/cache/store_tests.rs index 25e60aa2..5abadced 100644 --- a/src/cache/store_tests.rs +++ b/src/cache/store_tests.rs @@ -1,6 +1,4 @@ use super::*; -#[cfg(feature = "cli-disk-tier")] -use crate::cache::{disable_disk_tier, enable_disk_tier}; #[test] fn round_trips() { @@ -150,32 +148,6 @@ fn memory_store_rejects_malformed_tokens() { ); } -#[test] -#[cfg(feature = "cli-disk-tier")] -fn disk_tier_survives_memory_miss() { - let _guard = crate::cache::DISK_TIER_TEST_LOCK - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - let dir = std::env::temp_dir().join(format!("tj-ccr-{}", short_hash("disk-test-seed"))); - let _ = std::fs::remove_dir_all(&dir); - enable_disk_tier(dir.clone()); - let original = "disk tier unique payload charlie ".repeat(40); - let hash = offload(&original); - // Simulate memory eviction by clearing the in-memory map directly. - { - let mut inner = global().lock().unwrap_or_else(|p| p.into_inner()); - inner.map.remove(&hash); - } - assert_eq!( - retrieve(&hash).as_deref(), - Some(original.as_str()), - "disk fallback" - ); - // Disable the tier for other tests and clean up. - disable_disk_tier(); - let _ = std::fs::remove_dir_all(&dir); -} - #[test] fn offload_with_hash_round_trips() { let original = "ccr precomputed-hash unique payload delta ".repeat(30); diff --git a/vendor/tinybus b/vendor/tinybus deleted file mode 160000 index 1f33d1be..00000000 --- a/vendor/tinybus +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1f33d1be1901a2d44bfe674cd7cf294cf3848821