diff --git a/Cargo.lock b/Cargo.lock index 00d5b6dd..c735f251 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.5" @@ -33,15 +23,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" @@ -50,7 +31,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -59,17 +40,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[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 = "axum" version = "0.8.9" @@ -134,15 +104,9 @@ checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" [[package]] name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "block-buffer" @@ -176,9 +140,9 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cc" -version = "1.4.2" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" dependencies = [ "find-msvc-tools", "jobserver", @@ -188,9 +152,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" @@ -200,59 +164,15 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures 0.2.17", -] - -[[package]] -name = "chacha20" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures 0.3.0", + "cpufeatures 0.3.1", "rand_core 0.10.1", ] -[[package]] -name = "chacha20poly1305" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" -dependencies = [ - "aead", - "chacha20 0.9.1", - "cipher", - "poly1305", - "zeroize", -] - -[[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 = "const-oid" version = "0.10.2" @@ -286,28 +206,22 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ "libc", ] [[package]] name = "crc32fast" -version = "1.5.0" +version = "1.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-utils" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" - [[package]] name = "crypto-common" version = "0.1.7" @@ -315,7 +229,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", - "rand_core 0.6.4", "typenum", ] @@ -334,17 +247,6 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" -[[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.119", -] - [[package]] name = "digest" version = "0.10.7" @@ -353,7 +255,6 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", "crypto-common 0.1.7", - "subtle", ] [[package]] @@ -396,7 +297,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -407,9 +308,9 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -421,6 +322,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.5.0" @@ -439,18 +352,19 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.10" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "flate2" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ "crc32fast", "miniz_oxide", + "zlib-rs", ] [[package]] @@ -459,6 +373,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "foreign-types" version = "0.3.2" @@ -483,16 +403,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "fs4" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" -dependencies = [ - "rustix 1.1.4", - "windows-sys 0.61.2", -] - [[package]] name = "futures-channel" version = "0.3.34" @@ -522,7 +432,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -604,9 +514,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.18" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "839c0e8a181239723652be9062bb56ca5bf5f64011f73b623f6f4fc59086a228" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -623,26 +533,29 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.17.1" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash", +] [[package]] -name = "hkdf" -version = "0.12.4" +name = "hashbrown" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ - "hmac", + "foldhash", ] [[package]] -name = "hmac" -version = "0.12.1" +name = "hashlink" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" dependencies = [ - "digest 0.10.7", + "hashbrown 0.17.1", ] [[package]] @@ -692,18 +605,18 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hybrid-array" -version = "0.4.14" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ "typenum", ] [[package]] name = "hyper" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", @@ -723,9 +636,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.9" +version = "0.27.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" dependencies = [ "http", "hyper", @@ -755,16 +668,17 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", "futures-channel", "futures-util", "http", "http-body", + "httparse", "hyper", "ipnet", "libc", @@ -882,28 +796,19 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" 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]] name = "ipnet" -version = "2.12.1" +version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" [[package]] name = "itoa" @@ -923,9 +828,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.104" +version = "0.3.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" dependencies = [ "cfg-if", "futures-util", @@ -934,24 +839,29 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libredox" -version = "0.1.20" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d0a00925a9f930d679b6789b721e3a7f9ed110f41b86d2497caa780c3a070a" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ "libc", ] [[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" @@ -976,15 +886,15 @@ dependencies = [ [[package]] name = "log" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "lru-slab" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "matchit" @@ -1006,9 +916,9 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "miniz_oxide" -version = "0.8.9" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" dependencies = [ "adler2", "simd-adler32", @@ -1016,9 +926,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.2" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -1043,16 +953,22 @@ dependencies = [ ] [[package]] -name = "once_cell" -version = "1.21.4" +name = "nix" +version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] [[package]] -name = "opaque-debug" -version = "0.3.1" +name = "once_cell" +version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "openssl" @@ -1060,7 +976,7 @@ version = "0.10.81" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" dependencies = [ - "bitflags 2.13.1", + "bitflags", "cfg-if", "foreign-types", "libc", @@ -1144,17 +1060,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" -[[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 = "potential_utf" version = "0.1.6" @@ -1184,9 +1089,9 @@ dependencies = [ [[package]] name = "quinn" -version = "0.11.11" +version = "0.11.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", "cfg_aliases", @@ -1204,14 +1109,14 @@ dependencies = [ [[package]] name = "quinn-proto" -version = "0.11.17" +version = "0.11.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand 0.10.2", + "rand 0.10.3", "rand_pcg", "ring", "rustc-hash", @@ -1226,9 +1131,9 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", @@ -1271,11 +1176,11 @@ dependencies = [ [[package]] name = "rand" -version = "0.10.2" +version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "chacha20 0.10.1", + "chacha20", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -1290,15 +1195,6 @@ dependencies = [ "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", -] - [[package]] name = "rand_core" version = "0.9.5" @@ -1329,16 +1225,15 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags 2.13.1", + "bitflags", ] [[package]] name = "redox_users" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" dependencies = [ - "getrandom 0.2.17", "libredox", "thiserror", ] @@ -1360,7 +1255,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -1452,34 +1347,46 @@ dependencies = [ ] [[package]] -name = "rustc-hash" -version = "2.1.3" +name = "rsqlite-vfs" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c" +dependencies = [ + "hashbrown 0.16.1", + "thiserror", +] [[package]] -name = "rustix" -version = "0.38.44" +name = "rusqlite" +version = "0.40.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" dependencies = [ - "bitflags 2.13.1", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ - "bitflags 2.13.1", + "bitflags", "errno", "libc", - "linux-raw-sys 0.12.1", + "linux-raw-sys", "windows-sys 0.61.2", ] @@ -1542,9 +1449,9 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "dyn-clone", "ref-cast", @@ -1555,14 +1462,14 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98c67716b46af2f0b8cf752abc930f6f9aecfbf671ecfb531db8a31dbe4e2ba" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -1577,7 +1484,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.13.1", + "bitflags", "core-foundation", "core-foundation-sys", "libc", @@ -1621,7 +1528,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -1632,14 +1539,14 @@ checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -1661,9 +1568,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" dependencies = [ "serde_core", ] @@ -1693,12 +1600,12 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures 0.3.0", + "cpufeatures 0.3.1", "digest 0.11.3", ] @@ -1732,9 +1639,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.2" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" [[package]] name = "socket2" @@ -1746,6 +1653,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[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 = "stable_deref_trait" version = "1.2.1" @@ -1771,9 +1690,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.3" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", @@ -1791,13 +1710,13 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -1820,28 +1739,28 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.4", + "rustix", "windows-sys 0.61.2", ] [[package]] name = "thiserror" -version = "2.0.20" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "2.0.20" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -1854,7 +1773,7 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "flate2", @@ -1875,7 +1794,7 @@ dependencies = [ [[package]] name = "tinybus-macros" -version = "0.1.5" +version = "0.1.6" dependencies = [ "proc-macro2", "quote", @@ -1884,7 +1803,7 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "serde", @@ -1902,23 +1821,26 @@ dependencies = [ "async-trait", "axum", "base64 0.23.1", + "data-encoding", "dirs", "futures-util", "parking_lot", "reqwest", "serde", "serde_json", - "sha2 0.11.0", + "sha2 0.11.1", "tempfile", "thiserror", "tinybox-bus", "tinybus", "tinybus-module", "tinymcp-bus", + "tinystoragedrivers-api", "tinystoragedrivers-busproxy", - "tinystoragedrivers-client", - "tinystoragedrivers-core", + "tinystoragedrivers-document", "tinystoragedrivers-secrets", + "tinystoragedrivers-testkit", + "tinystoragedrivers-types", "tinytools", "tokio", "tokio-stream", @@ -1933,93 +1855,175 @@ name = "tinymcp-bus" version = "0.20.0" dependencies = [ "base64 0.23.1", + "data-encoding", "regex", "schemars", "serde", "serde_json", - "tinystoragedrivers-core", + "sha2 0.11.1", + "tinystoragedrivers-testkit", + "tinystoragedrivers-types", "tokio", "url", ] +[[package]] +name = "tinystoragedrivers-api" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" +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=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" +dependencies = [ + "async-trait", + "bytes", + "futures-core", + "serde", + "serde_json", + "tinystoragedrivers-api", + "tinystoragedrivers-types", +] + [[package]] name = "tinystoragedrivers-bus" -version = "1.5.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.5.0#c9ea6ff1615b77b55d7269403af5fd11bedc9ce8" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" dependencies = [ "serde", "serde_json", "tinybus", + "tinystoragedrivers-types", ] [[package]] name = "tinystoragedrivers-busproxy" -version = "1.5.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.5.0#c9ea6ff1615b77b55d7269403af5fd11bedc9ce8" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" 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.5.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.5.0#c9ea6ff1615b77b55d7269403af5fd11bedc9ce8" +name = "tinystoragedrivers-connect" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" +dependencies = [ + "rusqlite", + "serde_json", + "tinystoragedrivers-types", + "tokio", + "zstd", +] + +[[package]] +name = "tinystoragedrivers-document" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" dependencies = [ "async-trait", + "data-encoding", + "rusqlite", "serde", "serde_json", - "tinystoragedrivers-bus", - "tinystoragedrivers-core", - "tinystoragedrivers-secrets", + "sha2 0.10.9", + "tinystoragedrivers-api", + "tinystoragedrivers-connect", + "tinystoragedrivers-types", "tokio", + "zstd", ] [[package]] -name = "tinystoragedrivers-core" -version = "1.5.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.5.0#c9ea6ff1615b77b55d7269403af5fd11bedc9ce8" +name = "tinystoragedrivers-kv" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" +dependencies = [ + "async-trait", + "serde", + "serde_json", + "tinystoragedrivers-api", + "tinystoragedrivers-types", +] + +[[package]] +name = "tinystoragedrivers-queue" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" dependencies = [ "async-trait", "data-encoding", "serde", "serde_json", "sha2 0.10.9", - "thiserror", + "tinystoragedrivers-api", + "tinystoragedrivers-types", "tokio", "ulid", - "zstd", ] [[package]] name = "tinystoragedrivers-secrets" -version = "1.5.0" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.5.0#c9ea6ff1615b77b55d7269403af5fd11bedc9ce8" +version = "2.1.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" 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=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" +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=2856dfa6f5b4de981a4db2801ae6be80c6432b3b#2856dfa6f5b4de981a4db2801ae6be80c6432b3b" +dependencies = [ + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -2043,24 +2047,15 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.12.0" +version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.53.1" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", @@ -2080,7 +2075,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[package]] @@ -2095,9 +2090,9 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.4" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -2117,9 +2112,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", @@ -2131,9 +2126,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.1.6+spec-1.1.0" +version = "1.1.8+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap", "serde_core", @@ -2146,27 +2141,27 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" dependencies = [ "serde_core", ] [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" [[package]] name = "tower" @@ -2189,7 +2184,7 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags 2.13.1", + "bitflags", "bytes", "futures-util", "http", @@ -2250,6 +2245,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[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" @@ -2268,19 +2269,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "universal-hash" -version = "0.5.1" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common 0.1.7", - "subtle", -] +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "untrusted" @@ -2290,9 +2281,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "ureq" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "972d7902c8735f2695410b8aed7df6ed12a47394aa1c8d7af49f0497b731a94d" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ "base64 0.23.1", "flate2", @@ -2307,9 +2298,9 @@ dependencies = [ [[package]] name = "ureq-proto" -version = "0.6.1" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da5f78b09e6941e1a0f2e30e695e4b120377b54d5e0aec11b594bb57b3971613" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" dependencies = [ "base64 0.23.1", "http", @@ -2372,9 +2363,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -2396,9 +2387,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.127" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" dependencies = [ "cfg-if", "once_cell", @@ -2409,19 +2400,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.77" +version = "0.4.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.127" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2429,22 +2421,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.127" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.127" +version = "0.2.129" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" dependencies = [ "unicode-ident", ] @@ -2464,9 +2456,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.104" +version = "0.3.106" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" dependencies = [ "js-sys", "wasm-bindgen", @@ -2491,53 +2483,12 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "windows-link" 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" @@ -2626,12 +2577,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" @@ -2651,7 +2596,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.4", + "rustix", ] [[package]] @@ -2667,13 +2612,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "synstructure", ] @@ -2708,21 +2653,21 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", "synstructure", ] [[package]] name = "zeroize" -version = "1.9.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] name = "zerotrie" @@ -2754,43 +2699,34 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.3", + "syn 3.0.9", ] [[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]] -name = "zmij" -version = "1.0.23" +name = "zlib-rs" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" [[package]] -name = "zopfli" -version = "0.8.3" +name = "zmij" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" -dependencies = [ - "bumpalo", - "crc32fast", - "log", - "simd-adler32", -] +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zstd" diff --git a/Cargo.toml b/Cargo.toml index 22e1bf6e..138157ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -110,23 +110,21 @@ futures-util = { version = "0.3", default-features = false, features = ["std"] } # Structured diagnostics. Endpoints are always passed through `redact_endpoint` # before they reach a log line. tracing = { version = "0.1", default-features = false, features = ["std"] } -# The storage ports (documents, streams) the installed-server store and the audit -# log are written against, and the `Blocking` bridge that lets the synchronous -# store call them. A git tag, like every other tinystoragedrivers consumer, so a -# host that vendors the repository once redirects it with a `[patch]`. This -# crate links no database: the host picks the backend. -tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.5.0", features = ["blocking"] } -# The `SecretStore` port: server environment values and OAuth bundles are kept -# there, never in a document. Its release is pinned independently from core. -tinystoragedrivers-secrets = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.5.0" } +# Runtime-neutral storage ports and their shared serialized types. TinyMCP +# owns its typed repositories and migrations; the host chooses the engines. +tinystoragedrivers-api = { git = "https://github.com/tinyhumansai/tinystoragedrivers", version = "2.1.0", rev = "2856dfa6f5b4de981a4db2801ae6be80c6432b3b" } +tinystoragedrivers-types = { git = "https://github.com/tinyhumansai/tinystoragedrivers", version = "2.1.0", rev = "2856dfa6f5b4de981a4db2801ae6be80c6432b3b" } # The module-side storage bus: `connect_storage` over the module's TinyBus # connection, giving the same port traits the host serves. Used only by the # `module` feature (a cdylib reaches storage through the host, never a file). -tinystoragedrivers-busproxy = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.5.0" } -tinystoragedrivers-client = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.5.0" } +tinystoragedrivers-busproxy = { git = "https://github.com/tinyhumansai/tinystoragedrivers", version = "2.1.0", rev = "2856dfa6f5b4de981a4db2801ae6be80c6432b3b" } +tinystoragedrivers-testkit = { git = "https://github.com/tinyhumansai/tinystoragedrivers", version = "2.1.0", rev = "2856dfa6f5b4de981a4db2801ae6be80c6432b3b" } +tinystoragedrivers-document = { git = "https://github.com/tinyhumansai/tinystoragedrivers", version = "2.1.0", rev = "2856dfa6f5b4de981a4db2801ae6be80c6432b3b", default-features = false, features = ["memory"] } +tinystoragedrivers-secrets = { git = "https://github.com/tinyhumansai/tinystoragedrivers", version = "2.1.0", rev = "2856dfa6f5b4de981a4db2801ae6be80c6432b3b" } # Locating a user's home directory, to find the version-manager shim # directories a desktop launch's stripped PATH leaves out. dirs = "7" +data-encoding = "2" # SHA-256: PKCE code challenges in the authorization-code flow, and the digest # in an action tool's name (`tinymcp-bus`'s `agent_tools::searchable_name`). sha2 = "0.11" @@ -200,3 +198,9 @@ tinybus-macros = { path = "vendor/tinybus/crates/tinybus-macros" } # the module's `Connection` and the storage transport's are one type. [patch."https://github.com/tinyhumansai/tinybus"] tinybus = { path = "vendor/tinybus/crates/tinybus" } + +# The storage-driver fork pins its TinyBus SDK commit until the canonical +# source and release pin are updated together. Keep all bus types on this +# workspace checkout while consuming that commit. +[patch."https://github.com/senamakel/tinybus"] +tinybus = { path = "vendor/tinybus/crates/tinybus" } diff --git a/crates/tinymcp-bus/Cargo.toml b/crates/tinymcp-bus/Cargo.toml index 729c3506..74b1d173 100644 --- a/crates/tinymcp-bus/Cargo.toml +++ b/crates/tinymcp-bus/Cargo.toml @@ -26,13 +26,16 @@ schemars = { workspace = true, optional = true } # Decoding a widget document a tool result embedded as a base64 `blob`, for # the pure tool-UI rules in `ui`. No dependencies of its own. base64 = { workspace = true } -# The storage *ports* only (`Schema`, `Step`, `CollectionSpec`): no driver and -# no I/O. Its sole tokio features are io-util and time, so this adds no runtime -# to a host that links the contract. Backs `storage::storage_schema`; optional, -# enabled only by the `storage` feature so the default closure stays pure. -tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.5.0", default-features = false, optional = true } +# Encode stable document identifiers for storage migration compatibility. +data-encoding = { workspace = true, optional = true } +# Hash overlong composite document identifiers used by the storage schema. +sha2 = { workspace = true, optional = true } +# Pure collection declaration types for the module's storage grant. The bus +# contract does not run migrations or depend on storage implementation code. +tinystoragedrivers-types = { workspace = true, optional = true } [dev-dependencies] +tinystoragedrivers-testkit = { workspace = true } # The WHATWG parser the `ui` link splitter must agree with: its differential # tests check every web link the splitter accepts against `url`'s reading. url = { workspace = true } @@ -45,9 +48,8 @@ tokio = { workspace = true, features = ["rt"] } default = [] # Derive `JsonSchema` on the configuration payloads. See `src/config/mod.rs`. schemars = ["dep:schemars"] -# `storage::storage_schema` and its v1 to v2 migration steps. Off by default: the -# only extra dependency is the storage ports crate (no driver, no I/O). -storage = ["dep:tinystoragedrivers-core"] +# Pure storage collection payloads. Migration behavior belongs to `tinymcp`. +storage = ["dep:data-encoding", "dep:sha2", "dep:tinystoragedrivers-types"] [lints] workspace = true diff --git a/crates/tinymcp-bus/src/storage/migrate.rs b/crates/tinymcp-bus/src/storage/migrate.rs deleted file mode 100644 index 27c4a39e..00000000 --- a/crates/tinymcp-bus/src/storage/migrate.rs +++ /dev/null @@ -1,201 +0,0 @@ -//! The v1 to v2 steps: the previous release's `mcp_*` collections and stream -//! become the `mcp.*` ones. -//! -//! Each step is a pure function of the records it is handed, so a resumed or -//! repeated run produces the same output. A step keeps a record's creation -//! time and expiry, renames its `*_at` time fields to `*_ms`, and re-keys it -//! with [`id`]. A cache row or index row that cannot be carried over (its body -//! is not JSON, or the field its new key is built from is missing) is dropped -//! instead of failing the step: it holds nothing the module cannot fetch -//! again, and one bad row must not keep a whole database from migrating. - -use serde_json::{Map, Value}; -use tinystoragedrivers_core::schema::{SourceRecord, Step, TargetRecord}; - -use super::schema::{ - AUDIT_STREAM, REGISTRY_CACHE, REGISTRY_INDEX, REGISTRY_INDEX_STATE, SERVER_NAMES, SERVERS, - TOOL_CACHE, doc_id, -}; - -/// The version the steps read. -const FROM: u32 = 1; -/// The version the steps write. -const TO: u32 = 2; - -/// The v1 stream the audit log was appended to. -const LEGACY_AUDIT: &str = "mcp_audit"; - -/// A document step's per-record rule: the new id and body, or `None` to drop -/// the record. -type Rewrite = fn( - &SourceRecord, - Map, -) -> tinystoragedrivers_core::Result>; - -/// Every step, in the order they run. -pub(super) fn steps() -> Vec { - vec![ - documents("servers_v2", SERVERS, "mcp_servers", server), - documents("server_names_v2", SERVER_NAMES, "mcp_server_names", claim), - documents( - "registry_cache_v2", - REGISTRY_CACHE, - "mcp_registry_cache", - cached_response, - ), - documents("tool_cache_v2", TOOL_CACHE, "mcp_tool_cache", cached_tools), - documents( - "registry_index_v2", - REGISTRY_INDEX, - "mcp_registry_index", - index_row, - ), - documents( - "registry_index_state_v2", - REGISTRY_INDEX_STATE, - "mcp_registry_index_state", - index_state, - ), - Step::stream("audit_v2", AUDIT_STREAM, FROM, TO, |name, entries| { - let rest = name - .strip_prefix(LEGACY_AUDIT) - .unwrap_or(&name) - .trim_start_matches('/'); - let target = if rest.is_empty() { - AUDIT_STREAM.to_owned() - } else { - format!("{AUDIT_STREAM}/{rest}") - }; - Ok(Some((target, entries))) - }) - .source_prefix(LEGACY_AUDIT), - ] -} - -/// A step reading the legacy collection `legacy` and writing `item`, applying -/// `rewrite` to each record's body. -fn documents(id: &'static str, item: &'static str, legacy: &'static str, rewrite: Rewrite) -> Step { - Step::new(id, item, FROM, TO, move |batch| { - let mut targets = Vec::with_capacity(batch.len()); - for record in batch { - let Value::Object(body) = record.body.clone() else { - continue; - }; - if let Some((new_id, body)) = rewrite(&record, body)? { - let mut target = - TargetRecord::new(item, new_id, body).expires_ms(record.meta.expires_ms); - if record.meta.created_ms > 0 { - target = target.created_ms(record.meta.created_ms); - } - targets.push(target); - } - } - Ok(targets) - }) - .source(legacy) -} - -/// Moves `from` to `to` when the record has it. -fn rename(body: &mut Map, from: &str, to: &str) { - if let Some(value) = body.remove(from) { - body.insert(to.to_owned(), value); - } -} - -/// The string field `name`, if the record has it. -fn text<'a>(body: &'a Map, name: &str) -> Option<&'a str> { - body.get(name).and_then(Value::as_str) -} - -/// Replaces the JSON text in `from` with the value it holds, under `to`. -/// `None` when the field is missing or is not JSON. -fn unwrap_json(body: &mut Map, from: &str, to: &str) -> Option<()> { - let parsed = serde_json::from_str::(text(body, from)?).ok()?; - body.remove(from); - body.insert(to.to_owned(), parsed); - Some(()) -} - -fn server( - record: &SourceRecord, - mut body: Map, -) -> tinystoragedrivers_core::Result> { - rename(&mut body, "installed_at", "installed_ms"); - rename(&mut body, "last_connected_at", "last_connected_ms"); - Ok(Some((doc_id(&[&record.id])?, Value::Object(body)))) -} - -/// A name claim: keyed by the qualified name it holds. A claim from before -/// claims were timed reads as claimed at `0`, i.e. long expired. -fn claim( - _record: &SourceRecord, - mut body: Map, -) -> tinystoragedrivers_core::Result> { - let Some(name) = text(&body, "qualified_name").map(ToOwned::to_owned) else { - return Ok(None); - }; - let claimed = body - .remove("claimed_at") - .and_then(|value| value.as_i64()) - .unwrap_or(0); - body.insert("claimed_ms".to_owned(), Value::from(claimed)); - Ok(Some((doc_id(&[&name])?, Value::Object(body)))) -} - -fn cached_response( - _record: &SourceRecord, - mut body: Map, -) -> tinystoragedrivers_core::Result> { - let Some(key) = text(&body, "cache_key").map(ToOwned::to_owned) else { - return Ok(None); - }; - if unwrap_json(&mut body, "body_json", "body").is_none() { - return Ok(None); - } - rename(&mut body, "cached_at", "cached_ms"); - Ok(Some((doc_id(&[&key])?, Value::Object(body)))) -} - -fn cached_tools( - _record: &SourceRecord, - mut body: Map, -) -> tinystoragedrivers_core::Result> { - let Some(key) = text(&body, "server_key").map(ToOwned::to_owned) else { - return Ok(None); - }; - rename(&mut body, "cached_at", "cached_ms"); - Ok(Some((doc_id(&[&key])?, Value::Object(body)))) -} - -fn index_row( - _record: &SourceRecord, - mut body: Map, -) -> tinystoragedrivers_core::Result> { - let (Some(source), Some(name)) = ( - text(&body, "source").map(ToOwned::to_owned), - text(&body, "qualified_name").map(ToOwned::to_owned), - ) else { - return Ok(None); - }; - if unwrap_json(&mut body, "record_json", "record").is_none() { - return Ok(None); - } - rename(&mut body, "synced_at", "synced_ms"); - Ok(Some((doc_id(&[&source, &name])?, Value::Object(body)))) -} - -fn index_state( - _record: &SourceRecord, - mut body: Map, -) -> tinystoragedrivers_core::Result> { - let Some(source) = text(&body, "source").map(ToOwned::to_owned) else { - return Ok(None); - }; - rename(&mut body, "started_at", "started_ms"); - rename(&mut body, "synced_at", "synced_ms"); - Ok(Some((doc_id(&[&source])?, Value::Object(body)))) -} - -#[cfg(test)] -#[path = "migrate_tests.rs"] -mod tests; diff --git a/crates/tinymcp-bus/src/storage/migrate_tests.rs b/crates/tinymcp-bus/src/storage/migrate_tests.rs deleted file mode 100644 index 31108202..00000000 --- a/crates/tinymcp-bus/src/storage/migrate_tests.rs +++ /dev/null @@ -1,361 +0,0 @@ -//! Tests for the v1 to v2 steps, run through the registry over v1-shaped fixtures. - -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - -use serde_json::{Value, json}; -use tinystoragedrivers_core::schema::{MigrateOptions, MigrationReport, Registry}; -use tinystoragedrivers_core::{ - CollectionSpec, DocumentStoreExt as _, Filter, MemoryStorage, Precondition, Query, Scope, - ScopedStorage, StorageBackend, Versioned, -}; - -use super::*; -use crate::storage::schema::{SCHEMA_VERSION, storage_schema}; - -/// A memory backend holding v1 data, and the registry that migrates it. -struct Fixture { - blocking: tokio::runtime::Runtime, - storage: ScopedStorage, - registry: Registry, -} - -impl Fixture { - fn new() -> Self { - let blocking = tokio::runtime::Builder::new_current_thread() - .build() - .unwrap(); - let backend = MemoryStorage::new(); - let registry = Registry::compose([storage_schema()]).unwrap(); - blocking.block_on(registry.prepare(&backend)).unwrap(); - let scope = Scope::local().module("tinymcp").unwrap(); - let storage = backend.for_scope(&scope).unwrap(); - Self { - blocking, - storage, - registry, - } - } - - /// Writes one v1 document the way the previous release did. - fn legacy(&self, collection: &str, id: &str, body: Value) { - let documents = self.storage.documents().clone(); - let collection = collection.to_string(); - let id = id.to_string(); - self.blocking - .block_on(async move { - documents - .ensure_collection(&CollectionSpec::new(&collection)) - .await?; - documents - .put(&collection, &id, body, Precondition::None) - .await - }) - .unwrap(); - } - - fn legacy_stream(&self, name: &str, entries: &[Value]) { - let streams = self.storage.streams().clone(); - let name = name.to_string(); - let entries = entries.to_vec(); - self.blocking - .block_on(async move { - for entry in entries { - streams.append(&name, entry).await?; - } - Ok::<_, tinystoragedrivers_core::StorageError>(()) - }) - .unwrap(); - } - - fn migrate(&self) -> MigrationReport { - self.blocking - .block_on(self.registry.migrate(&self.storage, &MigrateOptions::new())) - .unwrap() - } - - fn get(&self, collection: &str, id: &str) -> Option> { - let documents = self.storage.documents().clone(); - let collection = collection.to_string(); - let id = id.to_string(); - self.blocking - .block_on(async move { documents.get(&collection, &id).await }) - .unwrap() - } - - fn all(&self, collection: &str) -> Vec> { - let documents = self.storage.documents().clone(); - let collection = collection.to_string(); - self.blocking - .block_on(async move { documents.query_all(&collection, &Query::all()).await }) - .unwrap() - } - - fn count_where(&self, collection: &str, filter: Filter) -> u64 { - let documents = self.storage.documents().clone(); - let collection = collection.to_string(); - self.blocking - .block_on(async move { documents.count(&collection, &filter).await }) - .unwrap() - } - - fn stream(&self, name: &str) -> Vec { - let streams = self.storage.streams().clone(); - let name = name.to_string(); - self.blocking - .block_on(async move { - let len = streams.len(&name).await?; - let window = streams.read_window(&name, 0, 1024).await?; - assert_eq!(window.len() as u64, len); - Ok::, tinystoragedrivers_core::StorageError>( - window.into_iter().map(|entry| entry.value).collect(), - ) - }) - .unwrap() - } -} - -fn v1_server() -> Value { - json!({ - "server_id": "srv-1", - "qualified_name": "@acme/files", - "display_name": "Files", - "command_kind": "node", - "command": "npx", - "args": ["-y", "files"], - "env_keys": ["TOKEN"], - "installed_at": 1_700_000_000_000_i64, - "last_connected_at": 1_700_000_100_000_i64, - "transport": "stdio", - "enabled": true, - "catalog_managed": true, - }) -} - -#[test] -fn a_v1_server_moves_to_the_v2_collection_with_ms_time_fields() { - let fixture = Fixture::new(); - fixture.legacy("mcp_servers", "srv-1", v1_server()); - - fixture.migrate(); - - let moved = fixture.get(SERVERS, "srv-1").expect("the server moved"); - assert_eq!(moved.doc["installed_ms"], 1_700_000_000_000_i64); - assert_eq!(moved.doc["last_connected_ms"], 1_700_000_100_000_i64); - assert!(moved.doc.get("installed_at").is_none()); - assert!(moved.doc.get("last_connected_at").is_none()); - assert_eq!(moved.doc["qualified_name"], "@acme/files"); - assert_eq!(moved.doc["catalog_managed"], true); - assert_eq!(moved.doc["args"], json!(["-y", "files"])); - assert_eq!(moved.meta.schema, SCHEMA_VERSION); - assert_eq!(fixture.all("mcp_servers").len(), 0); -} - -#[test] -fn a_server_never_connected_keeps_no_last_connected_field() { - let fixture = Fixture::new(); - let mut server = v1_server(); - server.as_object_mut().unwrap().remove("last_connected_at"); - fixture.legacy("mcp_servers", "srv-1", server); - - fixture.migrate(); - - let moved = fixture.get(SERVERS, "srv-1").unwrap(); - assert!(moved.doc.get("last_connected_ms").is_none()); - assert_eq!(moved.doc["installed_ms"], 1_700_000_000_000_i64); -} - -#[test] -fn a_server_id_with_a_slash_is_escaped_into_its_v2_key() { - let fixture = Fixture::new(); - fixture.legacy("mcp_servers", "a/b", v1_server()); - - fixture.migrate(); - - assert!(fixture.get(SERVERS, "a%2Fb").is_some()); -} - -#[test] -fn a_name_claim_is_keyed_by_the_qualified_name_and_keeps_its_time() { - let fixture = Fixture::new(); - fixture.legacy( - "mcp_server_names", - "legacy-claim-files", - json!({"qualified_name": "@acme/files", "server_id": "srv-1", "claimed_at": 5_000}), - ); - fixture.legacy( - "mcp_server_names", - "legacy-claim-old", - json!({"qualified_name": "@acme/old", "server_id": "srv-0"}), - ); - - fixture.migrate(); - - let claim = fixture.get(SERVER_NAMES, "@acme%2Ffiles").unwrap(); - assert_eq!( - claim.doc, - json!({"qualified_name": "@acme/files", "server_id": "srv-1", "claimed_ms": 5_000}) - ); - // A claim that predates the time reads as long expired. - let old = fixture.get(SERVER_NAMES, "@acme%2Fold").unwrap(); - assert_eq!(old.doc["claimed_ms"], 0); - assert_eq!(fixture.all("mcp_server_names").len(), 0); -} - -#[test] -fn a_cached_browse_response_becomes_an_object_body_with_a_cached_time() { - let fixture = Fixture::new(); - fixture.legacy( - "mcp_registry_cache", - "digest-1", - json!({"cache_key": "official:search:slack", "body_json": "{\"servers\":[1,2]}", "cached_at": 9_000}), - ); - - fixture.migrate(); - - let moved = fixture - .get(REGISTRY_CACHE, "official:search:slack") - .unwrap(); - assert_eq!( - moved.doc, - json!({"cache_key": "official:search:slack", "body": {"servers": [1, 2]}, "cached_ms": 9_000}) - ); -} - -#[test] -fn a_cached_response_that_is_not_json_is_dropped_rather_than_blocking_the_step() { - let fixture = Fixture::new(); - fixture.legacy( - "mcp_registry_cache", - "digest-1", - json!({"cache_key": "k", "body_json": "not json", "cached_at": 1}), - ); - fixture.legacy( - "mcp_registry_cache", - "digest-2", - json!({"cache_key": "ok", "body_json": "[]", "cached_at": 2}), - ); - - fixture.migrate(); - - assert!(fixture.get(REGISTRY_CACHE, "k").is_none()); - assert!(fixture.get(REGISTRY_CACHE, "ok").is_some()); - assert_eq!(fixture.all("mcp_registry_cache").len(), 0); -} - -#[test] -fn cached_tools_are_keyed_by_the_server_key() { - let fixture = Fixture::new(); - fixture.legacy( - "mcp_tool_cache", - "digest-1", - json!({"server_key": "static:docs", "fingerprint": "abc", "tools": [{"name": "t"}], "cached_at": 7_000}), - ); - - fixture.migrate(); - - let moved = fixture.get(TOOL_CACHE, "static:docs").unwrap(); - assert_eq!( - moved.doc, - json!({"server_key": "static:docs", "fingerprint": "abc", "tools": [{"name": "t"}], "cached_ms": 7_000}) - ); -} - -#[test] -fn an_index_row_gets_an_object_record_a_synced_time_and_a_composite_key() { - let fixture = Fixture::new(); - fixture.legacy( - "mcp_registry_index", - "digest-1", - json!({ - "source": "official", - "qualified_name": "@acme/files", - "label": "files", - "description": "read files", - "record_json": "{\"name\":\"files\"}", - "synced_at": 4_000, - "search": "fi fil file files", - }), - ); - - fixture.migrate(); - - let moved = fixture - .get(REGISTRY_INDEX, "official/@acme%2Ffiles") - .unwrap(); - assert_eq!(moved.doc["record"], json!({"name": "files"})); - assert_eq!(moved.doc["synced_ms"], 4_000); - assert!(moved.doc.get("record_json").is_none()); - assert!(moved.doc.get("synced_at").is_none()); - assert_eq!(moved.doc["search"], "fi fil file files"); - assert_eq!( - fixture.count_where(REGISTRY_INDEX, Filter::eq("source", "official")), - 1 - ); -} - -#[test] -fn an_index_state_moves_its_times_to_ms_fields() { - let fixture = Fixture::new(); - fixture.legacy( - "mcp_registry_index_state", - "digest-1", - json!({"source": "official", "base_url": "https://r", "cursor": "c", "pages": 3, "started_at": 100, "synced_at": 50}), - ); - fixture.legacy( - "mcp_registry_index_state", - "digest-2", - json!({"source": "other", "base_url": "https://o", "pages": 0}), - ); - - fixture.migrate(); - - let state = fixture.get(REGISTRY_INDEX_STATE, "official").unwrap(); - assert_eq!( - state.doc, - json!({"source": "official", "base_url": "https://r", "cursor": "c", "pages": 3, "started_ms": 100, "synced_ms": 50}) - ); - let idle = fixture.get(REGISTRY_INDEX_STATE, "other").unwrap(); - assert!(idle.doc.get("started_ms").is_none()); - assert!(idle.doc.get("synced_ms").is_none()); -} - -#[test] -fn the_audit_stream_moves_in_order_under_its_v2_name() { - let fixture = Fixture::new(); - let entries = [ - json!({"timestamp_ms": 1, "client_info": "c", "tool_name": "a", "args_summary": {}, "success": true}), - json!({"timestamp_ms": 2, "client_info": "c", "tool_name": "b", "args_summary": {}, "success": false, "error_message": "boom"}), - ]; - fixture.legacy_stream("mcp_audit", &entries); - - fixture.migrate(); - - assert_eq!(fixture.stream(AUDIT_STREAM), entries); - assert_eq!(fixture.stream("mcp_audit").len(), 0); -} - -#[test] -fn migrating_again_changes_nothing() { - let fixture = Fixture::new(); - fixture.legacy("mcp_servers", "srv-1", v1_server()); - fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); - - fixture.migrate(); - let before = fixture.get(SERVERS, "srv-1").unwrap(); - fixture.migrate(); - - let after = fixture.get(SERVERS, "srv-1").unwrap(); - assert_eq!(before, after); - assert_eq!(fixture.stream(AUDIT_STREAM).len(), 1); -} - -#[test] -fn the_module_can_be_used_once_every_step_has_finished() { - let fixture = Fixture::new(); - assert!(fixture.registry.check_ready(SERVERS).is_err()); - - fixture.migrate(); - - fixture.registry.check_ready(SERVERS).unwrap(); - fixture.registry.check_ready(AUDIT_STREAM).unwrap(); -} diff --git a/crates/tinymcp-bus/src/storage/mod.rs b/crates/tinymcp-bus/src/storage/mod.rs index 38d0c3a3..9d44e202 100644 --- a/crates/tinymcp-bus/src/storage/mod.rs +++ b/crates/tinymcp-bus/src/storage/mod.rs @@ -1,15 +1,15 @@ -//! The module's storage declaration: [`storage_schema`], its v1 to v2 -//! migration steps, and the names they share. +//! The MCP module's pure storage declarations. //! -//! This lives in the contract crate so a host composes the schema and -//! generates the module's storage grant without linking the implementation. It -//! needs only the storage *ports* (`tinystoragedrivers-core`, no driver, no -//! I/O of its own); every step is a pure function of the records it is handed. +//! This contract lists the collection shapes and stable names that a host may +//! provision. Migration execution and storage behavior live in `tinymcp`. -mod migrate; mod schema; pub use schema::{ - AUDIT_STREAM, OWNER, REGISTRY_CACHE, REGISTRY_INDEX, REGISTRY_INDEX_STATE, SCHEMA_VERSION, - SERVER_NAMES, SERVERS, TOOL_CACHE, doc_id, storage_schema, write_options, + AUDIT_STREAM, MIGRATIONS, OWNER, REGISTRY_CACHE, REGISTRY_INDEX, REGISTRY_INDEX_STATE, + SCHEMA_VERSION, SERVER_NAMES, SERVERS, TOOL_CACHE, collection_specs, doc_id, write_options, }; + +#[cfg(test)] +#[path = "schema_tests.rs"] +mod tests; diff --git a/crates/tinymcp-bus/src/storage/schema.rs b/crates/tinymcp-bus/src/storage/schema.rs index 4aeab30c..bfc50875 100644 --- a/crates/tinymcp-bus/src/storage/schema.rs +++ b/crates/tinymcp-bus/src/storage/schema.rs @@ -1,43 +1,12 @@ -//! The module's storage declaration: what it keeps, under which names. -//! -//! [`storage_schema`] is the one place the module's collections and stream are -//! named. A host composes it with every other owner's schema -//! (`Registry::compose`), prepares the backend from it, runs its migration -//! steps over the module's scope, and generates the module's storage grant from -//! it (see [`grant`](super::grant)). -//! -//! # Names -//! -//! Every name starts with the owner `mcp`. Documents use bare `snake_case` -//! bodies, times are epoch milliseconds in `*_ms` fields, and ids are built -//! with `Key::of`, so a qualified name such as `@acme/files` is stored as -//! `@acme%2Ffiles` and never needs a digest to be a safe id. -//! -//! | v1 | v2 | -//! | --- | --- | -//! | `mcp_servers` | `mcp.servers` | -//! | `mcp_server_names` | `mcp.server_names` | -//! | `mcp_registry_cache` | `mcp.registry_cache` | -//! | `mcp_tool_cache` | `mcp.tool_cache` | -//! | `mcp_registry_index` | `mcp.registry_index` | -//! | `mcp_registry_index_state` | `mcp.registry_index_state` | -//! | stream `mcp_audit` | stream `mcp.audit` | -//! -//! The secrets (`mcp_client_env/`, `mcp_cache_fingerprint_key`) keep -//! their names: a secret cannot be renamed by a migration step, and a name -//! outside the owner prefix cannot be declared as an item, so the grant lists -//! them beside the schema. +//! Pure collection names and shapes for MCP storage. -use tinystoragedrivers_core::schema::{Owner, Schema, ScopeClass}; -use tinystoragedrivers_core::{CollectionSpec, IndexSpec, Key, WriteOptions}; - -use super::migrate; +use sha2::{Digest, Sha256}; +use tinystoragedrivers_types::{CollectionSpec, IndexSpec, Key, MAX_ID_LEN, WriteOptions}; /// The owner every name below starts with. pub const OWNER: &str = "mcp"; -/// The body version every collection is declared at. Version 1 is the layout -/// of the previous release, whose collections carried `mcp_` names. +/// The body version every collection is declared at. pub const SCHEMA_VERSION: u32 = 2; /// One document per installed server. @@ -52,50 +21,25 @@ pub const TOOL_CACHE: &str = "mcp.tool_cache"; pub const REGISTRY_INDEX: &str = "mcp.registry_index"; /// Where each catalog's sync stands. pub const REGISTRY_INDEX_STATE: &str = "mcp.registry_index_state"; - /// The append-only stream of tool-write audit records. pub const AUDIT_STREAM: &str = "mcp.audit"; +/// Shared progress records used by MCP's owner-local migrations. +pub const MIGRATIONS: &str = "tsd.migrations"; -/// Everything the module stores, with the steps that bring a v1 database -/// forward. -/// -/// All items live in [`ScopeClass::Module`]: the module never names a tenant, -/// the handles it is given carry the scope. -/// -/// # Panics -/// -/// Never in practice: the owner name is a constant that `Owner::new` accepts, -/// and a unit test pins that. +/// Collection declarations the module asks the host to provision. #[must_use] -#[expect( - clippy::expect_used, - reason = "the owner is the constant `mcp`, which `Owner::new` accepts; a test pins it" -)] -pub fn storage_schema() -> Schema { - let owner = Owner::new(OWNER).expect("`mcp` is a valid owner name"); - let schema = Schema::new(owner) - .collection_with( - SCHEMA_VERSION, - CollectionSpec::new(SERVERS) - .index(IndexSpec::new("qualified_name", ["qualified_name"])) - .index(IndexSpec::new("installed_ms", ["installed_ms"])), - ScopeClass::Module, - ) - .collection(SERVER_NAMES, SCHEMA_VERSION, ScopeClass::Module) - .collection_with( - SCHEMA_VERSION, - CollectionSpec::new(REGISTRY_CACHE).index(IndexSpec::new("cache_key", ["cache_key"])), - ScopeClass::Module, - ) - .collection(TOOL_CACHE, SCHEMA_VERSION, ScopeClass::Module) - .collection_with( - SCHEMA_VERSION, - CollectionSpec::new(REGISTRY_INDEX).index(IndexSpec::new("source", ["source"])), - ScopeClass::Module, - ) - .collection(REGISTRY_INDEX_STATE, SCHEMA_VERSION, ScopeClass::Module) - .stream(AUDIT_STREAM, ScopeClass::Module); - migrate::steps().into_iter().fold(schema, Schema::step) +pub fn collection_specs() -> Vec { + vec![ + CollectionSpec::new(SERVERS) + .index(IndexSpec::new("qualified_name", ["qualified_name"])) + .index(IndexSpec::new("installed_ms", ["installed_ms"])), + CollectionSpec::new(SERVER_NAMES), + CollectionSpec::new(REGISTRY_CACHE).index(IndexSpec::new("cache_key", ["cache_key"])), + CollectionSpec::new(TOOL_CACHE), + CollectionSpec::new(REGISTRY_INDEX).index(IndexSpec::new("source", ["source"])), + CollectionSpec::new(REGISTRY_INDEX_STATE), + CollectionSpec::new(MIGRATIONS), + ] } /// The options every document write carries: the body version. @@ -104,16 +48,39 @@ pub fn write_options() -> WriteOptions { WriteOptions::new().schema(SCHEMA_VERSION) } -/// The document id for `parts`: joined and escaped by [`Key::of`], and hashed -/// when it would be too long. +/// The document id for `parts`, using the released TSD composite-key encoding. /// /// # Errors /// /// Returns the storage error for an empty key. -pub fn doc_id(parts: &[&str]) -> tinystoragedrivers_core::Result { - Key::of(parts).map(|key| key.as_str().to_owned()) +pub fn doc_id(parts: &[&str]) -> tinystoragedrivers_types::Result { + if parts.is_empty() { + return Err(tinystoragedrivers_types::StorageError::invalid_input( + "a key needs at least one part", + )); + } + let mut encoded = String::new(); + for (index, part) in parts.iter().enumerate() { + if index != 0 { + encoded.push('/'); + } + for (character_index, character) in part.chars().enumerate() { + match character { + '%' => encoded.push_str("%25"), + '/' => encoded.push_str("%2F"), + '\0' => encoded.push_str("%00"), + '~' if index == 0 && character_index == 0 => encoded.push_str("%7E"), + other => encoded.push(other), + } + } + } + if encoded.len() > MAX_ID_LEN { + encoded = format!( + "~{}", + data_encoding::BASE32_NOPAD + .encode(&Sha256::digest(encoded.as_bytes())) + .to_ascii_lowercase() + ); + } + Key::new(encoded).map(|key| key.as_str().to_owned()) } - -#[cfg(test)] -#[path = "schema_tests.rs"] -mod tests; diff --git a/crates/tinymcp-bus/src/storage/schema_tests.rs b/crates/tinymcp-bus/src/storage/schema_tests.rs index 22aae1b2..066be604 100644 --- a/crates/tinymcp-bus/src/storage/schema_tests.rs +++ b/crates/tinymcp-bus/src/storage/schema_tests.rs @@ -1,63 +1,27 @@ -//! Tests for the module's storage declaration. +//! Tests for the storage names and shapes carried by the bus contract. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use tinystoragedrivers_core::schema::{Item, Registry, ScopeClass}; - use super::*; #[test] -fn the_schema_composes_under_the_mcp_owner() { - let registry = Registry::compose([storage_schema()]).unwrap(); - assert_eq!(registry.owners().collect::>(), [OWNER]); - for collection in [ - SERVERS, - SERVER_NAMES, - REGISTRY_CACHE, - TOOL_CACHE, - REGISTRY_INDEX, - REGISTRY_INDEX_STATE, - ] { - assert_eq!( - registry.collection_version(collection), - Some(SCHEMA_VERSION) - ); - } -} - -#[test] -fn every_item_is_module_scoped_and_named_under_the_owner() { - let schema = storage_schema(); - assert!(!schema.items.is_empty()); - for item in &schema.items { - assert_eq!(item.scope(), ScopeClass::Module, "{}", item.name()); - assert!(item.name().starts_with("mcp."), "{}", item.name()); - } -} - -#[test] -fn the_audit_log_is_a_declared_stream() { - let schema = storage_schema(); - assert!( - schema - .items - .iter() - .any(|item| matches!(item, Item::Stream { name, .. } if name == AUDIT_STREAM)) +fn collection_contract_keeps_v2_names_and_indexes() { + let specs = collection_specs(); + let names: Vec<_> = specs.iter().map(|spec| spec.name.as_str()).collect(); + assert_eq!( + names, + [ + SERVERS, + SERVER_NAMES, + REGISTRY_CACHE, + TOOL_CACHE, + REGISTRY_INDEX, + REGISTRY_INDEX_STATE, + MIGRATIONS, + ] ); -} - -#[test] -fn the_declared_indexes_use_v2_field_names() { - let schema = storage_schema(); - let servers = schema - .items - .iter() - .find_map(|item| match item { - Item::Collection { name, spec, .. } if name == SERVERS => Some(spec), - _ => None, - }) - .unwrap(); - let indexed: Vec<&str> = servers + let servers = specs.iter().find(|spec| spec.name == SERVERS).unwrap(); + let indexed: Vec<_> = servers .indexes .iter() .map(|index| index.name.as_str()) @@ -73,6 +37,24 @@ fn ids_are_escaped_keys() { } #[test] -fn writes_declare_the_schema_version() { +fn composite_ids_escape_reserved_bytes_without_changing_component_boundaries() { + assert_eq!( + doc_id(&["~owner%", "part/with\0bytes"]).unwrap(), + "%7Eowner%25/part%2Fwith%00bytes" + ); + assert_eq!(doc_id(&["owner", "~leading"]).unwrap(), "owner/~leading"); + assert!(doc_id(&[]).is_err()); +} + +#[test] +fn overlong_composite_ids_keep_the_legacy_digest_encoding() { + let component = "x".repeat(513); + let id = doc_id(&[&component]).unwrap(); + assert_eq!(id.len(), 53); + assert_eq!(id, "~gww6aciomttu22wqiicabhbdutruxav56d2pgf73zrpsn6nrajaq"); +} + +#[test] +fn write_options_pin_the_collection_schema_version() { assert_eq!(write_options().schema, SCHEMA_VERSION); } diff --git a/crates/tinymcp/Cargo.toml b/crates/tinymcp/Cargo.toml index 742bb29c..1d2d7193 100644 --- a/crates/tinymcp/Cargo.toml +++ b/crates/tinymcp/Cargo.toml @@ -38,10 +38,10 @@ base64 = { workspace = true } futures-util = { workspace = true } tracing = { workspace = true } dirs = { workspace = true } -tinystoragedrivers-core = { workspace = true } -tinystoragedrivers-secrets = { workspace = true } +data-encoding = { workspace = true } +tinystoragedrivers-api = { workspace = true } +tinystoragedrivers-types = { workspace = true } tinystoragedrivers-busproxy = { workspace = true, optional = true } -tinystoragedrivers-client = { workspace = true, optional = true } uuid = { workspace = true } sha2 = { workspace = true } serde = { workspace = true } @@ -70,6 +70,9 @@ name = "verify_github_release" required-features = ["module"] [dev-dependencies] +# The compiled-module verifier must admit the artifact through TinyBus's +# test attestation helper before exercising confidential storage calls. +tinybus = { workspace = true, features = ["test-support"] } # `net` stands up the loopback test servers; `test-util` pauses the clock so a # five-minute timeout is testable without waiting five minutes. The rest comes # from the ordinary dependency entry above. @@ -78,13 +81,17 @@ tokio = { workspace = true, features = ["net", "test-util"] } axum = { workspace = true, features = ["form"] } # Temporary directories for the command-resolution tests. tempfile = { workspace = true } +# Real memory engines and decorators for storage-port tests only. +tinystoragedrivers-testkit = { workspace = true } +tinystoragedrivers-document = { workspace = true } +tinystoragedrivers-secrets = { workspace = true, features = ["memory"] } [features] default = ["module", "rustls-tls"] # Build the `TinyBus` adapter and the ABI exports. On by default because the # released artifact is a loadable module; a host consuming this crate as a path # dependency turns it off and links neither `tinybus` nor its module SDK. -module = ["dep:tinybus", "dep:tinybus-module", "dep:tinystoragedrivers-busproxy", "dep:tinystoragedrivers-client"] +module = ["dep:tinybus", "dep:tinybus-module", "dep:tinystoragedrivers-busproxy"] # Link the TinyBus module into a host binary with Rust-addressable entry points. static-link = ["module"] # Bundle a TLS stack, so a build needs no system OpenSSL. The default. diff --git a/crates/tinymcp/examples/verify_module.rs b/crates/tinymcp/examples/verify_module.rs index 9a58dcfb..e7b54cc5 100644 --- a/crates/tinymcp/examples/verify_module.rs +++ b/crates/tinymcp/examples/verify_module.rs @@ -13,6 +13,7 @@ use std::io; use std::path::PathBuf; +use std::sync::Arc; use std::time::Duration; use tinybus::Connection; @@ -20,6 +21,12 @@ use tinybus::broker::Broker; use tinybus::module::ModuleHost; use tinybus::transport::memory::MemoryBus; use tinymcp::{ConnectedServerOverview, InstalledServer, McpTool, names}; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_busproxy::{ + PerCallerEndpoint, StorageServer, prepare_storage_host_callbacks, serve_with_host_callbacks, +}; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::Scope; /// How long to wait for the module to claim its name. const CLAIM_TIMEOUT: Duration = Duration::from_secs(5); @@ -32,9 +39,41 @@ async fn main() -> Result<(), Box> { let broker = Broker::new(); let broker_task = broker.spawn(bus.clone()); + // A module must get storage from its host. The explicit memory engine is + // confined to this verification host; production module startup has no + // local fallback. let module_host = ModuleHost::new(broker); - let info = module_host.load_file(&module)?; + let binding = prepare_storage_host_callbacks(&module_host).await?; + let storage_backend = MemoryBackend::new(); + let storage = storage_backend.for_scope(&Scope::new("mcp-module-e2e")?)?; + let endpoint = PerCallerEndpoint::new(move |_| Some(StorageServer::new(storage.clone()))); + let _served_storage = + serve_with_host_callbacks(Arc::clone(&binding), Arc::new(endpoint)).await?; + + // The host callback loader verifies the artifact against its adjacent + // `modules.toml` before granting this exact module the callback binding. + // The destination is host-provisioned configuration, never a scope input. + let info = module_host + .load_file_with_host_callbacks( + &module, + serde_json::json!({ + "storage_callback": binding.unique_name().as_str(), + }), + &binding, + ) + .await?; + + verify_module_calls(&module_host, &bus, &module, info).await?; + broker_task.abort(); + Ok(()) +} +async fn verify_module_calls( + module_host: &ModuleHost, + bus: &MemoryBus, + module: &std::path::Path, + info: tinybus::module::ModuleInfo, +) -> Result<(), Box> { if info.name != env!("CARGO_PKG_NAME") { return Err(io::Error::other(format!( "loaded module `{}` instead of `{}`", @@ -75,12 +114,27 @@ async fn main() -> Result<(), Box> { tokio::task::yield_now().await; } }) - .await??; + .await + .map_err(|error| { + io::Error::other(format!( + "the loaded module did not claim its interface; state: {:?}; {error}", + module_host.list() + )) + })??; let proxy = client.proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)?; // Needs nothing configured: this is dispatch working at all. - let declared: Vec = proxy.call(names::methods::STATIC_LIST, ()).await?; + let declared: Vec = + proxy + .call(names::methods::STATIC_LIST, ()) + .await + .map_err(|error| { + io::Error::other(format!( + "StaticList did not respond; module state: {:?}; {error}", + module_host.list() + )) + })?; if !declared.is_empty() { return Err(io::Error::other(format!( "an unconfigured module declared {} static servers", @@ -130,7 +184,6 @@ async fn main() -> Result<(), Box> { names::INTERFACE ); - broker_task.abort(); Ok(()) } diff --git a/crates/tinymcp/src/audit/store/types.rs b/crates/tinymcp/src/audit/store/types.rs index e09a2583..aeb4d687 100644 --- a/crates/tinymcp/src/audit/store/types.rs +++ b/crates/tinymcp/src/audit/store/types.rs @@ -2,9 +2,9 @@ use crate::McpWriteListQueryExt; +use crate::storage::types::{StorageError, StreamEntry}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use tinystoragedrivers_core::{StorageError, StreamEntry}; use crate::error::{Error, Result}; use crate::storage::{AUDIT_STREAM, StoragePorts}; @@ -44,6 +44,9 @@ impl AuditStore { /// /// Returns [`Error::Store`] when the stream cannot be reached. pub fn open(ports: StoragePorts) -> Result { + // Opening this owner handle also runs the owner's schema and stream + // migrations, including when callers do not open the registry store. + ports.prepare()?; ports.run("opening the audit log", |ports| async move { ports.streams.len(AUDIT_STREAM).await.map(|_| ()) })?; @@ -55,6 +58,7 @@ impl AuditStore { /// # Errors /// /// Returns [`Error::Store`] when the backend cannot be opened. + #[cfg(test)] pub fn open_in_memory() -> Result { Self::open(StoragePorts::memory()?) } diff --git a/crates/tinymcp/src/error/mod.rs b/crates/tinymcp/src/error/mod.rs index 2e52b0f2..af92446e 100644 --- a/crates/tinymcp/src/error/mod.rs +++ b/crates/tinymcp/src/error/mod.rs @@ -302,7 +302,7 @@ pub enum Error { action: String, /// What the storage port reported. #[source] - source: Box, + source: Box, }, /// A host-supplied credential store could not do what was asked of it. @@ -397,7 +397,7 @@ impl Error { /// Builds a [`Self::Store`] describing what was being attempted. pub(crate) fn store( action: impl Into, - source: tinystoragedrivers_core::StorageError, + source: crate::storage::types::StorageError, ) -> Self { Self::Store { action: action.into(), diff --git a/crates/tinymcp/src/error/mod_tests.rs b/crates/tinymcp/src/error/mod_tests.rs index 4c94cb8b..32493343 100644 --- a/crates/tinymcp/src/error/mod_tests.rs +++ b/crates/tinymcp/src/error/mod_tests.rs @@ -354,7 +354,7 @@ fn one_of_every_variant() -> Vec { errors.push(serde_json::from_str::("x").unwrap_err().into()); errors.push(Error::store( "listing", - tinystoragedrivers_core::StorageError::not_found("missing"), + crate::storage::types::StorageError::not_found("missing"), )); errors.push(Error::StoreIo { path: "/nowhere".into(), diff --git a/crates/tinymcp/src/registry/store/index.rs b/crates/tinymcp/src/registry/store/index.rs index 8ea100ff..464e2a26 100644 --- a/crates/tinymcp/src/registry/store/index.rs +++ b/crates/tinymcp/src/registry/store/index.rs @@ -14,9 +14,9 @@ //! stay until a sync finishes, at which point any server it did not see again //! is removed. +use crate::storage::types::{Capability, DocumentStore, Filter, Precondition, Query, WriteOp}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use tinystoragedrivers_core::{Capability, DocumentStore, Filter, Precondition, Query, WriteOp}; use super::types::{Store, now_ms}; use crate::error::Result; @@ -185,7 +185,7 @@ impl Store { .map(|row| serde_json::from_value(row.doc)) .transpose() .map_err(|error| { - tinystoragedrivers_core::StorageError::serialization(error.to_string()) + crate::storage::types::StorageError::serialization(error.to_string()) })?; let same_catalog = previous .as_ref() @@ -206,7 +206,7 @@ impl Store { .filter(|_| same_catalog), }; let value = serde_json::to_value(state).map_err(|error| { - tinystoragedrivers_core::StorageError::serialization(error.to_string()) + crate::storage::types::StorageError::serialization(error.to_string()) })?; documents .put_with( @@ -272,12 +272,12 @@ impl Store { }; let mut state: StateDoc = serde_json::from_value(found.doc.clone()).map_err(|error| { - tinystoragedrivers_core::StorageError::serialization(error.to_string()) + crate::storage::types::StorageError::serialization(error.to_string()) })?; state.cursor = next_cursor; state.pages += 1; let value = serde_json::to_value(state).map_err(|error| { - tinystoragedrivers_core::StorageError::serialization(error.to_string()) + crate::storage::types::StorageError::serialization(error.to_string()) })?; documents .put_with( @@ -309,7 +309,7 @@ impl Store { }; let mut state: StateDoc = serde_json::from_value(found.doc.clone()).map_err(|error| { - tinystoragedrivers_core::StorageError::serialization(error.to_string()) + crate::storage::types::StorageError::serialization(error.to_string()) })?; if let Some(started_ms) = state.started_ms { documents @@ -325,7 +325,7 @@ impl Store { state.started_ms = None; state.synced_ms = Some(now); let value = serde_json::to_value(state).map_err(|error| { - tinystoragedrivers_core::StorageError::serialization(error.to_string()) + crate::storage::types::StorageError::serialization(error.to_string()) })?; documents .put_with( @@ -363,7 +363,7 @@ impl Store { // inside a word (`ack` in `slack`) is not among its hits. The // substring filter below is the contract, and candidates must // be a superset of it: read the source's rows. - let page = tinystoragedrivers_core::DocumentStoreExt::query_all( + let page = crate::storage::types::DocumentStoreExt::query_all( documents.as_ref(), REGISTRY_INDEX, &Query::filter(Filter::eq("source", source.clone())), @@ -400,7 +400,7 @@ async fn write_chunk( documents: &dyn DocumentStore, chunk: Vec, atomic: bool, -) -> tinystoragedrivers_core::Result<()> { +) -> crate::storage::types::Result<()> { if atomic { return documents.atomic_batch(chunk).await.map(|_| ()); } diff --git a/crates/tinymcp/src/registry/store/mod.rs b/crates/tinymcp/src/registry/store/mod.rs index 07af56b7..4ed658ad 100644 --- a/crates/tinymcp/src/registry/store/mod.rs +++ b/crates/tinymcp/src/registry/store/mod.rs @@ -41,8 +41,8 @@ mod testing; mod tool_cache; mod types; +pub(crate) use tool_cache::fingerprint; pub use tool_cache::{CachedTools, installed_fingerprint, static_cache_key}; -pub(crate) use tool_cache::{fingerprint, hex_digest}; pub use types::Store; pub(crate) use types::now_ms; diff --git a/crates/tinymcp/src/registry/store/mod_tests.rs b/crates/tinymcp/src/registry/store/mod_tests.rs index 9d2e1e7c..9c180b28 100644 --- a/crates/tinymcp/src/registry/store/mod_tests.rs +++ b/crates/tinymcp/src/registry/store/mod_tests.rs @@ -16,8 +16,8 @@ use std::collections::BTreeMap; +use crate::storage::types::Filter; use serde_json::json; -use tinystoragedrivers_core::Filter; use super::types::Store; use crate::Error; @@ -994,7 +994,7 @@ fn meta_of( ports: &StoragePorts, collection: &'static str, id: &str, -) -> tinystoragedrivers_core::Meta { +) -> crate::storage::types::Meta { let id = id.to_string(); ports .run("reading metadata", move |ports| async move { diff --git a/crates/tinymcp/src/registry/store/testing.rs b/crates/tinymcp/src/registry/store/testing.rs index 52a4ed8c..2b071f67 100644 --- a/crates/tinymcp/src/registry/store/testing.rs +++ b/crates/tinymcp/src/registry/store/testing.rs @@ -2,8 +2,8 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use crate::storage::types::{DocumentStoreExt as _, Precondition, Query}; use serde_json::Value; -use tinystoragedrivers_core::{DocumentStoreExt as _, Precondition, Query}; use super::types::Store; diff --git a/crates/tinymcp/src/registry/store/tool_cache.rs b/crates/tinymcp/src/registry/store/tool_cache.rs index 45a0e515..8f3147fc 100644 --- a/crates/tinymcp/src/registry/store/tool_cache.rs +++ b/crates/tinymcp/src/registry/store/tool_cache.rs @@ -22,9 +22,9 @@ //! A read whose fingerprint differs misses, so editing a server's definition //! can never surface the old server's tools under the new one. +use crate::storage::types::Precondition; use serde::{Deserialize, Serialize}; use sha2::{Digest as _, Sha256}; -use tinystoragedrivers_core::Precondition; use super::types::{Store, now_ms}; use crate::error::Result; @@ -105,12 +105,6 @@ pub(super) fn keyed_fingerprint(key: &[u8; 32], value: &str) -> String { hex(&outer.finalize()) } -/// Lower-case hex of the SHA-256 of `bytes`: a document id that is safe for -/// any key, however long or whatever it contains. -pub(crate) fn hex_digest(bytes: &[u8]) -> String { - hex(&Sha256::digest(bytes)) -} - /// Lower-case hex of `bytes`. pub(crate) fn hex(bytes: &[u8]) -> String { use std::fmt::Write as _; diff --git a/crates/tinymcp/src/registry/store/types.rs b/crates/tinymcp/src/registry/store/types.rs index e31f8dcb..e571dae4 100644 --- a/crates/tinymcp/src/registry/store/types.rs +++ b/crates/tinymcp/src/registry/store/types.rs @@ -3,11 +3,10 @@ use std::collections::BTreeMap; use std::time::{SystemTime, UNIX_EPOCH}; +use crate::storage::Repo; +use crate::storage::types::{DocumentStoreExt as _, ErrorKind, Filter, Precondition, Query, Sort}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use tinystoragedrivers_core::{ - DocumentStoreExt as _, ErrorKind, Filter, Precondition, Query, Repo, Sort, -}; use crate::error::{Error, Result}; use crate::storage::{ @@ -160,11 +159,12 @@ impl Store { } /// Opens a store over a private in-memory backend, for tests and for a - /// host that wants no persistence. + /// unit tests. /// /// # Errors /// /// Returns [`Error::Store`] when the backend cannot be opened. + #[cfg(test)] pub fn open_in_memory() -> Result { Self::open(StoragePorts::memory()?) } @@ -260,7 +260,7 @@ impl Store { if !acquire_claim(documents.as_ref(), &claim_id, claim).await? { return Ok(false); } - let owns_claim = |held: Option>| { + let owns_claim = |held: Option>| { held.filter(|claim| { claim.doc.get("server_id").and_then(Value::as_str) == Some(id.as_str()) }) @@ -692,10 +692,10 @@ impl Store { /// is taken over once, but only after its lease: within it the holder may /// simply not have written its server yet. async fn acquire_claim( - documents: &dyn tinystoragedrivers_core::DocumentStore, + documents: &dyn crate::storage::types::DocumentStore, claim_id: &str, claim: Value, -) -> tinystoragedrivers_core::Result { +) -> crate::storage::types::Result { match documents .put_with( SERVER_NAMES, @@ -800,7 +800,7 @@ fn load_cache_fingerprint_key(ports: &StoragePorts) -> Result<[u8; CACHE_FINGERP decode_hex_key(&stored).ok_or_else(|| { Error::store( "loading the cache key", - tinystoragedrivers_core::StorageError::serialization( + crate::storage::types::StorageError::serialization( "the stored cache fingerprint key is malformed", ), ) diff --git a/crates/tinymcp/src/storage/bus.rs b/crates/tinymcp/src/storage/bus.rs index 83bac9ee..b764b7e4 100644 --- a/crates/tinymcp/src/storage/bus.rs +++ b/crates/tinymcp/src/storage/bus.rs @@ -10,10 +10,12 @@ use std::path::Path; use std::sync::Arc; -use tinybus::Connection; -use tinystoragedrivers_busproxy::{connect_storage, module_scope_label}; -use tinystoragedrivers_core::StorageBackend; -use tinystoragedrivers_secrets::SecretStore; +use crate::storage::types::SecretStore; +use tinybus::{BusName, Connection}; +use tinystoragedrivers_api::Storage; +#[cfg(test)] +use tinystoragedrivers_busproxy::connect_storage; +use tinystoragedrivers_busproxy::connect_storage_at; use super::{StoragePorts, StorageProvider}; use crate::error::{Error, Result}; @@ -28,34 +30,52 @@ pub struct BusProvider { } impl BusProvider { - /// Connects to the host's storage objects and binds the granted scope. + /// Connects to the explicit host callback that was provisioned for this + /// module instance. /// /// # Errors /// /// Returns [`Error::Store`] when the host serves no storage, refuses the /// capability calls, or the bus fails. - pub async fn connect(connection: Connection) -> Result { - Self::connect_with(connection, None).await + pub async fn connect_at(connection: Connection, destination: BusName) -> Result { + Self::connect_at_with(connection, destination, None).await } - /// [`connect`](Self::connect), with `secrets` standing in for the host's - /// secret store. Secrets travel only on the confidential route, which a - /// broker grants to attested artifacts alone, so a test over an in-process - /// broker supplies its own. - pub(crate) async fn connect_with( + async fn connect_at_with( + connection: Connection, + destination: BusName, + secrets: Option>, + ) -> Result { + Self::from_storage_result(connect_storage_at(connection, destination).await, secrets) + } + + fn from_storage_result( + storage: tinystoragedrivers_types::Result, + secrets: Option>, + ) -> Result { + let storage = + storage.map_err(|source| Error::store("connecting to the host storage", source))?; + Ok(Self::from_storage(&storage, secrets)) + } + + fn from_storage(storage: &Storage, secrets: Option>) -> Self { + let secrets = secrets.unwrap_or_else(|| Arc::clone(storage.secrets())); + Self { + ports: StoragePorts::from_storage(storage, secrets), + } + } + + /// Ordinary, non-attested bus connections are used only by the in-process + /// port tests. Production module setup always uses [`connect_at`]. + #[cfg(test)] + pub(crate) async fn connect_ordinary_with( connection: Connection, secrets: Option>, ) -> Result { let storage = connect_storage(connection) .await .map_err(|source| Error::store("connecting to the host storage", source))?; - let scoped = storage - .for_scope(&module_scope_label()) - .map_err(|source| Error::store("opening the host-bound scope", source))?; - let secrets = secrets.unwrap_or_else(|| storage.secrets()); - Ok(Self { - ports: StoragePorts::from_scoped(&scoped, secrets), - }) + Ok(Self::from_storage(&storage, secrets)) } /// A provider over already-connected `ports`. @@ -65,8 +85,16 @@ impl BusProvider { } } +#[cfg(test)] +#[path = "bus_unit_tests.rs"] +mod tests; + impl StorageProvider for BusProvider { fn ports_for(&self, _data_dir: &Path) -> Result { Ok(self.ports.clone()) } + + fn default_ports(&self) -> Result { + Ok(self.ports.clone()) + } } diff --git a/crates/tinymcp/src/storage/bus_tests.rs b/crates/tinymcp/src/storage/bus_tests.rs index 7fc4bfaa..ed1b9f91 100644 --- a/crates/tinymcp/src/storage/bus_tests.rs +++ b/crates/tinymcp/src/storage/bus_tests.rs @@ -5,9 +5,12 @@ use std::sync::Arc; -use tinybus::{Connection, broker::Broker, transport::memory::MemoryBus}; -use tinystoragedrivers_core::MemoryStorage; +use serde_json::json; +use tinybus::{BusName, Connection, broker::Broker, transport::memory::MemoryBus}; +use tinystoragedrivers_api::StorageBackend; use tinystoragedrivers_secrets::{MemorySecrets, SecretStore}; +use tinystoragedrivers_testkit::MemoryBackend as MemoryStorage; +use tinystoragedrivers_types::{CollectionSpec, Precondition, Scope, WriteOptions}; use super::test_host::{TestHost, serve_storage}; use super::*; @@ -45,7 +48,7 @@ async fn module(bus: &MemoryBus, secrets: &Arc) -> BusProvider { let connection = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); - BusProvider::connect_with(connection, Some(secrets.clone() as Arc)) + BusProvider::connect_ordinary_with(connection, Some(secrets.clone() as Arc)) .await .unwrap() } @@ -105,23 +108,53 @@ async fn connecting_without_a_host_is_an_error_not_a_silent_memory_store() { let lonely = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); - assert!(BusProvider::connect(lonely).await.is_err()); + assert!( + BusProvider::connect_ordinary_with(lonely, None) + .await + .is_err() + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn callback_connection_requires_a_live_admitted_host_capability() { + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let connection = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let destination = BusName::new("org.example.Storage").unwrap(); + let error = BusProvider::connect_at(connection, destination) + .await + .expect_err("ordinary peers cannot impersonate a provisioned host callback"); + assert!(matches!(error, crate::Error::Store { .. })); } #[tokio::test(flavor = "multi_thread")] -async fn the_default_connect_routes_secrets_to_the_attested_host_store_only() { +async fn an_ordinary_unattested_connection_cannot_use_the_secret_store() { let backend = MemoryStorage::new(); let (bus, _host) = host(&backend, "module-tinymcp").await; let connection = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); - let provider = BusProvider::connect(connection).await.unwrap(); + let provider = BusProvider::connect_ordinary_with(connection, None) + .await + .unwrap(); let ports = provider.ports_for(&std::env::temp_dir().join("c")).unwrap(); ports.prepare().unwrap(); // An in-process broker cannot attest the caller, so the confidential // secret route is refused rather than silently served. let refused = Store::open(ports).unwrap_err(); - assert!(refused.to_string().contains("NotAttested"), "{refused}"); + assert!( + matches!( + &refused, + crate::Error::Store { source, .. } + if matches!( + source.kind(), + tinystoragedrivers_types::ErrorKind::Unsupported(_) + ) + ), + "{refused}" + ); } #[tokio::test(flavor = "multi_thread")] @@ -139,3 +172,81 @@ async fn a_provider_over_ready_ports_hands_out_clones_of_them() { assert!(!again.has_state().unwrap()); assert!(format!("{provider:?}").contains("BusProvider")); } + +#[tokio::test(flavor = "multi_thread")] +async fn owner_migration_omits_host_only_creation_time_on_the_bus() { + let backend = MemoryStorage::new(); + let storage = backend + .for_scope(&Scope::new("module-tinymcp").unwrap()) + .unwrap(); + let local_docs = Arc::clone(storage.documents()); + local_docs + .ensure_collection(&CollectionSpec::new("flows.items")) + .await + .unwrap(); + local_docs + .put_with( + "flows.items", + "one", + json!({"value": "before"}), + Precondition::Absent, + WriteOptions::new().schema(1).created_ms(123), + ) + .await + .unwrap(); + + let (bus, _host) = host(&backend, "module-tinymcp").await; + let secrets = Arc::new(MemorySecrets::new()); + let ports = module(&bus, &secrets) + .await + .ports_for(&std::env::temp_dir().join("schema-created-ms")) + .unwrap(); + let before = ports + .documents + .get("flows.items", "one") + .await + .unwrap() + .unwrap(); + let schema = + crate::storage::local::Schema::new(crate::storage::local::Owner::new("flows").unwrap()) + .collection_with( + 2, + CollectionSpec::new("flows.items"), + crate::storage::local::ScopeClass::Tenant, + ) + .step(crate::storage::local::Step::new( + "items_v2", + "flows.items", + 1, + 2, + |rows| { + Ok(rows + .into_iter() + .map(|row| { + crate::storage::local::TargetRecord::new( + "flows.items", + row.id, + json!({"value": "after"}), + ) + }) + .collect()) + }, + )); + + schema + .migrate( + &ports.documents, + &crate::storage::local::MigrateOptions::default(), + ) + .await + .unwrap(); + let after = ports + .documents + .get("flows.items", "one") + .await + .unwrap() + .unwrap(); + assert_eq!(after.doc["value"], "after"); + assert_eq!(after.meta.schema, 2); + assert_eq!(after.meta.created_ms, before.meta.created_ms); +} diff --git a/crates/tinymcp/src/storage/bus_unit_tests.rs b/crates/tinymcp/src/storage/bus_unit_tests.rs new file mode 100644 index 00000000..39fae4d7 --- /dev/null +++ b/crates/tinymcp/src/storage/bus_unit_tests.rs @@ -0,0 +1,31 @@ +//! Tests for the TinyBus-backed storage provider's port wiring. + +use super::*; + +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::Scope; + +#[test] +fn callback_provider_uses_all_ports_from_the_host_storage_handle() +-> std::result::Result<(), Box> { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + let storage = runtime + .block_on(async { MemoryBackend::new().for_scope(&Scope::new("module-tinymcp")?) })?; + let provider = BusProvider::from_storage_result(Ok(storage), None)?; + let ports = provider.default_ports()?; + ports.prepare()?; + assert!(format!("{provider:?}").contains("BusProvider")); + let error = BusProvider::from_storage_result( + Err(tinystoragedrivers_types::StorageError::unavailable( + "host is offline", + )), + None, + ) + .err() + .ok_or("unavailable callback storage was accepted")?; + assert!(matches!(error, crate::error::Error::Store { .. })); + Ok(()) +} diff --git a/crates/tinymcp/src/storage/failing.rs b/crates/tinymcp/src/storage/failing.rs index 992a02ab..41f4634d 100644 --- a/crates/tinymcp/src/storage/failing.rs +++ b/crates/tinymcp/src/storage/failing.rs @@ -3,11 +3,11 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use serde_json::Value; -use tinystoragedrivers_core::{ +use crate::storage::types::{ Capabilities, CollectionSpec, DocumentStore, Filter, Page, Precondition, Query, Result, - SearchHit, Sort, StorageError, Version, Versioned, async_trait, + SearchHit, Sort, StorageError, Version, Versioned, }; +use serde_json::Value; use super::StoragePorts; @@ -28,7 +28,7 @@ impl FailingDocuments { } } -#[async_trait] +#[tinystoragedrivers_api::async_trait] impl DocumentStore for FailingDocuments { fn capabilities(&self) -> Capabilities { Capabilities::none() @@ -39,17 +39,25 @@ impl DocumentStore for FailingDocuments { } async fn get(&self, _collection: &str, _id: &str) -> Result>> { - self.down() + if _collection == "tsd.migrations" { + Ok(None) + } else { + self.down() + } } async fn put( &self, - _collection: &str, + collection: &str, _id: &str, _doc: Value, _precondition: Precondition, ) -> Result { - self.down() + if collection == "tsd.migrations" { + Ok(Version::FIRST) + } else { + self.down() + } } async fn delete( @@ -61,8 +69,15 @@ impl DocumentStore for FailingDocuments { self.down() } - async fn query(&self, _collection: &str, _query: &Query) -> Result>> { - self.down() + async fn query(&self, collection: &str, _query: &Query) -> Result>> { + if collection.starts_with("mcp_") { + Ok(Page { + items: Vec::new(), + next: None, + }) + } else { + self.down() + } } async fn count(&self, _collection: &str, _filter: &Filter) -> Result { diff --git a/crates/tinymcp/src/storage/fixtures/README.md b/crates/tinymcp/src/storage/fixtures/README.md new file mode 100644 index 00000000..d5d5aa97 --- /dev/null +++ b/crates/tinymcp/src/storage/fixtures/README.md @@ -0,0 +1,44 @@ +# Previous-release storage fixture + +`tinymcp-v0.19.1-server.json` is the document body emitted by the public +`Store::insert_server` writer in TinyMCP v0.19.1, with its real v1.0.0 +`tinystoragedrivers-core` dependency. The checked-in bytes came from running +`emit_previous_release_server_fixture`, injected into the archived release's +test module, plus that tag's TinyBus submodule: + +```sh +mkdir -p target/legacy-writer-v0191/vendor/tinybus +git archive v0.19.1 | tar -x -C target/legacy-writer-v0191 +git -C vendor/tinybus archive 1f33d1be1901a2d44bfe674cd7cf294cf3848821 \ + | tar -x -C target/legacy-writer-v0191/vendor/tinybus +python3 -c 'from pathlib import Path; p=Path("target/legacy-writer-v0191/crates/tinymcp/src/registry/store/mod_tests.rs"); s=p.read_text(); marker="#[test]\nfn a_record_from_before_the_enabled_field_loads_as_enabled()"; generator="""#[test] +fn emit_previous_release_server_fixture() { + let store = store(); + store.insert_server(&stdio_server("released-fixture-server")).unwrap(); + let stored = store + .get_raw(SERVERS, "released-fixture-server") + .expect("the previous public writer persisted its server"); + println!("PREVIOUS_RELEASE_SERVER={}", serde_json::to_string(&stored).unwrap()); +} + +"""; assert marker in s; p.write_text(s.replace(marker, generator + marker, 1))' +set -o pipefail +TMPDIR="$PWD/target/legacy-writer-v0191/target/compiler-scratch" CARGO_BUILD_JOBS=1 \ + cargo test --locked \ + --manifest-path target/legacy-writer-v0191/Cargo.toml \ + -p tinymcp --lib emit_previous_release_server_fixture -- --nocapture \ + | sed -n 's/^PREVIOUS_RELEASE_SERVER=//p' \ + > crates/tinymcp/src/storage/fixtures/tinymcp-v0.19.1-server.json +``` + +The release tag resolves to `5f5eb4171fa73e6e7f8e869b4dc39ee41c5f3c6e`; +the TSD dependency resolves to v1.0.0 commit +`141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d`. The generator used the +released `Store::open_in_memory` and `Store::insert_server` APIs, then read the +stored body through the release's test-only raw read helper. The migration +regression opens the fixture through today's public `Store::open` path and +checks the typed readback; the separate v1 migration tests exercise legacy +collection conversion. The archived production source is unmodified; only its +test module is injected with the generator shown above. The checked-in fixture +SHA-256 is +`48d484e92efa488bf99da036254ea7f582e33307c649dcfd70ce5aa1eaebfb86`. diff --git a/crates/tinymcp/src/storage/fixtures/tinymcp-v0.19.1-server.json b/crates/tinymcp/src/storage/fixtures/tinymcp-v0.19.1-server.json new file mode 100644 index 00000000..37774f05 --- /dev/null +++ b/crates/tinymcp/src/storage/fixtures/tinymcp-v0.19.1-server.json @@ -0,0 +1 @@ +{"args":["-y","@test/server"],"catalog_managed":false,"command":"npx","command_kind":"node","description":"A test server","display_name":"Test Server","enabled":true,"env_keys":["API_KEY"],"installed_ms":1700000000000,"qualified_name":"@test/server","server_id":"released-fixture-server","transport":"stdio"} diff --git a/crates/tinymcp/src/storage/grant.rs b/crates/tinymcp/src/storage/grant.rs index 157a19db..0a348c06 100644 --- a/crates/tinymcp/src/storage/grant.rs +++ b/crates/tinymcp/src/storage/grant.rs @@ -1,15 +1,14 @@ //! What the module declares it needs from storage. //! -//! The collections and the stream come from [`storage_schema`], so the grant -//! cannot drift from what the module declares. Only the secret names are -//! listed here: a secret is not renamed by a migration step, and a name outside -//! the `mcp/` owner prefix cannot be declared as a schema item. +//! Current collections come from the private `storage_schema` helper; legacy +//! source names are added because first-open migrations read them. Secret +//! names are listed here because migrations cannot rename secrets and names +//! outside the `mcp/` owner prefix cannot be declared as schema items. use serde::Serialize; -use tinystoragedrivers_core::CollectionSpec; -use tinystoragedrivers_core::schema::Item; +use tinystoragedrivers_types::CollectionSpec; -use super::schema::storage_schema; +use super::schema::AUDIT_STREAM; /// Prefix of the secret holding one server's environment and OAuth values: /// the full name is this prefix plus the install identifier. @@ -17,6 +16,16 @@ pub const ENV_SECRET_PREFIX: &str = "mcp_client_env/"; /// The secret holding the key the tool-cache fingerprints are keyed with. pub const CACHE_KEY_SECRET: &str = "mcp_cache_fingerprint_key"; +pub(super) const LEGACY_COLLECTIONS: [&str; 6] = [ + "mcp_servers", + "mcp_server_names", + "mcp_registry_cache", + "mcp_tool_cache", + "mcp_registry_index", + "mcp_registry_index_state", +]; +const LEGACY_AUDIT_STREAM: &str = "mcp_audit"; + /// Everything the module reads or writes through the storage ports. /// /// A host that serves storage to this module over the bus uses it as the @@ -28,35 +37,28 @@ pub struct StorageGrant { pub collections: Vec, /// Collections that need full-text search. pub searchable: Vec, - /// Stream names (exact) the module appends to and reads. + /// Stream names and prefixes the module appends to and reads. pub streams: Vec, /// Secret names the module uses, as exact names or `prefix*` patterns. pub secrets: Vec, } -/// The module's storage grant, generated from [`storage_schema`]. +/// The module's storage grant, generated from the private `storage_schema` helper. #[must_use] pub fn grant() -> StorageGrant { - let schema = storage_schema(); - let mut collections = Vec::new(); - let mut searchable = Vec::new(); - let mut streams = Vec::new(); - for item in schema.items { - match item { - Item::Collection { name, spec, .. } => { - if spec.search.is_some() { - searchable.push(name.clone()); - } - collections.push(name); - } - Item::Stream { name, .. } => streams.push(name), - Item::Blobs { .. } | Item::Secrets { .. } => {} - } - } + let mut collections: Vec = collection_specs() + .into_iter() + .map(|spec| spec.name) + .collect(); + collections.extend(LEGACY_COLLECTIONS.map(str::to_owned)); StorageGrant { collections, - searchable, - streams, + searchable: Vec::new(), + streams: vec![ + AUDIT_STREAM.to_owned(), + LEGACY_AUDIT_STREAM.to_owned(), + format!("{LEGACY_AUDIT_STREAM}/"), + ], secrets: vec![ format!("{ENV_SECRET_PREFIX}*"), CACHE_KEY_SECRET.to_string(), @@ -67,12 +69,5 @@ pub fn grant() -> StorageGrant { /// The collections the module declares, with their indexes. #[must_use] pub fn collection_specs() -> Vec { - storage_schema() - .items - .into_iter() - .filter_map(|item| match item { - Item::Collection { spec, .. } => Some(spec), - _ => None, - }) - .collect() + tinymcp_bus::storage::collection_specs() } diff --git a/crates/tinymcp/src/storage/local/blocking.rs b/crates/tinymcp/src/storage/local/blocking.rs new file mode 100644 index 00000000..1ac7cb8a --- /dev/null +++ b/crates/tinymcp/src/storage/local/blocking.rs @@ -0,0 +1,164 @@ +//! Calling the async ports from synchronous code. +//! +//! Some consumer traits that storage sits behind are still synchronous (a +//! workflow store, a keyring backend). [`Blocking`] runs a port's future to +//! completion on a runtime thread it owns, so a synchronous caller can use any +//! driver without knowing whether it is already inside a tokio runtime. +//! `block_in_place` would panic on a current-thread runtime, and +//! `Handle::block_on` from inside a runtime panics too; a dedicated thread has +//! neither problem. +//! +//! This is a bridge, not a destination: each synchronous consumer should +//! become async, at which point it calls the port directly. + +use std::fmt; +use std::future::Future; +use std::pin::Pin; +use std::sync::mpsc as std_mpsc; +use std::thread; + +use tokio::sync::mpsc; + +use tinystoragedrivers_types::{Result, StorageError}; + +type Job = Pin + Send>>; + +thread_local! { + static ON_BRIDGE: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// A dedicated runtime thread that runs futures for synchronous callers. +/// +/// Many callers may share one `Blocking`: each submitted future runs as its own +/// task, so a slow call does not hold up the others. Dropping the last handle +/// stops the thread once in-flight work finishes. +/// +/// ```ignore +/// use crate::storage::local::Blocking; +/// use tinystoragedrivers_api::{Precondition, StorageBackend}; +/// use tinystoragedrivers_types::{Scope, StorageError}; +/// use tinystoragedrivers_testkit::MemoryBackend; +/// use serde_json::json; +/// use std::sync::Arc; +/// +/// let bridge = Blocking::new()?; +/// let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; +/// let docs = Arc::clone(storage.documents()); +/// let version = bridge.run(async move { +/// docs.put("settings", "theme", json!({"dark": true}), Precondition::None).await +/// })??; +/// assert_eq!(version.0, 1); +/// # Ok::<(), StorageError>(()) +/// ``` +#[derive(Clone)] +pub(crate) struct Blocking { + jobs: mpsc::UnboundedSender, +} + +impl fmt::Debug for Blocking { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Blocking").finish_non_exhaustive() + } +} + +impl Blocking { + /// Start the runtime thread. + /// + /// # Errors + /// + /// [`ErrorKind::Backend`](crate::ErrorKind::Backend) when the runtime or + /// thread cannot be created. + pub(crate) fn new() -> Result { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(startup_error("cannot build the blocking bridge runtime"))?; + let (jobs, mut receiver) = mpsc::unbounded_channel::(); + thread::Builder::new() + .name("tinystoragedrivers-blocking".into()) + .spawn(move || { + ON_BRIDGE.with(|flag| flag.set(true)); + runtime.block_on(async move { + // Each call is its own task, so a slow one does not hold up + // the rest; the runtime drives them while this loop waits. + let mut running = tokio::task::JoinSet::new(); + while let Some(job) = receiver.recv().await { + running.spawn(job); + while running.try_join_next().is_some() {} + } + // Every handle is gone; let in-flight calls finish rather + // than cancelling them with the runtime. + while running.join_next().await.is_some() {} + }); + }) + .map_err(startup_error("cannot start the blocking bridge thread"))?; + Ok(Self { jobs }) + } + + /// Run `future` on the bridge thread and wait for its output. + /// + /// The calling thread blocks until the future completes. The future runs + /// on the bridge's own runtime, but it may still wait on tasks of the + /// caller's runtime: the MongoDB driver's connection pool, for one, runs + /// on the runtime that built the client. On a multi-thread runtime's + /// worker the wait goes through [`tokio::task::block_in_place`], so the + /// runtime keeps driving those tasks on another thread. From inside a + /// current-thread runtime nothing can, and a future that awaits a task + /// spawned on *that* runtime never completes. + /// + /// # Errors + /// + /// [`ErrorKind::Backend`](crate::ErrorKind::Backend) when called from the + /// bridge thread itself (which would deadlock), when the bridge has + /// stopped, or when the future panicked. + 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( + "a future running on the blocking bridge called back into it", + )); + } + let (reply, wait) = std_mpsc::sync_channel(1); + let job: Job = Box::pin(async move { + // The caller may have given up waiting; nothing to do then. + let _ = reply.send(future.await); + }); + self.jobs + .send(job) + .map_err(|_| StorageError::backend("the blocking bridge has stopped"))?; + let receive = || { + wait.recv().map_err(|_| { + StorageError::backend("the blocking bridge dropped the call (did it panic?)") + }) + }; + // On a multi-thread runtime's worker, hand the worker's other tasks to + // another thread while this one waits. A driver's future may depend on + // them: MongoDB's connection pool runs as a task on the runtime that + // built the client, and with this worker blocked (or the runtime's only + // one) the call would never complete. + if on_multi_thread_worker() { + tokio::task::block_in_place(receive) + } else { + receive() + } + } +} + +/// Whether the current thread runs inside a multi-thread tokio runtime, +/// where [`tokio::task::block_in_place`] is allowed. +fn on_multi_thread_worker() -> bool { + tokio::runtime::Handle::try_current() + .is_ok_and(|handle| handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread) +} + +/// Map an I/O failure while starting the bridge to a backend error. +fn startup_error(what: &'static str) -> impl FnOnce(std::io::Error) -> StorageError { + move |error| StorageError::backend(what).with_source(error) +} + +#[cfg(test)] +#[path = "blocking_tests.rs"] +mod tests; diff --git a/crates/tinymcp/src/storage/local/blocking_tests.rs b/crates/tinymcp/src/storage/local/blocking_tests.rs new file mode 100644 index 00000000..7c3f134d --- /dev/null +++ b/crates/tinymcp/src/storage/local/blocking_tests.rs @@ -0,0 +1,75 @@ +//! Tests for the blocking bridge that runs storage futures for synchronous callers. + +use super::*; + +type TestResult = std::result::Result<(), Box>; + +#[test] +fn bridge_runs_futures_from_sync_and_current_thread_runtime_contexts() -> TestResult { + let bridge = Blocking::new()?; + assert_eq!(bridge.run(async { 42 })?, 42); + + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + assert_eq!( + runtime.block_on(async { bridge.run(async { "ready" }) })?, + "ready" + ); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn bridge_runs_from_a_multithread_worker() -> TestResult { + let bridge = Blocking::new()?; + assert_eq!(bridge.run(async { 7usize })?, 7); + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn bridge_runs_from_a_spawn_blocking_thread() -> TestResult { + let bridge = Blocking::new()?; + assert_eq!( + tokio::task::spawn_blocking(move || bridge.run(async { 11usize })).await??, + 11 + ); + Ok(()) +} + +#[test] +fn a_future_cannot_reenter_its_own_bridge() -> TestResult { + let bridge = Blocking::new()?; + let inner = bridge.clone(); + let inner_result = bridge.run(async move { inner.run(async {}) })?; + let error = inner_result.err().ok_or("reentry would deadlock")?; + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Backend); + Ok(()) +} + +#[test] +fn panicking_jobs_are_reported_to_the_waiting_caller() -> TestResult { + let bridge = Blocking::new()?; + let result = + bridge.run(async { std::panic::resume_unwind(Box::new("intentional bridge job failure")) }); + let error = result + .err() + .ok_or("panicking job should close its reply channel")?; + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Backend); + Ok(()) +} + +#[test] +fn bridge_reports_closed_worker_and_startup_io_failures() -> TestResult { + let (jobs, receiver) = tokio::sync::mpsc::unbounded_channel(); + drop(receiver); + let bridge = Blocking { jobs }; + let error = bridge + .run(async {}) + .err() + .ok_or("closed bridge accepted work")?; + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Backend); + let error = startup_error("cannot start test bridge")(std::io::Error::other("denied")); + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Backend); + assert!(format!("{bridge:?}").contains("Blocking")); + Ok(()) +} diff --git a/crates/tinymcp/src/storage/local/mod.rs b/crates/tinymcp/src/storage/local/mod.rs new file mode 100644 index 00000000..36ed1f18 --- /dev/null +++ b/crates/tinymcp/src/storage/local/mod.rs @@ -0,0 +1,12 @@ +//! MCP-owned storage helpers used by its synchronous stores. + +mod blocking; +pub(crate) mod primitives; +pub(crate) mod schema; + +pub(crate) use blocking::Blocking; +pub(crate) use primitives::repo::Repo; +pub(crate) use schema::{ + MigrateOptions, Migrations, Owner, Schema, ScopeClass, SourceRecord, Step, StreamProgress, + TargetRecord, +}; diff --git a/crates/tinymcp/src/storage/local/primitives/mod.rs b/crates/tinymcp/src/storage/local/primitives/mod.rs new file mode 100644 index 00000000..a9b7be86 --- /dev/null +++ b/crates/tinymcp/src/storage/local/primitives/mod.rs @@ -0,0 +1,3 @@ +//! Small document-store primitives owned by `TinyMCP`. + +pub(crate) mod repo; diff --git a/crates/tinymcp/src/storage/local/primitives/repo.rs b/crates/tinymcp/src/storage/local/primitives/repo.rs new file mode 100644 index 00000000..aeb60c4d --- /dev/null +++ b/crates/tinymcp/src/storage/local/primitives/repo.rs @@ -0,0 +1,299 @@ +//! [`Repo`]: a typed collection handle and the one compare-and-swap loop. + +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hasher}; +use std::marker::PhantomData; +use std::sync::Arc; +use std::time::Duration; + +use serde::Serialize; +use serde::de::DeserializeOwned; + +use tinystoragedrivers_api::DocumentStore; +use tinystoragedrivers_types::{ + ErrorKind, Precondition, Result, Version, Versioned, WriteOptions, validate_collection, +}; + +/// How long [`Repo::update`] keeps retrying a lost compare-and-swap. +/// +/// The default is the spec's budget: 32 attempts with a jittered backoff that +/// starts at 1 ms and doubles up to 8 ms. A lost swap means another writer +/// made progress, so the loop converges; the backoff only spreads the retries. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct RetryPolicy { + /// Total attempts, including the first. At least one is always made. + pub(crate) attempts: u32, + /// The pause before the second attempt; doubles each attempt. + pub(crate) initial_backoff: Duration, + /// The longest pause. Each pause is jittered into its upper half. + pub(crate) max_backoff: Duration, +} + +impl RetryPolicy { + /// A policy with the given budget and backoff bounds. + #[must_use] + pub(crate) const fn new( + attempts: u32, + initial_backoff: Duration, + max_backoff: Duration, + ) -> Self { + Self { + attempts, + initial_backoff, + max_backoff, + } + } + + /// The full budget with no pause between attempts, for tests. + #[must_use] + #[cfg(test)] + pub(crate) const fn immediate() -> Self { + Self::new(32, Duration::ZERO, Duration::ZERO) + } + + /// The pause after the failed attempt number `attempt` (counting from 0): + /// the doubled backoff capped at the maximum, jittered into its upper half. + fn pause(&self, attempt: u32) -> Duration { + let doubled = self + .initial_backoff + .saturating_mul(1_u32.checked_shl(attempt).unwrap_or(u32::MAX)); + let cap = doubled.min(self.max_backoff); + let nanos = u64::try_from(cap.as_nanos()).unwrap_or(u64::MAX); + if nanos == 0 { + return Duration::ZERO; + } + // `RandomState` draws fresh keys per instance: jitter without a + // random-number dependency. + let random = RandomState::new().build_hasher().finish(); + let half = nanos / 2; + Duration::from_nanos(half + random % (nanos - half + 1)) + } +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self::new(32, Duration::from_millis(1), Duration::from_millis(8)) + } +} + +/// A typed handle on one collection of one scope. +/// +/// Bodies are `T` serialized as a JSON object (see +/// [`validate_doc`](crate::validate_doc)). Every write carries the repo's +/// [`WriteOptions`], so a collection declares its schema version (and, for a +/// short-lived one, an expiry) once. +/// +/// ```ignore +/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async { +/// use serde::{Deserialize, Serialize}; +/// use crate::storage::local::primitives::Repo; +/// use tinystoragedrivers_api::StorageBackend; +/// use tinystoragedrivers_types::{Scope, StorageError}; +/// use tinystoragedrivers_testkit::MemoryBackend; +/// +/// #[derive(Serialize, Deserialize, PartialEq, Debug)] +/// struct Job { runs: u32 } +/// +/// let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; +/// let jobs = Repo::::new(storage.documents(), "cron.jobs")?; +/// let (job, _version) = jobs +/// .update("nightly", |job| Ok(Some(Job { runs: job.map_or(1, |j| j.runs + 1) }))) +/// .await? +/// .unwrap(); +/// assert_eq!(job.runs, 2); +/// # Ok::<(), StorageError>(()) +/// # }).unwrap(); +/// ``` +pub(crate) struct Repo { + docs: Arc, + collection: String, + options: WriteOptions, + retry: RetryPolicy, + // `fn() -> T` keeps the handle `Send + Sync` whatever `T` is. + marker: PhantomData T>, +} + +impl Clone for Repo { + fn clone(&self) -> Self { + Self { + docs: Arc::clone(&self.docs), + collection: self.collection.clone(), + options: self.options, + retry: self.retry, + marker: PhantomData, + } + } +} + +impl std::fmt::Debug for Repo { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Repo") + .field("collection", &self.collection) + .field("options", &self.options) + .field("retry", &self.retry) + .finish_non_exhaustive() + } +} + +impl Repo { + /// A handle on `collection`, with plain writes and the default + /// [`RetryPolicy`]. + /// + /// The collection is not created: declare it with + /// [`ensure_collection`](DocumentStore::ensure_collection) when it needs + /// indexes. + /// + /// # Errors + /// + /// [`ErrorKind::InvalidInput`] for an invalid collection name. + pub(crate) fn new( + docs: &Arc, + collection: impl Into, + ) -> Result { + let collection = collection.into(); + validate_collection(&collection)?; + Ok(Self { + docs: Arc::clone(docs), + collection, + options: WriteOptions::default(), + retry: RetryPolicy::default(), + marker: PhantomData, + }) + } + + /// Declare the schema version and expiry every write of this handle carries. + #[must_use] + pub(crate) fn with_options(mut self, options: WriteOptions) -> Self { + self.options = options; + self + } + + /// Replace the [`RetryPolicy`] of [`update`](Self::update). + #[must_use] + #[cfg(test)] + pub(crate) fn with_retry(mut self, retry: RetryPolicy) -> Self { + self.retry = retry; + self + } +} + +impl Repo { + /// Remove a record only when `matches` accepts its current value, as one + /// compare-and-swap: the delete is conditional on the version `keep_if` + /// saw, so a writer that got in between turns it into a retry, not a + /// lost update. Returns whether a record was removed; `false` when the + /// record is absent or `matches` declined it. + /// + /// `matches` is called again on every retry, so it must be free of side + /// effects. After [`RetryPolicy::attempts`] lost swaps the last + /// [`Conflict`](ErrorKind::Conflict) is returned. + /// + /// # Errors + /// + /// A conflict past the budget, or any other read or delete error. + #[cfg(test)] + pub(crate) async fn delete_if(&self, id: &str, mut matches: F) -> Result + where + F: FnMut(&T) -> bool + Send, + { + let attempts = self.retry.attempts.max(1); + let mut attempt = 0; + loop { + let Some(found) = self.docs.get(&self.collection, id).await? else { + return Ok(false); + }; + let found = decode::(found)?; + if !matches(&found.doc) { + return Ok(false); + } + match self + .docs + .delete(&self.collection, id, Precondition::Version(found.version)) + .await + { + Ok(removed) => return Ok(removed), + Err(error) if error.kind() == ErrorKind::Conflict => { + attempt += 1; + if attempt >= attempts { + return Err(error); + } + let pause = self.retry.pause(attempt - 1); + if !pause.is_zero() { + tokio::time::sleep(pause).await; + } + } + Err(error) => return Err(error), + } + } + } + + /// Read-modify-write one record as a single compare-and-swap loop. + /// + /// `f` receives the current value (`None` when the record is missing) and + /// returns the value to store, or `None` to leave the record as it is. + /// The write is conditional on the version `f` saw (or on the record still + /// being absent). When another writer got in first the loop re-reads and + /// calls `f` again, so `f` must be free of side effects. After + /// [`RetryPolicy::attempts`] lost swaps the last + /// [`Conflict`](ErrorKind::Conflict) is returned. + /// + /// Returns the stored value and its version, or `None` when `f` declined. + /// + /// # Errors + /// + /// `f`'s error (nothing is written), a conflict past the budget, or any + /// other read or write error. + pub(crate) async fn update(&self, id: &str, mut f: F) -> Result> + where + F: FnMut(Option) -> Result> + Send, + { + let attempts = self.retry.attempts.max(1); + let mut attempt = 0; + loop { + let (precondition, current) = match self.docs.get(&self.collection, id).await? { + Some(found) => { + let found = decode::(found)?; + (Precondition::Version(found.version), Some(found.doc)) + } + None => (Precondition::Absent, None), + }; + let Some(next) = f(current)? else { + return Ok(None); + }; + match self.write(id, &next, precondition).await { + Ok(version) => return Ok(Some((next, version))), + Err(error) if error.kind() == ErrorKind::Conflict => { + attempt += 1; + if attempt >= attempts { + return Err(error); + } + let pause = self.retry.pause(attempt - 1); + if !pause.is_zero() { + tokio::time::sleep(pause).await; + } + } + Err(error) => return Err(error), + } + } + } + + async fn write(&self, id: &str, value: &T, precondition: Precondition) -> Result { + let body = serde_json::to_value(value)?; + self.docs + .put_with(&self.collection, id, body, precondition, self.options) + .await + } +} + +fn decode(found: Versioned) -> Result> { + Ok(Versioned { + id: found.id, + version: found.version, + doc: serde_json::from_value(found.doc)?, + meta: found.meta, + }) +} + +#[cfg(test)] +#[path = "repo_tests.rs"] +mod tests; diff --git a/crates/tinymcp/src/storage/local/primitives/repo_tests.rs b/crates/tinymcp/src/storage/local/primitives/repo_tests.rs new file mode 100644 index 00000000..d440f96a --- /dev/null +++ b/crates/tinymcp/src/storage/local/primitives/repo_tests.rs @@ -0,0 +1,168 @@ +//! Tests for the typed `Repo` compare-and-swap loop and its retry policy. + +use super::*; + +use serde::{Deserialize, Serialize}; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_testkit::{ConflictOnce, MemoryBackend}; +use tinystoragedrivers_types::{CollectionSpec, Scope}; + +type TestResult = std::result::Result<(), Box>; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +struct Row { + value: u32, +} + +#[tokio::test] +async fn repo_update_is_atomic_and_conditional_delete_preserves_unmatched_rows() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = storage.documents(); + docs.ensure_collection(&CollectionSpec::new("flows.rows")) + .await?; + let repo = Repo::::new(docs, "flows.rows")?.with_retry(RetryPolicy::immediate()); + let (row, _) = repo + .update("one", |old| { + Ok(Some(Row { + value: old.map_or(1, |row| row.value + 1), + })) + }) + .await? + .ok_or("first write was not accepted")?; + assert_eq!(row.value, 1); + let (row, _) = repo + .update("one", |old| { + Ok(Some(Row { + value: old.map_or(1, |row| row.value + 1), + })) + }) + .await? + .ok_or("second write was not accepted")?; + assert_eq!(row.value, 2); + assert!(!repo.delete_if("one", |row| row.value == 1).await?); + assert!(repo.delete_if("one", |row| row.value == 2).await?); + Ok(()) +} + +#[tokio::test] +async fn repo_declines_updates_and_conditional_deletes_without_mutating_storage() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = storage.documents(); + docs.ensure_collection(&CollectionSpec::new("flows.rows")) + .await?; + let repo = Repo::::new(docs, "flows.rows")?.with_retry(RetryPolicy::immediate()); + assert!(repo.update("missing", |_| Ok(None)).await?.is_none()); + assert!(!repo.delete_if("missing", |_| true).await?); + repo.update("one", |_| Ok(Some(Row { value: 1 }))).await?; + assert!(repo.update("one", |_| Ok(None)).await?.is_none()); + assert!(!repo.delete_if("one", |_| false).await?); + assert_eq!( + docs.get("flows.rows", "one") + .await? + .ok_or("row missing")? + .doc["value"], + 1 + ); + assert!(Repo::::new(docs, "bad/name").is_err()); + let clone = repo.clone(); + assert!(format!("{clone:?}").contains("flows.rows")); + Ok(()) +} + +#[tokio::test] +async fn repo_reports_decode_and_update_closure_errors_without_overwriting_rows() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = storage.documents(); + docs.ensure_collection(&CollectionSpec::new("flows.rows")) + .await?; + docs.put( + "flows.rows", + "bad", + serde_json::json!({"value": "wrong type"}), + Precondition::Absent, + ) + .await?; + let repo = Repo::::new(docs, "flows.rows")?.with_retry(RetryPolicy::immediate()); + assert!( + repo.update("bad", |_| Ok(Some(Row { value: 2 }))) + .await + .is_err() + ); + assert!( + repo.update("new", |_| Err( + tinystoragedrivers_types::StorageError::backend("closure") + )) + .await + .is_err() + ); + assert!(docs.get("flows.rows", "new").await?.is_none()); + let default = RetryPolicy::default(); + assert_eq!(default.attempts, 32); + let first_pause = default.pause(0); + assert!((500_000..=1_000_000).contains(&first_pause.as_nanos())); + assert_eq!(RetryPolicy::immediate().pause(10), Duration::ZERO); + Ok(()) +} + +#[tokio::test] +async fn repo_retries_a_lost_update_and_delete_compare_and_swap() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = storage.documents(); + docs.ensure_collection(&CollectionSpec::new("flows.rows")) + .await?; + docs.put( + "flows.rows", + "one", + serde_json::json!({"value": 1}), + tinystoragedrivers_types::Precondition::Absent, + ) + .await?; + + let conflicted: Arc = Arc::new(ConflictOnce::new(Arc::clone(docs))); + let repo = Repo::::new(&conflicted, "flows.rows")?.with_retry(RetryPolicy::immediate()); + let calls = std::sync::atomic::AtomicUsize::new(0); + let (row, _) = repo + .update("one", |old| { + calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(Some(Row { + value: old.map_or(1, |row| row.value + 1), + })) + }) + .await? + .ok_or("retry did not store an updated row")?; + assert_eq!(row.value, 2); + assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 2); + + let conflicted: Arc = Arc::new(ConflictOnce::new(Arc::clone(docs))); + let repo = Repo::::new(&conflicted, "flows.rows")?.with_retry(RetryPolicy::immediate()); + assert!(repo.delete_if("one", |row| row.value == 2).await?); + assert!(docs.get("flows.rows", "one").await?.is_none()); + + docs.put( + "flows.rows", + "one", + serde_json::json!({"value": 3}), + tinystoragedrivers_types::Precondition::Absent, + ) + .await?; + let conflicted: Arc = Arc::new(ConflictOnce::new(Arc::clone(docs))); + let single_attempt = Repo::::new(&conflicted, "flows.rows")?.with_retry(RetryPolicy::new( + 1, + Duration::ZERO, + Duration::ZERO, + )); + let error = single_attempt + .update("one", |_| Ok(Some(Row { value: 4 }))) + .await + .err() + .ok_or("the exhausted retry budget must return its conflict")?; + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Conflict); + assert_eq!( + docs.get("flows.rows", "one") + .await? + .ok_or("row disappeared")? + .doc["value"], + 3 + ); + Ok(()) +} diff --git a/crates/tinymcp/src/storage/local/schema.rs b/crates/tinymcp/src/storage/local/schema.rs new file mode 100644 index 00000000..d23f75db --- /dev/null +++ b/crates/tinymcp/src/storage/local/schema.rs @@ -0,0 +1,614 @@ +//! TinyMCP-owned collection declarations and resumable owner migrations. + +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use tinystoragedrivers_api::{DocumentStore, DocumentStoreExt}; +use tinystoragedrivers_types::{ + CollectionSpec, ErrorKind, Filter, ID_FIELD, Key, MAX_ID_LEN, Meta, Precondition, Query, + Result, Sort, StorageError, WriteOptions, +}; + +const PAGE_SIZE: usize = 100; +const MIGRATIONS_COLLECTION: &str = "tsd.migrations"; + +/// Encodes the composite ids used by the released TSD v1 migration ledger. +/// +/// TSD v2 deliberately exposes validation rather than the old engine's key +/// builder, so the owner keeps the small on-disk encoding it needs to resume +/// its own progress records. +pub(crate) fn composite_key(parts: &[&str]) -> Result { + if parts.is_empty() { + return Err(StorageError::invalid_input("a key needs at least one part")); + } + let mut encoded = String::new(); + for (index, part) in parts.iter().enumerate() { + if index != 0 { + encoded.push('/'); + } + for (character_index, character) in part.chars().enumerate() { + match character { + '%' => encoded.push_str("%25"), + '/' => encoded.push_str("%2F"), + '\0' => encoded.push_str("%00"), + '~' if index == 0 && character_index == 0 => encoded.push_str("%7E"), + other => encoded.push(other), + } + } + } + if encoded.len() > MAX_ID_LEN { + encoded = format!( + "~{}", + data_encoding::BASE32_NOPAD + .encode(&Sha256::digest(encoded.as_bytes())) + .to_ascii_lowercase() + ); + } + Key::new(encoded) +} + +/// Which product scope owns a declared collection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ScopeClass { + /// Tenant or local user data. + Tenant, +} + +/// A validated `TinyFlows` storage owner name. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct Owner(String); + +impl Owner { + /// Validate an owner name. + pub(crate) fn new(name: &str) -> Result { + let valid = (2..=24).contains(&name.len()) + && name.as_bytes().first().is_some_and(u8::is_ascii_lowercase) + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'); + if !valid || name == "tsd" { + return Err(StorageError::invalid_input("invalid storage owner name")); + } + Ok(Self(name.to_owned())) + } + + /// Owner name. + #[must_use] + pub(crate) fn as_str(&self) -> &str { + &self.0 + } +} + +/// A source document passed to a migration step. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct SourceRecord { + /// Existing source id. + pub(crate) id: String, + /// Existing document body. + pub(crate) body: Value, + /// Existing storage metadata. + pub(crate) meta: Meta, +} + +/// A document emitted by a migration step. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct TargetRecord { + /// Destination collection. + pub(crate) collection: String, + /// Destination id. + pub(crate) id: String, + /// Destination body. + pub(crate) body: Value, + /// Creation timestamp to preserve where available. + pub(crate) created_ms: Option, + /// Expiry timestamp to preserve where available. + pub(crate) expires_ms: Option, +} + +impl TargetRecord { + /// Create a migrated document. + #[must_use] + pub(crate) fn new(collection: impl Into, id: impl Into, body: Value) -> Self { + Self { + collection: collection.into(), + id: id.into(), + body, + created_ms: None, + expires_ms: None, + } + } + + /// Preserve the source creation timestamp. + #[must_use] + pub(crate) fn created_ms(mut self, value: i64) -> Self { + self.created_ms = Some(value); + self + } + + /// Preserve the source expiry timestamp. + #[must_use] + pub(crate) fn expires_ms(mut self, value: Option) -> Self { + self.expires_ms = value; + self + } +} + +type StepFn = dyn Fn(Vec) -> Result> + Send + Sync; + +/// One document-collection migration step. +#[derive(Clone)] +pub(crate) struct Step { + /// Stable step id. + pub(crate) id: &'static str, + /// Destination collection. + pub(crate) item: &'static str, + /// Source schema version. + pub(crate) from: u32, + /// Destination schema version. + pub(crate) to: u32, + /// Legacy source collection, when different from `item`. + pub(crate) source: Option<&'static str>, + run: Arc, +} + +impl Step { + /// Define a document migration step. + #[must_use] + pub(crate) fn new( + id: &'static str, + item: &'static str, + from: u32, + to: u32, + run: impl Fn(Vec) -> Result> + Send + Sync + 'static, + ) -> Self { + Self { + id, + item, + from, + to, + source: None, + run: Arc::new(run), + } + } + + /// Read from a legacy collection rather than the destination. + #[must_use] + pub(crate) fn source(mut self, name: &'static str) -> Self { + self.source = Some(name); + self + } +} + +/// One owner’s collections and migrations, opened by that owner. +#[derive(Clone)] +pub(crate) struct Schema { + /// Storage owner for these collections. + pub(crate) owner: Owner, + /// Declared collections and versions. + pub(crate) items: Vec<(CollectionSpec, u32, ScopeClass)>, + /// Ordered migrations. + pub(crate) steps: Vec, +} + +impl Schema { + /// Start a declaration for `owner`. + #[must_use] + pub(crate) fn new(owner: Owner) -> Self { + Self { + owner, + items: Vec::new(), + steps: Vec::new(), + } + } + + /// Declare a fully specified collection and schema version. + #[must_use] + pub(crate) fn collection_with( + mut self, + version: u32, + spec: CollectionSpec, + scope: ScopeClass, + ) -> Self { + self.items.push((spec, version, scope)); + self + } + + /// Add an ordered collection migration. + #[must_use] + pub(crate) fn step(mut self, step: Step) -> Self { + self.steps.push(step); + self + } + + /// Pure collection declarations for host bootstrap and documentation. + #[must_use] + pub(crate) fn collections(&self) -> Vec { + let mut specs = self + .items + .iter() + .map(|(spec, _, _)| spec.clone()) + .collect::>(); + specs.push(CollectionSpec::new(MIGRATIONS_COLLECTION)); + specs + } + + /// Ensure this owner’s collections, then migrate its data in place. + /// + /// The shared `tsd.migrations` collection records one progress row per + /// owner, item and step. Backends are supplied by the caller; this method + /// never constructs an engine or an in-memory fallback. + #[expect( + clippy::too_many_lines, + reason = "a migration step orders writes, source deletion, and its durable checkpoint" + )] + pub(crate) async fn migrate( + &self, + docs: &Arc, + options: &MigrateOptions, + ) -> Result { + if options.batch_size == 0 { + return Err(StorageError::invalid_input( + "migration batch size must be at least 1", + )); + } + for spec in self.collections() { + docs.ensure_collection(&spec).await?; + } + let migrations = Migrations { + docs: Arc::clone(docs), + }; + let mut report = MigrationReport::default(); + for step in &self.steps { + let progress_key = composite_key(&[self.owner.as_str(), step.item, step.id])? + .as_str() + .to_owned(); + let progress = migrations.load(&progress_key).await?; + if progress.as_ref().is_some_and(|p| p.done) { + report.already_done += 1; + continue; + } + let source = step.source.unwrap_or(step.item); + if source != step.item { + docs.ensure_collection(&CollectionSpec::new(source)).await?; + } + let mut query = Query::filter(Filter::default()) + .sort(Sort::asc(ID_FIELD)) + .limit(options.batch_size); + if let Some(cursor) = progress.as_ref().and_then(|p| p.cursor.clone()) { + query = query.after(tinystoragedrivers_types::Cursor(cursor)); + } + let mut written = progress.as_ref().map_or(0, |saved| saved.written); + loop { + let page = docs.query(source, &query).await?; + if page.items.is_empty() { + break; + } + let last_cursor = page.next.clone(); + let inputs = page + .items + .iter() + .filter(|row| source != step.item || row.meta.schema < step.to) + .map(|row| SourceRecord { + id: row.id.clone(), + body: row.doc.clone(), + meta: row.meta, + }) + .collect(); + let outputs = (step.run)(inputs)?; + let output_ids: std::collections::HashSet<(String, String)> = outputs + .iter() + .map(|r| (r.collection.clone(), r.id.clone())) + .collect(); + for target in outputs { + if !target.body.is_object() { + return Err(StorageError::invalid_input( + "migration output must be an object", + )); + } + let output_schema = self.target_schema(step, &target)?; + let source_row = (source == step.item && target.collection == step.item) + .then(|| page.items.iter().find(|row| row.id == target.id)); + let source_row = source_row.flatten(); + let precondition = source_row.map_or(Precondition::Absent, |row| { + Precondition::Version(row.version) + }); + let created_ms = target + .created_ms + .or_else(|| source_row.map(|row| row.meta.created_ms)); + let mut options = WriteOptions::new(); + options = options.schema(output_schema); + // `created_ms` is host-only and is rejected by the + // module-facing bus contract. Same-row engine writes keep + // their existing creation timestamp automatically; a + // cross-collection move receives the destination's time. + let expected_expiry = target + .expires_ms + .or_else(|| source_row.and_then(|row| row.meta.expires_ms)); + if let Some(expires_ms) = expected_expiry { + options = options.expires_ms(expires_ms); + } + match docs + .put_with( + &target.collection, + &target.id, + target.body.clone(), + precondition, + options, + ) + .await + { + Ok(_) => written += 1, + Err(error) + if matches!( + error.kind(), + ErrorKind::Conflict | ErrorKind::AlreadyExists + ) => + { + let existing = docs.get(&target.collection, &target.id).await?; + let identical = existing.is_some_and(|row| { + row.doc == target.body + && row.meta.schema == output_schema + && (source_row.is_none_or(|_| { + created_ms + .is_none_or(|created| row.meta.created_ms == created) + })) + && row.meta.expires_ms == expected_expiry + }); + if !identical { + return Err(error); + } + written += 1; + } + Err(error) => return Err(error), + } + } + for row in &page.items { + if source != step.item + || row.meta.schema < step.to + && !output_ids.contains(&(step.item.to_owned(), row.id.clone())) + { + match docs + .delete(source, &row.id, Precondition::Version(row.version)) + .await + { + Err(error) + if error.kind() == ErrorKind::Conflict + && docs.get(source, &row.id).await?.is_none() => {} + other => { + other?; + } + } + } + } + let cursor = last_cursor.map(|cursor| cursor.0); + migrations + .save( + &progress_key, + &Progress { + owner: self.owner.as_str().to_owned(), + step: step.id.to_owned(), + from: step.from, + to: step.to, + cursor, + written, + done: false, + }, + ) + .await?; + if let Some(next) = page.next { + query = query.after(next); + } else { + break; + } + } + migrations + .save( + &progress_key, + &Progress { + owner: self.owner.as_str().to_owned(), + step: step.id.to_owned(), + from: step.from, + to: step.to, + cursor: None, + written, + done: true, + }, + ) + .await?; + report.ran.push(StepReport { + owner: self.owner.as_str().to_owned(), + item: step.item.to_owned(), + step: step.id.to_owned(), + written, + }); + } + Ok(report) + } + + fn target_schema(&self, step: &Step, target: &TargetRecord) -> Result { + let owned = target + .collection + .strip_prefix(self.owner.as_str()) + .is_some_and(|rest| rest.starts_with('.')); + let version = self + .items + .iter() + .find(|(spec, _, _)| spec.name == target.collection) + .map(|(_, version, _)| *version) + .filter(|_| owned) + .ok_or_else(|| { + StorageError::invalid_input( + "migration output targets an undeclared owner collection", + ) + })?; + Ok(if target.collection == step.item { + step.to + } else { + version + }) + } +} + +/// Batch size for owner migration runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct MigrateOptions { + batch_size: usize, +} +impl MigrateOptions { + /// Defaults to 100 documents per batch. + #[must_use] + pub(crate) const fn new() -> Self { + Self { + batch_size: PAGE_SIZE, + } + } +} +impl Default for MigrateOptions { + fn default() -> Self { + Self::new() + } +} + +/// Summary of an owner migration run. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct MigrationReport { + /// Steps completed by this invocation. + pub(crate) ran: Vec, + /// Steps already marked complete. + pub(crate) already_done: usize, +} + +/// A completed migration step. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct StepReport { + /// Owner name. + pub(crate) owner: String, + /// Collection being migrated. + pub(crate) item: String, + /// Stable step identifier. + pub(crate) step: String, + /// Number of destination records written. + pub(crate) written: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Progress { + owner: String, + step: String, + from: u32, + to: u32, + cursor: Option, + written: u64, + done: bool, +} + +/// Per-source checkpoint for an append-only stream import. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct StreamProgress { + pub(crate) owner: String, + pub(crate) step: String, + pub(crate) source: String, + pub(crate) target: String, + pub(crate) source_offset: u64, + pub(crate) target_offset: u64, +} + +/// Per-owner migration completion markers. +#[derive(Debug, Clone)] +pub(crate) struct Migrations { + docs: Arc, +} +impl Migrations { + /// Bind markers to the caller-provided document store and owner. + #[must_use] + pub(crate) fn new(docs: &Arc, _owner: &str) -> Self { + Self { + docs: Arc::clone(docs), + } + } + + /// Whether a step has completed. + pub(crate) async fn done(&self, owner: &str, step: &str) -> Result { + self.ensure().await?; + let id = composite_key(&[owner, step])?.as_str().to_owned(); + Ok(self + .docs + .get_as::(MIGRATIONS_COLLECTION, &id) + .await? + .is_some_and(|row| row.doc.done)) + } + + /// Mark an external import step complete. + pub(crate) async fn mark_done(&self, owner: &str, step: &str) -> Result<()> { + self.ensure().await?; + let id = composite_key(&[owner, step])?.as_str().to_owned(); + self.save( + &id, + &Progress { + owner: owner.to_owned(), + step: step.to_owned(), + from: 0, + to: 0, + cursor: None, + written: 0, + done: true, + }, + ) + .await + } + + /// Load one source stream's durable import checkpoint. + pub(crate) async fn stream_progress( + &self, + owner: &str, + step: &str, + source: &str, + ) -> Result> { + self.ensure().await?; + let id = composite_key(&[owner, step, source])?.as_str().to_owned(); + Ok(self + .docs + .get_as::(MIGRATIONS_COLLECTION, &id) + .await? + .map(|row| row.doc)) + } + + /// Save one source stream's durable import checkpoint. + pub(crate) async fn save_stream_progress(&self, progress: &StreamProgress) -> Result<()> { + self.ensure().await?; + let id = composite_key(&[&progress.owner, &progress.step, &progress.source])? + .as_str() + .to_owned(); + self.docs + .put_as(MIGRATIONS_COLLECTION, &id, progress, Precondition::None) + .await + .map(|_| ()) + } + + async fn load(&self, id: &str) -> Result> { + Ok(self + .docs + .get_as::(MIGRATIONS_COLLECTION, id) + .await? + .map(|row| row.doc)) + } + + async fn ensure(&self) -> Result<()> { + self.docs + .ensure_collection(&CollectionSpec::new(MIGRATIONS_COLLECTION)) + .await + } + + async fn save(&self, id: &str, progress: &Progress) -> Result<()> { + self.docs + .put_as(MIGRATIONS_COLLECTION, id, progress, Precondition::None) + .await + .map(|_| ()) + } +} + +#[cfg(test)] +#[path = "schema_tests.rs"] +mod tests; diff --git a/crates/tinymcp/src/storage/local/schema_tests.rs b/crates/tinymcp/src/storage/local/schema_tests.rs new file mode 100644 index 00000000..4862b09e --- /dev/null +++ b/crates/tinymcp/src/storage/local/schema_tests.rs @@ -0,0 +1,351 @@ +//! Tests for owner collection migrations and the shared `tsd.migrations` progress ledger. + +use super::*; + +type TestResult = std::result::Result<(), Box>; + +use serde_json::json; +use std::sync::Arc; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_document::memory::MemoryConnection; +use tinystoragedrivers_testkit::{MemoryBackend, TestClock}; +use tinystoragedrivers_types::Scope; + +#[tokio::test] +async fn owner_migration_rewrites_in_place_once_and_preserves_document_metadata() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = Arc::clone(storage.documents()); + docs.ensure_collection(&CollectionSpec::new("flows.items")) + .await?; + docs.put_with( + "flows.items", + "one", + json!({"value": "before"}), + Precondition::Absent, + WriteOptions::new() + .schema(1) + .created_ms(123) + .expires_ms(i64::MAX), + ) + .await?; + let before = docs + .query("flows.items", &Query::filter(Filter::default()).limit(100)) + .await?; + assert_eq!(before.items.len(), 1); + assert_eq!(before.items[0].meta.schema, 1); + + let schema = Schema::new(Owner::new("flows")?) + .collection_with(2, CollectionSpec::new("flows.items"), ScopeClass::Tenant) + .step(Step::new("items_v2", "flows.items", 1, 2, |rows| { + assert_eq!(rows.len(), 1, "one source row should be passed to the step"); + Ok(rows + .into_iter() + .map(|row| TargetRecord::new("flows.items", row.id, json!({"value": "after"}))) + .collect()) + })); + + let first = schema.migrate(&docs, &MigrateOptions::default()).await?; + let stored = docs.get("flows.items", "one").await?; + assert!(stored.is_some(), "migration report: {first:?}"); + let stored = stored.ok_or("row retained")?; + assert_eq!(stored.doc["value"], "after"); + assert_eq!(stored.meta.schema, 2); + assert_eq!(stored.meta.created_ms, 123); + assert_eq!(stored.meta.expires_ms, Some(i64::MAX)); + assert_eq!(first.ran.len(), 1); + + let second = schema.migrate(&docs, &MigrateOptions::default()).await?; + assert_eq!(second.already_done, 1); + assert_eq!( + docs.get("flows.items", "one") + .await? + .ok_or("row retained")? + .doc["value"], + "after" + ); + Ok(()) +} + +#[tokio::test] +async fn owner_migration_rejects_same_id_conflicts_in_a_different_declared_collection() -> TestResult +{ + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = Arc::clone(storage.documents()); + docs.ensure_collection(&CollectionSpec::new("legacy.items")) + .await?; + docs.put_with( + "legacy.items", + "same-id", + json!({"value": "legacy"}), + Precondition::Absent, + WriteOptions::new().schema(1), + ) + .await?; + docs.put_with( + "flows.other", + "same-id", + json!({"value": "stale target"}), + Precondition::Absent, + WriteOptions::new().schema(1), + ) + .await?; + + let schema = Schema::new(Owner::new("flows")?) + .collection_with(2, CollectionSpec::new("flows.items"), ScopeClass::Tenant) + .collection_with(9, CollectionSpec::new("flows.other"), ScopeClass::Tenant) + .step( + Step::new("items_v2", "flows.items", 1, 2, |rows| { + Ok(rows + .into_iter() + .map(|row| { + TargetRecord::new("flows.other", row.id, json!({"value": "migrated"})) + }) + .collect()) + }) + .source("legacy.items"), + ); + + let error = schema + .migrate(&docs, &MigrateOptions::default()) + .await + .err() + .ok_or("a different collection's same-id row must not be overwritten")?; + assert_eq!(error.kind(), ErrorKind::Conflict); + assert_eq!( + docs.get("flows.other", "same-id") + .await? + .ok_or("target remains")? + .doc["value"], + "stale target" + ); + assert!(docs.get("legacy.items", "same-id").await?.is_some()); + Ok(()) +} + +#[tokio::test] +async fn owner_migration_uses_the_declared_version_of_a_different_target_collection() -> TestResult +{ + let clock = TestClock::new(100); + let connection = MemoryConnection::with_clock(Arc::new({ + let clock = clock.clone(); + move || clock.now_ms() + })); + let docs = connection.for_scope(Scope::new("local")?).documents(); + docs.ensure_collection(&CollectionSpec::new("legacy.items")) + .await?; + docs.put_with( + "legacy.items", + "one", + json!({"value": "before"}), + Precondition::Absent, + WriteOptions::new().schema(1), + ) + .await?; + + let schema = Schema::new(Owner::new("flows")?) + .collection_with(2, CollectionSpec::new("flows.items"), ScopeClass::Tenant) + .collection_with(9, CollectionSpec::new("flows.archive"), ScopeClass::Tenant) + .step( + Step::new("items_to_archive", "flows.items", 1, 2, |rows| { + Ok(rows + .into_iter() + .map(|row| { + TargetRecord::new("flows.archive", row.id, json!({"value": "archived"})) + .created_ms(456) + .expires_ms(Some(789)) + }) + .collect()) + }) + .source("legacy.items"), + ); + + let report = schema.migrate(&docs, &MigrateOptions::default()).await?; + assert_eq!(report.ran.len(), 1); + let archived = docs + .get("flows.archive", "one") + .await? + .ok_or("archived row missing")?; + assert_eq!(archived.meta.schema, 9); + assert!(archived.meta.created_ms > 0); + assert_ne!(archived.meta.created_ms, 456); + assert_eq!(archived.meta.expires_ms, Some(789)); + assert_eq!(archived.doc["value"], "archived"); + assert_eq!(clock.advance(700), 800); + assert!(docs.get("flows.archive", "one").await?.is_none()); + Ok(()) +} + +#[tokio::test] +async fn owner_migration_reads_compatible_shared_progress_records() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = Arc::clone(storage.documents()); + let key = composite_key(&["flows", "flows.items", "items_v2"])?; + docs.put_as( + "tsd.migrations", + key.as_str(), + &json!({ + "owner": "flows", + "step": "items_v2", + "from": 1, + "to": 2, + "cursor": null, + "written": 0, + "done": true + }), + Precondition::Absent, + ) + .await?; + let schema = Schema::new(Owner::new("flows")?) + .collection_with(2, CollectionSpec::new("flows.items"), ScopeClass::Tenant) + .step(Step::new("items_v2", "flows.items", 1, 2, |_| { + Err(StorageError::backend( + "completed migration should skip the step", + )) + })); + + let report = schema.migrate(&docs, &MigrateOptions::default()).await?; + assert_eq!(report.already_done, 1); + Ok(()) +} + +#[tokio::test] +async fn migration_rejects_zero_batches_non_object_outputs_and_undeclared_targets() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = Arc::clone(storage.documents()); + let schema = Schema::new(Owner::new("flows")?) + .collection_with(2, CollectionSpec::new("flows.items"), ScopeClass::Tenant) + .step(Step::new("items_v2", "flows.items", 1, 2, |_| { + Ok(vec![TargetRecord::new( + "other.items", + "one", + json!(["not an object"]), + )]) + })); + let error = schema + .migrate(&docs, &MigrateOptions { batch_size: 0 }) + .await + .err() + .ok_or("zero-sized migration batches are invalid")?; + assert_eq!(error.kind(), ErrorKind::InvalidInput); + + docs.put_with( + "flows.items", + "one", + json!({"old": true}), + Precondition::Absent, + WriteOptions::new().schema(1), + ) + .await?; + let error = schema + .migrate(&docs, &MigrateOptions::default()) + .await + .err() + .ok_or("migration outputs must be objects")?; + assert_eq!(error.kind(), ErrorKind::InvalidInput); + + let undeclared = Schema::new(Owner::new("flows")?) + .collection_with(2, CollectionSpec::new("flows.items"), ScopeClass::Tenant) + .step(Step::new("items_v2", "flows.items", 1, 2, |_| { + Ok(vec![TargetRecord::new( + "other.items", + "one", + json!({"new": true}), + )]) + })); + let error = undeclared + .migrate(&docs, &MigrateOptions::default()) + .await + .err() + .ok_or("migration cannot write outside declared owner collections")?; + assert_eq!(error.kind(), ErrorKind::InvalidInput); + assert!(docs.get("flows.items", "one").await?.is_some()); + Ok(()) +} + +#[test] +fn owner_and_progress_keys_validate_and_keep_the_legacy_encoding() -> TestResult { + assert_eq!(Owner::new("flows")?.as_str(), "flows"); + for invalid in ["", "tsd", "Flows", "a", "bad-name", "has.dot"] { + assert!(Owner::new(invalid).is_err(), "accepted owner {invalid:?}"); + } + assert_eq!( + composite_key(&["~flows%", "step/one\0"])?.as_str(), + "%7Eflows%25/step%2Fone%00" + ); + assert!(composite_key(&[]).is_err()); + let long = "x".repeat(513); + assert_eq!(composite_key(&[&long])?.as_str().len(), 53); + Ok(()) +} + +#[tokio::test] +async fn stream_progress_and_external_completion_round_trip_in_the_shared_ledger() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = Arc::clone(storage.documents()); + let migrations = Migrations::new(&docs, "flows"); + assert!(!migrations.done("flows", "import").await?); + migrations.mark_done("flows", "import").await?; + assert!(migrations.done("flows", "import").await?); + let progress = StreamProgress { + owner: "flows".into(), + step: "audit".into(), + source: "legacy.audit".into(), + target: "flows.audit".into(), + source_offset: 2, + target_offset: 4, + }; + assert!( + migrations + .stream_progress("flows", "audit", "legacy.audit") + .await? + .is_none() + ); + migrations.save_stream_progress(&progress).await?; + let persisted = migrations + .stream_progress("flows", "audit", "legacy.audit") + .await? + .ok_or("saved checkpoint")?; + assert_eq!(persisted.source_offset, progress.source_offset); + assert_eq!(persisted.target_offset, progress.target_offset); + Ok(()) +} + +#[tokio::test] +async fn migration_accepts_an_identical_destination_after_a_lost_write_reply() -> TestResult { + let storage = MemoryBackend::new().for_scope(&Scope::new("local")?)?; + let docs = Arc::clone(storage.documents()); + docs.put_with( + "legacy.items", + "one", + json!({"value": "before"}), + Precondition::Absent, + WriteOptions::new().schema(1), + ) + .await?; + docs.put_with( + "flows.archive", + "one", + json!({"value": "after"}), + Precondition::Absent, + WriteOptions::new().schema(9), + ) + .await?; + let schema = Schema::new(Owner::new("flows")?) + .collection_with(2, CollectionSpec::new("flows.items"), ScopeClass::Tenant) + .collection_with(9, CollectionSpec::new("flows.archive"), ScopeClass::Tenant) + .step( + Step::new("archive_v1", "flows.items", 1, 2, |rows| { + Ok(rows + .into_iter() + .map(|row| { + TargetRecord::new("flows.archive", row.id, json!({"value": "after"})) + }) + .collect()) + }) + .source("legacy.items"), + ); + let report = schema.migrate(&docs, &MigrateOptions::default()).await?; + assert_eq!(report.ran[0].written, 1); + assert!(docs.get("legacy.items", "one").await?.is_none()); + Ok(()) +} diff --git a/crates/tinymcp/src/storage/migrate.rs b/crates/tinymcp/src/storage/migrate.rs new file mode 100644 index 00000000..661a6444 --- /dev/null +++ b/crates/tinymcp/src/storage/migrate.rs @@ -0,0 +1,402 @@ +//! The v1 to v2 steps: the previous release's `mcp_*` collections and stream +//! become the `mcp.*` ones. +//! +//! Each step is a pure function of the records it is handed, so a resumed or +//! repeated run produces the same output. A step keeps a record's creation +//! time and expiry, renames its `*_at` time fields to `*_ms`, and re-keys it +//! with [`id`]. A cache row or index row that cannot be carried over (its body +//! is not JSON, or the field its new key is built from is missing) is dropped +//! instead of failing the step: it holds nothing the module cannot fetch +//! again, and one bad row must not keep a whole database from migrating. + +use serde_json::{Map, Value}; +use tinystoragedrivers_api::StreamStore; +use tinystoragedrivers_types::{ErrorKind, Result as StorageResult, StreamEntry}; + +use super::local::{Migrations, SourceRecord, Step, StreamProgress, TargetRecord}; +use super::migration_legacy::{ + LegacyServerDocument, convert_legacy_server, convert_legacy_server_name_claim, + legacy_audit_stream_target, +}; +use super::schema::{ + OWNER, REGISTRY_CACHE, REGISTRY_INDEX, REGISTRY_INDEX_STATE, SERVER_NAMES, SERVERS, TOOL_CACHE, + doc_id, +}; + +/// The version the steps read. +const FROM: u32 = 1; +/// The version the steps write. +const TO: u32 = 2; + +/// The v1 stream the audit log was appended to. +const LEGACY_AUDIT: &str = "mcp_audit"; + +/// A document step's per-record rule: the new id and body, or `None` to drop +/// the record. +type Rewrite = fn(&SourceRecord, Map) -> StorageResult>; + +/// Every step, in the order they run. +pub(super) fn steps() -> Vec { + vec![ + documents("servers_v2", SERVERS, "mcp_servers", server), + documents("server_names_v2", SERVER_NAMES, "mcp_server_names", claim), + documents( + "registry_cache_v2", + REGISTRY_CACHE, + "mcp_registry_cache", + cached_response, + ), + documents("tool_cache_v2", TOOL_CACHE, "mcp_tool_cache", cached_tools), + documents( + "registry_index_v2", + REGISTRY_INDEX, + "mcp_registry_index", + index_row, + ), + documents( + "registry_index_state_v2", + REGISTRY_INDEX_STATE, + "mcp_registry_index_state", + index_state, + ), + ] +} + +/// Move the old audit stream family to `mcp.audit`, resuming each source from a +/// durable positional checkpoint so pre-existing target entries are retained. +/// The host must quiesce writers to both stream families for the duration of +/// this one-time migration; stream ports do not provide an atomic append plus +/// checkpoint operation. +pub(crate) async fn migrate_audit_streams( + streams: &dyn StreamStore, + migrations: &Migrations, +) -> StorageResult<()> { + const STEP: &str = "audit_streams_v2"; + if migrations.done(OWNER, STEP).await? { + return Ok(()); + } + for source in streams.streams(LEGACY_AUDIT).await? { + let Some(target) = audit_target(&source) else { + continue; + }; + migrate_audit_source(streams, migrations, &source, &target).await?; + } + migrations.mark_done(OWNER, STEP).await +} + +fn audit_target(source: &str) -> Option { + legacy_audit_stream_target(source) +} + +async fn migrate_audit_source( + streams: &dyn StreamStore, + migrations: &Migrations, + source: &str, + target: &str, +) -> StorageResult<()> { + const STEP: &str = "audit_streams_v2"; + let source_len = stream_len(streams, source).await?; + let mut progress = + if let Some(progress) = migrations.stream_progress(OWNER, STEP, source).await? { + progress + } else { + let progress = StreamProgress { + owner: OWNER.to_owned(), + step: STEP.to_owned(), + source: source.to_owned(), + target: target.to_owned(), + source_offset: 0, + target_offset: stream_len(streams, target).await?, + }; + migrations.save_stream_progress(&progress).await?; + progress + }; + if progress.target != target { + return Err(tinystoragedrivers_types::StorageError::conflict( + "audit migration target changed after progress was recorded", + )); + } + while progress.source_offset < source_len { + let Some(mut batch) = source_batch( + streams, + migrations, + source, + progress.source_offset, + source_len, + ) + .await? + else { + progress.source_offset = source_len; + break; + }; + let remaining = usize::try_from(source_len - progress.source_offset).unwrap_or(usize::MAX); + batch.truncate(remaining); + if batch.is_empty() { + return Err(tinystoragedrivers_types::StorageError::conflict( + "audit source ended before its reported length", + )); + } + let batch_size = batch.len(); + let count = u64::try_from(batch_size).unwrap_or(u64::MAX); + let values = batch + .into_iter() + .map(|entry| entry.value) + .collect::>(); + let copied = streams + .read_window(target, progress.target_offset, batch_size) + .await? + .into_iter() + .map(|entry| entry.value) + .collect::>(); + if copied == values { + progress.source_offset = progress.source_offset.saturating_add(count); + progress.target_offset = progress.target_offset.saturating_add(count); + migrations.save_stream_progress(&progress).await?; + continue; + } + if stream_len(streams, target).await? != progress.target_offset { + return Err(tinystoragedrivers_types::StorageError::conflict( + "audit target changed while migrating its source stream", + )); + } + let first_offset = match streams + .append_batch_if_offset(target, progress.target_offset, values.clone()) + .await + { + Ok(first_offset) => first_offset, + Err(error) if error.kind() == ErrorKind::Conflict => { + // Another opener may have copied this exact source batch + // after our checkpoint read. Accept only the identical + // batch at the expected offset; any different write stays + // a conflict and leaves the source and checkpoint intact. + let raced = streams + .read_window(target, progress.target_offset, batch_size) + .await? + .into_iter() + .map(|entry| entry.value) + .collect::>(); + if raced != values { + return Err(error); + } + progress.source_offset = progress.source_offset.saturating_add(count); + progress.target_offset = progress.target_offset.saturating_add(count); + migrations.save_stream_progress(&progress).await?; + continue; + } + Err(error) => return Err(error), + }; + progress.source_offset = progress.source_offset.saturating_add(count); + progress.target_offset = first_offset.saturating_add(count); + migrations.save_stream_progress(&progress).await?; + } + if progress.source_offset == source_len { + delete_migrated_source(streams, source, source_len).await?; + } + Ok(()) +} + +async fn delete_migrated_source( + streams: &dyn StreamStore, + source: &str, + source_len: u64, +) -> StorageResult<()> { + let current_len = stream_len(streams, source).await?; + if current_len != source_len && !(current_len == 0 && source_len > 0) { + return Err(tinystoragedrivers_types::StorageError::conflict( + "audit source changed while it was being migrated", + )); + } + match streams.delete_stream(source).await { + Ok(_) => Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound && current_len == 0 => Ok(()), + Err(error) => Err(error), + } +} + +async fn stream_len(streams: &dyn StreamStore, source: &str) -> StorageResult { + match streams.len(source).await { + Ok(length) => Ok(length), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(0), + Err(error) => Err(error), + } +} + +async fn source_batch( + streams: &dyn StreamStore, + migrations: &Migrations, + source: &str, + source_offset: u64, + source_len: u64, +) -> StorageResult>> { + match streams.read_window(source, source_offset, 256).await { + Ok(batch) if batch.is_empty() => { + let current_len = stream_len(streams, source).await?; + let checkpoint = migrations + .stream_progress(OWNER, "audit_streams_v2", source) + .await?; + if current_len == 0 && checkpoint.is_some_and(|saved| saved.source_offset >= source_len) + { + Ok(None) + } else { + Ok(Some(batch)) + } + } + Ok(batch) => Ok(Some(batch)), + Err(error) if error.kind() == ErrorKind::NotFound => { + let current_len = stream_len(streams, source).await?; + let checkpoint = migrations + .stream_progress(OWNER, "audit_streams_v2", source) + .await?; + if current_len == 0 && checkpoint.is_some_and(|saved| saved.source_offset >= source_len) + { + Ok(None) + } else { + Err(error) + } + } + Err(error) => Err(error), + } +} + +/// A step reading the legacy collection `legacy` and writing `item`, applying +/// `rewrite` to each record's body. +fn documents(id: &'static str, item: &'static str, legacy: &'static str, rewrite: Rewrite) -> Step { + Step::new(id, item, FROM, TO, move |batch| { + let mut targets = Vec::with_capacity(batch.len()); + for record in batch { + let Value::Object(body) = record.body.clone() else { + continue; + }; + if let Some((new_id, body)) = rewrite(&record, body)? { + let mut target = + TargetRecord::new(item, new_id, body).expires_ms(record.meta.expires_ms); + if record.meta.created_ms > 0 { + target = target.created_ms(record.meta.created_ms); + } + targets.push(target); + } + } + Ok(targets) + }) + .source(legacy) +} + +/// Moves `from` to `to` when the record has it. +fn rename(body: &mut Map, from: &str, to: &str) { + if let Some(value) = body.remove(from) { + body.insert(to.to_owned(), value); + } +} + +/// The string field `name`, if the record has it. +fn text<'a>(body: &'a Map, name: &str) -> Option<&'a str> { + body.get(name).and_then(Value::as_str) +} + +/// Replaces the JSON text in `from` with the value it holds, under `to`. +/// `None` when the field is missing or is not JSON. +fn unwrap_json(body: &mut Map, from: &str, to: &str) -> Option<()> { + let parsed = serde_json::from_str::(text(body, from)?).ok()?; + body.remove(from); + body.insert(to.to_owned(), parsed); + Some(()) +} + +fn server( + record: &SourceRecord, + body: Map, +) -> StorageResult> { + let body = serde_json::from_value(Value::Object(body)).map_err(|error| { + tinystoragedrivers_types::StorageError::invalid_input(format!( + "malformed legacy MCP server record: {error}" + )) + })?; + let converted = convert_legacy_server(LegacyServerDocument { + storage_id: record.id.clone(), + body, + })?; + let body = serde_json::to_value(converted.body).map_err(|error| { + tinystoragedrivers_types::StorageError::invalid_input(format!( + "serialize converted MCP server record: {error}" + )) + })?; + Ok(Some((converted.id, body))) +} + +/// A name claim: keyed by the qualified name it holds. A claim from before +/// claims were timed reads as claimed at `0`, i.e. long expired. +fn claim( + _record: &SourceRecord, + body: Map, +) -> StorageResult> { + let claim = serde_json::from_value(Value::Object(body)).map_err(|error| { + tinystoragedrivers_types::StorageError::invalid_input(format!( + "malformed legacy MCP server-name claim: {error}" + )) + })?; + let converted = convert_legacy_server_name_claim(claim)?; + let body = serde_json::to_value(converted.body).map_err(|error| { + tinystoragedrivers_types::StorageError::invalid_input(format!( + "serialize converted MCP server-name claim: {error}" + )) + })?; + Ok(Some((converted.id, body))) +} + +fn cached_response( + _record: &SourceRecord, + mut body: Map, +) -> StorageResult> { + let Some(key) = text(&body, "cache_key").map(ToOwned::to_owned) else { + return Ok(None); + }; + if unwrap_json(&mut body, "body_json", "body").is_none() { + return Ok(None); + } + rename(&mut body, "cached_at", "cached_ms"); + Ok(Some((doc_id(&[&key])?, Value::Object(body)))) +} + +fn cached_tools( + _record: &SourceRecord, + mut body: Map, +) -> StorageResult> { + let Some(key) = text(&body, "server_key").map(ToOwned::to_owned) else { + return Ok(None); + }; + rename(&mut body, "cached_at", "cached_ms"); + Ok(Some((doc_id(&[&key])?, Value::Object(body)))) +} + +fn index_row( + _record: &SourceRecord, + mut body: Map, +) -> StorageResult> { + let (Some(source), Some(name)) = ( + text(&body, "source").map(ToOwned::to_owned), + text(&body, "qualified_name").map(ToOwned::to_owned), + ) else { + return Ok(None); + }; + if unwrap_json(&mut body, "record_json", "record").is_none() { + return Ok(None); + } + rename(&mut body, "synced_at", "synced_ms"); + Ok(Some((doc_id(&[&source, &name])?, Value::Object(body)))) +} + +fn index_state( + _record: &SourceRecord, + mut body: Map, +) -> StorageResult> { + let Some(source) = text(&body, "source").map(ToOwned::to_owned) else { + return Ok(None); + }; + rename(&mut body, "started_at", "started_ms"); + rename(&mut body, "synced_at", "synced_ms"); + Ok(Some((doc_id(&[&source])?, Value::Object(body)))) +} + +#[cfg(test)] +#[path = "migrate_tests.rs"] +mod tests; diff --git a/crates/tinymcp/src/storage/migrate_tests.rs b/crates/tinymcp/src/storage/migrate_tests.rs new file mode 100644 index 00000000..0eaae637 --- /dev/null +++ b/crates/tinymcp/src/storage/migrate_tests.rs @@ -0,0 +1,1263 @@ +//! Tests for the v1 to v2 steps, run through the registry over v1-shaped fixtures. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use crate::storage::AUDIT_STREAM; +use crate::storage::StoragePorts; +use crate::storage::local::schema::MigrationReport; +use crate::storage::local::{MigrateOptions, Migrations, Schema, StreamProgress}; +use crate::storage::migrate; +use crate::storage::types::{ + CollectionSpec, DocumentStoreExt as _, Filter, Precondition, Query, Scope, Versioned, +}; +use serde_json::{Value, json}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use tinystoragedrivers_api::StreamStore; +use tinystoragedrivers_api::{Storage, StorageBackend}; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::StreamEntry; + +use super::*; +use crate::audit::AuditStore; +use crate::registry::store::Store; +use crate::storage::schema::{OWNER, storage_schema}; +use tinymcp_bus::storage::SCHEMA_VERSION; + +/// A memory backend holding v1 data, and the registry that migrates it. +struct Fixture { + blocking: tokio::runtime::Runtime, + storage: Storage, + schema: Schema, +} + +impl Fixture { + fn new() -> Self { + let blocking = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let backend = MemoryBackend::new(); + let scope = Scope::new("tinymcp").unwrap(); + let storage = backend.for_scope(&scope).unwrap(); + let schema = storage_schema().unwrap(); + Self { + blocking, + storage, + schema, + } + } + + /// Writes one v1 document the way the previous release did. + fn legacy(&self, collection: &str, id: &str, body: Value) { + let documents = self.storage.documents().clone(); + let collection = collection.to_string(); + let id = id.to_string(); + self.blocking + .block_on(async move { + documents + .ensure_collection(&CollectionSpec::new(&collection)) + .await?; + documents + .put(&collection, &id, body, Precondition::Absent) + .await + }) + .unwrap(); + } + + fn legacy_stream(&self, name: &str, entries: &[Value]) { + let streams = self.storage.streams().clone(); + let name = name.to_string(); + let entries = entries.to_vec(); + self.blocking + .block_on(async move { + for entry in entries { + streams.append(&name, entry).await?; + } + Ok::<_, crate::storage::types::StorageError>(()) + }) + .unwrap(); + } + + fn migrate(&self) -> MigrationReport { + let documents = Arc::clone(self.storage.documents()); + let streams = Arc::clone(self.storage.streams()); + self.blocking + .block_on(async { + let report = self + .schema + .migrate(&documents, &MigrateOptions::new()) + .await?; + let migrations = Migrations::new(&documents, OWNER); + migrate::migrate_audit_streams(&*streams, &migrations).await?; + Ok::<_, crate::storage::types::StorageError>(report) + }) + .unwrap() + } + + fn get(&self, collection: &str, id: &str) -> Option> { + let documents = self.storage.documents().clone(); + let collection = collection.to_string(); + let id = id.to_string(); + self.blocking + .block_on(async move { documents.get(&collection, &id).await }) + .unwrap() + } + + fn all(&self, collection: &str) -> Vec> { + let documents = self.storage.documents().clone(); + let collection = collection.to_string(); + self.blocking + .block_on(async move { documents.query_all(&collection, &Query::all()).await }) + .unwrap() + } + + fn count_where(&self, collection: &str, filter: Filter) -> u64 { + let documents = self.storage.documents().clone(); + let collection = collection.to_string(); + self.blocking + .block_on(async move { documents.count(&collection, &filter).await }) + .unwrap() + } + + fn stream(&self, name: &str) -> Vec { + let streams = self.storage.streams().clone(); + let name = name.to_string(); + self.blocking + .block_on(async move { + let len = streams.len(&name).await?; + let window = streams.read_window(&name, 0, 1024).await?; + assert_eq!(window.len() as u64, len); + Ok::, crate::storage::types::StorageError>( + window.into_iter().map(|entry| entry.value).collect(), + ) + }) + .unwrap() + } +} + +/// Persists the first migrated batch, then simulates the caller losing the +/// acknowledgement before its progress marker can be written. +#[derive(Debug)] +struct FailAfterFirstAppend { + inner: Arc, + fail: AtomicBool, +} + +#[tinystoragedrivers_api::async_trait] +impl StreamStore for FailAfterFirstAppend { + fn capabilities(&self) -> tinystoragedrivers_types::Capabilities { + self.inner.capabilities() + } + + async fn append(&self, stream: &str, value: Value) -> crate::storage::types::Result { + self.inner.append(stream, value).await + } + + async fn append_batch( + &self, + stream: &str, + values: Vec, + ) -> crate::storage::types::Result { + let first = self.inner.append_batch(stream, values).await?; + if self.fail.swap(false, Ordering::SeqCst) { + return Err(crate::storage::types::StorageError::unavailable( + "lost append acknowledgement", + )); + } + Ok(first) + } + + async fn append_batch_if_offset( + &self, + stream: &str, + expected_next_offset: u64, + values: Vec, + ) -> crate::storage::types::Result { + let first = self + .inner + .append_batch_if_offset(stream, expected_next_offset, values) + .await?; + if self.fail.swap(false, Ordering::SeqCst) { + return Err(crate::storage::types::StorageError::unavailable( + "lost conditional append acknowledgement", + )); + } + Ok(first) + } + + async fn read_window( + &self, + stream: &str, + from: u64, + limit: usize, + ) -> crate::storage::types::Result> { + self.inner.read_window(stream, from, limit).await + } + + async fn len(&self, stream: &str) -> crate::storage::types::Result { + self.inner.len(stream).await + } + + async fn truncate_before( + &self, + stream: &str, + offset: u64, + ) -> crate::storage::types::Result { + self.inner.truncate_before(stream, offset).await + } + + async fn delete_stream(&self, stream: &str) -> crate::storage::types::Result { + self.inner.delete_stream(stream).await + } + + async fn streams(&self, prefix: &str) -> crate::storage::types::Result> { + self.inner.streams(prefix).await + } +} + +/// Makes one nonempty legacy stream return an empty page or an error during a +/// read, as a failing backend can do. +#[derive(Debug)] +struct EmptyFirstRead { + inner: Arc, + fail: AtomicBool, + return_error: bool, +} + +#[tinystoragedrivers_api::async_trait] +impl StreamStore for EmptyFirstRead { + fn capabilities(&self) -> tinystoragedrivers_types::Capabilities { + self.inner.capabilities() + } + + async fn append(&self, stream: &str, value: Value) -> crate::storage::types::Result { + self.inner.append(stream, value).await + } + + async fn append_batch( + &self, + stream: &str, + values: Vec, + ) -> crate::storage::types::Result { + self.inner.append_batch(stream, values).await + } + + async fn append_batch_if_offset( + &self, + stream: &str, + expected_next_offset: u64, + values: Vec, + ) -> crate::storage::types::Result { + self.inner + .append_batch_if_offset(stream, expected_next_offset, values) + .await + } + + async fn read_window( + &self, + stream: &str, + from: u64, + limit: usize, + ) -> crate::storage::types::Result> { + if stream == "mcp_audit" && self.fail.swap(false, Ordering::SeqCst) { + if self.return_error { + return Err(crate::storage::types::StorageError::unavailable( + "simulated audit read failure", + )); + } + return Ok(Vec::new()); + } + self.inner.read_window(stream, from, limit).await + } + + async fn len(&self, stream: &str) -> crate::storage::types::Result { + self.inner.len(stream).await + } + + async fn truncate_before( + &self, + stream: &str, + offset: u64, + ) -> crate::storage::types::Result { + self.inner.truncate_before(stream, offset).await + } + + async fn delete_stream(&self, stream: &str) -> crate::storage::types::Result { + self.inner.delete_stream(stream).await + } + + async fn streams(&self, prefix: &str) -> crate::storage::types::Result> { + self.inner.streams(prefix).await + } +} + +/// Adds an entry to the source after its length was read but before the page +/// containing its original contents is returned. +#[derive(Debug)] +struct AppendDuringRead { + inner: Arc, + append: AtomicBool, + before_read: bool, + missing_empty_streams: bool, +} + +/// Models a second, independent opener winning the target append after this +/// importer reads its checkpoint but before its own conditional append. +#[derive(Debug)] +struct CompetingAuditAppend { + inner: Arc, + raced: AtomicBool, + competing_batch: Option>, +} + +/// Completes the same source migration through another opener before the +/// first opener reads its next source batch. +#[derive(Debug)] +struct CompetingAuditDelete { + inner: Arc, + migrations: Migrations, + raced: AtomicBool, +} + +#[tinystoragedrivers_api::async_trait] +impl StreamStore for CompetingAuditDelete { + fn capabilities(&self) -> tinystoragedrivers_types::Capabilities { + self.inner.capabilities() + } + + async fn append(&self, stream: &str, value: Value) -> crate::storage::types::Result { + self.inner.append(stream, value).await + } + + async fn append_batch( + &self, + stream: &str, + values: Vec, + ) -> crate::storage::types::Result { + self.inner.append_batch(stream, values).await + } + + async fn append_batch_if_offset( + &self, + stream: &str, + expected_next_offset: u64, + values: Vec, + ) -> crate::storage::types::Result { + self.inner + .append_batch_if_offset(stream, expected_next_offset, values) + .await + } + + async fn read_window( + &self, + stream: &str, + from: u64, + limit: usize, + ) -> crate::storage::types::Result> { + if stream == "mcp_audit" && !self.raced.swap(true, Ordering::SeqCst) { + migrate::migrate_audit_streams(&*self.inner, &self.migrations).await?; + } + self.inner.read_window(stream, from, limit).await + } + + async fn len(&self, stream: &str) -> crate::storage::types::Result { + self.inner.len(stream).await + } + + async fn truncate_before( + &self, + stream: &str, + offset: u64, + ) -> crate::storage::types::Result { + self.inner.truncate_before(stream, offset).await + } + + async fn delete_stream(&self, stream: &str) -> crate::storage::types::Result { + self.inner.delete_stream(stream).await + } + + async fn streams(&self, prefix: &str) -> crate::storage::types::Result> { + self.inner.streams(prefix).await + } +} + +#[tinystoragedrivers_api::async_trait] +impl StreamStore for CompetingAuditAppend { + fn capabilities(&self) -> tinystoragedrivers_types::Capabilities { + self.inner.capabilities() + } + + async fn append(&self, stream: &str, value: Value) -> crate::storage::types::Result { + self.inner.append(stream, value).await + } + + async fn append_batch( + &self, + stream: &str, + values: Vec, + ) -> crate::storage::types::Result { + // This is the pre-fix importer path. Make the competing opener append + // first, then allow the unconditional append to expose duplication. + if stream == AUDIT_STREAM && !self.raced.swap(true, Ordering::SeqCst) { + self.inner + .append_batch( + stream, + self.competing_batch + .clone() + .unwrap_or_else(|| values.clone()), + ) + .await?; + } + self.inner.append_batch(stream, values).await + } + + async fn append_batch_if_offset( + &self, + stream: &str, + expected_next_offset: u64, + values: Vec, + ) -> crate::storage::types::Result { + if stream == AUDIT_STREAM && !self.raced.swap(true, Ordering::SeqCst) { + // A second independently bound port handle wins at precisely the + // expected target offset. The current importer must recognize the + // exact batch after its conditional append reports a conflict. + self.inner + .append_batch_if_offset( + stream, + expected_next_offset, + self.competing_batch + .clone() + .unwrap_or_else(|| values.clone()), + ) + .await?; + } + self.inner + .append_batch_if_offset(stream, expected_next_offset, values) + .await + } + + async fn read_window( + &self, + stream: &str, + from: u64, + limit: usize, + ) -> crate::storage::types::Result> { + self.inner.read_window(stream, from, limit).await + } + + async fn len(&self, stream: &str) -> crate::storage::types::Result { + self.inner.len(stream).await + } + + async fn truncate_before( + &self, + stream: &str, + offset: u64, + ) -> crate::storage::types::Result { + self.inner.truncate_before(stream, offset).await + } + + async fn delete_stream(&self, stream: &str) -> crate::storage::types::Result { + self.inner.delete_stream(stream).await + } + + async fn streams(&self, prefix: &str) -> crate::storage::types::Result> { + self.inner.streams(prefix).await + } +} + +#[tinystoragedrivers_api::async_trait] +impl StreamStore for AppendDuringRead { + fn capabilities(&self) -> tinystoragedrivers_types::Capabilities { + self.inner.capabilities() + } + + async fn append(&self, stream: &str, value: Value) -> crate::storage::types::Result { + self.inner.append(stream, value).await + } + + async fn append_batch( + &self, + stream: &str, + values: Vec, + ) -> crate::storage::types::Result { + self.inner.append_batch(stream, values).await + } + + async fn append_batch_if_offset( + &self, + stream: &str, + expected_next_offset: u64, + values: Vec, + ) -> crate::storage::types::Result { + self.inner + .append_batch_if_offset(stream, expected_next_offset, values) + .await + } + + async fn read_window( + &self, + stream: &str, + from: u64, + limit: usize, + ) -> crate::storage::types::Result> { + if stream == "mcp_audit" && self.before_read && self.append.swap(false, Ordering::SeqCst) { + self.inner + .append(stream, json!({"timestamp_ms": 2})) + .await?; + } + let page = self.inner.read_window(stream, from, limit).await?; + if stream == "mcp_audit" && !self.before_read && self.append.swap(false, Ordering::SeqCst) { + self.inner + .append(stream, json!({"timestamp_ms": 2})) + .await?; + } + Ok(page) + } + + async fn len(&self, stream: &str) -> crate::storage::types::Result { + let len = self.inner.len(stream).await?; + if len == 0 && self.missing_empty_streams { + return Err(crate::storage::types::StorageError::not_found( + "simulated missing stream", + )); + } + Ok(len) + } + + async fn truncate_before( + &self, + stream: &str, + offset: u64, + ) -> crate::storage::types::Result { + self.inner.truncate_before(stream, offset).await + } + + async fn delete_stream(&self, stream: &str) -> crate::storage::types::Result { + self.inner.delete_stream(stream).await + } + + async fn streams(&self, prefix: &str) -> crate::storage::types::Result> { + self.inner.streams(prefix).await + } +} + +fn v1_server() -> Value { + json!({ + "server_id": "srv-1", + "qualified_name": "@acme/files", + "display_name": "Files", + "command_kind": "node", + "command": "npx", + "args": ["-y", "files"], + "env_keys": ["TOKEN"], + "installed_at": 1_700_000_000_000_i64, + "last_connected_at": 1_700_000_100_000_i64, + "transport": "stdio", + "enabled": true, + "catalog_managed": true, + }) +} + +#[test] +fn a_v1_server_moves_to_the_v2_collection_with_ms_time_fields() { + let fixture = Fixture::new(); + fixture.legacy("mcp_servers", "srv-1", v1_server()); + + fixture.migrate(); + + let moved = fixture.get(SERVERS, "srv-1").expect("the server moved"); + assert_eq!(moved.doc["installed_ms"], 1_700_000_000_000_i64); + assert_eq!(moved.doc["last_connected_ms"], 1_700_000_100_000_i64); + assert!(moved.doc.get("installed_at").is_none()); + assert!(moved.doc.get("last_connected_at").is_none()); + assert_eq!(moved.doc["qualified_name"], "@acme/files"); + assert_eq!(moved.doc["catalog_managed"], true); + assert_eq!(moved.doc["args"], json!(["-y", "files"])); + assert_eq!(moved.meta.schema, SCHEMA_VERSION); + assert_eq!(fixture.all("mcp_servers").len(), 0); +} + +#[test] +fn a_malformed_legacy_server_is_not_converted_or_consumed() { + let fixture = Fixture::new(); + let mut malformed = v1_server(); + malformed["installed_at"] = json!("yesterday"); + fixture.legacy("mcp_servers", "srv-1", malformed.clone()); + + let documents = Arc::clone(fixture.storage.documents()); + let error = fixture + .blocking + .block_on(fixture.schema.migrate(&documents, &MigrateOptions::new())) + .expect_err("malformed legacy timestamps must fail the owner migration"); + + assert!( + error + .to_string() + .contains("malformed legacy MCP server record") + ); + assert_eq!(fixture.get("mcp_servers", "srv-1").unwrap().doc, malformed); + assert!(fixture.get(SERVERS, "srv-1").is_none()); +} + +#[test] +fn opening_the_registry_store_runs_the_owner_document_migrations() { + let fixture = Fixture::new(); + fixture.legacy("mcp_servers", "srv-1", v1_server()); + let ports = crate::storage::StoragePorts::from_storage( + &fixture.storage, + Arc::clone(fixture.storage.secrets()), + ); + + let _store = Store::open(ports).unwrap(); + + let moved = fixture + .get(SERVERS, "srv-1") + .expect("owner open migrated the row"); + assert_eq!(moved.doc["installed_ms"], 1_700_000_000_000_i64); + assert_eq!(fixture.all("mcp_servers").len(), 0); +} + +#[test] +fn previous_release_public_writer_data_is_readable_after_owner_open() { + let fixture = Fixture::new(); + let released_document: Value = + serde_json::from_str(include_str!("fixtures/tinymcp-v0.19.1-server.json")).unwrap(); + fixture.legacy(SERVERS, "released-fixture-server", released_document); + let ports = crate::storage::StoragePorts::from_storage( + &fixture.storage, + Arc::clone(fixture.storage.secrets()), + ); + + let store = Store::open(ports).unwrap(); + let loaded = store.get_server("released-fixture-server").unwrap(); + + assert_eq!(loaded.qualified_name, "@test/server"); + assert_eq!(loaded.display_name, "Test Server"); + assert_eq!(loaded.command, "npx"); + assert_eq!(loaded.args, ["-y", "@test/server"]); + assert_eq!(loaded.env_keys, ["API_KEY"]); + assert_eq!(loaded.installed_at, 1_700_000_000_000); + assert!(loaded.enabled); + assert_eq!(loaded.transport, tinymcp_bus::Transport::Stdio); +} + +#[test] +fn a_server_never_connected_keeps_no_last_connected_field() { + let fixture = Fixture::new(); + let mut server = v1_server(); + server.as_object_mut().unwrap().remove("last_connected_at"); + fixture.legacy("mcp_servers", "srv-1", server); + + fixture.migrate(); + + let moved = fixture.get(SERVERS, "srv-1").unwrap(); + assert!(moved.doc.get("last_connected_ms").is_none()); + assert_eq!(moved.doc["installed_ms"], 1_700_000_000_000_i64); +} + +#[test] +fn a_server_id_with_a_slash_is_escaped_into_its_v2_key() { + let fixture = Fixture::new(); + let mut server = v1_server(); + server["server_id"] = json!("a/b"); + fixture.legacy("mcp_servers", "a%2Fb", server); + + fixture.migrate(); + + assert!(fixture.get(SERVERS, "a%2Fb").is_some()); + assert!(fixture.get(SERVERS, "a%252Fb").is_none()); +} + +#[test] +fn a_name_claim_is_keyed_by_the_qualified_name_and_keeps_its_time() { + let fixture = Fixture::new(); + fixture.legacy( + "mcp_server_names", + "legacy-claim-files", + json!({"qualified_name": "@acme/files", "server_id": "srv-1", "claimed_at": 5_000}), + ); + fixture.legacy( + "mcp_server_names", + "legacy-claim-old", + json!({"qualified_name": "@acme/old", "server_id": "srv-0"}), + ); + + fixture.migrate(); + + let claim = fixture.get(SERVER_NAMES, "@acme%2Ffiles").unwrap(); + assert_eq!( + claim.doc, + json!({"qualified_name": "@acme/files", "server_id": "srv-1", "claimed_ms": 5_000}) + ); + // A claim that predates the time reads as long expired. + let old = fixture.get(SERVER_NAMES, "@acme%2Fold").unwrap(); + assert_eq!(old.doc["claimed_ms"], 0); + assert_eq!(fixture.all("mcp_server_names").len(), 0); +} + +#[test] +fn a_malformed_legacy_name_claim_is_not_converted_or_consumed() { + let fixture = Fixture::new(); + let malformed = json!({ + "qualified_name": "@acme/files", + "server_id": "srv-1", + "claimed_at": "yesterday" + }); + fixture.legacy("mcp_server_names", "legacy-claim-files", malformed.clone()); + + let documents = Arc::clone(fixture.storage.documents()); + let error = fixture + .blocking + .block_on(fixture.schema.migrate(&documents, &MigrateOptions::new())) + .expect_err("malformed legacy claim times must fail the owner migration"); + + assert!( + error + .to_string() + .contains("malformed legacy MCP server-name claim") + ); + assert_eq!( + fixture + .get("mcp_server_names", "legacy-claim-files") + .unwrap() + .doc, + malformed + ); + assert!(fixture.get(SERVER_NAMES, "@acme%2Ffiles").is_none()); +} + +#[test] +fn a_cached_browse_response_becomes_an_object_body_with_a_cached_time() { + let fixture = Fixture::new(); + fixture.legacy( + "mcp_registry_cache", + "digest-1", + json!({"cache_key": "official:search:slack", "body_json": "{\"servers\":[1,2]}", "cached_at": 9_000}), + ); + + fixture.migrate(); + + let moved = fixture + .get(REGISTRY_CACHE, "official:search:slack") + .unwrap(); + assert_eq!( + moved.doc, + json!({"cache_key": "official:search:slack", "body": {"servers": [1, 2]}, "cached_ms": 9_000}) + ); +} + +#[test] +fn a_cached_response_that_is_not_json_is_dropped_rather_than_blocking_the_step() { + let fixture = Fixture::new(); + fixture.legacy( + "mcp_registry_cache", + "digest-1", + json!({"cache_key": "k", "body_json": "not json", "cached_at": 1}), + ); + fixture.legacy( + "mcp_registry_cache", + "digest-2", + json!({"cache_key": "ok", "body_json": "[]", "cached_at": 2}), + ); + + fixture.migrate(); + + assert!(fixture.get(REGISTRY_CACHE, "k").is_none()); + assert!(fixture.get(REGISTRY_CACHE, "ok").is_some()); + assert_eq!(fixture.all("mcp_registry_cache").len(), 0); +} + +#[test] +fn cached_tools_are_keyed_by_the_server_key() { + let fixture = Fixture::new(); + fixture.legacy( + "mcp_tool_cache", + "digest-1", + json!({"server_key": "static:docs", "fingerprint": "abc", "tools": [{"name": "t"}], "cached_at": 7_000}), + ); + + fixture.migrate(); + + let moved = fixture.get(TOOL_CACHE, "static:docs").unwrap(); + assert_eq!( + moved.doc, + json!({"server_key": "static:docs", "fingerprint": "abc", "tools": [{"name": "t"}], "cached_ms": 7_000}) + ); +} + +#[test] +fn an_index_row_gets_an_object_record_a_synced_time_and_a_composite_key() { + let fixture = Fixture::new(); + fixture.legacy( + "mcp_registry_index", + "digest-1", + json!({ + "source": "official", + "qualified_name": "@acme/files", + "label": "files", + "description": "read files", + "record_json": "{\"name\":\"files\"}", + "synced_at": 4_000, + "search": "fi fil file files", + }), + ); + + fixture.migrate(); + + let moved = fixture + .get(REGISTRY_INDEX, "official/@acme%2Ffiles") + .unwrap(); + assert_eq!(moved.doc["record"], json!({"name": "files"})); + assert_eq!(moved.doc["synced_ms"], 4_000); + assert!(moved.doc.get("record_json").is_none()); + assert!(moved.doc.get("synced_at").is_none()); + assert_eq!(moved.doc["search"], "fi fil file files"); + assert_eq!( + fixture.count_where(REGISTRY_INDEX, Filter::eq("source", "official")), + 1 + ); +} + +#[test] +fn an_index_state_moves_its_times_to_ms_fields() { + let fixture = Fixture::new(); + fixture.legacy( + "mcp_registry_index_state", + "digest-1", + json!({"source": "official", "base_url": "https://r", "cursor": "c", "pages": 3, "started_at": 100, "synced_at": 50}), + ); + fixture.legacy( + "mcp_registry_index_state", + "digest-2", + json!({"source": "other", "base_url": "https://o", "pages": 0}), + ); + + fixture.migrate(); + + let state = fixture.get(REGISTRY_INDEX_STATE, "official").unwrap(); + assert_eq!( + state.doc, + json!({"source": "official", "base_url": "https://r", "cursor": "c", "pages": 3, "started_ms": 100, "synced_ms": 50}) + ); + let idle = fixture.get(REGISTRY_INDEX_STATE, "other").unwrap(); + assert!(idle.doc.get("started_ms").is_none()); + assert!(idle.doc.get("synced_ms").is_none()); +} + +#[test] +fn the_audit_stream_moves_in_order_under_its_v2_name() { + let fixture = Fixture::new(); + let entries = [ + json!({"timestamp_ms": 1, "client_info": "c", "tool_name": "a", "args_summary": {}, "success": true}), + json!({"timestamp_ms": 2, "client_info": "c", "tool_name": "b", "args_summary": {}, "success": false, "error_message": "boom"}), + ]; + fixture.legacy_stream("mcp_audit", &entries); + + fixture.migrate(); + + assert_eq!(fixture.stream(AUDIT_STREAM), entries); + assert_eq!(fixture.stream("mcp_audit").len(), 0); +} + +#[test] +fn opening_the_audit_store_runs_owner_stream_migrations() { + let fixture = Fixture::new(); + let entries = [json!({"timestamp_ms": 1}), json!({"timestamp_ms": 2})]; + fixture.legacy_stream("mcp_audit", &entries); + let ports = crate::storage::StoragePorts::from_storage( + &fixture.storage, + Arc::clone(fixture.storage.secrets()), + ); + + let _audit = AuditStore::open(ports).unwrap(); + + assert_eq!(fixture.stream(AUDIT_STREAM), entries); + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); +} + +#[test] +fn audit_import_keeps_existing_target_rows_and_duplicate_source_events() { + let fixture = Fixture::new(); + let repeated = json!({"timestamp_ms": 1, "tool_name": "same"}); + fixture.legacy_stream("mcp.audit", &[json!({"timestamp_ms": 0})]); + fixture.legacy_stream("mcp_audit", &[repeated.clone(), repeated.clone()]); + + fixture.migrate(); + + assert_eq!( + fixture.stream(AUDIT_STREAM), + [json!({"timestamp_ms": 0}), repeated.clone(), repeated] + ); +} + +#[test] +fn concurrent_owner_openers_do_not_duplicate_an_audit_batch() { + let fixture = Fixture::new(); + let repeated = json!({"timestamp_ms": 1, "tool_name": "same"}); + fixture.legacy_stream("mcp_audit", &[repeated.clone(), repeated.clone()]); + + // These are independently constructed owner handles over the same real + // memory engine scope. The stream decorator deterministically lets the + // competing opener win after this importer has observed its baseline. + let first = StoragePorts::from_storage(&fixture.storage, Arc::clone(fixture.storage.secrets())); + let competing = + StoragePorts::from_storage(&fixture.storage, Arc::clone(fixture.storage.secrets())); + let racing = CompetingAuditAppend { + inner: Arc::clone(&competing.streams), + raced: AtomicBool::new(false), + competing_batch: None, + }; + let migrations = Migrations::new(&first.documents, OWNER); + + fixture + .blocking + .block_on(migrate::migrate_audit_streams(&racing, &migrations)) + .unwrap(); + + assert_eq!(fixture.stream(AUDIT_STREAM), [repeated.clone(), repeated]); + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); +} + +#[test] +fn audit_import_keeps_its_source_when_a_different_batch_wins_the_offset() { + let fixture = Fixture::new(); + let source = json!({"timestamp_ms": 1, "tool_name": "source"}); + let competing = json!({"timestamp_ms": 9, "tool_name": "other"}); + fixture.legacy_stream("mcp_audit", std::slice::from_ref(&source)); + let storage = + StoragePorts::from_storage(&fixture.storage, Arc::clone(fixture.storage.secrets())); + let racing = CompetingAuditAppend { + inner: Arc::clone(&storage.streams), + raced: AtomicBool::new(false), + competing_batch: Some(vec![competing.clone()]), + }; + let migrations = Migrations::new(&storage.documents, OWNER); + + let error = fixture + .blocking + .block_on(migrate::migrate_audit_streams(&racing, &migrations)) + .unwrap_err(); + + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Conflict); + assert_eq!(fixture.stream("mcp_audit"), [source]); + assert_eq!(fixture.stream(AUDIT_STREAM), [competing]); + let progress = fixture + .blocking + .block_on(migrations.stream_progress(OWNER, "audit_streams_v2", "mcp_audit")) + .unwrap() + .unwrap(); + assert_eq!(progress.source_offset, 0); + assert_eq!(progress.target_offset, 0); + assert!( + !fixture + .blocking + .block_on(migrations.done(OWNER, "audit_streams_v2")) + .unwrap() + ); +} + +#[test] +fn audit_import_only_moves_exact_legacy_stream_names() { + let fixture = Fixture::new(); + let alias = json!({"timestamp_ms": 9}); + fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); + fixture.legacy_stream("mcp_audit_extra", std::slice::from_ref(&alias)); + fixture.legacy_stream("mcp_audit/archive", &[json!({"timestamp_ms": 2})]); + + fixture.migrate(); + + assert_eq!(fixture.stream(AUDIT_STREAM), [json!({"timestamp_ms": 1})]); + assert_eq!( + fixture.stream("mcp.audit/archive"), + [json!({"timestamp_ms": 2})] + ); + assert_eq!(fixture.stream("mcp_audit_extra"), [alias]); +} + +#[test] +fn audit_import_retries_after_an_empty_page_before_source_end() { + let fixture = Fixture::new(); + let entries = [json!({"timestamp_ms": 1})]; + fixture.legacy_stream("mcp_audit", &entries); + let streams = Arc::new(EmptyFirstRead { + inner: Arc::clone(fixture.storage.streams()), + fail: AtomicBool::new(true), + return_error: false, + }); + let documents = Arc::clone(fixture.storage.documents()); + let migrations = Migrations::new(&documents, OWNER); + + let first = fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)); + assert!( + first.is_err(), + "an empty page before the declared end is an error" + ); + assert_eq!(fixture.stream("mcp_audit"), entries); + assert_eq!(fixture.stream(AUDIT_STREAM), Vec::::new()); + + fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)) + .unwrap(); + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); + assert_eq!(fixture.stream(AUDIT_STREAM), entries); +} + +#[test] +fn audit_import_preserves_its_source_when_a_read_fails() { + let fixture = Fixture::new(); + let entries = [json!({"timestamp_ms": 1})]; + fixture.legacy_stream("mcp_audit", &entries); + let streams = EmptyFirstRead { + inner: Arc::clone(fixture.storage.streams()), + fail: AtomicBool::new(true), + return_error: true, + }; + let migrations = Migrations::new(fixture.storage.documents(), OWNER); + + let error = fixture + .blocking + .block_on(migrate::migrate_audit_streams(&streams, &migrations)) + .unwrap_err(); + + assert_eq!( + error.kind(), + tinystoragedrivers_types::ErrorKind::Unavailable + ); + assert_eq!(fixture.stream("mcp_audit"), entries); + assert_eq!(fixture.stream(AUDIT_STREAM), Vec::::new()); +} + +#[test] +fn audit_import_refuses_a_checkpoint_for_a_different_target() { + let fixture = Fixture::new(); + fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); + let streams = Arc::clone(fixture.storage.streams()); + let migrations = Migrations::new(fixture.storage.documents(), OWNER); + fixture + .blocking + .block_on(migrations.save_stream_progress(&StreamProgress { + owner: OWNER.to_owned(), + step: "audit_streams_v2".to_owned(), + source: "mcp_audit".to_owned(), + target: "mcp.audit/wrong".to_owned(), + source_offset: 0, + target_offset: 0, + })) + .unwrap(); + + let error = fixture + .blocking + .block_on(migrate::migrate_audit_source( + &*streams, + &migrations, + "mcp_audit", + AUDIT_STREAM, + )) + .unwrap_err(); + + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Conflict); + assert_eq!(fixture.stream("mcp_audit").len(), 1); +} + +#[test] +fn audit_import_refuses_a_target_that_changed_after_its_checkpoint() { + let fixture = Fixture::new(); + fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); + fixture.legacy_stream(AUDIT_STREAM, &[json!({"timestamp_ms": 9})]); + let streams = Arc::clone(fixture.storage.streams()); + let migrations = Migrations::new(fixture.storage.documents(), OWNER); + fixture + .blocking + .block_on(migrations.save_stream_progress(&StreamProgress { + owner: OWNER.to_owned(), + step: "audit_streams_v2".to_owned(), + source: "mcp_audit".to_owned(), + target: AUDIT_STREAM.to_owned(), + source_offset: 0, + target_offset: 0, + })) + .unwrap(); + + let error = fixture + .blocking + .block_on(migrate::migrate_audit_source( + &*streams, + &migrations, + "mcp_audit", + AUDIT_STREAM, + )) + .unwrap_err(); + + assert_eq!(error.kind(), tinystoragedrivers_types::ErrorKind::Conflict); + assert_eq!(fixture.stream("mcp_audit").len(), 1); + assert_eq!(fixture.stream(AUDIT_STREAM), [json!({"timestamp_ms": 9})]); +} + +#[test] +fn audit_import_rechecks_source_length_before_deleting_it() { + let fixture = Fixture::new(); + fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); + let streams = Arc::new(AppendDuringRead { + inner: Arc::clone(fixture.storage.streams()), + append: AtomicBool::new(true), + before_read: false, + missing_empty_streams: false, + }); + let documents = Arc::clone(fixture.storage.documents()); + let migrations = Migrations::new(&documents, OWNER); + + let first = fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)); + assert!( + first.is_err(), + "a source changed during import must be preserved" + ); + assert_eq!(fixture.stream("mcp_audit").len(), 2); + assert_eq!(fixture.stream(AUDIT_STREAM), [json!({"timestamp_ms": 1})]); + + fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)) + .unwrap(); + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); + assert_eq!( + fixture.stream(AUDIT_STREAM), + [json!({"timestamp_ms": 1}), json!({"timestamp_ms": 2})] + ); +} + +#[test] +fn audit_import_rejects_an_append_before_reading_the_captured_source_length() { + let fixture = Fixture::new(); + fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); + let streams = Arc::new(AppendDuringRead { + inner: Arc::clone(fixture.storage.streams()), + append: AtomicBool::new(true), + before_read: true, + missing_empty_streams: false, + }); + let documents = Arc::clone(fixture.storage.documents()); + let migrations = Migrations::new(&documents, OWNER); + + let first = fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)); + assert!( + first.is_err(), + "a source appended after its length read must be preserved" + ); + assert_eq!( + fixture.stream("mcp_audit"), + [json!({"timestamp_ms": 1}), json!({"timestamp_ms": 2})] + ); + assert_eq!(fixture.stream(AUDIT_STREAM), [json!({"timestamp_ms": 1})]); + + fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)) + .unwrap(); + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); + assert_eq!( + fixture.stream(AUDIT_STREAM), + [json!({"timestamp_ms": 1}), json!({"timestamp_ms": 2})] + ); +} + +#[test] +fn audit_import_treats_a_missing_target_stream_as_empty() { + let fixture = Fixture::new(); + fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); + let streams = Arc::new(AppendDuringRead { + inner: Arc::clone(fixture.storage.streams()), + append: AtomicBool::new(false), + before_read: false, + missing_empty_streams: true, + }); + let documents = Arc::clone(fixture.storage.documents()); + let migrations = Migrations::new(&documents, OWNER); + + fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)) + .unwrap(); + + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); + assert_eq!(fixture.stream(AUDIT_STREAM), [json!({"timestamp_ms": 1})]); +} + +#[test] +fn audit_import_accepts_a_source_removed_by_a_competing_opener() { + let fixture = Fixture::new(); + let entry = json!({"timestamp_ms": 1, "tool_name": "copied"}); + fixture.legacy_stream("mcp_audit", std::slice::from_ref(&entry)); + let storage = + StoragePorts::from_storage(&fixture.storage, Arc::clone(fixture.storage.secrets())); + let migrations = Migrations::new(&storage.documents, OWNER); + let racing = CompetingAuditDelete { + inner: Arc::clone(&storage.streams), + migrations: migrations.clone(), + raced: AtomicBool::new(false), + }; + + fixture + .blocking + .block_on(migrate::migrate_audit_streams(&racing, &migrations)) + .expect("a concurrently completed import is accepted"); + + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); + assert_eq!(fixture.stream(AUDIT_STREAM), [entry]); + assert!( + fixture + .blocking + .block_on(migrations.done(OWNER, "audit_streams_v2")) + .unwrap() + ); +} + +#[test] +fn audit_import_recovers_when_append_succeeds_but_progress_write_is_lost() { + let fixture = Fixture::new(); + let repeated = json!({"timestamp_ms": 1, "tool_name": "same"}); + fixture.legacy_stream("mcp_audit", &[repeated.clone(), repeated.clone()]); + let streams = Arc::new(FailAfterFirstAppend { + inner: Arc::clone(fixture.storage.streams()), + fail: AtomicBool::new(true), + }); + let documents = Arc::clone(fixture.storage.documents()); + let migrations = Migrations::new(&documents, OWNER); + + let first = fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)); + assert!( + first.is_err(), + "the simulated lost acknowledgement must fail the first run" + ); + fixture + .blocking + .block_on(migrate::migrate_audit_streams(&*streams, &migrations)) + .unwrap(); + + assert_eq!(fixture.stream(AUDIT_STREAM), [repeated.clone(), repeated]); + assert_eq!(fixture.stream("mcp_audit"), Vec::::new()); +} + +#[test] +fn migrating_again_changes_nothing() { + let fixture = Fixture::new(); + fixture.legacy("mcp_servers", "srv-1", v1_server()); + fixture.legacy_stream("mcp_audit", &[json!({"timestamp_ms": 1})]); + + fixture.migrate(); + let before = fixture.get(SERVERS, "srv-1").unwrap(); + fixture.migrate(); + + let after = fixture.get(SERVERS, "srv-1").unwrap(); + assert_eq!(before, after); + assert_eq!(fixture.stream(AUDIT_STREAM).len(), 1); +} diff --git a/crates/tinymcp/src/storage/migration_legacy.rs b/crates/tinymcp/src/storage/migration_legacy.rs new file mode 100644 index 00000000..788bf803 --- /dev/null +++ b/crates/tinymcp/src/storage/migration_legacy.rs @@ -0,0 +1,232 @@ +//! Pure conversions for records written by the previous storage schema. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::BTreeMap; + +use super::schema::{AUDIT_STREAM, doc_id}; + +/// A server document written by the previous `mcp_servers` collection. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(super) struct LegacyServerDocument { + /// The document key in the old collection. + pub(super) storage_id: String, + /// The old server body, including any fields unknown to this contract. + pub(super) body: LegacyServerBody, +} + +/// The previous release's server record shape. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(super) struct LegacyServerBody { + /// The server's stable owner ID. + pub server_id: String, + /// Its qualified registry name. + pub qualified_name: String, + /// Its display name. + pub display_name: String, + /// Optional user-facing description. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Optional registry icon URL. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon_url: Option, + /// The command launcher kind. + pub command_kind: String, + /// The command or executable. + pub command: String, + /// Arguments passed to the command. + #[serde(default)] + pub args: Vec, + /// Names of environment variables required by the server. + #[serde(default)] + pub env_keys: Vec, + /// Optional opaque configuration. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, + /// Installation timestamp in the old field. + pub installed_at: i64, + /// Optional last successful connection timestamp in the old field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_connected_at: Option, + /// Optional transport discriminator. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transport: Option, + /// Optional deployment URL for remote transport. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deployment_url: Option, + /// Whether the server is enabled when the field was present. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enabled: Option, + /// Whether the server came from a managed catalog when present. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub catalog_managed: Option, + /// Unrecognized fields retained verbatim by the conversion. + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// A server record in the current `mcp.servers` document shape. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(super) struct ServerDocument { + /// The composite-key-escaped document ID. + pub(super) id: String, + /// The current server body. + pub(super) body: ServerDocumentBody, +} + +/// The current owner document body for an installed MCP server. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub(super) struct ServerDocumentBody { + /// The server's stable owner ID. + pub server_id: String, + /// Its qualified registry name. + pub qualified_name: String, + /// Its display name. + pub display_name: String, + /// Optional user-facing description. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Optional registry icon URL. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon_url: Option, + /// The command launcher kind. + pub command_kind: String, + /// The command or executable. + pub command: String, + /// Arguments passed to the command. + #[serde(default)] + pub args: Vec, + /// Names of environment variables required by the server. + #[serde(default)] + pub env_keys: Vec, + /// Optional opaque configuration. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub config: Option, + /// Installation timestamp in Unix milliseconds. + pub installed_ms: i64, + /// Optional last successful connection timestamp in Unix milliseconds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_connected_ms: Option, + /// Optional transport discriminator. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transport: Option, + /// Optional deployment URL for remote transport. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub deployment_url: Option, + /// Whether the server is enabled when the field was present. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub enabled: Option, + /// Whether the server came from a managed catalog when present. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub catalog_managed: Option, + /// Unrecognized fields retained verbatim by the conversion. + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// Converts an old server record to its current collection ID and body. +/// +/// # Errors +/// +/// Returns a storage error when the old body is malformed or its ID cannot be +/// represented as a storage key. +pub(super) fn convert_legacy_server( + record: LegacyServerDocument, +) -> tinystoragedrivers_types::Result { + let body = record.body; + let id = doc_id(&[&body.server_id])?; + Ok(ServerDocument { + id, + body: ServerDocumentBody { + server_id: body.server_id, + qualified_name: body.qualified_name, + display_name: body.display_name, + description: body.description, + icon_url: body.icon_url, + command_kind: body.command_kind, + command: body.command, + args: body.args, + env_keys: body.env_keys, + config: body.config, + installed_ms: body.installed_at, + last_connected_ms: body.last_connected_at, + transport: body.transport, + deployment_url: body.deployment_url, + enabled: body.enabled, + catalog_managed: body.catalog_managed, + extra: body.extra, + }, + }) +} + +/// A qualified-name claim written by the previous collection. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct LegacyServerNameClaim { + /// The qualified name held by this claim. + pub qualified_name: String, + /// The server ID that owns the claim. + pub server_id: String, + /// Optional timestamp in the old field. + #[serde(default)] + pub claimed_at: Option, + /// Unknown fields retained by conversion. + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// A qualified-name claim in the current `mcp.server_names` collection. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct ServerNameClaim { + /// The composite-key-escaped ID, derived from `qualified_name`. + pub(super) id: String, + /// The current owner document body. + pub(super) body: ServerNameClaimBody, +} + +/// The current owner body for one qualified-name claim. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub(super) struct ServerNameClaimBody { + /// The qualified name held by this claim. + pub qualified_name: String, + /// The server ID that owns the claim. + pub server_id: String, + /// A missing legacy timestamp means the claim was already expired. + pub claimed_ms: i64, + /// Unknown fields retained by conversion. + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// Converts an old qualified-name claim into the current document shape. +/// +/// # Errors +/// +/// Returns a storage error when the qualified name cannot be represented as +/// a storage key. +pub(super) fn convert_legacy_server_name_claim( + claim: LegacyServerNameClaim, +) -> tinystoragedrivers_types::Result { + Ok(ServerNameClaim { + id: doc_id(&[&claim.qualified_name])?, + body: ServerNameClaimBody { + qualified_name: claim.qualified_name, + server_id: claim.server_id, + claimed_ms: claim.claimed_at.unwrap_or(0), + extra: claim.extra, + }, + }) +} + +/// Maps an old audit stream family to the current owner stream family. +/// +/// Only the exact legacy family and its slash-delimited descendants match. +#[must_use] +pub(super) fn legacy_audit_stream_target(source: &str) -> Option { + if source == "mcp_audit" { + Some(AUDIT_STREAM.to_owned()) + } else { + source + .strip_prefix("mcp_audit/") + .map(|suffix| format!("{AUDIT_STREAM}/{suffix}")) + } +} diff --git a/crates/tinymcp/src/storage/mod.rs b/crates/tinymcp/src/storage/mod.rs index 8a18c4a4..a155f3fb 100644 --- a/crates/tinymcp/src/storage/mod.rs +++ b/crates/tinymcp/src/storage/mod.rs @@ -10,11 +10,9 @@ //! | `SecretStore` | each server's environment values and OAuth bundle, and the key that keys the tool-cache fingerprints | //! //! The crate links no database client and picks no backend. A host hands over -//! [`StoragePorts`] (in process, the handles of its installed backend; across -//! the bus, the same port traits implemented by the storage bus client), or -//! installs a [`StorageProvider`] that does so per data directory. Without -//! one, a process-wide in-memory provider answers, which is the right shape -//! for tests and for a host that wants only its statically declared servers. +//! [`StoragePorts`] or installs a [`StorageProvider`] that supplies those +//! handles. Service construction fails until a host provides them; tests use +//! the TSD testkit memory backend explicitly. //! //! # The grant //! @@ -35,6 +33,9 @@ mod bus; #[cfg(test)] mod failing; mod grant; +mod local; +mod migrate; +mod migration_legacy; mod ports; mod provider; mod schema; @@ -43,16 +44,24 @@ mod schema; pub use bus::BusProvider; pub use grant::{CACHE_KEY_SECRET, ENV_SECRET_PREFIX, StorageGrant, collection_specs, grant}; pub use ports::StoragePorts; -pub use provider::{ - MemoryProvider, StorageProvider, install_provider, installed_provider, provider_installed, -}; +pub(crate) mod types { + //! Stable TSD v2 ports and portable value types used by MCP. + pub(crate) use tinystoragedrivers_api::{DocumentStore, DocumentStoreExt, SecretStore}; + pub(crate) use tinystoragedrivers_types::*; +} +pub(crate) use local::Repo; +#[cfg(test)] +pub(crate) use provider::MemoryProvider; #[cfg(test)] -pub(crate) use schema::SCHEMA_VERSION; -pub use schema::{AUDIT_STREAM, OWNER, storage_schema}; +pub(crate) use provider::shared_test_provider; +pub use provider::{StorageProvider, install_provider, installed_provider, provider_installed}; +pub use schema::{AUDIT_STREAM, OWNER}; pub(crate) use schema::{ REGISTRY_CACHE, REGISTRY_INDEX, REGISTRY_INDEX_STATE, SERVER_NAMES, SERVERS, TOOL_CACHE, doc_id, write_options, }; +#[cfg(test)] +pub(crate) use tinymcp_bus::storage::SCHEMA_VERSION; #[cfg(all(test, feature = "module"))] pub(crate) mod test_host; diff --git a/crates/tinymcp/src/storage/mod_tests.rs b/crates/tinymcp/src/storage/mod_tests.rs index 19d3998b..be38d057 100644 --- a/crates/tinymcp/src/storage/mod_tests.rs +++ b/crates/tinymcp/src/storage/mod_tests.rs @@ -10,7 +10,10 @@ use std::path::{Path, PathBuf}; fn dir(name: &str) -> PathBuf { std::env::temp_dir().join("tinymcp-test").join(name) } -use tinystoragedrivers_core::{Filter, MemoryStorage}; +use crate::storage::types::{CollectionSpec, Filter, Precondition, Scope}; +use std::sync::Arc; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_testkit::MemoryBackend as MemoryStorage; use crate::{AuditStore, Store}; use tinymcp_bus::NewMcpWriteRecord; @@ -32,14 +35,24 @@ fn the_grant_names_every_collection_the_specs_declare() { let specs = collection_specs(); let granted = grant(); let declared: Vec = specs.into_iter().map(|spec| spec.name).collect(); - assert_eq!(granted.collections, declared); + assert!( + declared + .iter() + .all(|name| granted.collections.contains(name)) + ); assert!( granted .searchable .iter() .all(|name| declared.contains(name)) ); - assert_eq!(granted.streams, [AUDIT_STREAM]); + assert!(granted.collections.contains(&"mcp_servers".to_owned())); + assert!( + granted + .collections + .contains(&"mcp_registry_index_state".to_owned()) + ); + assert_eq!(granted.streams, [AUDIT_STREAM, "mcp_audit", "mcp_audit/"]); assert!(granted.secrets.contains(&format!("{ENV_SECRET_PREFIX}*"))); assert!(granted.secrets.contains(&CACHE_KEY_SECRET.to_string())); } @@ -100,6 +113,47 @@ fn installed_servers_count_as_stored_state() { assert!(ports.has_state().unwrap()); } +#[test] +fn legacy_mcp_collections_and_audit_streams_count_as_stored_state() { + let backend = MemoryStorage::new(); + let scope = Scope::new("legacy-state-probe").unwrap(); + let storage = backend.for_scope(&scope).unwrap(); + let documents = Arc::clone(storage.documents()); + let streams = Arc::clone(storage.streams()); + let ports = StoragePorts::from_storage(&storage, Arc::clone(storage.secrets())); + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + + runtime.block_on(async { + documents + .ensure_collection(&CollectionSpec::new("mcp_servers")) + .await + .unwrap(); + documents + .put( + "mcp_servers", + "legacy-server", + serde_json::json!({"server_id": "legacy-server"}), + Precondition::Absent, + ) + .await + .unwrap(); + }); + assert!(ports.has_state().unwrap()); + + runtime.block_on(async { + streams + .append( + "mcp_audit/workspace/legacy", + serde_json::json!({"event": true}), + ) + .await + .unwrap(); + }); + assert!(ports.has_state().unwrap()); +} + #[test] fn the_memory_provider_answers_the_same_state_for_one_directory() { let provider = MemoryProvider::new(); @@ -143,20 +197,16 @@ fn an_installed_provider_replaces_the_default() { // A private slot, so this test cannot reroute the services other tests // build through the process-wide one. let slot = super::provider::ProviderSlot::new(); - let first = slot.current(); + assert!(slot.current().is_err()); + let first: std::sync::Arc = std::sync::Arc::new(MemoryProvider::new()); + slot.install(std::sync::Arc::clone(&first)); + assert!(std::sync::Arc::ptr_eq(&slot.current().unwrap(), &first)); let replacement: std::sync::Arc = std::sync::Arc::new(MemoryProvider::new()); slot.install(std::sync::Arc::clone(&replacement)); - assert!(std::sync::Arc::ptr_eq(&slot.current(), &replacement)); - assert!(!std::sync::Arc::ptr_eq(&slot.current(), &first)); -} - -#[test] -fn the_process_wide_provider_answers_for_a_directory() { - let ports = installed_provider() - .ports_for(&dir("process-wide")) - .unwrap(); - assert!(!ports.has_state().unwrap()); + let current = slot.current().unwrap(); + assert!(std::sync::Arc::ptr_eq(¤t, &replacement)); + assert!(!std::sync::Arc::ptr_eq(¤t, &first)); } #[test] @@ -184,13 +234,13 @@ fn the_memory_provider_refuses_a_relative_directory() { #[tokio::test] async fn failing_documents_refuse_every_call_except_declaring_collections() { use super::failing::FailingDocuments; - use tinystoragedrivers_core::{DocumentStore, Precondition, Query}; + use crate::storage::types::{DocumentStore, Precondition, Query}; let documents = FailingDocuments::default(); assert!( !documents .capabilities() - .contains(tinystoragedrivers_core::Capability::Transactions) + .contains(crate::storage::types::Capability::Transactions) ); for spec in collection_specs() { documents.ensure_collection(&spec).await.unwrap(); diff --git a/crates/tinymcp/src/storage/ports.rs b/crates/tinymcp/src/storage/ports.rs index de8fafb1..0d086939 100644 --- a/crates/tinymcp/src/storage/ports.rs +++ b/crates/tinymcp/src/storage/ports.rs @@ -3,12 +3,14 @@ use std::future::Future; use std::sync::{Arc, OnceLock}; -use tinystoragedrivers_core::{ - Blocking, DocumentStore, MemoryStorage, Scope, ScopedStorage, StorageBackend, StreamStore, -}; -use tinystoragedrivers_secrets::{MemorySecrets, SecretStore}; +#[cfg(test)] +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_api::{DocumentStore, SecretStore, Storage, StreamStore}; +use tinystoragedrivers_types::{ErrorKind, Filter, Result as StorageResult}; + +use super::grant::LEGACY_COLLECTIONS; +use super::local::{Blocking, MigrateOptions, Migrations}; -use super::grant::collection_specs; use super::schema::SERVERS; use crate::error::{Error, Result}; @@ -16,7 +18,7 @@ use crate::error::{Error, Result}; /// /// Cheap to clone: every field is a shared handle. The module's stores are /// synchronous, so each call runs its port future on one shared -/// [`Blocking`] bridge thread. +/// blocking bridge thread. #[derive(Clone)] pub struct StoragePorts { pub(crate) documents: Arc, @@ -53,7 +55,7 @@ impl StoragePorts { /// Uses a scoped backend handle for documents and streams, and `secrets` /// for secret values. #[must_use] - pub fn from_scoped(scoped: &ScopedStorage, secrets: Arc) -> Self { + pub fn from_storage(scoped: &Storage, secrets: Arc) -> Self { Self::new( Arc::clone(scoped.documents()), Arc::clone(scoped.streams()), @@ -66,8 +68,9 @@ impl StoragePorts { /// # Errors /// /// Returns [`Error::Store`] when the scope cannot be opened. - pub fn memory() -> Result { - Self::memory_scoped(&MemoryStorage::new(), "local") + #[cfg(test)] + pub(crate) fn memory() -> Result { + Self::memory_scoped(&tinystoragedrivers_testkit::MemoryBackend::new(), "local") } /// The `scope` of a shared in-memory backend. @@ -79,12 +82,20 @@ impl StoragePorts { /// # Errors /// /// Returns [`Error::Store`] when the scope is invalid. - pub fn memory_scoped(backend: &MemoryStorage, scope: &str) -> Result { - let scope = Scope::new(scope).map_err(|source| Error::store("opening a scope", source))?; + #[cfg(test)] + pub(crate) fn memory_scoped( + backend: &tinystoragedrivers_testkit::MemoryBackend, + scope: &str, + ) -> Result { + let scope = tinystoragedrivers_types::Scope::new(scope) + .map_err(|source| Error::store("opening a scope", source))?; let scoped = backend .for_scope(&scope) .map_err(|source| Error::store("opening a scope", source))?; - Ok(Self::from_scoped(&scoped, Arc::new(MemorySecrets::new()))) + Ok(Self::from_storage( + &scoped, + Arc::new(tinystoragedrivers_secrets::MemorySecrets::new()), + )) } /// Asks the documents port for the collections [`grant`](super::grant) @@ -95,9 +106,12 @@ impl StoragePorts { /// Returns [`Error::Store`] when the port refuses a collection. pub fn prepare(&self) -> Result<()> { self.run("declaring the collections", |ports| async move { - for spec in collection_specs() { - ports.documents.ensure_collection(&spec).await?; - } + let schema = super::schema::storage_schema()?; + schema + .migrate(&ports.documents, &MigrateOptions::default()) + .await?; + let migration = Migrations::new(&ports.documents, super::schema::OWNER); + super::migrate::migrate_audit_streams(&*ports.streams, &migration).await?; Ok(()) }) } @@ -110,22 +124,33 @@ impl StoragePorts { /// Returns [`Error::Store`] when the port fails. pub fn has_state(&self) -> Result { self.run("checking for stored state", |ports| async move { - let servers = ports - .documents - .count(SERVERS, &tinystoragedrivers_core::Filter::default()) - .await - .or_else(|error| { - // A collection never declared here holds nothing, and the - // probe must not create it; any other failure (an - // unavailable or refusing port) is not "no installs". - if error.kind() == tinystoragedrivers_core::ErrorKind::NotFound { - Ok(0) - } else { - Err(error) - } - })?; + for collection in std::iter::once(SERVERS).chain(LEGACY_COLLECTIONS) { + let count = ports + .documents + .count(collection, &Filter::default()) + .await + .or_else(|error| { + // A collection never declared here holds nothing, and + // the probe must not create it; any other failure (an + // unavailable or refusing port) is not "no installs". + if error.kind() == ErrorKind::NotFound { + Ok(0) + } else { + Err(error) + } + })?; + if count > 0 { + return Ok(true); + } + } let audited = ports.streams.len(super::schema::AUDIT_STREAM).await?; - Ok(servers > 0 || audited > 0) + if audited > 0 { + return Ok(true); + } + let legacy_audit = ports.streams.streams("mcp_audit").await?; + Ok(legacy_audit + .iter() + .any(|name| name == "mcp_audit" || name.starts_with("mcp_audit/"))) }) } @@ -138,7 +163,7 @@ impl StoragePorts { ) -> Result where T: Send + 'static, - F: Future> + Send + 'static, + F: Future> + Send + 'static, { let future = work(self.clone()); bridge() @@ -150,7 +175,7 @@ impl StoragePorts { } /// The one bridge thread every store in the process shares. -fn bridge() -> tinystoragedrivers_core::Result<&'static Blocking> { +fn bridge() -> StorageResult<&'static Blocking> { static BRIDGE: OnceLock = OnceLock::new(); if let Some(bridge) = BRIDGE.get() { return Ok(bridge); diff --git a/crates/tinymcp/src/storage/provider.rs b/crates/tinymcp/src/storage/provider.rs index 2b815273..953f1719 100644 --- a/crates/tinymcp/src/storage/provider.rs +++ b/crates/tinymcp/src/storage/provider.rs @@ -1,98 +1,70 @@ -//! Choosing the ports for a data directory. +//! Installing the host-selected storage ports. -use std::collections::HashMap; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::sync::{Arc, OnceLock}; use parking_lot::Mutex; -use tinystoragedrivers_core::MemoryStorage; use super::StoragePorts; -use crate::error::Result; +use crate::error::{Error, Result}; /// Hands the module its storage ports, one set per data directory. -/// -/// A host that serves several directories (profiles, tenants) maps each to -/// its own scope; the module only asks. pub trait StorageProvider: Send + Sync + std::fmt::Debug { - /// The ports for `data_dir`. Calling it again for the same directory - /// answers the same state. + /// Ports for `data_dir`, already bound by the host to the correct scope. /// /// # Errors - /// - /// Returns [`crate::Error::Store`] when the directory has no storage. + /// Returns [`Error::Store`] when storage cannot be opened. fn ports_for(&self, data_dir: &Path) -> Result; -} - -/// An in-memory provider: one backend, one scope per directory. -/// -/// State lives as long as the provider, so reopening a directory in the same -/// process finds what was written. Nothing is written to disk. A directory -/// must be an absolute path, as everywhere else the module takes one. -#[derive(Debug, Default)] -pub struct MemoryProvider { - backend: MemoryStorage, - opened: Mutex>, -} -impl MemoryProvider { - /// An empty provider. - #[must_use] - pub fn new() -> Self { - Self::default() - } -} - -impl StorageProvider for MemoryProvider { - fn ports_for(&self, data_dir: &Path) -> Result { - if !data_dir.is_absolute() { - return Err(crate::Error::invalid_argument( - "a data directory must be a non-empty absolute path", - )); - } - // Keyed by the original path: a lossy string would merge distinct - // directories whose names differ only in invalid UTF-8 bytes. - let key = data_dir.to_path_buf(); - let mut opened = self.opened.lock(); - if let Some(ports) = opened.get(&key) { - return Ok(ports.clone()); - } - let scope = format!( - "dir-{}", - crate::registry::store::hex_digest(&path_bytes(&key)) - ); - let ports = StoragePorts::memory_scoped(&self.backend, &scope)?; - opened.insert(key, ports.clone()); - Ok(ports) + /// Ports for a service that has no configured data directory. + /// + /// Hosts that support ephemeral or static-only services must provide an + /// explicit storage binding. There is no implicit in-memory fallback. + /// + /// # Errors + /// Returns [`Error::Store`] when the host has no default binding. + fn default_ports(&self) -> Result { + Err(Error::store( + "opening storage without a data directory", + crate::storage::types::StorageError::unavailable( + "the host did not provide a default storage binding", + ), + )) } } -/// The slot holding the provider services are built with. -#[derive(Debug)] +/// The slot holding the host provider services are built with. +#[derive(Debug, Default)] pub(crate) struct ProviderSlot { - provider: Mutex>, - explicit: std::sync::atomic::AtomicBool, + provider: Mutex>>, } impl ProviderSlot { - /// A slot holding a fresh in-memory provider. + /// An empty slot; the host must install its backend before service setup. pub(crate) fn new() -> Self { - Self { - provider: Mutex::new(Arc::new(MemoryProvider::new())), - explicit: std::sync::atomic::AtomicBool::new(false), - } + Self::default() } /// Replaces the provider. pub(crate) fn install(&self, provider: Arc) { - *self.provider.lock() = provider; - self.explicit - .store(true, std::sync::atomic::Ordering::SeqCst); + *self.provider.lock() = Some(provider); } - /// The current provider. - pub(crate) fn current(&self) -> Arc { - Arc::clone(&self.provider.lock()) + /// Whether the host supplied a provider. + pub(crate) fn is_installed(&self) -> bool { + self.provider.lock().is_some() + } + + /// The current provider, failing closed when none has been installed. + pub(crate) fn current(&self) -> Result> { + self.provider.lock().clone().ok_or_else(|| { + Error::store( + "opening the host storage provider", + crate::storage::types::StorageError::unavailable( + "the host has not installed storage ports", + ), + ) + }) } } @@ -102,37 +74,81 @@ fn slot() -> &'static ProviderSlot { } /// Makes `provider` the process's storage, for every service built afterwards. -/// -/// A host calls this once at startup, before building a service. pub fn install_provider(provider: Arc) { slot().install(provider); } -/// Whether a host installed a provider, as opposed to the in-memory default. +/// Whether the host installed storage ports. #[must_use] pub fn provider_installed() -> bool { - slot().explicit.load(std::sync::atomic::Ordering::SeqCst) + slot().is_installed() } -/// The provider services are built with: the installed one, or the -/// process-wide in-memory provider. -#[must_use] -pub fn installed_provider() -> Arc { +/// The host provider services are built with. +/// +/// # Errors +/// Returns [`Error::Store`] before the host installs its storage provider. +pub fn installed_provider() -> Result> { slot().current() } -/// The bytes of a path, without lossy conversion. -fn path_bytes(path: &Path) -> Vec { - #[cfg(unix)] - { - std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str()).to_vec() +#[cfg(test)] +pub(crate) use memory::MemoryProvider; + +#[cfg(test)] +pub(crate) fn shared_test_provider() -> Arc { + static PROVIDER: OnceLock> = OnceLock::new(); + PROVIDER + .get_or_init(|| Arc::new(MemoryProvider::new())) + .clone() +} + +#[cfg(test)] +mod memory { + //! Explicit test-only memory provider. + + use parking_lot::Mutex; + use std::collections::HashMap; + use std::path::{Path, PathBuf}; + use tinystoragedrivers_testkit::MemoryBackend; + + use super::*; + + /// An in-memory provider used only by `TinyMCP`'s tests. + #[derive(Debug, Default)] + pub(crate) struct MemoryProvider { + backend: MemoryBackend, + opened: Mutex>, + } + + impl MemoryProvider { + /// An empty provider. + #[must_use] + pub(crate) fn new() -> Self { + Self::default() + } } - #[cfg(not(unix))] - { - // Windows paths are UTF-16; encode the code units so distinct - // (even ill-formed) names stay distinct. - std::os::windows::ffi::OsStrExt::encode_wide(path.as_os_str()) - .flat_map(u16::to_le_bytes) - .collect() + + impl StorageProvider for MemoryProvider { + fn ports_for(&self, data_dir: &Path) -> Result { + if !data_dir.is_absolute() { + return Err(crate::Error::invalid_argument( + "a data directory must be a non-empty absolute path", + )); + } + let key = data_dir.to_path_buf(); + let mut opened = self.opened.lock(); + if let Some(ports) = opened.get(&key) { + return Ok(ports.clone()); + } + let label = format!("test-{}", opened.len()); + let ports = StoragePorts::memory_scoped(&self.backend, &label)?; + opened.insert(key, ports.clone()); + Ok(ports) + } + + fn default_ports(&self) -> Result { + StoragePorts::memory_scoped(&self.backend, "test-default") + } } } diff --git a/crates/tinymcp/src/storage/schema.rs b/crates/tinymcp/src/storage/schema.rs index ba210dcd..60376bed 100644 --- a/crates/tinymcp/src/storage/schema.rs +++ b/crates/tinymcp/src/storage/schema.rs @@ -1,11 +1,38 @@ -//! The module's storage declaration lives in the contract crate -//! (`tinymcp_bus::storage`); this path re-exports it so the rest of the crate -//! and its callers keep one definition. - -#[cfg(test)] -pub(crate) use tinymcp_bus::storage::SCHEMA_VERSION; -pub use tinymcp_bus::storage::{AUDIT_STREAM, OWNER, storage_schema}; -pub(crate) use tinymcp_bus::storage::{ - REGISTRY_CACHE, REGISTRY_INDEX, REGISTRY_INDEX_STATE, SERVER_NAMES, SERVERS, TOOL_CACHE, - doc_id, write_options, -}; +//! TinyMCP-owned migrations composed with the pure bus collection declarations. + +use crate::storage::local::{Owner, Schema, ScopeClass}; +use tinymcp_bus::storage::{SCHEMA_VERSION, collection_specs}; + +/// Owner of all MCP documents and migration progress. +pub const OWNER: &str = "mcp"; +/// Audit stream storing tool write records. +pub const AUDIT_STREAM: &str = "mcp.audit"; +pub(crate) const SERVERS: &str = "mcp.servers"; +pub(crate) const SERVER_NAMES: &str = "mcp.server_names"; +pub(crate) const REGISTRY_CACHE: &str = "mcp.registry_cache"; +pub(crate) const TOOL_CACHE: &str = "mcp.tool_cache"; +pub(crate) const REGISTRY_INDEX: &str = "mcp.registry_index"; +pub(crate) const REGISTRY_INDEX_STATE: &str = "mcp.registry_index_state"; + +/// MCP's owned collection and schema migrations. +pub(crate) fn storage_schema() -> tinystoragedrivers_types::Result { + let mut schema = Schema::new(Owner::new(OWNER)?); + for spec in collection_specs() { + schema = schema.collection_with(SCHEMA_VERSION, spec, ScopeClass::Tenant); + } + for step in super::migrate::steps() { + schema = schema.step(step); + } + Ok(schema) +} + +/// A document id made from escaped key components. +pub(crate) fn doc_id(parts: &[&str]) -> tinystoragedrivers_types::Result { + super::local::schema::composite_key(parts).map(|key| key.as_str().to_owned()) +} + +/// The schema version every MCP document write declares. +#[must_use] +pub(crate) fn write_options() -> tinystoragedrivers_types::WriteOptions { + tinystoragedrivers_types::WriteOptions::new().schema(SCHEMA_VERSION) +} diff --git a/crates/tinymcp/src/storage/test_host.rs b/crates/tinymcp/src/storage/test_host.rs index bfead929..f2e0957c 100644 --- a/crates/tinymcp/src/storage/test_host.rs +++ b/crates/tinymcp/src/storage/test_host.rs @@ -3,12 +3,12 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; - use tinybus::{Connection, transport::memory::MemoryBus}; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_busproxy::StorageServer; use tinystoragedrivers_busproxy::{PerCallerEndpoint, ServedStorage, serve}; -use tinystoragedrivers_client::StorageServer; -use tinystoragedrivers_core::{MemoryStorage, Scope, StorageBackend}; -use tinystoragedrivers_secrets::MemorySecrets; +use tinystoragedrivers_testkit::MemoryBackend as MemoryStorage; +use tinystoragedrivers_types::Scope; /// Keeps the served objects registered while it lives. pub(crate) struct TestHost { @@ -29,10 +29,7 @@ pub(crate) async fn serve_storage( .await .unwrap(); let storage = backend.for_scope(&Scope::new(scope).unwrap()).unwrap(); - let secrets = Arc::new(MemorySecrets::new()); - let endpoint = PerCallerEndpoint::new(move |_sender| { - Some(StorageServer::new(storage.clone()).with_secrets(secrets.clone())) - }); + let endpoint = PerCallerEndpoint::new(move |_sender| Some(StorageServer::new(storage.clone()))); let served = serve(&connection, Arc::new(endpoint)).await.unwrap(); TestHost { _connection: connection, diff --git a/crates/tinymcp/src/tinybus_module/config.rs b/crates/tinymcp/src/tinybus_module/config.rs index 516d8fc4..92887e24 100644 --- a/crates/tinymcp/src/tinybus_module/config.rs +++ b/crates/tinymcp/src/tinybus_module/config.rs @@ -10,7 +10,8 @@ use tinymcp_bus::McpClientConfig; /// /// Arrives as JSON in the loader's configuration slot. A host that configures /// nothing supplies either the empty object or `null`, so both decode to the -/// same thing: a working module with no servers and an in-memory store. +/// same empty configuration. Loading the module still requires the host to +/// provision its storage callback; the module never falls back to memory. /// /// `#[serde(default)]` covers the empty object, because it fills in absent /// *fields*. It does not cover `null`, which is a whole document of the wrong @@ -18,11 +19,14 @@ use tinymcp_bus::McpClientConfig; /// `null` would fail to load for exactly the host that asked nothing of it. #[derive(Debug, Clone, Default, Serialize)] pub struct ModuleConfig { + /// The host-provisioned private storage callback destination for this + /// module instance. It is not a scope selector; the host binding chooses + /// the scope before the module connects. + pub storage_callback: Option, /// Where the store and the audit log live. /// - /// `None` keeps both in memory, which is what a host that only wants the - /// statically declared servers should pass — there is nothing to persist, - /// and creating files for it would leave state nobody asked for. + /// `None` leaves the storage root unspecified. Storage itself is supplied + /// separately through [`ModuleConfig::storage_callback`]. pub data_dir: Option, /// The servers, credentials, identity, and proxy. pub client: McpClientConfig, @@ -35,6 +39,7 @@ pub struct ModuleConfig { #[derive(Deserialize, Default)] #[serde(default)] struct Wire { + storage_callback: Option, data_dir: Option, client: McpClientConfig, } @@ -49,6 +54,7 @@ impl<'de> Deserialize<'de> for ModuleConfig { let wire = Option::::deserialize(deserializer)?.unwrap_or_default(); Ok(Self { + storage_callback: wire.storage_callback, data_dir: wire.data_dir, client: wire.client, }) diff --git a/crates/tinymcp/src/tinybus_module/directories/mod_tests.rs b/crates/tinymcp/src/tinybus_module/directories/mod_tests.rs index 3b8b2664..bc0b5803 100644 --- a/crates/tinymcp/src/tinybus_module/directories/mod_tests.rs +++ b/crates/tinymcp/src/tinybus_module/directories/mod_tests.rs @@ -17,7 +17,7 @@ use tinymcp_bus::{ use super::MAX_OPEN_DIRECTORIES; use crate::registry::SupervisorConfig; -use crate::tinybus_module::{McpService, ModuleConfig, test_linked_module}; +use crate::tinybus_module::{ModuleConfig, test_linked_module}; /// Owns the host and broker alongside a connection so the linked test module /// stays alive and receives the same attestation as production-linked code. @@ -47,9 +47,7 @@ async fn serve_root(config: &ModuleConfig) -> TestBus { // Installed once: the slot is process-wide, so replacing it per test would // swap the store out from under tests running in parallel. INSTALL_ONCE.call_once(|| { - crate::storage::install_provider( - std::sync::Arc::new(crate::storage::MemoryProvider::new()), - ); + crate::storage::install_provider(crate::storage::shared_test_provider()); }); let host = tinybus::module::ModuleHost::new(broker.clone()); let module = test_linked_module().unwrap(); @@ -82,7 +80,7 @@ async fn serve_untrusted_root(config: &ModuleConfig) -> Connection { .await .unwrap(); let service = std::sync::Arc::new( - McpService::new(config) + crate::tinybus_module::test_service(config) .unwrap() .with_opener(connection.clone(), config, SupervisorConfig::default()) .unwrap(), @@ -359,6 +357,7 @@ async fn reconfiguring_the_load_time_directory_keeps_the_root_opener() { mock_static_server("beta provider").await, ); let config = ModuleConfig { + storage_callback: None, client: configured_client("alpha", &alpha_url), ..config_in(root_dir.path()) }; @@ -514,6 +513,7 @@ async fn root_transition_status_is_nonblocking_before_tree_writer_registration() let alpha_url = mock_static_server_with_gate("alpha provider", Some(Arc::clone(&gate))).await; let beta_url = mock_static_server("beta provider").await; let config = ModuleConfig { + storage_callback: None, client: configured_client("alpha", &alpha_url), ..config_in(root_dir.path()) }; @@ -930,6 +930,7 @@ async fn closing_the_root_resets_its_configuration_and_keeps_the_opener_alive() let root_dir = tempfile::tempdir().unwrap(); let endpoint = mock_static_server("signed-in provider").await; let config = ModuleConfig { + storage_callback: None, client: configured_client("signed-in", &endpoint), ..config_in(root_dir.path()) }; @@ -1119,7 +1120,7 @@ async fn a_service_that_is_not_a_root_refuses_to_open() { connection .serve_at( "/ai/tinyhumans/tinymcp/Plain".try_into().unwrap(), - McpService::new(&ModuleConfig::default()).unwrap(), + crate::tinybus_module::test_service(&ModuleConfig::default()).unwrap(), ) .await .unwrap(); diff --git a/crates/tinymcp/src/tinybus_module/directories/types.rs b/crates/tinymcp/src/tinybus_module/directories/types.rs index ae77856b..fcc2f2e5 100644 --- a/crates/tinymcp/src/tinybus_module/directories/types.rs +++ b/crates/tinymcp/src/tinybus_module/directories/types.rs @@ -550,7 +550,14 @@ impl DirectoryOpener { client: McpClientConfig, ) -> Result { let stdio = crate::tinybus_module::stdio_launchers(Some(&self.connection), &client); - McpService::new_with_stdio(&ModuleConfig { data_dir, client }, stdio) + McpService::new_with_stdio( + &ModuleConfig { + data_dir, + storage_callback: None, + client, + }, + stdio, + ) } async fn configured_service( diff --git a/crates/tinymcp/src/tinybus_module/directories/types_tests.rs b/crates/tinymcp/src/tinybus_module/directories/types_tests.rs index 1c950e85..108b04b9 100644 --- a/crates/tinymcp/src/tinybus_module/directories/types_tests.rs +++ b/crates/tinymcp/src/tinybus_module/directories/types_tests.rs @@ -12,7 +12,7 @@ async fn connected_service() -> (Connection, Arc) { let connection = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); - let service = Arc::new(McpService::new(&ModuleConfig::default()).unwrap()); + let service = Arc::new(crate::tinybus_module::test_service(&ModuleConfig::default()).unwrap()); connection .serve_at( "/ai/tinyhumans/tinymcp/Test".try_into().unwrap(), @@ -143,7 +143,7 @@ async fn successful_unserve_completes_cleanup_and_removes_the_object() { async fn scheduled_serve_registers_and_replaces_before_completing_transition() { let (connection, _) = connected_service().await; let path: tinybus::ObjectPath = "/ai/tinyhumans/tinymcp/Lifecycle".try_into().unwrap(); - let original = Arc::new(McpService::new(&ModuleConfig::default()).unwrap()); + let original = Arc::new(crate::tinybus_module::test_service(&ModuleConfig::default()).unwrap()); let first_status = Arc::new(Mutex::new(HashMap::from([( "t1".to_string(), TransitionStatus::Pending, @@ -174,7 +174,8 @@ async fn scheduled_serve_registers_and_replaces_before_completing_transition() { TransitionStatus::Complete ); - let replacement = Arc::new(McpService::new(&ModuleConfig::default()).unwrap()); + let replacement = + Arc::new(crate::tinybus_module::test_service(&ModuleConfig::default()).unwrap()); let replacement_status = Arc::new(Mutex::new(HashMap::from([( "t2".to_string(), TransitionStatus::Pending, diff --git a/crates/tinymcp/src/tinybus_module/mod.rs b/crates/tinymcp/src/tinybus_module/mod.rs index 53f738dc..bd6c0a33 100644 --- a/crates/tinymcp/src/tinybus_module/mod.rs +++ b/crates/tinymcp/src/tinybus_module/mod.rs @@ -30,6 +30,11 @@ mod service; pub use config::ModuleConfig; pub use service::McpService; +#[cfg(test)] +pub(crate) fn test_service(config: &ModuleConfig) -> crate::Result { + McpService::with_provider(config, Arc::new(crate::storage::MemoryProvider::new())) +} + use std::sync::Arc; use tinybus::{Connection, Result as TinyBusResult}; use tinymcp_bus::names; @@ -55,37 +60,39 @@ pub(super) async fn setup(connection: Connection, config: ModuleConfig) -> TinyB // // Directory operations (`Open`, `OpenConfigured`, `HasStoredState`) build // services over the installed provider whatever the load-time `data_dir` - // was, so a host with no root directory still needs host storage. There the - // storage is best-effort: a root with nothing to persist keeps working - // without it, and the failure is logged rather than failing the load. - let provider = if crate::storage::provider_installed() { - None - } else { - host_storage_for(connection.clone(), &config).await? - }; + // was, so even a static-only module needs host storage. Missing storage is + // a load failure; silently continuing in memory would lose state. + let provider = provider_for_setup( + connection.clone(), + &config, + crate::storage::provider_installed(), + ) + .await?; if let Some(provider) = provider { crate::storage::install_provider(provider); } setup_over_installed_storage(connection, config).await } -/// The host-storage provider to install for `config`, if one can be had. -/// -/// `None` means the host has no storage to give a root that persists nothing, -/// so directory operations stay on the in-memory default. +async fn provider_for_setup( + connection: Connection, + config: &ModuleConfig, + provider_installed: bool, +) -> TinyBusResult>> { + if provider_installed { + Ok(None) + } else { + host_storage_for(connection, config).await + } +} + +/// The host-storage provider to install for `config`. pub(super) async fn host_storage_for( connection: Connection, config: &ModuleConfig, ) -> TinyBusResult>> { - match bus_provider(connection).await { + match bus_provider(connection, config).await { Ok(provider) => Ok(Some(provider)), - Err(error) if config.data_dir.is_none() => { - tracing::warn!( - %error, - "tinymcp: host storage unavailable; directory operations stay in memory" - ); - Ok(None) - } Err(error) => Err(error), } } @@ -93,8 +100,15 @@ pub(super) async fn host_storage_for( /// The provider that reaches the host's storage over `connection`. pub(super) async fn bus_provider( connection: Connection, + config: &ModuleConfig, ) -> TinyBusResult> { - let provider = crate::storage::BusProvider::connect(connection) + let destination = config + .storage_callback + .as_deref() + .ok_or_else(|| tinybus::Error::failed("tinymcp has no host storage callback"))?; + let destination = tinybus::BusName::new(destination) + .map_err(|_| tinybus::Error::failed("tinymcp has an invalid host storage callback"))?; + let provider = crate::storage::BusProvider::connect_at(connection, destination) .await .map_err(|error| { tinybus::Error::failed(format!("tinymcp could not reach host storage: {error}")) @@ -111,11 +125,19 @@ pub(super) fn stdio_launchers( connection: Option<&Connection>, client: &tinymcp_bus::McpClientConfig, ) -> crate::transport::stdio::jailed::StdioLaunchers { - use crate::transport::stdio::jailed::{BusJail, JailedSpawner, StdioLaunchers}; + use crate::transport::stdio::jailed::BusJail; + stdio_launchers_for_bus(client, connection.map(BusJail::connect)) +} + +fn stdio_launchers_for_bus( + client: &tinymcp_bus::McpClientConfig, + bus: Option>, +) -> crate::transport::stdio::jailed::StdioLaunchers { + use crate::transport::stdio::jailed::{JailedSpawner, StdioLaunchers}; let Some(sandbox) = client.stdio_sandbox.clone() else { return StdioLaunchers::new(); }; - if let Some(Ok(bus)) = connection.map(BusJail::connect) { + if let Some(Ok(bus)) = bus { return StdioLaunchers::sandboxed(Arc::new(JailedSpawner::new(Arc::new(bus), sandbox))); } tracing::warn!("a stdio sandbox is configured but the sandbox module is not reachable"); @@ -128,14 +150,16 @@ pub(super) async fn setup_over_installed_storage( config: ModuleConfig, ) -> TinyBusResult<()> { let supervisor = SupervisorConfig::default(); + let stdio = stdio_launchers(Some(&connection), &config.client); let service = Arc::new( - McpService::new_with_stdio(&config, stdio_launchers(Some(&connection), &config.client)) + McpService::new_with_stdio(&config, stdio) .map_err(|error| tinybus::Error::failed(format!("tinymcp could not start: {error}")))? .with_maintenance(supervisor.clone()) .await .with_opener(connection.clone(), &config, supervisor) .map_err(|error| tinybus::Error::failed(format!("tinymcp could not start: {error}")))?, ); + let service = Arc::new(service); service.register_root(); diff --git a/crates/tinymcp/src/tinybus_module/mod_tests.rs b/crates/tinymcp/src/tinybus_module/mod_tests.rs index 9dae3f5b..042ce733 100644 --- a/crates/tinymcp/src/tinybus_module/mod_tests.rs +++ b/crates/tinymcp/src/tinybus_module/mod_tests.rs @@ -17,6 +17,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use crate::storage::StorageProvider; use tinybus::service::Interface; use super::config::ModuleConfig; @@ -26,7 +27,7 @@ use tinymcp_bus::{McpClientConfig, McpServerConfig, names}; /// A service over nothing, for inspecting its interface. fn service() -> McpService { - McpService::new(&ModuleConfig::default()).expect("the service builds") + super::test_service(&ModuleConfig::default()).expect("the service builds") } // --------------------------------------------------------------------------- @@ -189,7 +190,8 @@ async fn prepare_bridge_tools_returns_the_owner_declarations() { #[tokio::test] async fn the_stored_state_probe_reports_installs_without_creating_any() { let requested = tempfile::tempdir().unwrap(); - let service = service(); + let provider = std::sync::Arc::new(crate::storage::MemoryProvider::new()); + let service = McpService::with_provider(&ModuleConfig::default(), provider.clone()).unwrap(); assert_eq!( ok( @@ -201,9 +203,7 @@ async fn the_stored_state_probe_reports_installs_without_creating_any() { json!(false) ); - let ports = crate::storage::installed_provider() - .ports_for(requested.path()) - .unwrap(); + let ports = provider.ports_for(requested.path()).unwrap(); crate::Store::open(ports) .unwrap() .insert_server(&remote_install("srv-1", "http://127.0.0.1:1/")) @@ -252,6 +252,7 @@ fn an_absent_configuration_decodes_to_a_working_default() { let config: ModuleConfig = serde_json::from_str("{}").expect("the empty object decodes"); assert_eq!(config.data_dir, None); + assert_eq!(config.storage_callback, None); assert_eq!(config.client.servers.len(), 0); assert!(config.client.enabled); } @@ -260,6 +261,7 @@ fn an_absent_configuration_decodes_to_a_working_default() { fn a_configuration_round_trips() { let config = ModuleConfig { data_dir: Some("/data/tinymcp".into()), + storage_callback: Some("ai.tinyhumans.storage.mcp-123".into()), client: McpClientConfig { servers: vec![McpServerConfig { name: "weather".into(), @@ -274,6 +276,7 @@ fn a_configuration_round_trips() { let decoded: ModuleConfig = serde_json::from_value(encoded).unwrap(); assert_eq!(decoded.data_dir, config.data_dir); + assert_eq!(decoded.storage_callback, config.storage_callback); assert_eq!(decoded.client.servers.len(), 1); } @@ -305,7 +308,7 @@ impl crate::storage::StorageProvider for RefusingProvider { ) -> crate::Result { Err(crate::Error::store( "opening storage", - tinystoragedrivers_core::StorageError::unavailable("no storage here"), + crate::storage::types::StorageError::unavailable("no storage here"), )) } } @@ -315,6 +318,7 @@ fn a_service_whose_provider_has_no_storage_fails_to_build() { let error = McpService::with_provider( &ModuleConfig { data_dir: Some(std::path::PathBuf::from("/srv/mcp")), + storage_callback: None, client: McpClientConfig::default(), }, std::sync::Arc::new(RefusingProvider), @@ -324,29 +328,33 @@ fn a_service_whose_provider_has_no_storage_fails_to_build() { } #[test] -fn a_service_without_a_data_directory_never_asks_the_provider() { - McpService::with_provider( +fn a_static_service_requires_host_storage_even_without_a_data_directory() { + let error = McpService::with_provider( &ModuleConfig::default(), std::sync::Arc::new(RefusingProvider), ) - .expect("an in-memory service needs no provider"); + .expect_err("a host must bind storage for a static-only service"); + assert!(matches!(error, crate::Error::Store { .. }), "{error}"); } #[test] fn a_service_with_a_data_directory_creates_its_stores() { let directory = tempfile::tempdir().unwrap(); + let provider = std::sync::Arc::new(crate::storage::MemoryProvider::new()); - let service = McpService::new(&ModuleConfig { - data_dir: Some(directory.path().to_path_buf()), - client: McpClientConfig::default(), - }) + let service = McpService::with_provider( + &ModuleConfig { + data_dir: Some(directory.path().to_path_buf()), + storage_callback: None, + client: McpClientConfig::default(), + }, + provider.clone(), + ) .expect("the service builds"); // The service's stores write through the provider's ports for the // directory, so what it records is what a state probe then finds. - let ports = crate::storage::installed_provider() - .ports_for(directory.path()) - .unwrap(); + let ports = provider.ports_for(directory.path()).unwrap(); assert!(!ports.has_state().unwrap()); service .dynamic() @@ -358,8 +366,9 @@ fn a_service_with_a_data_directory_creates_its_stores() { #[test] fn a_service_registers_the_statically_declared_servers() { - let service = McpService::new(&ModuleConfig { + let service = super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "weather".into(), @@ -378,11 +387,16 @@ fn a_service_registers_the_statically_declared_servers() { #[test] fn a_service_reopens_an_existing_store() { let directory = tempfile::tempdir().unwrap(); + let provider = std::sync::Arc::new(crate::storage::MemoryProvider::new()); - let first = McpService::new(&ModuleConfig { - data_dir: Some(directory.path().to_path_buf()), - client: McpClientConfig::default(), - }) + let first = McpService::with_provider( + &ModuleConfig { + data_dir: Some(directory.path().to_path_buf()), + storage_callback: None, + client: McpClientConfig::default(), + }, + provider.clone(), + ) .unwrap(); first .audit() @@ -398,10 +412,14 @@ fn a_service_reopens_an_existing_store() { .unwrap(); drop(first); - let second = McpService::new(&ModuleConfig { - data_dir: Some(directory.path().to_path_buf()), - client: McpClientConfig::default(), - }) + let second = McpService::with_provider( + &ModuleConfig { + data_dir: Some(directory.path().to_path_buf()), + storage_callback: None, + client: McpClientConfig::default(), + }, + provider, + ) .unwrap(); assert_eq!( @@ -493,8 +511,9 @@ async fn catalog() -> (String, Arc) { /// A service over a temporary workspace, browsing `catalog_base`. fn service_at(directory: &std::path::Path, catalog_base: &str) -> McpService { - McpService::new(&ModuleConfig { + super::test_service(&ModuleConfig { data_dir: Some(directory.to_path_buf()), + storage_callback: None, client: McpClientConfig { registry_auth: McpRegistryAuthConfig { mcp_official_base: Some(catalog_base.to_string()), @@ -980,8 +999,9 @@ async fn installing_and_connecting_with_a_bad_handle_is_refused_before_anything_ #[tokio::test] async fn the_static_list_names_what_the_host_declared() { - let service = McpService::new(&ModuleConfig { + let service = super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "weather".into(), @@ -1001,8 +1021,9 @@ async fn the_static_list_names_what_the_host_declared() { #[tokio::test] async fn static_server_summaries_keep_legacy_fields_and_redact_endpoint_secrets() { - let service = McpService::new(&ModuleConfig { + let service = super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "weather".into(), @@ -1431,8 +1452,9 @@ async fn static_tool_call_redacts_the_configured_credential_before_bus_return() ), ); let endpoint = serve(app).await; - let service = McpService::new(&ModuleConfig { + let service = super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "secret-server".into(), @@ -1472,8 +1494,9 @@ async fn static_tool_call_redacts_the_configured_credential_before_bus_return() #[tokio::test] async fn static_tool_metadata_redacts_configured_credentials_before_bus_return() { let credential = "mcp-static-metadata-secret-731"; - let service = McpService::new(&ModuleConfig { + let service = super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "weather".into(), @@ -1544,8 +1567,9 @@ async fn classified_static_call_scrubs_rendered_success_and_envelope() { }), ); let endpoint = serve(app).await; - let service = McpService::new(&ModuleConfig { + let service = super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "secret-server".into(), @@ -1595,8 +1619,9 @@ async fn classified_static_call_preserves_unauthorized_oauth_signals() { }), ); let endpoint = serve(app).await; - let service = McpService::new(&ModuleConfig { + let service = super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "oauth-server".into(), @@ -1763,6 +1788,10 @@ use tinybus::transport::memory::MemoryBus; /// A connection to a broker running in this process. async fn in_process_connection() -> Connection { + static INSTALL_TEST_PROVIDER: std::sync::Once = std::sync::Once::new(); + INSTALL_TEST_PROVIDER.call_once(|| { + crate::storage::install_provider(crate::storage::shared_test_provider()); + }); let bus = MemoryBus::new(); Broker::new().spawn(bus.clone()); Connection::connect(bus.connect().await.expect("a transport")) @@ -1779,6 +1808,7 @@ async fn setting_up_serves_the_interface_and_claims_its_name() { connection, ModuleConfig { data_dir: Some(directory.path().to_path_buf()), + storage_callback: None, client: McpClientConfig::default(), }, ) @@ -1805,6 +1835,7 @@ async fn a_module_that_came_up_answers_a_call_on_its_object_path() { serving, ModuleConfig { data_dir: Some(directory.path().to_path_buf()), + storage_callback: None, client: McpClientConfig::default(), }, ) @@ -1842,6 +1873,7 @@ async fn a_module_that_cannot_open_its_store_fails_to_come_up() { ModuleConfig { // An empty directory names nothing a provider could serve. data_dir: Some(std::path::PathBuf::new()), + storage_callback: None, client: McpClientConfig::default(), }, ) @@ -1865,6 +1897,7 @@ fn a_null_configuration_decodes_to_a_working_default() { serde_json::from_value(serde_json::Value::Null).expect("null decodes"); assert_eq!(config.data_dir, None); + assert_eq!(config.storage_callback, None); assert_eq!(config.client.servers.len(), 0); assert!(config.client.enabled); } @@ -1874,7 +1907,7 @@ fn a_service_builds_from_a_null_configuration() { // The whole path the loader takes, not just the decode. let config: ModuleConfig = serde_json::from_value(serde_json::Value::Null).unwrap(); - let service = McpService::new(&config).expect("the service builds"); + let service = super::test_service(&config).expect("the service builds"); assert!(service.static_servers().is_empty()); } @@ -1955,8 +1988,10 @@ async fn the_cached_overview_replays_persisted_tools_without_dialling() { async fn static_cached_tools_survive_service_reopen_without_dialling() { let directory = tempfile::tempdir().unwrap(); let (url, hits) = mock_mcp_server_counted().await; + let provider = std::sync::Arc::new(crate::storage::MemoryProvider::new()); let config = ModuleConfig { data_dir: Some(directory.path().to_path_buf()), + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "weather".into(), @@ -1966,7 +2001,7 @@ async fn static_cached_tools_survive_service_reopen_without_dialling() { ..McpClientConfig::default() }, }; - let service = McpService::new(&config).unwrap(); + let service = McpService::with_provider(&config, provider.clone()).unwrap(); let listed = ok( &service, @@ -1978,7 +2013,7 @@ async fn static_cached_tools_survive_service_reopen_without_dialling() { let calls_after_listing = hits.load(Ordering::SeqCst); assert!(calls_after_listing > 0); - let service = McpService::new(&config).unwrap(); + let service = McpService::with_provider(&config, provider).unwrap(); let cached = ok(&service, "StaticCachedListTools", json!(["weather"])).await; assert_eq!(cached[0]["name"], json!("forecast")); @@ -2047,8 +2082,9 @@ async fn service_with_connected_app_server(directory: &std::path::Path, url: &st /// A service declaring the app server at `url` as the static server `apps`, /// authenticated with `token`. fn service_with_static_app_server(url: &str, token: &str) -> McpService { - McpService::new(&ModuleConfig { + super::test_service(&ModuleConfig { data_dir: None, + storage_callback: None, client: McpClientConfig { servers: vec![McpServerConfig { name: "apps".into(), @@ -2593,8 +2629,10 @@ async fn a_module_comes_up_without_waiting_for_a_server_that_never_answers() { }); let directory = tempfile::tempdir().unwrap(); + let connection = in_process_connection().await; let store = crate::Store::open( crate::storage::installed_provider() + .unwrap() .ports_for(directory.path()) .unwrap(), ) @@ -2608,9 +2646,10 @@ async fn a_module_comes_up_without_waiting_for_a_server_that_never_answers() { tokio::time::timeout( std::time::Duration::from_secs(10), super::setup_over_installed_storage( - in_process_connection().await, + connection, ModuleConfig { data_dir: Some(directory.path().to_path_buf()), + storage_callback: None, client: McpClientConfig::default(), }, ), @@ -3008,7 +3047,7 @@ async fn the_stored_state_probe_asks_the_provider_the_service_was_built_over() { } #[tokio::test(flavor = "multi_thread")] -async fn a_module_with_a_data_directory_cannot_come_up_without_host_storage() { +async fn bus_provider_requires_an_explicit_host_callback_destination() { use tinybus::{broker::Broker, transport::memory::MemoryBus}; let bus = MemoryBus::new(); @@ -3016,13 +3055,19 @@ async fn a_module_with_a_data_directory_cannot_come_up_without_host_storage() { let connection = tinybus::Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); - let error = super::bus_provider(connection).await.err().unwrap(); + let error = super::bus_provider(connection, &ModuleConfig::default()) + .await + .err() + .unwrap(); - assert!(error.to_string().contains("host storage"), "{error}"); + assert!( + error.to_string().contains("host storage callback"), + "{error}" + ); } #[tokio::test(flavor = "multi_thread")] -async fn a_module_without_a_data_directory_runs_without_host_storage() { +async fn bus_provider_rejects_an_invalid_host_callback_destination() { use tinybus::{broker::Broker, transport::memory::MemoryBus}; let bus = MemoryBus::new(); @@ -3030,14 +3075,57 @@ async fn a_module_without_a_data_directory_runs_without_host_storage() { let connection = tinybus::Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); + let config = ModuleConfig { + storage_callback: Some("not a valid bus name".into()), + ..ModuleConfig::default() + }; - let provider = super::host_storage_for(connection.clone(), &ModuleConfig::default()) + let error = super::bus_provider(connection, &config) + .await + .expect_err("invalid callback destinations must fail closed"); + + assert!(error.to_string().contains("invalid host storage callback")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn setup_uses_host_storage_only_when_no_provider_was_installed() { + use tinybus::{broker::Broker, transport::memory::MemoryBus}; + + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let connection = tinybus::Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); + let callback = ModuleConfig { + storage_callback: Some("org.example.Storage".into()), + ..ModuleConfig::default() + }; assert!( - provider.is_none(), - "no host storage means the memory default" + super::provider_for_setup(connection.clone(), &callback, true) + .await + .unwrap() + .is_none() ); + let error = super::provider_for_setup(connection, &callback, false) + .await + .expect_err("missing attested host capability must fail closed"); + assert!(error.to_string().contains("host storage"), "{error}"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_module_without_a_data_directory_still_requires_host_storage() { + use tinybus::{broker::Broker, transport::memory::MemoryBus}; + + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let connection = tinybus::Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + + let provider = super::host_storage_for(connection.clone(), &ModuleConfig::default()) + .await + .expect_err("a host must provide storage even for a static-only module"); + assert!(provider.to_string().contains("host storage"), "{provider}"); let config = ModuleConfig { data_dir: Some(std::env::temp_dir()), @@ -3045,8 +3133,7 @@ async fn a_module_without_a_data_directory_runs_without_host_storage() { }; let error = super::host_storage_for(connection, &config) .await - .err() - .unwrap(); + .unwrap_err(); assert!(error.to_string().contains("host storage"), "{error}"); } @@ -3072,6 +3159,56 @@ fn stdio_launchers_need_a_configured_sandbox_and_a_reachable_bus() { assert!(!super::stdio_launchers(None, &configured).has_sandbox()); } +#[test] +fn configured_stdio_sandbox_refuses_a_connection_without_tinybox() { + use tinymcp_bus::StdioSandboxConfig; + + let config = McpClientConfig { + stdio_sandbox: Some(StdioSandboxConfig { + workspace: "/work".into(), + read_only: Vec::new(), + read_write: Vec::new(), + deny_read: Vec::new(), + allow_net: true, + allow_subprocess: true, + require_process_isolation: true, + enforcement: tinymcp_bus::StdioSandboxEnforcement::default(), + }), + ..McpClientConfig::default() + }; + let refused = super::stdio_launchers_for_bus( + &config, + Some(Err(tinybus::Error::failed("TinyBox unavailable"))), + ); + assert!(!refused.has_sandbox()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn configured_stdio_sandbox_builds_a_launcher_for_a_bus_connection() { + use tinybus::{broker::Broker, transport::memory::MemoryBus}; + use tinymcp_bus::StdioSandboxConfig; + + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let connection = tinybus::Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let config = McpClientConfig { + stdio_sandbox: Some(StdioSandboxConfig { + workspace: "/work".into(), + read_only: Vec::new(), + read_write: Vec::new(), + deny_read: Vec::new(), + allow_net: true, + allow_subprocess: true, + require_process_isolation: true, + enforcement: tinymcp_bus::StdioSandboxEnforcement::default(), + }), + ..McpClientConfig::default() + }; + assert!(super::stdio_launchers(Some(&connection), &config).has_sandbox()); +} + #[derive(Debug, Default)] struct RecordingSpawner(std::sync::Mutex>); @@ -3123,7 +3260,7 @@ async fn configured_tool_call_uses_the_services_sandbox_not_an_empty_launcher_se ); // With no sandbox the same call is refused before any launch. - let bare = McpService::new(&ModuleConfig::default()).expect("the service builds"); + let bare = super::test_service(&ModuleConfig::default()).expect("the service builds"); let reply = ok( &bare, names::methods::CONFIGURED_TOOL_CALL, diff --git a/crates/tinymcp/src/tinybus_module/service.rs b/crates/tinymcp/src/tinybus_module/service.rs index 6b49e738..c30fa037 100644 --- a/crates/tinymcp/src/tinybus_module/service.rs +++ b/crates/tinymcp/src/tinybus_module/service.rs @@ -66,7 +66,7 @@ impl McpService { /// Returns [`crate::Error::Store`] when the stores cannot be opened, and /// [`crate::Error::ClientBuild`] when an HTTP client cannot be built. pub fn new(config: &ModuleConfig) -> Result { - Self::with_provider(config, crate::storage::installed_provider()) + Self::with_provider(config, crate::storage::installed_provider()?) } /// Builds the service over the storage `provider` hands out for the @@ -88,7 +88,7 @@ impl McpService { /// /// As [`Self::new`]. pub fn new_with_stdio(config: &ModuleConfig, stdio: StdioLaunchers) -> Result { - Self::with_provider_and_stdio(config, crate::storage::installed_provider(), stdio) + Self::with_provider_and_stdio(config, crate::storage::installed_provider()?, stdio) } /// [`Self::with_provider`], starting stdio servers through `stdio`. @@ -104,11 +104,11 @@ impl McpService { provider: Arc, stdio: StdioLaunchers, ) -> Result { - // No data directory means nothing to persist, which is the right shape - // for a host that only wants its statically declared servers. + // Even a static-only service receives explicit ports from its host; + // the module never chooses an in-memory backend on the host's behalf. let ports = match config.data_dir.as_deref() { Some(dir) => provider.ports_for(&absolute_data_dir(dir)?)?, - None => crate::storage::StoragePorts::memory()?, + None => provider.default_ports()?, }; let (store, audit) = (Store::open(ports.clone())?, AuditStore::open(ports)?); diff --git a/crates/tinymcp/src/tools/mod_tests.rs b/crates/tinymcp/src/tools/mod_tests.rs index b173918f..b9f5ad50 100644 --- a/crates/tinymcp/src/tools/mod_tests.rs +++ b/crates/tinymcp/src/tools/mod_tests.rs @@ -26,6 +26,7 @@ use super::{ tools_for, }; use crate::registry::Store; +use crate::storage::StorageProvider; use crate::{McpRegistry, McpServerRegistry}; // --------------------------------------------------------------------------- @@ -442,17 +443,12 @@ fn a_rendered_result_keeps_its_error_flag_and_markdown() { async fn an_installed_server_is_callable_by_name_and_cached_for_the_next_boot() { let (url, calls) = mcp_server().await; let directory = tempfile::tempdir().unwrap(); + let provider = Arc::new(crate::storage::MemoryProvider::new()); // First process: install and connect, which caches the listing. { - let registry = dynamic_registry( - Store::open( - crate::storage::installed_provider() - .ports_for(directory.path()) - .unwrap(), - ) - .unwrap(), - ); + let registry = + dynamic_registry(Store::open(provider.ports_for(directory.path()).unwrap()).unwrap()); registry .store() .insert_server(&installed("s1", &url)) @@ -495,14 +491,8 @@ async fn an_installed_server_is_callable_by_name_and_cached_for_the_next_boot() } // Second process: nothing is connected, but the tools are offered. - let registry = dynamic_registry( - Store::open( - crate::storage::installed_provider() - .ports_for(directory.path()) - .unwrap(), - ) - .unwrap(), - ); + let registry = + dynamic_registry(Store::open(provider.ports_for(directory.path()).unwrap()).unwrap()); let overview = registry.cached_overview().await.unwrap(); assert_eq!(overview.len(), 1); assert_eq!(overview[0].tools.len(), 2); diff --git a/crates/tinymcp/tests/multi_server.rs b/crates/tinymcp/tests/multi_server.rs index 4becfa2e..5dae81f8 100644 --- a/crates/tinymcp/tests/multi_server.rs +++ b/crates/tinymcp/tests/multi_server.rs @@ -4,11 +4,12 @@ #[path = "support/mcp_server.rs"] mod mcp_server_fixture; +#[path = "support/storage.rs"] +mod storage_fixture; use std::sync::atomic::Ordering; use serde_json::{Value, json}; -use tinymcp::registry::Store; use tinymcp::{ CommandKind, InstalledServer, McpClientIdentityConfig, McpRegistry, McpRegistryAuthConfig, ServerStatus, Transport, @@ -19,7 +20,7 @@ use mcp_server_fixture::{ }; fn registry_with_servers(servers: &[InstalledServer]) -> McpRegistry { - let store = Store::open_in_memory().expect("open in-memory store"); + let store = storage_fixture::open_memory_store(); for server in servers { store.insert_server(server).expect("insert server"); } diff --git a/crates/tinymcp/tests/stores_through_the_storage_ports.rs b/crates/tinymcp/tests/stores_through_the_storage_ports.rs index 64b19c77..0aa57b33 100644 --- a/crates/tinymcp/tests/stores_through_the_storage_ports.rs +++ b/crates/tinymcp/tests/stores_through_the_storage_ports.rs @@ -7,9 +7,19 @@ #![allow(clippy::unwrap_used, clippy::expect_used)] use std::collections::BTreeMap; - +use std::sync::Arc; use tinymcp::storage::{self, StoragePorts}; use tinymcp::{AuditStore, CommandKind, InstalledServer, NewMcpWriteRecord, Store, Transport}; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::Scope; + +fn memory_ports() -> StoragePorts { + let backend = MemoryBackend::new(); + let scope = Scope::new("test").unwrap(); + let storage = backend.for_scope(&scope).unwrap(); + StoragePorts::from_storage(&storage, Arc::clone(storage.secrets())) +} fn server(id: &str, name: &str) -> InstalledServer { InstalledServer { @@ -32,7 +42,7 @@ fn server(id: &str, name: &str) -> InstalledServer { #[test] fn installs_and_credentials_survive_reopening_over_the_same_ports() { - let ports = StoragePorts::memory().unwrap(); + let ports = memory_ports(); let store = Store::open(ports.clone()).unwrap(); store .insert_server(&server("srv-1", "@acme/weather")) @@ -56,7 +66,7 @@ fn installs_and_credentials_survive_reopening_over_the_same_ports() { #[test] fn the_audit_log_and_the_servers_share_ports_but_not_records() { - let ports = StoragePorts::memory().unwrap(); + let ports = memory_ports(); let store = Store::open(ports.clone()).unwrap(); let audit = AuditStore::open(ports).unwrap(); store @@ -95,27 +105,34 @@ fn the_declared_grant_covers_the_collections_a_store_creates() { #[test] fn the_storage_schema_composes_and_the_grant_is_generated_from_it() { - use tinystoragedrivers_core::schema::{Item, Registry}; - - let schema = storage::storage_schema(); - Registry::compose([schema.clone()]).expect("the module's schema composes on its own"); - - let mut collections = Vec::new(); - let mut streams = Vec::new(); - for item in &schema.items { - match item { - Item::Collection { name, .. } => collections.push(name.clone()), - Item::Stream { name, .. } => streams.push(name.clone()), - Item::Blobs { .. } | Item::Secrets { .. } => {} - } - } + let collections: Vec<_> = storage::collection_specs() + .into_iter() + .map(|spec| spec.name) + .collect(); let granted = storage::grant(); - assert_eq!(granted.collections, collections); - assert_eq!(granted.streams, streams); assert!( collections .iter() - .chain(&streams) + .all(|name| granted.collections.contains(name)) + ); + assert!(granted.collections.contains(&"mcp_servers".to_owned())); + assert_eq!( + granted.streams, + vec![ + storage::AUDIT_STREAM.to_owned(), + "mcp_audit".to_owned(), + "mcp_audit/".to_owned() + ] + ); + assert!( + collections + .iter() + .any(|name| name == tinymcp_bus::storage::MIGRATIONS) + ); + assert!( + collections + .iter() + .filter(|name| name.as_str() != tinymcp_bus::storage::MIGRATIONS) .all(|name| name.starts_with(&format!("{}.", storage::OWNER))) ); } diff --git a/crates/tinymcp/tests/support/live_official_registry.rs b/crates/tinymcp/tests/support/live_official_registry.rs index 772f6d5f..36190990 100644 --- a/crates/tinymcp/tests/support/live_official_registry.rs +++ b/crates/tinymcp/tests/support/live_official_registry.rs @@ -14,6 +14,9 @@ use tinymcp::transport::stdio::jailed::StdioLaunchers; use tinymcp::transport::stdio::{StdioLaunch, StdioSpawner}; use tinymcp::{McpClientIdentityConfig, McpRegistryAuthConfig}; +#[path = "storage.rs"] +mod storage_fixture; + #[derive(Debug)] struct IsolatedSpawner { workspace: PathBuf, @@ -101,7 +104,7 @@ impl IsolatedRegistry { }); let auth = McpRegistryAuthConfig::default(); let registry = McpRegistry::new( - Store::open_in_memory().expect("open in-memory store"), + storage_fixture::open_memory_store(), auth.clone(), McpClientIdentityConfig::default(), None, @@ -121,7 +124,7 @@ impl IsolatedRegistry { .expect("build official registry client with live-test budgets"), ) .expect("build configured catalog dispatcher"); - let catalog_store = Store::open_in_memory().expect("open catalog cache"); + let catalog_store = storage_fixture::open_memory_store(); Self { _scratch: scratch, diff --git a/crates/tinymcp/tests/support/storage.rs b/crates/tinymcp/tests/support/storage.rs new file mode 100644 index 00000000..d2280bc5 --- /dev/null +++ b/crates/tinymcp/tests/support/storage.rs @@ -0,0 +1,18 @@ +//! Public-API storage fixtures for integration tests. + +use std::sync::Arc; + +use tinymcp::registry::Store; +use tinymcp::storage::StoragePorts; +use tinystoragedrivers_api::StorageBackend; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::Scope; + +/// Opens a store backed by fresh in-memory document, stream, and secret ports. +pub(crate) fn open_memory_store() -> Store { + let backend = MemoryBackend::new(); + let scope = Scope::new("integration-test").expect("valid test scope"); + let storage = backend.for_scope(&scope).expect("open in-memory storage"); + let ports = StoragePorts::from_storage(&storage, Arc::clone(storage.secrets())); + Store::open(ports).expect("open in-memory store") +} diff --git a/deny.toml b/deny.toml index f5b3642d..31cea379 100644 --- a/deny.toml +++ b/deny.toml @@ -62,6 +62,8 @@ 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/senamakel/tinystoragedrivers", + "https://github.com/senamakel/tinybus", # The TinyBox bus contract (types only), for the jailed stdio launcher. "https://github.com/tinyhumansai/tinybox", ] diff --git a/docs/specs/storage-ports.md b/docs/specs/storage-ports.md index 9de252b6..3c3d4a29 100644 --- a/docs/specs/storage-ports.md +++ b/docs/specs/storage-ports.md @@ -13,18 +13,18 @@ tenants in one process. The host owns storage; this crate asks for ports. ## What changed -- No database client. The crate depends on `tinystoragedrivers-core` (the - `DocumentStore` and `StreamStore` ports and the `Blocking` bridge) and - `tinystoragedrivers-secrets` (the `SecretStore` port), by git tag, and on no - driver. +- No database client. The crate depends on the `tinystoragedrivers-api` and + `tinystoragedrivers-types` port contracts and the bus proxy, and on no + storage engine. - `Store` and `AuditStore` open over `StoragePorts` (`documents`, `streams`, `secrets`). Their API stays synchronous; each call runs its port future on one shared bridge thread. -- A host supplies ports in process (`StoragePorts::from_scoped`), or installs a +- A host supplies ports in process (`StoragePorts::from_storage`), or installs a `StorageProvider` that maps a data directory to ports; the module's - `McpService` asks the installed provider. The default is an in-memory - provider. The storage bus client implements the same port traits, so the - module code is identical over the bus. + `McpService` asks the installed provider. Tests may install an in-memory + provider. A loaded module requires an explicit host callback destination and + never falls back to process-local memory. The storage bus client implements + the same port traits, so the module code is identical over the bus. ## Layout @@ -55,14 +55,17 @@ names, and refuses the rest. - Deleting a server also removes its secret, its cached tools and its claim. - Audit listing reads the stream in windows and filters, sorts and pages in memory, so ordering matches the previous SQL (`timestamp DESC, id DESC`). +- The v1 audit-stream import uses `StreamStore::append_batch_if_offset` to + serialize competing owner opens without duplicating entries. A host stream + backend that lacks conditional append support fails migration closed. ## Hosting as a loadable module Loaded as a `cdylib`, the module cannot reach the host's storage handles. When -its configuration names a `data_dir` and the host has not installed a -`StorageProvider` itself, `setup` connects to the host's -`ai.tinyhumans.tinystorage.Storage` objects (`BusProvider`, over -`tinystoragedrivers-busproxy::connect_storage`) and installs that as the +its host-provided `storage_callback` destination is present and the host has +not installed a `StorageProvider` itself, `setup` connects to that exact +callback (`BusProvider`, over +`tinystoragedrivers-busproxy::connect_storage_at`) and installs it as the provider. The host binds the scope from the broker-authenticated caller and enforces the grant above; the module never names a tenant. Every data directory answers the one host-bound scope. A host with no storage objects @@ -85,12 +88,14 @@ tests keep secrets in a local store. ## Schema v2 -The module's declarations are `tinymcp::storage::storage_schema()` (owner `mcp`, -scope class Module, tinystoragedrivers v1.0.0); the storage grant is generated -from it. v1 names become `mcp.*`, `*_at` times become `*_ms` fields, ids are -`Key::of` keys, and JSON kept inside strings (`body_json`, `record_json`) -becomes an object body. Steps `servers_v2`, `server_names_v2`, +The module's private declaration is composed from the public +`tinymcp_bus::storage::collection_specs()` (owner `mcp`, tenant-scoped data, +tinystoragedrivers v2.1); the storage grant includes those destinations and +the legacy migration sources. v1 names become `mcp.*`, `*_at` times become +`*_ms` fields, ids use the released escaped composite-key encoding with its +overlength digest fallback, and JSON kept inside strings (`body_json`, +`record_json`) becomes an object body. Steps `servers_v2`, `server_names_v2`, `registry_cache_v2`, `tool_cache_v2`, `registry_index_v2`, -`registry_index_state_v2` and the stream step `audit_v2` migrate a v1 database. +`registry_index_state_v2` and the stream step `audit_streams_v2` migrate a v1 database. Secret names are unchanged (a secret cannot be renamed by a step, and they sit outside the `mcp/` owner prefix). diff --git a/scripts/check-engine-deps.sh b/scripts/check-engine-deps.sh new file mode 100755 index 00000000..ce71947d --- /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}' +} + +# Python on Windows writes CRLF to captured stdout. Exercise the same package +# and cargo-tree parsing used below with Bash 3-compatible builtins. +crlf_packages=$'tinymcp\r\ntinymcp-storage\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" != $'tinymcp\ntinymcp-storage' ]]; then + echo "engine gate failed its CRLF package-list self-test" >&2 + exit 1 +fi +if [[ "$(tree_names $'tinymcp\r\nrusqlite\r\n')" != $'tinymcp\nrusqlite' ]]; then + echo "engine gate failed its CRLF cargo-tree self-test" >&2 + exit 1 +fi + +# Prove exact-name matching catches engines while allowing TSD ports. +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 tinystoragedrivers-api tinystoragedrivers-busproxy tinymcp 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 + +# Select every workspace package with a native library target from Cargo's +# package IDs, avoiding platform-dependent manifest path comparisons. +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")" + 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 5fe3ae46..4949b760 100755 --- a/scripts/test-features.sh +++ b/scripts/test-features.sh @@ -6,14 +6,6 @@ cargo test --locked --workspace cargo test --locked -p tinymcp --no-default-features --test library_feature_tests cargo test --locked -p tinymcp --no-default-features --features tools,ui,server-http --test library_feature_tests cargo test --locked --workspace --all-features - - -set -euo pipefail -# Default features are strict, tokio included. The optional `storage` feature adds -# the storage ports crate, which brings tokio (io-util/time, no runtime), so its -# graph is checked for everything else: no transport, HTTP client or native library. -# Capture each tree first so a failing `cargo tree` aborts under `set -e` instead of -# reading as an empty (clean) graph. default_tree="$(cargo tree -p tinymcp-bus -e normal,build --prefix none)" storage_tree="$(cargo tree -p tinymcp-bus --features storage -e normal,build --prefix none)" forbidden="$(printf '%s\n' "$default_tree" \ @@ -27,10 +19,10 @@ if [ -n "$forbidden" ]; then echo "tinymcp-bus pulled in a dependency its manifest forbids:" >&2 echo "$forbidden" >&2 echo >&2 - echo "The contract is what a host compiles against. It must stay free" >&2 - echo "of transports, async runtimes, HTTP clients and native libraries." >&2 + echo "The contract must stay free of transports, async runtimes, HTTP clients and native libraries." >&2 exit 1 fi +scripts/check-engine-deps.sh case "${RUNNER_OS:-$(uname -s)}" in Windows|MINGW*|MSYS*|CYGWIN*) ;; *) python3 scripts/test-package-layout.py ;; diff --git a/scripts/verify-module.sh b/scripts/verify-module.sh index 1f072d3e..711fa779 100755 --- a/scripts/verify-module.sh +++ b/scripts/verify-module.sh @@ -52,7 +52,7 @@ if [[ -n "$verifier_bin" ]]; then echo "verifier binary must be an executable repository file" >&2 exit 2 } - "$verifier_bin" "$library" + TINYMCP_MODULE_PATH="$library" "$verifier_bin" "$library" else - cargo run --locked --release --manifest-path Cargo.toml --package tinymcp --example verify_module -- "$library" + TINYMCP_MODULE_PATH="$library" cargo run --locked --release --manifest-path Cargo.toml --package tinymcp --example verify_module -- "$library" fi diff --git a/vendor/tinybus b/vendor/tinybus index 1f33d1be..11b0a728 160000 --- a/vendor/tinybus +++ b/vendor/tinybus @@ -1 +1 @@ -Subproject commit 1f33d1be1901a2d44bfe674cd7cf294cf3848821 +Subproject commit 11b0a728e62a5b7ae213c1cf6366f82b9e1a65de