diff --git a/.github/scripts/test_release_checksum.py b/.github/scripts/test_release_checksum.py new file mode 100644 index 0000000..22d2324 --- /dev/null +++ b/.github/scripts/test_release_checksum.py @@ -0,0 +1,70 @@ +"""Regression tests for the checksum selected by the release verifier.""" +from pathlib import Path +import subprocess +import sys +import tempfile +import textwrap +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +WORKFLOW = ROOT / ".github/workflows/release.yml" +SELECTOR_MARKER = ( + 'python3 - "$archive" release-assets/published/checksum.toml <<\'PY\'\n' +) + + +class ReleaseChecksumTests(unittest.TestCase): + def test_selects_archive_digest_not_embedded_library_digest(self): + workflow = WORKFLOW.read_text() + ci = (ROOT / ".github/workflows/ci.yml").read_text() + self.assertEqual( + ci.count("run: python3 .github/scripts/test_release_checksum.py"), 1 + ) + self.assertIn( + 'gh release download "$RELEASE_TAG" --repo "$REPOSITORY" ' + '--pattern checksum.toml --dir release-assets/published', + workflow, + ) + self.assertIn(SELECTOR_MARKER, workflow) + source_start = workflow.index(SELECTOR_MARKER) + len(SELECTOR_MARKER) + source_end = workflow.index("\n PY", source_start) + selector = textwrap.dedent(workflow[source_start:source_end]) + + archive = "tinyeventqueues-0.1.3-ubuntu-24.04-x86_64.tar.gz" + archive_digest = "4daf1ad06fdeb8fb5410ff48572aead4db4ce5d9446736bb5637e3083d6a3072" + library_digest = "718a226caac47b8fd3a570138c6e485dd89367e64a393231afa6428796586494" + (ROOT / "target").mkdir(exist_ok=True) + with tempfile.TemporaryDirectory( + prefix="release-checksum-selection-", dir=ROOT / "target" + ) as scratch: + checksum = Path(scratch) / "checksum.toml" + checksum.write_text( + f'[sha256]\n"{archive}" = "{archive_digest}"\n\n' + f'[library_sha256]\n"{archive}" = "{library_digest}"\n' + ) + result = subprocess.run( + [sys.executable, "-c", selector, archive, str(checksum)], + text=True, + capture_output=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, f"{archive_digest}\n") + self.assertNotEqual(result.stdout.strip(), library_digest) + + checksum.write_text( + f'[library_sha256]\n"{archive}" = "{library_digest}"\n' + ) + missing_archive = subprocess.run( + [sys.executable, "-c", selector, archive, str(checksum)], + text=True, + capture_output=True, + check=False, + ) + self.assertNotEqual(missing_archive.returncode, 0) + self.assertEqual(missing_archive.stdout, "") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c1aa23d..e67f27b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,9 @@ jobs: - uses: Swatinem/rust-cache@v2 + - name: Test published checksum selection + run: python3 .github/scripts/test_release_checksum.py + - name: Check formatting run: cargo fmt --all -- --check diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3a2efb2..d313e9d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -569,6 +569,16 @@ jobs: --generate-notes fi + - name: Download published checksum manifest + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ needs.prepare.outputs.tag }} + REPOSITORY: ${{ github.repository }} + run: | + set -euo pipefail + mkdir -p release-assets/published + gh release download "$RELEASE_TAG" --repo "$REPOSITORY" --pattern checksum.toml --dir release-assets/published + - name: Verify the published module through TinyBus shell: bash env: @@ -580,14 +590,23 @@ jobs: set -euo pipefail archive="${CRATE_NAME}-${VERSION}-ubuntu-24.04-x86_64.tar.gz" release_url="https://github.com/${REPOSITORY}/releases/tag/${RELEASE_TAG}" - sha256="$( - sed -n "s/^\"${archive}\" = \"\([0-9a-f]\{64\}\)\"$/\1/p" \ - release-assets/checksum.toml + sha256="$(python3 - "$archive" release-assets/published/checksum.toml <<'PY' + import re + import sys + import tomllib + + archive, checksum_path = sys.argv[1:] + with open(checksum_path, "rb") as checksum_file: + manifest = tomllib.load(checksum_file) + + archive_sha256 = manifest.get("sha256", {}).get(archive) + if not isinstance(archive_sha256, str) or re.fullmatch( + r"[0-9a-f]{64}", archive_sha256 + ) is None: + raise SystemExit(f"archive checksum missing or invalid for {archive}") + print(archive_sha256) + PY )" - if [[ -z "$sha256" ]]; then - echo "checksum missing for ${archive}" >&2 - exit 1 - fi cargo run --manifest-path vendor/tinybus/Cargo.toml --locked \ --package tinybus --all-features --example github_module_host -- \ diff --git a/AGENTS.md b/AGENTS.md index 32455a7..b4190d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,13 +64,12 @@ load, resolve against each other, and that the schema describes every field. ### Storage -The pipeline is generic over `Arc` and `Arc` -from `tinystoragedrivers-core`, plus an injectable `Clock`. Every piece of -durable state lives in those two stores, so a new `Pipeline` over the same -storage is a restart; tests simulate restarts exactly that way, on -`MemoryStorage` with a `ManualClock`. `tinystoragedrivers-core` is a git -dependency pinned to a tinyhumansai/tinystoragedrivers `rev`; move the pin in -its own commit. +The pipeline is generic over `QueueStore` and `DocumentStore` from +`tinystoragedrivers-api` v2, plus an injectable `Clock`. The host declares the +module's document collections and queue manifest, then serves the scoped +storage endpoint; the loaded module connects through that host-owned port. +Tests use the v2 memory backend with a `ManualClock`. Production code does not +select or construct a storage engine. ### The two-crate split diff --git a/Cargo.lock b/Cargo.lock index c3d140a..2390d01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,9 +63,9 @@ checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "cc" -version = "1.10.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" dependencies = [ "find-msvc-tools", "jobserver", @@ -79,12 +79,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" -[[package]] -name = "cfg_aliases" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" - [[package]] name = "const-oid" version = "0.10.2" @@ -111,9 +105,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.3" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" dependencies = [ "cfg-if", ] @@ -164,6 +158,17 @@ dependencies = [ "crypto-common 0.2.2", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -307,10 +312,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", - "js-sys", "libc", "r-efi 6.0.0", - "wasm-bindgen", ] [[package]] @@ -365,6 +368,95 @@ dependencies = [ "typenum", ] +[[package]] +name = "icu_casemap" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a6f143e9349267b80ae071a6ec25d4797c45756d8b2671a8b24b7b25b81ab94" +dependencies = [ + "icu_casemap_data", + "icu_collections", + "icu_locale_core", + "icu_properties", + "icu_provider", + "potential_utf", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_casemap_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71a5c321208537711696af55bc2ab5dad939e4f6e0aef92dd6a2555deceedf3a" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "serde", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -425,6 +517,12 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "log" version = "0.4.34" @@ -447,18 +545,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "nix" -version = "0.31.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" -dependencies = [ - "bitflags", - "cfg-if", - "cfg_aliases", - "libc", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -483,6 +569,17 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -551,6 +648,12 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rawzip" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac9999039f74cd73c03158cddfe4362991703c74efe5ce5c8073026f80a5e48c" + [[package]] name = "ring" version = "0.17.14" @@ -749,9 +852,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.4" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" [[package]] name = "sqlite-wasm-rs" @@ -765,6 +868,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "subtle" version = "2.6.1" @@ -793,6 +902,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "tar" version = "0.4.46" @@ -839,11 +959,13 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.3.6" +version = "0.3.12" dependencies = [ "async-trait", "flate2", + "icu_casemap", "libc", + "rawzip", "serde", "serde_json", "sha2 0.10.9", @@ -854,13 +976,13 @@ dependencies = [ "tokio", "toml", "tracing", + "unicode-normalization", "ureq", - "zip", ] [[package]] name = "tinybus-macros" -version = "0.3.6" +version = "0.3.12" dependencies = [ "proc-macro2", "quote", @@ -869,7 +991,7 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.3.6" +version = "0.3.12" dependencies = [ "async-trait", "serde", @@ -908,13 +1030,12 @@ version = "0.2.3" dependencies = [ "serde", "serde_json", - "tinystoragedrivers-types", ] [[package]] name = "tinystoragedrivers-api" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "bytes", @@ -927,8 +1048,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-blob" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "bytes", @@ -941,8 +1062,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-bus" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "serde", "serde_json", @@ -952,8 +1073,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-busproxy" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "bytes", @@ -970,8 +1091,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-connect" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "rusqlite", "serde_json", @@ -982,8 +1103,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-document" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "data-encoding", @@ -1000,8 +1121,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-kv" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "serde", @@ -1012,8 +1133,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-queue" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "data-encoding", @@ -1028,8 +1149,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-secrets" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "tinystoragedrivers-api", @@ -1039,8 +1160,8 @@ dependencies = [ [[package]] name = "tinystoragedrivers-testkit" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "async-trait", "bytes", @@ -1060,14 +1181,31 @@ dependencies = [ [[package]] name = "tinystoragedrivers-types" -version = "2.1.1" -source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=29471a164619bcec03e5858a7d7ee0c65f52bf22#29471a164619bcec03e5858a7d7ee0c65f52bf22" +version = "2.1.2" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?rev=6226b9484c8bd01c58741718cd89ba90a13a36bb#6226b9484c8bd01c58741718cd89ba90a13a36bb" dependencies = [ "serde", "serde_json", "thiserror", ] +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -1160,12 +1298,6 @@ dependencies = [ "once_cell", ] -[[package]] -name = "typed-path" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" - [[package]] name = "typenum" version = "1.20.1" @@ -1188,6 +1320,15 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "untrusted" version = "0.9.0" @@ -1196,9 +1337,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "ureq" -version = "3.5.0" +version = "3.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" dependencies = [ "base64", "flate2", @@ -1229,6 +1370,12 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + [[package]] name = "vcpkg" version = "0.2.15" @@ -1313,9 +1460,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "1.0.11" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -1420,6 +1567,12 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "xattr" version = "1.6.1" @@ -1430,6 +1583,29 @@ dependencies = [ "rustix", ] +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.63" @@ -1450,6 +1626,27 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + [[package]] name = "zeroize" version = "1.9.1" @@ -1457,19 +1654,38 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" [[package]] -name = "zip" -version = "9.1.1" +name = "zerotrie" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "518b847fd864440c379748ad684c449f293af68978a485a4ff16f7c901c1f7c4" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ - "crc32fast", - "flate2", - "getrandom 0.4.3", - "indexmap", - "memchr", - "nix", - "typed-path", - "windows-sys 0.61.2", + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", ] [[package]] @@ -1486,18 +1702,18 @@ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zstd" -version = "0.13.3" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +checksum = "db3ae9bf90af6e40197bef767eeefc46ad6397420fe873830bd85e5fbbfb3c70" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "7.3.0" +version = "8.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +checksum = "ded520f16b29e1a9b771c722221b2b0a0398c2316d9bb3c42b458a5414d7434b" dependencies = [ "zstd-sys", ] diff --git a/Cargo.toml b/Cargo.toml index c6f297c..baf5679 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,13 +32,13 @@ tinyeventqueues-bus = { path = "crates/tinyeventqueues-bus" } # TinyBus defines the message types, interface macro, and frozen module ABI # used by the generated integration. Socket and CLI features are unnecessary # here. -tinybus = { version = ">=0.3.6, <0.4", default-features = false, features = [ +tinybus = { version = "0.3.12", default-features = false, features = [ "macros", "modules", ] } # The module-side SDK owns the isolated runtime and exports the ABI entrypoints # required by TinyBus's dynamic loader. -tinybus-module = ">=0.3.6, <0.4" +tinybus-module = "0.3.12" # Derive macros for the crate-wide error type in # `crates/tinyeventqueues/src/error/`. thiserror = "2" @@ -48,10 +48,10 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" # Stable v2 storage contracts and pure value types; engine implementations are # selected by the host rather than this queue owner. -tinystoragedrivers-api = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "29471a164619bcec03e5858a7d7ee0c65f52bf22" } -tinystoragedrivers-types = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "29471a164619bcec03e5858a7d7ee0c65f52bf22" } +tinystoragedrivers-api = { version = "2.1.2", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "6226b9484c8bd01c58741718cd89ba90a13a36bb" } +tinystoragedrivers-types = { version = "2.1.2", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "6226b9484c8bd01c58741718cd89ba90a13a36bb" } # Module-side adapters to host-owned storage ports. -tinystoragedrivers-busproxy = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "29471a164619bcec03e5858a7d7ee0c65f52bf22" } +tinystoragedrivers-busproxy = { version = "2.1.2", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "6226b9484c8bd01c58741718cd89ba90a13a36bb" } # Module diagnostics; the host installs the logger. log = "0.4" # The host-callback trait (`Host`) is an async trait object. @@ -109,10 +109,18 @@ tinybus-macros = { path = "vendor/tinybus/crates/tinybus-macros" } [patch."https://github.com/tinyhumansai/tinybus"] tinybus = { path = "vendor/tinybus/crates/tinybus" } +tinybus-macros = { path = "vendor/tinybus/crates/tinybus-macros" } +tinybus-module = { path = "vendor/tinybus/crates/tinybus-module" } + +[patch."https://github.com/tinyhumansai/tinybus?rev=6b3c5b0cc14b1d07b68055b17a937b11de613efd"] +tinybus = { path = "vendor/tinybus/crates/tinybus" } +tinybus-macros = { path = "vendor/tinybus/crates/tinybus-macros" } +tinybus-module = { path = "vendor/tinybus/crates/tinybus-module" } [patch."https://github.com/senamakel/tinybus"] tinybus = { path = "vendor/tinybus/crates/tinybus" } + [profile.release] # Cross-crate optimization and smaller, faster binaries for release builds. lto = "thin" diff --git a/MODULE.md b/MODULE.md index 0c58a04..fc08128 100644 --- a/MODULE.md +++ b/MODULE.md @@ -17,19 +17,20 @@ one on demand. The interface names, object paths, member names and payload types are published as the `tinyeventqueues-bus` crate, so a host names them from a library rather than by string literal. -Storage is the host's: the module connects through the unique -`HostCallbackBinding` destination admitted by the loader and runs over the one -scope the host bound it to, documents for its `teq.*` state and the queue port -for the queues `queues.json` declares. `tinyeventqueues-bus` (feature -`storage`) publishes `collection_specs()` for the module's document state and -the shipped `queues.json`. The private module configuration must include the -host-provided `storage_callback` destination: the unique name of the callback -binding admitted for this instance, or `ai.tinyhumans.tinystorage.Storage` for -a host that serves one storage service for every module. Setup fails closed if -it is missing or unavailable. +Storage is the host's: the module connects through the invocation-scoped +`StorageAddress` admitted by its host and runs over the one scope the host +bound it to, documents for its `teq.*` state and the queue port for the queues +`queues.json` declares. `tinyeventqueues-bus` (feature `storage`) publishes +`collection_specs()` for the module's document state and the shipped +`queues.json`. The private module configuration carries the host-issued +`storage_address` (`host` and invocation `object_root`) or a mutually exclusive +`storage_callback` (an attested unique host peer). An explicit route never falls +back to another route. With neither field, the module uses the host's ordinary +caller-scoped storage endpoint; setup fails if that endpoint is unavailable. +There is no in-memory fallback. The module takes a private configuration blob: -`{"storage_callback": ":1.42", "queues": , "pipeline": , "timer": +`{"storage_address": {"host": ":1.42", "object_root": "/ai/tinyhumans/tinystorage/Invocation/abc123"}, "queues": , "pipeline": , "timer": {"enabled": true, "min_interval_ms": 100, "max_interval_ms": 5000}}`. Absent fields run the shipped files and the default timer. A host serving the queue port should declare the same manifest it passes in `queues`. diff --git a/README.md b/README.md index e1f7d5b..68d8f9f 100644 --- a/README.md +++ b/README.md @@ -108,14 +108,16 @@ cargo fmt --all -- --check cargo clippy --all-targets --all-features -- -D warnings cargo build --all-targets --all-features cargo test --all-features +# Build the cdylib before running default-feature native loader tests. +cargo build --workspace +cargo test cargo run -p tinyeventqueues --example basic .github/scripts/check-file-coverage.sh 90 coverage.json # needs cargo-llvm-cov ``` -The module depends on the `tinystoragedrivers-api` and -`tinystoragedrivers-types` contracts and the bus proxy, pinned to canonical -TinyStorageDrivers v2.1.0. Storage engines are selected by the host and are not -part of the module's library dependency tree. +The module uses the v2 `tinystoragedrivers-api`, `-types`, and `-busproxy` +contracts. Storage engines remain in the host; the testkit and queue memory +backend are development dependencies only. ## Releasing diff --git a/crates/tinyeventqueues-bus/Cargo.toml b/crates/tinyeventqueues-bus/Cargo.toml index fca47fa..6918858 100644 --- a/crates/tinyeventqueues-bus/Cargo.toml +++ b/crates/tinyeventqueues-bus/Cargo.toml @@ -19,17 +19,10 @@ publish = false [dependencies] serde = { workspace = true } serde_json = { workspace = true } -# Optional (feature `storage`, off by default): storage ports only (no driver, -# no I/O). The `storage` module declares what the module stores as a schema a -# host composes, so the host derives the module's storage grant from the -# contract instead of linking the implementation. The default dependency -# closure of this crate is unchanged without it, which CI asserts. -tinystoragedrivers-types = { workspace = true, optional = true } - [features] default = [] # `storage::collection_specs()`, the module's storage declaration. -storage = ["dep:tinystoragedrivers-types"] +storage = [] [lints] workspace = true diff --git a/crates/tinyeventqueues-bus/src/storage/mod.rs b/crates/tinyeventqueues-bus/src/storage/mod.rs index 00569dc..41398d4 100644 --- a/crates/tinyeventqueues-bus/src/storage/mod.rs +++ b/crates/tinyeventqueues-bus/src/storage/mod.rs @@ -11,7 +11,7 @@ //! [`collection_specs`] is the complete, pure collection declaration used by //! both the host and this module. -use tinystoragedrivers_types::{CollectionSpec, IndexSpec}; +use serde::{Deserialize, Serialize}; /// Terminal outcomes, one per event. pub const OUTCOMES: &str = "teq.outcomes"; @@ -45,28 +45,91 @@ pub const SHIPPED_QUEUES_JSON: &str = include_str!("../../../../queues.json"); /// The shipped pipeline configuration (`pipeline.json`). pub const SHIPPED_PIPELINE_JSON: &str = include_str!("../../../../pipeline.json"); +/// A collection declaration that the host can translate to its storage API. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CollectionDeclaration { + /// Stable collection name. + pub name: String, + /// Secondary indexes used by the pipeline. + #[serde(default)] + pub indexes: Vec, +} + +impl CollectionDeclaration { + /// Declare a collection by name. + #[must_use] + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + indexes: Vec::new(), + } + } + + /// Add an index declaration. + #[must_use] + pub fn index(mut self, index: IndexDeclaration) -> Self { + self.indexes.push(index); + self + } +} + +/// A secondary index declaration expressed as bus-owned data. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct IndexDeclaration { + /// Index name, unique within the collection. + pub name: String, + /// Dotted field paths, in key order. + pub fields: Vec, + /// Whether equal field values are rejected. + #[serde(default)] + pub unique: bool, +} + +impl IndexDeclaration { + /// Declare a non-unique index over `fields`. + #[must_use] + pub fn new>( + name: impl Into, + fields: impl IntoIterator, + ) -> Self { + Self { + name: name.into(), + fields: fields.into_iter().map(Into::into).collect(), + unique: false, + } + } + + /// Make the index unique. + #[must_use] + pub fn unique(mut self) -> Self { + self.unique = true; + self + } +} + /// The collections the pipeline uses, with their indexes. #[must_use] -pub fn collection_specs() -> Vec { +pub fn collection_specs() -> Vec { vec![ - CollectionSpec::new(OUTCOMES) - .index(IndexSpec::new("by_disposition", ["disposition"])) - .index(IndexSpec::new("by_expiry", ["expires_ms"])), - CollectionSpec::new(TOMBSTONES).index(IndexSpec::new("by_expiry", ["expires_ms"])), - CollectionSpec::new(REDRIVEN), - CollectionSpec::new(BUCKETS), - CollectionSpec::new(AMBIENT), - CollectionSpec::new(HABITUATION), - CollectionSpec::new(DIGEST), - CollectionSpec::new(STAGED) - .index(IndexSpec::new("by_due", ["due_ms"])) - .index(IndexSpec::new("by_cadence", ["cadence_key"])), - CollectionSpec::new(CADENCE), - CollectionSpec::new(CONVERSATIONS), - CollectionSpec::new(THREADS), - CollectionSpec::new(COALESCE) - .index(IndexSpec::new("by_due", ["due_ms"])) - .index(IndexSpec::new("by_thread", ["thread_group"])), + CollectionDeclaration::new(OUTCOMES) + .index(IndexDeclaration::new("by_disposition", ["disposition"])) + .index(IndexDeclaration::new("by_expiry", ["expires_ms"])), + CollectionDeclaration::new(TOMBSTONES) + .index(IndexDeclaration::new("by_expiry", ["expires_ms"])), + CollectionDeclaration::new(REDRIVEN), + CollectionDeclaration::new(BUCKETS), + CollectionDeclaration::new(AMBIENT), + CollectionDeclaration::new(HABITUATION), + CollectionDeclaration::new(DIGEST), + CollectionDeclaration::new(STAGED) + .index(IndexDeclaration::new("by_due", ["due_ms"])) + .index(IndexDeclaration::new("by_cadence", ["cadence_key"])), + CollectionDeclaration::new(CADENCE), + CollectionDeclaration::new(CONVERSATIONS), + CollectionDeclaration::new(THREADS), + CollectionDeclaration::new(COALESCE) + .index(IndexDeclaration::new("by_due", ["due_ms"])) + .index(IndexDeclaration::new("by_thread", ["thread_group"])), ] } diff --git a/crates/tinyeventqueues-bus/src/storage/mod_tests.rs b/crates/tinyeventqueues-bus/src/storage/mod_tests.rs index 2bd5276..33040eb 100644 --- a/crates/tinyeventqueues-bus/src/storage/mod_tests.rs +++ b/crates/tinyeventqueues-bus/src/storage/mod_tests.rs @@ -6,7 +6,7 @@ use super::*; #[test] fn collection_specs_are_pure_owner_declarations() { - let specs = collection_specs(); + let specs: Vec = collection_specs(); assert_eq!(specs.len(), 12); let mut names = std::collections::HashSet::new(); for spec in &specs { @@ -21,12 +21,22 @@ fn collection_specs_are_pure_owner_declarations() { assert_eq!(specs[0].indexes[0].fields, ["disposition"]); assert_eq!(specs[0].indexes[1].fields, ["expires_ms"]); assert_eq!(specs.last().unwrap().name, COALESCE); + assert_eq!( + serde_json::to_value(&specs[0]).unwrap(), + serde_json::json!({ + "name": OUTCOMES, + "indexes": [ + { "name": "by_disposition", "fields": ["disposition"], "unique": false }, + { "name": "by_expiry", "fields": ["expires_ms"], "unique": false } + ] + }) + ); } #[test] fn host_can_compose_collection_specs_with_its_other_storage() { let mut all = collection_specs(); - all.push(CollectionSpec::new("host.preferences")); + all.push(CollectionDeclaration::new("host.preferences")); let mut names = std::collections::HashSet::new(); assert!(all.iter().all(|spec| names.insert(spec.name.as_str()))); } diff --git a/crates/tinyeventqueues/Cargo.toml b/crates/tinyeventqueues/Cargo.toml index 6289efb..e696976 100644 --- a/crates/tinyeventqueues/Cargo.toml +++ b/crates/tinyeventqueues/Cargo.toml @@ -42,10 +42,10 @@ log = { workspace = true } [dev-dependencies] tokio = { workspace = true } # Real in-memory engines and shared queue conformance checks, for tests only. -tinystoragedrivers-testkit = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "29471a164619bcec03e5858a7d7ee0c65f52bf22" } +tinystoragedrivers-testkit = { version = "2.1.2", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "6226b9484c8bd01c58741718cd89ba90a13a36bb" } # Deterministic queue-clock tests use the v2 memory engine with the pipeline # ManualClock; production still receives QueueStore only from the host. -tinystoragedrivers-queue = { git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "29471a164619bcec03e5858a7d7ee0c65f52bf22" } +tinystoragedrivers-queue = { version = "2.1.2", git = "https://github.com/tinyhumansai/tinystoragedrivers", rev = "6226b9484c8bd01c58741718cd89ba90a13a36bb" } # The public-API test implements the `Host` trait as a downstream host does. async-trait = { workspace = true } # The release verifier passes an explicit empty module configuration, and the diff --git a/crates/tinyeventqueues/src/ports_tests.rs b/crates/tinyeventqueues/src/ports_tests.rs index e08275c..12816ee 100644 --- a/crates/tinyeventqueues/src/ports_tests.rs +++ b/crates/tinyeventqueues/src/ports_tests.rs @@ -20,21 +20,3 @@ fn oversized_composite_keys_are_bounded_and_deterministic() { assert!(first.as_str().starts_with('~')); assert!(first.as_str().len() <= tinystoragedrivers_types::MAX_KEY_LEN); } - -#[test] -fn oversized_keys_hash_exactly_like_the_legacy_key_of() { - // Golden values from the legacy `Key::of` (tinystoragedrivers-core - // 0c6dcfce): `~` + lowercase unpadded base32 of the SHA-256 of the escaped - // key. A different encoding would orphan dedupe and buffer rows written - // before the port. - let long = "x".repeat(600); - assert_eq!( - key_of(&[&long]).unwrap().as_str(), - "~keylgptlq757kmlo3ecj5gesj2yrbaalzovk3acq6zbpxjw7g7eq" - ); - let tail = "y".repeat(600); - assert_eq!( - key_of(&["a/b", &tail]).unwrap().as_str(), - "~2w4dnc7zzw6x7ml5j4pvc3pb6t34fqpcabnkn6yi6a2gpeyx5gba" - ); -} diff --git a/crates/tinyeventqueues/src/store/mod.rs b/crates/tinyeventqueues/src/store/mod.rs index 32a4c30..a2cd009 100644 --- a/crates/tinyeventqueues/src/store/mod.rs +++ b/crates/tinyeventqueues/src/store/mod.rs @@ -20,14 +20,15 @@ use std::sync::Arc; use crate::ports::{DocumentStore, Filter, Precondition, key_of}; use serde::{Deserialize, Serialize}; +use tinystoragedrivers_types::{CollectionSpec, IndexSpec}; use crate::Result; pub(crate) use ledger::Ledger; pub(crate) use repo::Repo; -// The collection names and specs are the contract's, so the host's grant and -// what the module ensures cannot drift. +// The contract owns the declaration data; this adapter maps it to the storage +// port's API so the host's grant and what the module ensures cannot drift. pub(crate) use tinyeventqueues_bus::storage::{ AMBIENT, BUCKETS, CADENCE, COALESCE, CONVERSATIONS, DIGEST, HABITUATION, OUTCOMES, REDRIVEN, STAGED, THREADS, TOMBSTONES, collection_specs, @@ -35,12 +36,28 @@ pub(crate) use tinyeventqueues_bus::storage::{ /// Declare every collection on `docs`. Idempotent. pub(crate) async fn ensure(docs: &dyn DocumentStore) -> Result<()> { - for spec in collection_specs() { + for declaration in collection_specs() { + let spec = collection_spec(declaration); docs.ensure_collection(&spec).await?; } Ok(()) } +/// Translate the bus-owned schema into the storage port's local type. +pub(crate) fn collection_spec( + declaration: tinyeventqueues_bus::storage::CollectionDeclaration, +) -> CollectionSpec { + let mut spec = CollectionSpec::new(declaration.name); + for index in declaration.indexes { + let mut spec_index = IndexSpec::new(index.name, index.fields); + if index.unique { + spec_index = spec_index.unique(); + } + spec = spec.index(spec_index); + } + spec +} + /// The document id of an event: its source and id, escaped and joined. pub(crate) fn event_id(source: &str, event_id: &str) -> Result { Ok(key_of(&[source, event_id])?.as_str().to_owned()) diff --git a/crates/tinyeventqueues/src/tinybus_module/README.md b/crates/tinyeventqueues/src/tinybus_module/README.md index f58b365..456bba8 100644 --- a/crates/tinyeventqueues/src/tinybus_module/README.md +++ b/crates/tinyeventqueues/src/tinybus_module/README.md @@ -19,14 +19,13 @@ The manifest method list must stay aligned with the interface macro's dispatch table and with `tinyeventqueues_bus::names::METHODS`; the unit tests check both. -- `settings.rs`: the private configuration blob (`storage_callback`, `queues`, +- `settings.rs`: the private configuration blob (`storage_address`, `queues`, `pipeline`, `timer`), strict, with the shipped files and default timer when absent. - `storage.rs`: the host's storage over the `tinystoragedrivers` storage bus, the one scope the host bound the module to: documents for the `teq.*` state (declared by `tinyeventqueues_bus::storage::collection_specs()`) and the - queue port for the manifest's queues. The host-provided `storage_callback` - setting names the unique callback binding admitted for this module instance, - or the shared storage service of a host that serves one for every module; + queue port for the manifest's queues. The host-provided `storage_address` + setting names the invocation route admitted for this module instance; missing or unusable host storage fails setup rather than starting with an ephemeral engine. - `host.rs`: `BusHost`, the pipeline's `Host`, calling the host's optional diff --git a/crates/tinyeventqueues/src/tinybus_module/mod.rs b/crates/tinyeventqueues/src/tinybus_module/mod.rs index 4e59587..85bcc89 100644 --- a/crates/tinyeventqueues/src/tinybus_module/mod.rs +++ b/crates/tinyeventqueues/src/tinybus_module/mod.rs @@ -6,13 +6,13 @@ //! //! * **Storage** ([`storage`]): the host's, over the storage bus — documents //! for the pipeline's `teq.*` state and the queue port for the queues the -//! manifest declares, in the one scope the host bound this module to. Setup -//! requires the unique host callback destination and never starts against an -//! in-memory fallback. +//! manifest declares, in the one scope the host bound this module to. An +//! explicit invocation address is never substituted, and setup requires +//! host-backed storage rather than an in-memory fallback. //! * **Configuration** ([`settings`]): the host's private configuration blob -//! may carry a `queues.json` and a `pipeline.json` document and the timer -//! bounds; absent, the shipped files run. The manifest is applied through -//! the queue port at setup. +//! may carry an invocation-scoped storage address, a `queues.json` and a +//! `pipeline.json` document, and timer bounds; absent, the shipped files run. +//! The manifest is applied through the queue port at setup. //! * **Host callbacks** ([`host`]): `ClassifySalience` and `Deliver` on the //! host's optional `ai.tinyhumans.tinyeventqueues.Host` interface. //! * **Passes** ([`ticker`]): the module runs passes on its own timer, waking @@ -130,9 +130,16 @@ fn setup_factory() -> impl Fn(Connection, serde_json::Value) -> SetupFuture + Cl async fn setup(connection: Connection, config: serde_json::Value, slot: Slot) -> TinyBusResult<()> { let settings = Settings::parse(config).map_err(|error| failed(&error))?; - let backing = storage::open(connection.clone(), settings.storage_callback.as_deref()) - .await - .map_err(|error| failed(&error))?; + let backing = if let Some(peer) = settings + .storage_callback() + .map_err(|error| failed(&error))? + { + storage::open_callback(connection.clone(), peer).await + } else { + let address = settings.storage_address().map_err(|error| failed(&error))?; + storage::open(connection.clone(), address).await + } + .map_err(|error| failed(&error))?; install(connection, settings, slot, backing).await } diff --git a/crates/tinyeventqueues/src/tinybus_module/mod_tests.rs b/crates/tinyeventqueues/src/tinybus_module/mod_tests.rs index 5e66037..2581015 100644 --- a/crates/tinyeventqueues/src/tinybus_module/mod_tests.rs +++ b/crates/tinyeventqueues/src/tinybus_module/mod_tests.rs @@ -15,10 +15,9 @@ use tinyeventqueues_bus::{ RedriveResponse, Sender, StatsRequest, StatsResponse, names, }; use tinystoragedrivers_api::StorageBackend; -use tinystoragedrivers_busproxy::StorageServer; -use tinystoragedrivers_busproxy::{PerCallerEndpoint, ServedStorage, serve}; +use tinystoragedrivers_busproxy::{PerCallerEndpoint, ServedStorage, StorageServer, serve}; #[cfg(all(target_os = "linux", not(feature = "static-link")))] -use tinystoragedrivers_busproxy::{prepare_storage_host_callbacks, serve_with_host_callbacks}; +use tinystoragedrivers_busproxy::{StorageAddress, serve_at_address}; use tinystoragedrivers_testkit::MemoryBackend; use tinystoragedrivers_types::Scope; @@ -335,18 +334,14 @@ async fn an_absent_host_makes_delivery_back_off() { } #[tokio::test] -async fn the_setup_factory_refuses_a_missing_storage_callback() { - let rig = rig(true).await; +async fn the_setup_factory_refuses_missing_host_storage() { + let rig = rig(false).await; let connection = Connection::connect(rig.bus.connect().await.unwrap()) .await .unwrap(); let setup = setup_factory(); let error = setup(connection, manual()).await.unwrap_err(); - assert!( - error - .to_string() - .contains("host callback destination is required") - ); + assert!(error.to_string().contains("storage"), "{error}"); } #[tokio::test] @@ -476,7 +471,7 @@ async fn the_module_timer_delivers_without_a_drain() { /// closed instead of borrowing the process-global storage service. #[cfg(feature = "static-link")] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn the_linked_module_without_a_storage_callback_fails_closed() { +async fn the_linked_module_without_host_storage_fails_closed() { use tinybus::module::ModuleHost; use tinybus::module::ModuleState; @@ -526,11 +521,101 @@ async fn the_linked_module_without_a_storage_callback_fails_closed() { ); } -/// The shipped cdylib uses the unique host callback destination admitted by -/// TinyBus and reads/writes the host's storage bundle through that binding. +/// The shipped cdylib uses the invocation address provided by its host and +/// cannot borrow the same storage endpoint from another bus peer. #[cfg(all(target_os = "linux", not(feature = "static-link")))] #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn a_loaded_module_uses_only_its_admitted_host_storage_callback() { +async fn a_loaded_module_uses_only_its_invocation_storage_address() { + let (dir, artifact) = trusted_module_artifact("invocation"); + + let bus = MemoryBus::new(); + let broker = Broker::new(); + let _broker_task = broker.clone().spawn(bus.clone()); + let modules = tinybus::module::ModuleHost::new(broker); + let storage_host = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let address = StorageAddress::try_new( + storage_host.unique_name().unwrap().clone(), + format!( + "{}/module_{}", + tinystoragedrivers_busproxy::INVOCATION_OBJECT_ROOT, + std::process::id() + ) + .parse() + .unwrap(), + ) + .unwrap(); + let backend = Arc::new(MemoryBackend::new()); + let bound = Arc::clone(&backend); + let first_peer = Arc::new(std::sync::Mutex::new(None)); + let endpoint_first_peer = Arc::clone(&first_peer); + let endpoint = PerCallerEndpoint::new(move |sender| { + let mut admitted = endpoint_first_peer.lock().ok()?; + match admitted.as_ref() { + Some(peer) if peer != sender => return None, + Some(_) => {} + None => *admitted = Some(sender.clone()), + } + let storage = bound.for_scope(&Scope::new("local").ok()?).ok()?; + Some(StorageServer::new(storage)) + }); + let _served = serve_at_address(&storage_host, address.clone(), Arc::new(endpoint)) + .await + .unwrap(); + + modules + .load_file_with_config( + &artifact, + json!({ + "storage_address": { + "host": address.host().as_str(), + "object_root": address.object_root().as_str(), + }, + "timer": { "enabled": false } + }), + ) + .unwrap(); + modules.ensure_ready(names::INTERFACE).await.unwrap(); + let client = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let proxy = client + .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE) + .unwrap(); + let event = InboundEvent::new( + "callback-test", + "stored", + "conversation", + Sender::new("user"), + EventKind::Message, + 1, + ); + let response: IngestResponse = proxy + .call(names::methods::INGEST, (IngestRequest::new(vec![event]),)) + .await + .unwrap(); + assert_eq!(response.results[0].disposition, Disposition::Accepted); + let stats: StatsResponse = proxy + .call(names::methods::STATS, (StatsRequest::new(),)) + .await + .unwrap(); + assert_eq!(stats.queues.iter().map(|queue| queue.ready).sum::(), 1); + + let outsider = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + assert!( + tinystoragedrivers_busproxy::connect_storage_at_address(outsider, address) + .await + .is_err() + ); + std::fs::remove_dir_all(dir).unwrap(); +} + +/// Stage a caller-selected build as operator-trusted test input, never a release pin. +#[cfg(all(target_os = "linux", not(feature = "static-link")))] +fn trusted_module_artifact(label: &str) -> (std::path::PathBuf, std::path::PathBuf) { let source = std::env::current_exe() .unwrap() .parent() @@ -546,7 +631,7 @@ async fn a_loaded_module_uses_only_its_admitted_host_storage_callback() { let dir = std::env::current_dir() .unwrap() .join("target") - .join(format!("callback-module-{}", std::process::id())); + .join(format!("callback-module-{label}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let artifact = dir.join("libtinyeventqueues.so"); @@ -557,33 +642,41 @@ async fn a_loaded_module_uses_only_its_admitted_host_storage_callback() { format!("\"libtinyeventqueues.so\" = \"{hash}\"\n"), ) .unwrap(); + (dir, artifact) +} +#[cfg(all(target_os = "linux", not(feature = "static-link")))] +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_loaded_module_uses_its_attested_storage_callback() { + let (dir, artifact) = trusted_module_artifact("bound-storage"); let bus = MemoryBus::new(); let broker = Broker::new(); let _broker_task = broker.clone().spawn(bus.clone()); let modules = tinybus::module::ModuleHost::new(broker); - let binding = prepare_storage_host_callbacks(&modules).await.unwrap(); - let backend = Arc::new(MemoryBackend::new()); - let bound = Arc::clone(&backend); - let endpoint = PerCallerEndpoint::new(move |_sender| { - let storage = bound.for_scope(&Scope::new("local").ok()?).ok()?; - Some(StorageServer::new(storage)) - }); - let _served = serve_with_host_callbacks(binding.clone(), Arc::new(endpoint)) + let binding = tinystoragedrivers_busproxy::prepare_storage_host_callbacks(&modules) .await .unwrap(); - + let backend = MemoryBackend::new(); + let storage = backend.for_scope(&Scope::new("callback").unwrap()).unwrap(); + let endpoint = PerCallerEndpoint::new(move |_| Some(StorageServer::new(storage.clone()))); + let served = tinystoragedrivers_busproxy::serve_with_host_callbacks( + Arc::clone(&binding), + Arc::new(endpoint), + ) + .await + .unwrap(); modules .load_file_with_host_callbacks( &artifact, json!({ - "storage_callback": binding.unique_name(), - "timer": { "enabled": false } + "storage_callback": binding.unique_name().as_str(), + "timer": {"enabled": false} }), &binding, ) .await .unwrap(); + modules.ensure_ready(names::INTERFACE).await.unwrap(); let client = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); @@ -591,7 +684,7 @@ async fn a_loaded_module_uses_only_its_admitted_host_storage_callback() { .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE) .unwrap(); let event = InboundEvent::new( - "callback-test", + "callback", "stored", "conversation", Sender::new("user"), @@ -608,14 +701,11 @@ async fn a_loaded_module_uses_only_its_admitted_host_storage_callback() { .await .unwrap(); assert_eq!(stats.queues.iter().map(|queue| queue.ready).sum::(), 1); - - let outsider = Connection::connect(bus.connect().await.unwrap()) - .await - .unwrap(); assert!( - tinystoragedrivers_busproxy::connect_storage_at(outsider, binding.unique_name().clone(),) + tinystoragedrivers_busproxy::connect_storage_at(client, binding.unique_name().clone()) .await .is_err() ); + served.shutdown().await.unwrap(); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/tinyeventqueues/src/tinybus_module/settings.rs b/crates/tinyeventqueues/src/tinybus_module/settings.rs index 46f1a1d..addabdd 100644 --- a/crates/tinyeventqueues/src/tinybus_module/settings.rs +++ b/crates/tinyeventqueues/src/tinybus_module/settings.rs @@ -5,21 +5,27 @@ //! //! ```json //! { -//! "storage_callback": ":1.42", +//! "storage_address": { +//! "host": ":1.42", +//! "object_root": "/ai/tinyhumans/tinystorage/Invocation/abc123" +//! }, //! "queues": { "version": 1, "queues": [ ... ] }, //! "pipeline": { "version": 1, ... }, //! "timer": { "enabled": true, "min_interval_ms": 100, "max_interval_ms": 5000 } //! } //! ``` //! -//! `storage_callback` is the unique destination of the storage callback -//! admitted by the host for this module instance, or the shared storage -//! service name (`ai.tinyhumans.tinystorage.Storage`) of a host that serves one -//! storage service for every module. `queues` is a `queues.json` -//! document and `pipeline` a `pipeline.json` document, both parsed as strictly -//! as the files are. A host that serves the module's queues should declare the -//! same manifest it passes here: its queue port admits an `EnsureQueue` only -//! for the spec it declared. +//! A `storage_callback` unique peer selects the host-bound callback endpoint. +//! It is mutually exclusive with `storage_address`; an explicit route never +//! falls back to global storage. +//! +//! `storage_address` identifies the host's invocation-scoped storage endpoint. +//! Its unique peer and invocation root must be issued by the host. An explicit +//! address never falls back to another storage route. `queues` is a +//! `queues.json` document and `pipeline` a `pipeline.json` document, both parsed +//! as strictly as the files are. A host that serves the module's queues should +//! declare the same manifest it passes here: its queue port admits an +//! `EnsureQueue` only for the spec it declared. use crate::config::{ QueueManifest, parse_manifest, parse_pipeline_config, shipped_manifest, shipped_pipeline_config, @@ -27,15 +33,20 @@ use crate::config::{ use crate::{Error, Result}; use serde::Deserialize; use serde_json::Value; +use tinybus::{BusName, ObjectPath}; use tinyeventqueues_bus::PipelineConfig; +use tinystoragedrivers_busproxy::StorageAddress; /// The module configuration. #[derive(Debug, Clone, Default, Deserialize)] #[serde(deny_unknown_fields)] pub(crate) struct Settings { - /// The host-admitted `TinyBus` callback destination for storage. + /// A host-bound storage callback peer; never a module-selected alias. + #[serde(default)] + storage_callback: Option, + /// Host-issued route for this module instance's scoped storage. #[serde(default)] - pub(crate) storage_callback: Option, + storage_address: Option, /// A `queues.json` document; the shipped one when absent. #[serde(default)] queues: Option, @@ -47,6 +58,14 @@ pub(crate) struct Settings { pub(crate) timer: TimerSettings, } +/// The JSON form of a host-issued invocation storage address. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +struct StorageAddressConfig { + host: String, + object_root: String, +} + /// The pass timer: how often the module runs a pass on its own. #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(deny_unknown_fields, default)] @@ -94,6 +113,54 @@ impl Settings { Ok(settings) } + /// Resolve the exact host callback peer without an invocation-route fallback. + /// + /// # Errors + /// Returns a configuration error for a non-unique peer or conflicting routes. + pub(crate) fn storage_callback(&self) -> Result> { + let Some(callback) = &self.storage_callback else { + return Ok(None); + }; + if self.storage_address.is_some() { + return Err(Error::config( + "storage_callback", + "cannot combine callback and invocation storage routes", + )); + } + let peer = BusName::new(callback) + .map_err(|_| Error::config("storage_callback", "expected a unique host peer"))?; + if !peer.is_unique() { + return Err(Error::config( + "storage_callback", + "expected a unique host peer", + )); + } + Ok(Some(peer)) + } + + /// Validate and build the host-issued invocation storage address, if set. + /// + /// # Errors + /// + /// [`Error::Config`] when the peer is not unique or the object root is + /// outside the invocation-scoped namespace. + pub(crate) fn storage_address(&self) -> Result> { + let Some(config) = &self.storage_address else { + return Ok(None); + }; + let host = BusName::new(&config.host) + .map_err(|_| Error::config("storage_address.host", "expected a unique bus name"))?; + let root = ObjectPath::new(&config.object_root).map_err(|_| { + Error::config( + "storage_address.object_root", + "expected an invocation object path", + ) + })?; + StorageAddress::try_new(host, root) + .map(Some) + .map_err(|_| Error::config("storage_address", "invalid invocation storage address")) + } + /// The queue manifest to run. /// /// # Errors diff --git a/crates/tinyeventqueues/src/tinybus_module/settings_tests.rs b/crates/tinyeventqueues/src/tinybus_module/settings_tests.rs index bf5936c..b35b2e0 100644 --- a/crates/tinyeventqueues/src/tinybus_module/settings_tests.rs +++ b/crates/tinyeventqueues/src/tinybus_module/settings_tests.rs @@ -11,6 +11,7 @@ use crate::config::{SHIPPED_PIPELINE_JSON, SHIPPED_QUEUES_JSON}; fn null_and_an_empty_object_run_the_shipped_files() { for blob in [Value::Null, json!({})] { let settings = Settings::parse(blob).unwrap(); + assert!(settings.storage_address().unwrap().is_none()); assert_eq!(settings.timer, TimerSettings::default()); assert_eq!(settings.manifest().unwrap(), shipped_manifest().unwrap()); assert_eq!( @@ -42,10 +43,70 @@ fn supplied_documents_replace_the_shipped_ones() { fn an_unknown_field_is_named() { let error = Settings::parse(json!({ "timers": {} })).unwrap_err(); assert!(error.to_string().contains("timers"), "{error}"); + let error = Settings::parse(json!({ "storage_addresses": {} })).unwrap_err(); + assert!(error.to_string().contains("storage_addresses"), "{error}"); let error = Settings::parse(json!({ "timer": { "every": 1 } })).unwrap_err(); assert!(error.to_string().contains("every"), "{error}"); } +#[test] +fn an_invocation_storage_address_is_validated_from_host_and_root() { + let settings = Settings::parse(json!({ + "storage_address": { + "host": ":1.23", + "object_root": "/ai/tinyhumans/tinystorage/Invocation/7" + } + })) + .unwrap(); + let address = settings.storage_address().unwrap().unwrap(); + assert_eq!(address.host().as_str(), ":1.23"); + assert_eq!( + address.object_root().as_str(), + "/ai/tinyhumans/tinystorage/Invocation/7" + ); +} + +#[test] +fn storage_addresses_reject_non_unique_hosts_and_unscoped_roots() { + for config in [ + json!({ "host": "ai.tinyhumans.host", "object_root": "/ai/tinyhumans/tinystorage/Invocation/7" }), + json!({ "host": ":1.23", "object_root": "/ai/tinyhumans/tinystorage/Leases/7" }), + ] { + let settings = Settings::parse(json!({ "storage_address": config })).unwrap(); + assert!(settings.storage_address().is_err()); + } +} + +#[test] +fn an_invalid_object_path_is_reported_as_a_configuration_error() { + let settings = Settings::parse(json!({ + "storage_address": { + "host": ":1.23", + "object_root": "not/an/object/path" + } + })) + .unwrap(); + + let error = settings.storage_address().unwrap_err(); + assert!( + error.to_string().contains("storage_address.object_root"), + "{error}" + ); +} + +#[test] +fn old_lease_descriptor_fields_are_not_accepted_as_an_address() { + let error = Settings::parse(json!({ + "storage_descriptor": { + "service_peer": ":1.23", + "registration_id": 7, + "object_root": "/ai/tinyhumans/tinystorage/Leases/7" + } + })) + .unwrap_err(); + assert!(error.to_string().contains("storage_descriptor"), "{error}"); +} + #[test] fn inverted_or_zero_timer_bounds_are_refused() { for timer in [ @@ -67,3 +128,30 @@ fn an_invalid_document_fails_when_it_is_read() { assert!(settings.manifest().is_err()); assert!(settings.pipeline().is_err()); } + +#[test] +fn a_host_bound_storage_callback_is_an_accepted_module_configuration() { + let settings = Settings::parse(json!({"storage_callback": ":1.23"})); + assert!( + settings.is_ok(), + "host callback config was refused: {settings:?}" + ); +} + +#[test] +fn storage_callbacks_require_a_unique_peer_and_one_route() { + let settings = Settings::parse(json!({"storage_callback": ":1.23"})).unwrap(); + assert_eq!( + settings.storage_callback().unwrap().unwrap().as_str(), + ":1.23" + ); + for peer in ["ai.tinyhumans.tinystorage.Storage", "not a peer", ""] { + let settings = Settings::parse(json!({"storage_callback": peer})).unwrap(); + assert!(settings.storage_callback().is_err()); + } + let settings = Settings::parse(json!({ + "storage_callback": ":1.23", + "storage_address": {"host": ":1.24", "object_root": "/ai/tinyhumans/tinystorage/Invocation/x"} + })).unwrap(); + assert!(settings.storage_callback().is_err()); +} diff --git a/crates/tinyeventqueues/src/tinybus_module/storage.rs b/crates/tinyeventqueues/src/tinybus_module/storage.rs index 1b3d69b..f582a0d 100644 --- a/crates/tinyeventqueues/src/tinybus_module/storage.rs +++ b/crates/tinyeventqueues/src/tinybus_module/storage.rs @@ -2,9 +2,9 @@ use std::sync::Arc; -use tinybus::Connection; +use tinybus::{BusName, Connection}; use tinystoragedrivers_api::{DocumentStore, QueueStore, Storage}; -use tinystoragedrivers_types::StorageError; +use tinystoragedrivers_busproxy::StorageAddress; use crate::{Error, Result}; @@ -24,48 +24,40 @@ impl Backing { } } -/// Connect to the host's storage ports. Missing or unusable host storage is a -/// setup error; this module never acknowledges work against an ephemeral -/// fallback engine. -pub(crate) async fn open(connection: Connection, callback: Option<&str>) -> Result { - let storage = match callback { - Some(destination) => { - let destination = tinybus::BusName::new(destination).map_err(|error| { - Error::from(tinystoragedrivers_types::StorageError::unavailable( - format!("invalid storage_callback {destination:?}: {error}"), - )) - })?; - let destination_display = destination.to_string(); - // A host that serves one storage service for every module names - // that service instead of a per-instance callback binding. The - // name is exact: any other name is used as-is, an absent one still - // fails, and so does a service nobody owns. - let connected = if destination.as_str() == tinystoragedrivers_busproxy::HOST_NAME { - tinystoragedrivers_busproxy::connect_storage(connection).await - } else { - tinystoragedrivers_busproxy::connect_storage_at(connection, destination).await - }; - connected.map_err(|error| { - Error::from( - StorageError::new( - error.kind(), - format!( - "storage_callback {destination_display} is unavailable: {}", - error.message() - ), - ) - .with_source(error), - ) - })? - } - None => { - return Err(Error::from( - tinystoragedrivers_types::StorageError::unavailable( - "host callback destination is required: set storage_callback in the module configuration", - ), - )); +/// Connect to one explicitly admitted host callback peer at the standard ports. +/// Invalid, missing, or unavailable peers never fall back to global storage. +/// +/// # Errors +/// Returns a configuration error for a non-unique peer, or the storage error +/// when the admitted callback cannot provide its ports. +pub(crate) async fn open_callback(connection: Connection, peer: BusName) -> Result { + if !peer.is_unique() { + return Err(Error::config( + "storage_callback", + "expected a unique host peer", + )); + } + let storage = tinystoragedrivers_busproxy::connect_storage_at(connection, peer) + .await + .map_err(Error::from)?; + Ok(Backing::of(&storage)) +} + +/// Connect to the host's v2 storage ports. An explicit invocation address is +/// used as-is; the default uses the host's ordinary caller-scoped endpoint. +/// Missing host storage is an error, so the module never acknowledges work +/// against an ephemeral engine. +pub(crate) async fn open( + connection: Connection, + address: Option, +) -> Result { + let storage = match address { + Some(address) => { + tinystoragedrivers_busproxy::connect_storage_at_address(connection, address).await } - }; + None => tinystoragedrivers_busproxy::connect_storage(connection).await, + } + .map_err(Error::from)?; Ok(Backing::of(&storage)) } diff --git a/crates/tinyeventqueues/src/tinybus_module/storage_tests.rs b/crates/tinyeventqueues/src/tinybus_module/storage_tests.rs index 1eb6221..534d18d 100644 --- a/crates/tinyeventqueues/src/tinybus_module/storage_tests.rs +++ b/crates/tinyeventqueues/src/tinybus_module/storage_tests.rs @@ -1,4 +1,4 @@ -//! Tests for opening host-provided storage and refusing missing storage. +//! Tests for the module's host-backed TSD v2 storage routes. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -8,47 +8,57 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use tinybus::Connection; use tinybus::broker::Broker; use tinybus::transport::memory::MemoryBus; +use tinyeventqueues_bus::storage::OUTCOMES; use tinystoragedrivers_api::StorageBackend; -use tinystoragedrivers_busproxy::{PerCallerEndpoint, StorageServer, serve}; -use tinystoragedrivers_types::Scope; +use tinystoragedrivers_busproxy::{ + PerCallerEndpoint, StorageAddress, StorageServer, connect_storage_at_address, serve_at_address, +}; +use tinystoragedrivers_testkit::MemoryBackend; +use tinystoragedrivers_types::{Precondition, Scope}; use super::*; -use crate::ports::ErrorKind; +use crate::store::{collection_spec, collection_specs}; use crate::tinybus_module::tests::rig; #[tokio::test] -async fn a_missing_callback_is_refused_even_when_the_global_host_is_serving_storage() { +async fn the_default_route_uses_the_host_scoped_storage_ports() { let rig = rig(true).await; let module = Connection::connect(rig.bus.connect().await.unwrap()) .await .unwrap(); - let refused = open(module, None).await; - assert!(matches!( - &refused, - Err(crate::Error::Storage(error)) if error.kind() == ErrorKind::Unavailable - )); - assert!( - refused - .unwrap_err() - .to_string() - .contains("storage_callback") - ); + let backing = open(module, None).await.unwrap(); + + for declaration in collection_specs() { + let spec = collection_spec(declaration); + backing.docs.ensure_collection(&spec).await.unwrap(); + } + backing + .docs + .put( + OUTCOMES, + "x", + serde_json::json!({"stored": true}), + Precondition::None, + ) + .await + .unwrap(); + let host = rig + .backend + .for_scope(&Scope::new("local").unwrap()) + .unwrap(); + assert!(host.documents().get(OUTCOMES, "x").await.unwrap().is_some()); } #[tokio::test] -async fn a_host_without_storage_refuses_setup_instead_of_using_memory() { +async fn missing_or_unusable_global_storage_fails_setup() { let rig = rig(false).await; let module = Connection::connect(rig.bus.connect().await.unwrap()) .await .unwrap(); assert!(open(module, None).await.is_err()); -} -#[tokio::test] -async fn a_storage_host_that_cannot_be_reached_fails_setup_instead_of_using_memory() { - let rig = rig(false).await; - // Something owns the storage name but serves no storage objects: a host - // whose storage is present but failing. + // A host name without the storage objects is unavailable, not permission + // to acknowledge work in memory. rig.host .request_name(tinystoragedrivers_busproxy::HOST_NAME) .await @@ -56,104 +66,137 @@ async fn a_storage_host_that_cannot_be_reached_fails_setup_instead_of_using_memo let module = Connection::connect(rig.bus.connect().await.unwrap()) .await .unwrap(); - let callback = rig.host.unique_name().unwrap(); - let refused = open(module, Some(callback.as_str())).await; - assert!(refused.is_err(), "fell back to memory: {refused:?}"); - assert!( - refused - .unwrap_err() - .to_string() - .contains("storage_callback") - ); + assert!(open(module, None).await.is_err()); } #[tokio::test] -async fn an_unadmitted_storage_destination_does_not_fall_back_to_global_storage() { +async fn an_explicit_invocation_address_never_falls_back_to_global_storage() { + let rig = rig(true).await; + let module = Connection::connect(rig.bus.connect().await.unwrap()) + .await + .unwrap(); + let host = rig.host.unique_name().unwrap().clone(); + let address = StorageAddress::try_new( + host, + format!( + "{}/missing", + tinystoragedrivers_busproxy::INVOCATION_OBJECT_ROOT + ) + .parse() + .unwrap(), + ) + .unwrap(); + + assert!(open(module, Some(address)).await.is_err()); +} + +#[tokio::test] +async fn an_issued_invocation_address_is_caller_bound_and_revocable() { let bus = MemoryBus::new(); Broker::new().spawn(bus.clone()); let host = Connection::connect(bus.connect().await.unwrap()) .await .unwrap(); - let backend = Arc::new(tinystoragedrivers_testkit::MemoryBackend::new()); - let providers = Arc::new(AtomicUsize::new(0)); - let served_backend = Arc::clone(&backend); - let provider_calls = Arc::clone(&providers); - let endpoint = PerCallerEndpoint::new(move |_sender| { - provider_calls.fetch_add(1, Ordering::Relaxed); - let storage = served_backend.for_scope(&Scope::new("local").ok()?).ok()?; + let module = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + let module_peer = module.unique_name().unwrap().clone(); + let address = StorageAddress::try_new( + host.unique_name().unwrap().clone(), + format!( + "{}/event_queues_1", + tinystoragedrivers_busproxy::INVOCATION_OBJECT_ROOT + ) + .parse() + .unwrap(), + ) + .unwrap(); + let backend = Arc::new(MemoryBackend::new()); + let scope = Scope::new("event-queues-bound").unwrap(); + let admitted_calls = Arc::new(AtomicUsize::new(0)); + let endpoint_backend = Arc::clone(&backend); + let endpoint_scope = scope.clone(); + let endpoint_peer = module_peer.clone(); + let endpoint_calls = Arc::clone(&admitted_calls); + let endpoint = PerCallerEndpoint::new(move |sender| { + if sender != &endpoint_peer { + return None; + } + endpoint_calls.fetch_add(1, Ordering::Relaxed); + let storage = endpoint_backend.for_scope(&endpoint_scope).ok()?; Some(StorageServer::new(storage)) }); - let _served = serve(&host, Arc::new(endpoint)).await.unwrap(); - let module = Connection::connect(bus.connect().await.unwrap()) + let served = serve_at_address(&host, address.clone(), Arc::new(endpoint)) .await .unwrap(); - // The ordinary global host is live, but a caller-supplied callback name is - // an authority boundary and must be used as-is. - let refused = open(module, Some(":1.999999")).await; - assert!(matches!( - &refused, - Err(crate::Error::Storage(error)) if error.kind() == ErrorKind::Unavailable - )); + let backing = open(module.clone(), Some(address.clone())).await.unwrap(); + for declaration in collection_specs() { + let spec = collection_spec(declaration); + backing.docs.ensure_collection(&spec).await.unwrap(); + } + backing + .docs + .put( + OUTCOMES, + "bound", + serde_json::json!({"stored": true}), + Precondition::None, + ) + .await + .unwrap(); + let scoped = backend.for_scope(&scope).unwrap(); assert!( - refused - .unwrap_err() - .to_string() - .contains("storage_callback") - ); - assert_eq!( - providers.load(Ordering::Relaxed), - 0, - "the rejected callback fell through to the global storage provider" + scoped + .documents() + .get(OUTCOMES, "bound") + .await + .unwrap() + .is_some() ); + + let outsider = Connection::connect(bus.connect().await.unwrap()) + .await + .unwrap(); + assert!(connect_storage_at_address(outsider, address).await.is_err()); + assert!(admitted_calls.load(Ordering::Relaxed) > 0); + + served.shutdown().await.unwrap(); + assert!(backing.docs.get(OUTCOMES, "bound").await.is_err()); } #[tokio::test] -async fn an_invalid_storage_destination_is_rejected_before_connecting() { +async fn an_unattested_callback_is_refused_even_when_it_serves_storage() { let rig = rig(true).await; let module = Connection::connect(rig.bus.connect().await.unwrap()) .await .unwrap(); - let refused = open(module, Some("")).await; - assert!(matches!( - &refused, - Err(crate::Error::Storage(error)) if error.kind() == ErrorKind::Unavailable - )); + let result = open_callback(module, rig.host.unique_name().unwrap().clone()).await; assert!( - refused - .unwrap_err() - .to_string() - .contains("storage_callback") + result.is_err(), + "ordinary peers must not acquire callback authority" ); } #[tokio::test] -async fn the_shared_storage_service_name_reaches_the_host_serving_it() { - // A host that serves one storage service for every module names that - // service instead of a per-instance callback binding. +async fn a_missing_callback_never_uses_working_global_storage() { let rig = rig(true).await; let module = Connection::connect(rig.bus.connect().await.unwrap()) .await .unwrap(); - let opened = open(module, Some(tinystoragedrivers_busproxy::HOST_NAME)).await; - assert!( - opened.is_ok(), - "the shared storage service was refused: {opened:?}" - ); + let missing = tinybus::BusName::new(":1.999999").unwrap(); + assert!(open_callback(module, missing).await.is_err()); } #[tokio::test] -async fn the_shared_storage_service_name_fails_setup_when_nobody_serves_it() { - let rig = rig(false).await; +async fn a_well_known_callback_name_cannot_borrow_working_global_storage() { + let rig = rig(true).await; let module = Connection::connect(rig.bus.connect().await.unwrap()) .await .unwrap(); - let refused = open(module, Some(tinystoragedrivers_busproxy::HOST_NAME)).await; - assert!(refused.is_err(), "fell back to memory: {refused:?}"); - assert!( - refused - .unwrap_err() - .to_string() - .contains("storage_callback") - ); + let peer = BusName::new("ai.tinyhumans.tinystorage").unwrap(); + let error = open_callback(module, peer).await.unwrap_err(); + let message = error.to_string(); + assert!(message.contains("storage_callback"), "{message}"); + assert!(message.contains("expected a unique host peer"), "{message}"); } diff --git a/deny.toml b/deny.toml index cce6729..7f88b29 100644 --- a/deny.toml +++ b/deny.toml @@ -49,5 +49,5 @@ deny = [] unknown-registry = "deny" unknown-git = "deny" allow-registry = ["https://github.com/rust-lang/crates.io-index"] -# TinyStorageDrivers is pinned to the canonical v2.1.0 source revision. +# TinyStorageDrivers is pinned to the canonical v2.1.2 release revision. allow-git = ["https://github.com/tinyhumansai/tinystoragedrivers"] diff --git a/docs/specs/event-pipeline.md b/docs/specs/event-pipeline.md index eadba01..78dd17e 100644 --- a/docs/specs/event-pipeline.md +++ b/docs/specs/event-pipeline.md @@ -168,11 +168,13 @@ are in `tinyeventqueues-bus`. declared by `tinyeventqueues-bus::storage::collection_specs()` (owner `teq`, module scope), from which the host derives the grant; its queues are those `queues.json` declares, served by the host's queue port. - Without the callback destination, setup fails; there is no in-memory - fallback. -- Configuration: the host-provided private blob carries `storage_callback` - (the unique name for the admitted storage callback, or the shared storage - service name `ai.tinyhumans.tinystorage.Storage`), plus `queues` (a `queues.json` + An explicit `storage_address` or `storage_callback` never falls back to + another route. With neither field, the module uses the host's ordinary + caller-scoped storage endpoint and fails if it is unavailable. There is no + in-memory fallback. +- Configuration: the host-provided private blob carries `storage_address` + (the host-issued invocation storage route) or a mutually exclusive + `storage_callback` (an attested unique host peer), plus `queues` (a `queues.json` document), `pipeline` (a `pipeline.json` document) and `timer` bounds; absent fields run the shipped files. The manifest is applied through the queue port at setup. diff --git a/vendor/tinybus b/vendor/tinybus index 6ce06bc..8534511 160000 --- a/vendor/tinybus +++ b/vendor/tinybus @@ -1 +1 @@ -Subproject commit 6ce06bc674e4f4d718aa51e643ef62c1f372e270 +Subproject commit 85345114f3066e94d5d70161ea8dc43252b83ae6