lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit 8b54f12ee947fdb6e86e622afdd74a48a0ca83c9
parent b004dcaaa0672e397f0b00da4ee81ee175e06d33
Author: triesap <tyson@radroots.org>
Date:   Sun, 18 Oct 2026 20:20:37 +0000

storage: add owned indexeddb atomic transactions

- Separate exact namespace creation from existing schema validation and reopening.
- Commit bounded compare-exchange batches only after actual transaction completion.
- Retain accepted local work and callbacks across observer loss and closing.
- Exercise rollback, conflicts, lifecycle and worker execution in three browsers.

Diffstat:
MCargo.lock | 12++++++++++++
MCargo.toml | 4++++
Mcontracts/coverage.toml | 1+
Mcontracts/crates/catalog.v2.toml | 20+++++++++++++++++++-
Mcontracts/crates/generated/package_groups.v1.toml | 10+++++-----
Mcontracts/crates/generated/platform_inventory.v1.toml | 4++--
Mcontracts/crates/generated/release_inventory.v2.toml | 4++--
Mcontracts/releases/publish_policy.toml | 1+
Acrates/storage_indexeddb/Cargo.toml | 25+++++++++++++++++++++++++
Acrates/storage_indexeddb/README.md | 29+++++++++++++++++++++++++++++
Acrates/storage_indexeddb/src/browser.rs | 519+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_indexeddb/src/lib.rs | 272+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_indexeddb/tests/browser/Cargo.lock | 1056+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_indexeddb/tests/browser/Cargo.toml | 19+++++++++++++++++++
Acrates/storage_indexeddb/tests/browser/run.mjs | 136+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/storage_indexeddb/tests/browser/src/lib.rs | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 2207 insertions(+), 10 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3648,6 +3648,18 @@ dependencies = [ ] [[package]] +name = "radroots_storage_indexeddb" +version = "0.1.0-alpha" +dependencies = [ + "futures", + "js-sys", + "radroots_storage", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] name = "radroots_storage_sqlite" version = "0.1.0-alpha" dependencies = [ diff --git a/Cargo.toml b/Cargo.toml @@ -14,6 +14,7 @@ members = [ "crates/secrets", "crates/storage", "crates/storage_sqlite", + "crates/storage_indexeddb", "crates/sync", "crates/geonames", "crates/nostrdb", @@ -153,6 +154,7 @@ radroots_secrets = { package = "radroots_secrets", path = "crates/secrets", vers radroots_signing = { package = "radroots_signing", path = "crates/signing", version = "=0.1.0-alpha", default-features = false } radroots_storage = { package = "radroots_storage", path = "crates/storage", version = "=0.1.0-alpha", default-features = false } radroots_storage_sqlite = { package = "radroots_storage_sqlite", path = "crates/storage_sqlite", version = "=0.1.0-alpha", default-features = false } +radroots_storage_indexeddb = { path = "crates/storage_indexeddb", version = "=0.1.0-alpha" } radroots_sync = { package = "radroots_sync", path = "crates/sync", version = "=0.1.0-alpha", default-features = false } radroots_trade = { package = "radroots_trade", path = "crates/trade", version = "=0.1.0-alpha", default-features = false } radroots_transport = { package = "radroots_transport", path = "crates/transport", version = "=0.1.0-alpha", default-features = false } @@ -273,7 +275,9 @@ url_nostd = { package = "url", version = "2", default-features = false } uuid = { version = "1.22.0", features = ["v4", "v7"] } uniffi = { version = "0.29.4" } wasm-bindgen = { version = "0.2" } +wasm-bindgen-futures = { version = "0.4" } wasm-bindgen-test = { version = "0.3" } +web-sys = { version = "0.3" } webpki-roots = { version = "0.26.11" } walkdir = { version = "2" } x509-parser = { version = "0.17", default-features = false } diff --git a/contracts/coverage.toml b/contracts/coverage.toml @@ -70,6 +70,7 @@ crates = [ "radroots_secrets", "radroots_signing", "radroots_storage", + "radroots_storage_indexeddb", "radroots_storage_sqlite", "radroots_sync", "radroots_transport_nostr", diff --git a/contracts/crates/catalog.v2.toml b/contracts/crates/catalog.v2.toml @@ -7,7 +7,7 @@ rust_version = "1.99.0" edition = "2024" resolver = "3" public_package_count = 21 -package_count = 53 +package_count = 54 digest_algorithm = "sha256-raw-bytes-v1" source_tree_digest_algorithm = "sha256-git-ls-tree-r-v1" native_introduction_tree_digest_algorithm = "sha256-git-tree-records-z-v1" @@ -349,6 +349,24 @@ compatibility = ["rust_api", "wire", "security", "features", "package"] replaces = [] [[package]] +name = "radroots_storage_indexeddb" +path = "crates/storage_indexeddb" +state = "active" +tier = "adapter" +visibility = "private_adapter" +publish = false +version = "0.1.0-alpha" +license = "MIT OR Apache-2.0" +platforms = ["wasm32"] +groups = ["coverage_required", "wasm"] +owners = ["storage"] +permitted_dependency_tiers = ["spi"] +provenance_kind = "native" +introduction_tree_sha256 = "82fc3620ff91692beab1d10d0f5384dc48fa236f0fe14d506ec12f28c9759b6c" +compatibility = ["package_private", "rust_api"] +replaces = [] + +[[package]] name = "radroots_storage_sqlite" path = "crates/storage_sqlite" state = "active" diff --git a/contracts/crates/generated/package_groups.v1.toml b/contracts/crates/generated/package_groups.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.package-groups.v1" -catalog_sha256 = "407a02944413642b772593c6bfd23967daccd0a21cb2daabef509aafa49f311a" +catalog_sha256 = "a64c4056370fcd715f6f13df879c71cf34f22520f29a53c0b8b17c7e9d17bde7" [[group]] id = "boundaries" @@ -9,8 +9,8 @@ reserved_packages = [] [[group]] id = "coverage_required" -packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] -active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_indexeddb", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] +active_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_core_bindings", "radroots_domain", "radroots_event", "radroots_event_bindings", "radroots_event_codec", "radroots_event_codec_wasm", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostr", "radroots_nostr_connect", "radroots_nostrdb", "radroots_protocol", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_secrets", "radroots_service_host", "radroots_service_sqlite", "radroots_signing", "radroots_sql_core", "radroots_storage", "radroots_storage_indexeddb", "radroots_storage_sqlite", "radroots_sync", "radroots_test_fixtures", "radroots_trade", "radroots_trade_bindings", "radroots_transport", "radroots_transport_nostr", "radroots_transport_reticulum", "xtask"] reserved_packages = [] [[group]] @@ -45,6 +45,6 @@ reserved_packages = [] [[group]] id = "wasm" -packages = ["radroots_event_codec_wasm", "radroots_replica_store_wasm", "radroots_replica_sync_wasm", "radroots_sdk_sql_wasm_runtime", "radroots_sql_core"] -active_packages = ["radroots_event_codec_wasm", "radroots_replica_store_wasm", "radroots_replica_sync_wasm", "radroots_sdk_sql_wasm_runtime", "radroots_sql_core"] +packages = ["radroots_event_codec_wasm", "radroots_replica_store_wasm", "radroots_replica_sync_wasm", "radroots_sdk_sql_wasm_runtime", "radroots_sql_core", "radroots_storage_indexeddb"] +active_packages = ["radroots_event_codec_wasm", "radroots_replica_store_wasm", "radroots_replica_sync_wasm", "radroots_sdk_sql_wasm_runtime", "radroots_sql_core", "radroots_storage_indexeddb"] reserved_packages = [] diff --git a/contracts/crates/generated/platform_inventory.v1.toml b/contracts/crates/generated/platform_inventory.v1.toml @@ -1,5 +1,5 @@ schema = "radroots.workspace.platform-inventory.v1" -catalog_sha256 = "407a02944413642b772593c6bfd23967daccd0a21cb2daabef509aafa49f311a" +catalog_sha256 = "a64c4056370fcd715f6f13df879c71cf34f22520f29a53c0b8b17c7e9d17bde7" [[platform]] id = "any" @@ -11,4 +11,4 @@ packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_geona [[platform]] id = "wasm32" -packages = ["radroots_event_codec_wasm", "radroots_replica_store_wasm", "radroots_replica_sync_wasm", "radroots_sdk_sql_wasm_runtime", "radroots_sql_core"] +packages = ["radroots_event_codec_wasm", "radroots_replica_store_wasm", "radroots_replica_sync_wasm", "radroots_sdk_sql_wasm_runtime", "radroots_sql_core", "radroots_storage_indexeddb"] diff --git a/contracts/crates/generated/release_inventory.v2.toml b/contracts/crates/generated/release_inventory.v2.toml @@ -1,7 +1,7 @@ schema = "radroots.workspace.release-inventory.v2" -catalog_sha256 = "407a02944413642b772593c6bfd23967daccd0a21cb2daabef509aafa49f311a" +catalog_sha256 = "a64c4056370fcd715f6f13df879c71cf34f22520f29a53c0b8b17c7e9d17bde7" architecture = "radroots.crates.release.v2" version = "0.1.0-alpha" public_packages = ["radroots", "radroots_blossom", "radroots_core", "radroots_domain", "radroots_event", "radroots_event_codec", "radroots_execution", "radroots_geonames", "radroots_identity", "radroots_nostr", "radroots_nostr_connect", "radroots_protocol", "radroots_sdk", "radroots_secrets", "radroots_signing", "radroots_storage", "radroots_storage_sqlite", "radroots_sync", "radroots_trade", "radroots_transport", "radroots_transport_nostr"] -private_packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_reticulum", "xtask"] +private_packages = ["radroots_core_bindings", "radroots_event_bindings", "radroots_event_codec_wasm", "radroots_identity_bindings", "radroots_mesh", "radroots_mesh_agent_client", "radroots_mesh_agent_proto", "radroots_nostrdb", "radroots_replica_schema", "radroots_replica_schema_bindings", "radroots_replica_store", "radroots_replica_store_wasm", "radroots_replica_sync", "radroots_replica_sync_wasm", "radroots_runtime_distribution", "radroots_runtime_manager", "radroots_runtime_paths", "radroots_sdk_ffi", "radroots_sdk_sql_wasm_runtime", "radroots_service_host", "radroots_service_sqlite", "radroots_simplex_agent_proto", "radroots_simplex_app_store", "radroots_simplex_chat_proto", "radroots_simplex_smp_crypto", "radroots_simplex_smp_proto", "radroots_simplex_smp_transport", "radroots_sql_core", "radroots_storage_indexeddb", "radroots_test_fixtures", "radroots_trade_bindings", "radroots_transport_reticulum", "xtask"] reserved_packages = [] diff --git a/contracts/releases/publish_policy.toml b/contracts/releases/publish_policy.toml @@ -63,6 +63,7 @@ private = [ "radroots_service_host", "radroots_service_sqlite", "radroots_sql_core", + "radroots_storage_indexeddb", ] build_codegen = [ "radroots_core_bindings", diff --git a/crates/storage_indexeddb/Cargo.toml b/crates/storage_indexeddb/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "radroots_storage_indexeddb" +publish = false +version = "0.1.0-alpha" +edition.workspace = true +rust-version.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +description = "Per-client IndexedDB atomic persistence for Radroots browser hosts" +readme = "README.md" + +[dependencies] +radroots_storage = { workspace = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +futures = { workspace = true } +js-sys = { workspace = true } +wasm-bindgen = { workspace = true } +wasm-bindgen-futures = { workspace = true } +web-sys = { workspace = true, features = ["DomException", "DomStringList", "Event", "EventTarget", "IdbDatabase", "IdbFactory", "IdbObjectStore", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbVersionChangeEvent"] } + +[lints] +workspace = true diff --git a/crates/storage_indexeddb/README.md b/crates/storage_indexeddb/README.md @@ -0,0 +1,29 @@ +# radroots_storage_indexeddb + +An explicit per-connection IndexedDB host for bounded opaque records. Namespace +identity comes from a supplied source generation. Creating a namespace and +opening an existing namespace are distinct operations; missing data never +silently creates a replacement. Importing the package performs no host work. + +Atomic compare/exchange checks every original value and writes the complete +batch in one real transaction. Dependent requests are issued from active +IndexedDB callbacks. Success is returned only after `complete`; request success +alone never acknowledges a commit. Accepted work remains owned after its +observer is dropped. Closing stops admission and waits for accepted work. + +This initial private host stores opaque bytes. It supplies no participant +custody, authenticated workspace, complete storage SPI or stock authority. +Callers must apply their own protected record codecs and exact journal rules. +Browser storage can be evicted; opening an absent namespace reports its absence. +No SQL global, memory fallback, network, implicit migration or automatic replay +is used. The transaction behavior follows the +[IndexedDB transaction lifecycle](https://w3c.github.io/IndexedDB/#transaction-lifecycle). + +The standalone fixture at `tests/browser/Cargo.toml` builds the real host to +WASM. Generate its web bindings with the `wasm-bindgen` version matching that +fixture's lockfile, using an external output directory and the output name +`fixture`. Run `tests/browser/run.mjs` with an installed Playwright package +directory, that output directory, and `chromium`, `firefox`, or `webkit`. +Both the page and dedicated worker import those generated bytes. The runner +uses isolated loopback origins and bounds each run to 90 seconds. Route builds, +generation and runner execution through `cargo extbuild run --`. diff --git a/crates/storage_indexeddb/src/browser.rs b/crates/storage_indexeddb/src/browser.rs @@ -0,0 +1,519 @@ +use super::{ + Batch, Commit, Error, LIVE_BYTES_MAX, Mutation, Namespace, OpenMode, RECORD_BYTES_MAX, + RecordKey, +}; +use futures::channel::oneshot; +use js_sys::{Reflect, Uint8Array}; +use std::{ + cell::{Cell, RefCell}, + future::poll_fn, + rc::{Rc, Weak}, + task::{Poll, Waker}, +}; +use wasm_bindgen::{JsCast, JsValue, closure::Closure}; +use wasm_bindgen_futures::spawn_local; +use web_sys::{ + Event, IdbDatabase, IdbFactory, IdbObjectStore, IdbOpenDbRequest, IdbRequest, IdbTransaction, + IdbTransactionMode, +}; + +const STORE: &str = "records"; +const WORK_MAX: usize = 32; +type EventCallback = Closure<dyn FnMut(Event)>; + +fn classify(value: JsValue) -> Error { + match value + .dyn_ref::<web_sys::DomException>() + .map(web_sys::DomException::name) + .as_deref() + { + Some("QuotaExceededError") => Error::Capacity, + Some("VersionError") => Error::IncompatibleSchema, + Some("InvalidStateError") => Error::Closed, + _ => Error::Unavailable, + } +} +fn key(value: RecordKey) -> JsValue { + Uint8Array::from(value.as_bytes().as_slice()).into() +} +fn bytes(value: JsValue) -> Result<Option<Vec<u8>>, Error> { + if value.is_undefined() { + return Ok(None); + } + let value = value + .dyn_into::<Uint8Array>() + .map_err(|_| Error::CorruptRecord)?; + if value.length() as usize > RECORD_BYTES_MAX { + return Err(Error::CorruptRecord); + } + Ok(Some(value.to_vec())) +} + +struct State { + db: IdbDatabase, + closing: Cell<bool>, + count: Cell<usize>, + bytes: Cell<usize>, + waiters: RefCell<Vec<Weak<RefCell<Option<Waker>>>>>, + version_change: RefCell<Option<EventCallback>>, +} +impl State { + fn stop(&self) { + self.closing.set(true); + if self.count.get() == 0 { + self.db.close(); + } + self.wake(); + } + fn wake(&self) { + self.waiters.borrow_mut().retain(|weak| { + if let Some(signal) = weak.upgrade() { + if let Some(waker) = signal.borrow_mut().take() { + waker.wake(); + } + true + } else { + false + } + }); + } + fn admit(self: &Rc<Self>, bytes: usize) -> Result<Work, Error> { + if self.closing.get() { + return Err(Error::Closed); + } + let total = self.bytes.get().checked_add(bytes).ok_or(Error::Capacity)?; + if self.count.get() >= WORK_MAX || total > LIVE_BYTES_MAX { + return Err(Error::Capacity); + } + self.count.set(self.count.get() + 1); + self.bytes.set(total); + Ok(Work { + state: self.clone(), + bytes, + }) + } +} +impl Drop for State { + fn drop(&mut self) { + self.db.set_onversionchange(None); + self.db.close(); + } +} +struct Work { + state: Rc<State>, + bytes: usize, +} +impl Drop for Work { + fn drop(&mut self) { + self.state.count.set(self.state.count.get() - 1); + self.state.bytes.set(self.state.bytes.get() - self.bytes); + if self.state.closing.get() && self.state.count.get() == 0 { + self.state.db.close(); + } + self.state.wake(); + } +} + +/// One explicit connection. Clones share admission, accepted work and closure. +/// Independent opens use independent handles; IndexedDB serializes conflicts. +#[derive(Clone)] +pub struct Database { + state: Rc<State>, +} +impl Database { + /// Explicitly opens the exact namespace. Dropped observation cannot leak a + /// subsequently opened connection or cancel an accepted schema transaction. + pub async fn open(namespace: Namespace, mode: OpenMode) -> Result<Self, Error> { + let factory = Reflect::get(&js_sys::global(), &JsValue::from_str("indexedDB")) + .map_err(classify)? + .dyn_into::<IdbFactory>() + .map_err(|_| Error::Unavailable)?; + let request = factory + .open_with_u32(&namespace.name(), 1) + .map_err(classify)?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let _ = send.send(open(request, mode).await); + }); + observe.await.unwrap_or(Err(Error::Unavailable)) + } + /// Reads exact bytes, acknowledging the read transaction only on complete. + /// Missing is distinct from an empty value and from a missing namespace. + pub async fn get(&self, record: RecordKey) -> Result<Option<Vec<u8>>, Error> { + let work = self.state.admit(RECORD_BYTES_MAX)?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let owner = work; + let result = match owner + .state + .db + .transaction_with_str_and_mode(STORE, IdbTransactionMode::Readonly) + { + Ok(tx) => read(tx, record).await, + Err(error) => Err(classify(error)), + }; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(Error::CommitUnknown)) + } + /// Atomically compares original values and installs all replacements. + /// All requests are enqueued in active callbacks; no user future runs + /// inside a transaction. Only the complete event returns a Commit. + pub async fn compare_exchange(&self, batch: Batch) -> Result<Commit, Error> { + let work = self.state.admit(batch.bytes)?; + let (send, observe) = oneshot::channel(); + spawn_local(async move { + let owner = work; + let result = match owner + .state + .db + .transaction_with_str_and_mode(STORE, IdbTransactionMode::Readwrite) + { + Ok(tx) => exchange(tx, batch).await, + Err(error) => Err(classify(error)), + }; + let _ = send.send(result); + }); + observe.await.unwrap_or(Err(Error::CommitUnknown)) + } + /// Stops admission immediately when polled, drains every accepted job and + /// closes the connection. A cancelled observer can explicitly resume close. + pub async fn close(&self) -> Result<(), Error> { + self.state.stop(); + if self.state.count.get() == 0 { + return Ok(()); + } + let signal = Rc::new(RefCell::new(None)); + { + let mut waiters = self.state.waiters.borrow_mut(); + waiters.retain(|weak| weak.strong_count() > 0); + if waiters.len() >= WORK_MAX { + return Err(Error::Capacity); + } + waiters.push(Rc::downgrade(&signal)); + } + poll_fn(|cx| { + if self.state.count.get() == 0 { + return Poll::Ready(()); + } + *signal.borrow_mut() = Some(cx.waker().clone()); + Poll::Pending + }) + .await; + Ok(()) + } +} + +struct OpenHandlers { + request: IdbOpenDbRequest, + _upgrade: Closure<dyn FnMut(Event)>, + _success: Closure<dyn FnMut(Event)>, + _error: Closure<dyn FnMut(Event)>, +} +impl Drop for OpenHandlers { + fn drop(&mut self) { + self.request.set_onupgradeneeded(None); + self.request.set_onsuccess(None); + self.request.set_onerror(None); + } +} +async fn open(request: IdbOpenDbRequest, mode: OpenMode) -> Result<Database, Error> { + let created = Rc::new(Cell::new(false)); + let failure = Rc::new(Cell::new(None)); + let (send, observe) = oneshot::channel(); + let reply = Rc::new(RefCell::new(Some(send))); + let upgrade = { + let request = request.clone(); + let created = created.clone(); + let failure = failure.clone(); + Closure::new(move |_: Event| { + let result = (|| { + if mode == OpenMode::Existing { + return Err(Error::MissingNamespace); + } + let db = request + .result() + .map_err(classify)? + .dyn_into::<IdbDatabase>() + .map_err(|_| Error::IncompatibleSchema)?; + db.create_object_store(STORE).map_err(classify)?; + created.set(true); + Ok(()) + })(); + if let Err(error) = result { + failure.set(Some(error)); + if let Some(tx) = request.transaction() { + let _ = tx.abort(); + } + } + }) + }; + let success = { + let request = request.clone(); + let created = created.clone(); + let failure = failure.clone(); + let reply = reply.clone(); + Closure::new(move |_: Event| { + let result = (|| { + let db = request + .result() + .map_err(classify)? + .dyn_into::<IdbDatabase>() + .map_err(|_| Error::IncompatibleSchema)?; + let validation = if let Some(error) = failure.get() { + Err(error) + } else if mode == OpenMode::CreateNew && !created.get() { + Err(Error::NamespaceExists) + } else { + validate_schema(&db) + }; + if let Err(error) = validation { + db.close(); + return Err(error); + } + let state = Rc::new(State { + db, + closing: Cell::new(false), + count: Cell::new(0), + bytes: Cell::new(0), + waiters: RefCell::new(Vec::new()), + version_change: RefCell::new(None), + }); + let weak = Rc::downgrade(&state); + let changed = Closure::new(move |_: Event| { + if let Some(state) = weak.upgrade() { + state.stop(); + state.db.close(); + } + }); + state + .db + .set_onversionchange(Some(changed.as_ref().unchecked_ref())); + *state.version_change.borrow_mut() = Some(changed); + Ok(Database { state }) + })(); + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(result); + } + }) + }; + let error = { + let request = request.clone(); + let reply = reply.clone(); + let failure = failure.clone(); + Closure::new(move |_: Event| { + let error = failure.get().unwrap_or_else(|| { + request + .error() + .ok() + .flatten() + .map(|e| classify(e.into())) + .unwrap_or(Error::Unavailable) + }); + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(Err(error)); + } + }) + }; + request.set_onupgradeneeded(Some(upgrade.as_ref().unchecked_ref())); + request.set_onsuccess(Some(success.as_ref().unchecked_ref())); + request.set_onerror(Some(error.as_ref().unchecked_ref())); + let _handlers = OpenHandlers { + request, + _upgrade: upgrade, + _success: success, + _error: error, + }; + observe.await.unwrap_or(Err(Error::Unavailable)) +} +fn validate_schema(db: &IdbDatabase) -> Result<(), Error> { + if db.version() != 1.0 + || db.object_store_names().length() != 1 + || !db.object_store_names().contains(STORE) + { + return Err(Error::IncompatibleSchema); + } + let tx = db.transaction_with_str(STORE).map_err(classify)?; + let store = tx.object_store(STORE).map_err(classify)?; + if store.auto_increment() + || !store.key_path().map_err(classify)?.is_null() + || store.index_names().length() != 0 + { + return Err(Error::IncompatibleSchema); + } + Ok(()) +} + +struct Completion { + tx: IdbTransaction, + result: oneshot::Receiver<Result<(), Error>>, + _complete: Closure<dyn FnMut(Event)>, + _abort: Closure<dyn FnMut(Event)>, +} +impl Completion { + fn new(tx: IdbTransaction, failure: Rc<Cell<Option<Error>>>) -> Self { + let (send, result) = oneshot::channel(); + let reply = Rc::new(RefCell::new(Some(send))); + let complete = { + let reply = reply.clone(); + let failure = failure.clone(); + Closure::new(move |_: Event| { + // An observed local refusal must never become a committed claim if + // an unexpected host failed to abort the transaction. + let result = if failure.get().is_some() { + Err(Error::CommitUnknown) + } else { + Ok(()) + }; + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(result); + } + }) + }; + let abort = { + let tx = tx.clone(); + Closure::new(move |_: Event| { + let error = failure.get().unwrap_or_else(|| { + tx.error() + .map(|e| { + if e.name() == "QuotaExceededError" { + Error::Capacity + } else { + Error::Aborted + } + }) + .unwrap_or(Error::Aborted) + }); + if let Some(send) = reply.borrow_mut().take() { + let _ = send.send(Err(error)); + } + }) + }; + tx.set_oncomplete(Some(complete.as_ref().unchecked_ref())); + tx.set_onabort(Some(abort.as_ref().unchecked_ref())); + Self { + tx, + result, + _complete: complete, + _abort: abort, + } + } + async fn wait(&mut self) -> Result<(), Error> { + (&mut self.result) + .await + .unwrap_or(Err(Error::CommitUnknown)) + } +} +impl Drop for Completion { + fn drop(&mut self) { + self.tx.set_oncomplete(None); + self.tx.set_onabort(None); + } +} +struct RequestHandler { + request: IdbRequest, + _success: Closure<dyn FnMut(Event)>, +} +impl Drop for RequestHandler { + fn drop(&mut self) { + self.request.set_onsuccess(None); + } +} +fn refuse(tx: &IdbTransaction, failure: &Cell<Option<Error>>, error: Error) { + if failure.get().is_none() { + failure.set(Some(error)); + } + let _ = tx.abort(); +} +async fn read(tx: IdbTransaction, record: RecordKey) -> Result<Option<Vec<u8>>, Error> { + let failure = Rc::new(Cell::new(None)); + let mut completion = Completion::new(tx.clone(), failure.clone()); + let value = Rc::new(RefCell::new(None)); + let request = match tx + .object_store(STORE) + .and_then(|store| store.get(&key(record))) + { + Ok(request) => request, + Err(error) => { + refuse(&tx, &failure, classify(error)); + completion.wait().await?; + return Err(Error::CommitUnknown); + } + }; + let success = { + let request = request.clone(); + let value = value.clone(); + let tx = tx.clone(); + Closure::new( + move |_: Event| match request.result().map_err(classify).and_then(bytes) { + Ok(result) => *value.borrow_mut() = Some(result), + Err(error) => refuse(&tx, &failure, error), + }, + ) + }; + request.set_onsuccess(Some(success.as_ref().unchecked_ref())); + let _handler = RequestHandler { + request, + _success: success, + }; + completion.wait().await?; + value.borrow_mut().take().ok_or(Error::CommitUnknown) +} +async fn exchange(tx: IdbTransaction, batch: Batch) -> Result<Commit, Error> { + let failure = Rc::new(Cell::new(None)); + let mut completion = Completion::new(tx.clone(), failure.clone()); + let mut handlers = Vec::with_capacity(batch.entries.len()); + let count = batch.entries.len(); + let store = match tx.object_store(STORE) { + Ok(store) => store, + Err(error) => { + refuse(&tx, &failure, classify(error)); + completion.wait().await?; + return Err(Error::CommitUnknown); + } + }; + // All reads are queued in this active turn. Each callback queues its write + // synchronously; any later conflict aborts every earlier write atomically. + for entry in batch.entries { + let request = match store.get(&key(entry.key)) { + Ok(request) => request, + Err(error) => { + refuse(&tx, &failure, classify(error)); + break; + } + }; + let success = { + let request = request.clone(); + let store = store.clone(); + let tx = tx.clone(); + let failure = failure.clone(); + Closure::new(move |_: Event| { + if failure.get().is_some() { + return; + } + if let Err(error) = apply(&store, &request, &entry) { + refuse(&tx, &failure, error); + } + }) + }; + request.set_onsuccess(Some(success.as_ref().unchecked_ref())); + handlers.push(RequestHandler { + request, + _success: success, + }); + } + completion.wait().await?; + Ok(Commit { records: count }) +} +fn apply(store: &IdbObjectStore, request: &IdbRequest, entry: &Mutation) -> Result<(), Error> { + let actual = bytes(request.result().map_err(classify)?)?; + if actual != entry.expected { + return Err(Error::Conflict); + } + match &entry.replacement { + Some(value) => store.put_with_key(&Uint8Array::from(value.as_slice()), &key(entry.key)), + None => store.delete(&key(entry.key)), + } + .map_err(classify)?; + Ok(()) +} diff --git a/crates/storage_indexeddb/src/lib.rs b/crates/storage_indexeddb/src/lib.rs @@ -0,0 +1,272 @@ +#![doc = include_str!("../README.md")] +#![forbid(unsafe_code)] + +use core::fmt; +use radroots_storage::event::SourceGeneration; + +#[cfg(target_arch = "wasm32")] +mod browser; +#[cfg(target_arch = "wasm32")] +pub use browser::Database; + +/// Maximum opaque record size; private codecs must enforce their lower limit. +pub const RECORD_BYTES_MAX: usize = 64 * 1024; +/// Maximum atomic batch width. +pub const BATCH_RECORDS_MAX: usize = 32; +/// Maximum retained input bytes across accepted work on one connection. +pub const LIVE_BYTES_MAX: usize = 4 * 1024 * 1024; + +/// Fixed source-redacted host errors. No browser exception message is exposed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum Error { + InvalidInput, + Unavailable, + MissingNamespace, + NamespaceExists, + IncompatibleSchema, + Closed, + Capacity, + Conflict, + CorruptRecord, + Aborted, + CommitUnknown, +} +impl Error { + pub const fn code(self) -> &'static str { + match self { + Self::InvalidInput => "invalid_input", + Self::Unavailable => "indexeddb_unavailable", + Self::MissingNamespace => "missing_namespace", + Self::NamespaceExists => "namespace_exists", + Self::IncompatibleSchema => "incompatible_schema", + Self::Closed => "closed", + Self::Capacity => "capacity_exhausted", + Self::Conflict => "record_conflict", + Self::CorruptRecord => "corrupt_record", + Self::Aborted => "transaction_aborted", + Self::CommitUnknown => "commit_unknown", + } + } +} +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.code()) + } +} +impl core::error::Error for Error {} + +/// Exact new-format namespace identity; never inferred from missing data. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Namespace(SourceGeneration); +impl Namespace { + pub const fn new(generation: SourceGeneration) -> Self { + Self(generation) + } + pub fn name(self) -> String { + use core::fmt::Write; + let mut name = String::from("radroots.indexeddb.v1."); + for byte in self.0.as_bytes() { + let _ = write!(name, "{byte:02x}"); + } + name + } +} + +/// Explicit first creation or exact existing-namespace opening. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum OpenMode { + CreateNew, + Existing, +} + +/// Opaque exact record identity, separate from any authorization claim. +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +pub struct RecordKey([u8; 32]); +impl RecordKey { + pub const fn new(bytes: [u8; 32]) -> Self { + Self(bytes) + } + pub const fn as_bytes(&self) -> &[u8; 32] { + &self.0 + } +} + +/// One compare/exchange entry. None denotes absence/deletion; empty is data. +/// Debug intentionally omits all bytes and identities. +pub struct Mutation { + key: RecordKey, + expected: Option<Vec<u8>>, + replacement: Option<Vec<u8>>, +} +impl Mutation { + pub fn new( + key: RecordKey, + expected: Option<Vec<u8>>, + replacement: Option<Vec<u8>>, + ) -> Result<Self, Error> { + if expected + .as_ref() + .is_some_and(|v| v.len() > RECORD_BYTES_MAX) + || replacement + .as_ref() + .is_some_and(|v| v.len() > RECORD_BYTES_MAX) + { + return Err(Error::InvalidInput); + } + Ok(Self { + key, + expected, + replacement, + }) + } + fn bytes(&self) -> usize { + 32 + self.expected.as_ref().map_or(0, Vec::len) + + self.replacement.as_ref().map_or(0, Vec::len) + } +} +impl fmt::Debug for Mutation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Mutation(<redacted>)") + } +} + +/// Validated bounded batch; duplicate keys are rejected before host work. +pub struct Batch { + entries: Vec<Mutation>, + bytes: usize, +} +impl Batch { + pub fn new(entries: Vec<Mutation>) -> Result<Self, Error> { + if entries.is_empty() || entries.len() > BATCH_RECORDS_MAX { + return Err(Error::InvalidInput); + } + let mut keys = std::collections::BTreeSet::new(); + let mut bytes = 0usize; + for entry in &entries { + if !keys.insert(entry.key) { + return Err(Error::InvalidInput); + } + bytes = bytes + .checked_add(entry.bytes()) + .ok_or(Error::InvalidInput)?; + } + if bytes > LIVE_BYTES_MAX { + return Err(Error::Capacity); + } + Ok(Self { entries, bytes }) + } + pub const fn retained_bytes(&self) -> usize { + self.bytes + } + pub fn len(&self) -> usize { + self.entries.len() + } + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} +impl fmt::Debug for Batch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Batch(<redacted>)") + } +} + +/// Witness returned only after actual IndexedDB transaction completion. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Commit { + records: usize, +} +impl Commit { + pub const fn records(self) -> usize { + self.records + } +} + +#[cfg(test)] +mod tests { + use super::{ + BATCH_RECORDS_MAX, Batch, Error, LIVE_BYTES_MAX, Mutation, Namespace, RECORD_BYTES_MAX, + RecordKey, + }; + use radroots_storage::event::SourceGeneration; + #[test] + fn exact_namespace_and_bounded_redacted_batches() { + let ns = Namespace::new(SourceGeneration::new([1; 32]).unwrap()); + assert_eq!( + ns.name(), + format!("radroots.indexeddb.v1.{}", "01".repeat(32)) + ); + let entry = |n, size| Mutation::new(RecordKey::new([n; 32]), None, Some(vec![7; size])); + assert_eq!(RecordKey::new([2; 32]).as_bytes(), &[2; 32]); + assert_eq!( + entry(1, RECORD_BYTES_MAX + 1).unwrap_err(), + Error::InvalidInput + ); + assert_eq!( + Mutation::new( + RecordKey::new([1; 32]), + Some(vec![0; RECORD_BYTES_MAX + 1]), + None + ) + .unwrap_err(), + Error::InvalidInput + ); + assert_eq!(Batch::new(vec![]).unwrap_err(), Error::InvalidInput); + assert_eq!( + Batch::new( + (0..=BATCH_RECORDS_MAX) + .map(|n| entry(n as u8, 0).unwrap()) + .collect() + ) + .unwrap_err(), + Error::InvalidInput + ); + assert_eq!( + Batch::new(vec![entry(1, 0).unwrap(), entry(1, 1).unwrap()]).unwrap_err(), + Error::InvalidInput + ); + let maximum = Batch::new( + (0..BATCH_RECORDS_MAX) + .map(|n| { + Mutation::new( + RecordKey::new([n as u8; 32]), + Some(vec![0; RECORD_BYTES_MAX]), + Some(vec![1; RECORD_BYTES_MAX]), + ) + .unwrap() + }) + .collect(), + ); + assert_eq!(maximum.unwrap_err(), Error::Capacity); + let batch = Batch::new(vec![ + entry(1, RECORD_BYTES_MAX).unwrap(), + Mutation::new(RecordKey::new([2; 32]), Some(vec![]), None).unwrap(), + ]) + .unwrap(); + assert!(!batch.is_empty()); + assert_eq!(batch.len(), 2); + assert_eq!(batch.retained_bytes(), RECORD_BYTES_MAX + 64); + assert!(batch.retained_bytes() < LIVE_BYTES_MAX); + assert_eq!(format!("{batch:?}"), "Batch(<redacted>)"); + assert_eq!( + format!("{:?}", entry(4, 1).unwrap()), + "Mutation(<redacted>)" + ); + for error in [ + Error::InvalidInput, + Error::Unavailable, + Error::MissingNamespace, + Error::NamespaceExists, + Error::IncompatibleSchema, + Error::Closed, + Error::Capacity, + Error::Conflict, + Error::CorruptRecord, + Error::Aborted, + Error::CommitUnknown, + ] { + assert_eq!(error.to_string(), error.code()); + } + } +} diff --git a/crates/storage_indexeddb/tests/browser/Cargo.lock b/crates/storage_indexeddb/tests/browser/Cargo.lock @@ -0,0 +1,1056 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "cc" +version = "1.2.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a0dd1ca384932ff3641c8718a02769f1698e7563dc6974ffd03346116310423" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "ff", + "generic-array", + "group", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff-tzdb" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e" + +[[package]] +name = "js-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "k256" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +dependencies = [ + "cfg-if", + "elliptic-curve", +] + +[[package]] +name = "libc" +version = "0.2.183" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[package]] +name = "mediatype" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "120fa187be19d9962f0926633453784691731018a2bf936ddb4e29101b79c4a7" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "radroots_blossom" +version = "0.1.0-alpha" +dependencies = [ + "mediatype", + "sha2", + "unicode-general-category", + "url", +] + +[[package]] +name = "radroots_core" +version = "0.1.0-alpha" +dependencies = [ + "rust_decimal", + "serde", +] + +[[package]] +name = "radroots_domain" +version = "0.1.0-alpha" +dependencies = [ + "radroots_identity", + "serde", + "zeroize", +] + +[[package]] +name = "radroots_event" +version = "0.1.0-alpha" +dependencies = [ + "hex", + "jiff-tzdb", + "radroots_blossom", + "radroots_core", + "radroots_identity", + "radroots_protocol", + "serde", + "serde_json", + "sha2", + "unicode-general-category", + "url", +] + +[[package]] +name = "radroots_event_codec" +version = "0.1.0-alpha" +dependencies = [ + "hex", + "radroots_blossom", + "radroots_core", + "radroots_event", + "radroots_identity", + "radroots_protocol", + "secp256k1", + "serde", + "serde_json", + "sha2", +] + +[[package]] +name = "radroots_identity" +version = "0.1.0-alpha" +dependencies = [ + "k256", + "serde", + "thiserror", +] + +[[package]] +name = "radroots_indexeddb_browser_fixture" +version = "0.0.0" +dependencies = [ + "futures", + "js-sys", + "radroots_storage", + "radroots_storage_indexeddb", + "wasm-bindgen", + "wasm-bindgen-futures", +] + +[[package]] +name = "radroots_protocol" +version = "0.1.0-alpha" +dependencies = [ + "radroots_identity", + "serde", + "sha2", + "zeroize", +] + +[[package]] +name = "radroots_storage" +version = "0.1.0-alpha" +dependencies = [ + "radroots_domain", + "radroots_event", + "radroots_event_codec", + "radroots_protocol", + "radroots_trade", + "radroots_transport", + "serde", + "sha2", + "zeroize", +] + +[[package]] +name = "radroots_storage_indexeddb" +version = "0.1.0-alpha" +dependencies = [ + "futures", + "js-sys", + "radroots_storage", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "radroots_trade" +version = "0.1.0-alpha" +dependencies = [ + "radroots_core", + "radroots_event", + "radroots_identity", + "serde", +] + +[[package]] +name = "radroots_transport" +version = "0.1.0-alpha" +dependencies = [ + "radroots_event", + "radroots_identity", + "radroots_protocol", + "serde", + "sha2", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rust_decimal" +version = "1.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61f703d19852dbf87cbc513643fa81428361eb6940f1ac14fd58155d295a3eb0" +dependencies = [ + "arrayvec", + "num-traits", + "serde", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "subtle", + "zeroize", +] + +[[package]] +name = "secp256k1" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9465315bc9d4566e1724f0fffcbcc446268cb522e60f9a27bcded6b19c108113" +dependencies = [ + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +dependencies = [ + "cc", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +dependencies = [ + "cfg-if", + "futures-util", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" + +[[patch.unused]] +name = "radroots_geonames" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_nostr" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_nostr_connect" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_secrets" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_signing" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_storage_sqlite" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_sync" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_transport_nostr" +version = "0.1.0-alpha" diff --git a/crates/storage_indexeddb/tests/browser/Cargo.toml b/crates/storage_indexeddb/tests/browser/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "radroots_indexeddb_browser_fixture" +version = "0.0.0" +publish = false +edition = "2024" +rust-version = "1.99.0" + +[workspace] + +[lib] +crate-type = ["cdylib"] + +[dependencies] +radroots_storage_indexeddb = { path = "../.." } +radroots_storage = { path = "../../../storage" } +futures = "=0.3.32" +js-sys = "=0.3.91" +wasm-bindgen = "=0.2.114" +wasm-bindgen-futures = "=0.4.64" diff --git a/crates/storage_indexeddb/tests/browser/run.mjs b/crates/storage_indexeddb/tests/browser/run.mjs @@ -0,0 +1,136 @@ +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { resolve, sep } from 'node:path'; + +// Caller supplies its installed Playwright package and an external generated +// WASM directory. No dependency installation or generated bytes live here. +const [moduleRoot, packageDir, engine = 'chromium'] = process.argv.slice(2); +assert(moduleRoot && packageDir, 'usage: node run.mjs PLAYWRIGHT_PACKAGE WASM_DIRECTORY [ENGINE]'); +const playwright = createRequire(resolve(moduleRoot, 'package.json'))('playwright'); +assert(['chromium','firefox','webkit'].includes(engine)); +const root = resolve(packageDir); +const server = createServer(async (req,res) => { + try { + const path = resolve(root, '.' + new URL(req.url, 'http://localhost').pathname); + assert(path.startsWith(root + sep)); + if (path.endsWith('/index.html')) { + res.setHeader('content-type','text/html'); res.end('<!doctype html><title>IndexedDB fixture</title>'); return; + } + if (path.endsWith('/worker.js')) { + res.setHeader('content-type','text/javascript'); + res.end(`import init, {Fixture} from './fixture.js'; + await init(); + self.onmessage=async()=>{try{const db=await Fixture.open(77,true);await db.write(1,undefined,new Uint8Array([77]));await db.close();const again=await Fixture.open(77,false);const value=await again.read(1);await again.close();self.postMessage({value:Array.from(value)});}catch(error){self.postMessage({error:String(error)});}}; + self.postMessage({ready:true});`); return; + } + res.setHeader('content-type',path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript'); + res.end(await readFile(path)); + } catch {res.statusCode=404;res.end();} +}); +await new Promise(resolve => server.listen(0,'127.0.0.1',resolve)); +let browser; +const deadline=setTimeout(()=>{void browser?.close();},90000); +deadline.unref(); +try { + browser = await playwright[engine].launch({headless:true}); + const page = await browser.newPage(); + page.on('pageerror',error=>console.error('PAGE_ERROR',error.message)); + page.on('console',message=>{if(message.type()==='log')console.log(message.text());}); + await page.goto(`http://127.0.0.1:${server.address().port}/index.html`); + const result=await page.evaluate(async()=>{ + const {default:init,Fixture}=await import('./fixture.js'); await init(); + console.log('STEP wasm_initialized'); + const events=[]; + const nativeTransaction=IDBDatabase.prototype.transaction; + IDBDatabase.prototype.transaction=function(...args) { + const tx=nativeTransaction.apply(this,args); + tx.addEventListener('complete',()=>events.push('complete')); + tx.addEventListener('abort',()=>events.push('abort')); + return tx; + }; + const same=(a,b)=>{if(JSON.stringify(a)!==JSON.stringify(b))throw Error('assertion mismatch');}; + const rejects=async(fn,code)=>{try{await fn();}catch(error){same(String(error),code);return;}throw Error('expected refusal');}; + const value=async(db,k)=>{const raw=await db.read(k);return raw===undefined ? undefined : Array.from(raw);}; + const tests=[]; + const passed=name=>{tests.push(name);console.log('PASS '+name);}; + try { + await rejects(()=>Fixture.open(12,false),'missing_namespace'); + console.log('STEP missing_existing_refused'); + const db=await Fixture.open(12,true); + await rejects(()=>Fixture.open(12,true),'namespace_exists'); + same(await value(db,1),undefined); + const before=events.length; + same(await db.write(1,undefined,new Uint8Array([1])),1); + if(!events.slice(before).includes('complete'))throw Error('no actual completion before return'); + await db.write(2,undefined,new Uint8Array([2])); + const failedBefore=events.length; + await rejects(()=>db.atomic_pair(99),'record_conflict'); + if(!events.slice(failedBefore).includes('abort'))throw Error('no actual atomic abort'); + same(await value(db,1),[1]);same(await value(db,2),[2]); + const nativePut=IDBObjectStore.prototype.put; + let firstWriteSucceeded=false; + IDBObjectStore.prototype.put=function(...args) { + const request=nativePut.apply(this,args); + if(args[1] instanceof Uint8Array && args[1][0]===1) { + request.addEventListener('success',()=>{firstWriteSucceeded=true;this.transaction.abort();},{once:true}); + } + return request; + }; + try {await rejects(()=>db.atomic_pair(2),'transaction_aborted');} + finally {IDBObjectStore.prototype.put=nativePut;} + same(firstWriteSucceeded,true);same(await value(db,1),[1]);same(await value(db,2),[2]); + passed('actual abort after write-request success never acknowledges commit'); + same(await db.atomic_pair(2),2);same(await value(db,1),[3]);same(await value(db,2),[4]); + passed('actual completion and all-or-nothing conflict rollback'); + await db.write(3,undefined,new Uint8Array()); same(await value(db,3),[]); + await db.write(3,new Uint8Array(),undefined);same(await value(db,3),undefined); + passed('missing versus empty and exact deletion'); + const second=await Fixture.open(12,false); + const race=await Promise.allSettled([db.write(1,new Uint8Array([3]),new Uint8Array([5])),second.write(1,new Uint8Array([3]),new Uint8Array([6]))]); + same(race.filter(r=>r.status==='fulfilled').length,1); + same(race.filter(r=>r.status==='rejected').map(r=>String(r.reason)),['record_conflict']); + await second.close();passed('independent connections serialize compare/exchange'); + db.abandon_write(9); + for(let n=0;n<64;n++) db.abandon_close(); + await db.close(); + await rejects(()=>db.read(9),'closed'); + const reopened=await Fixture.open(12,false);same(await value(reopened,9),[9]); + same(reopened.abandon_reads(33),32);await reopened.close();passed('observer loss, bounded admission and actual close/reopen'); + const isolated=await Fixture.open(13,true);same(await value(isolated,9),undefined);await isolated.close();passed('exact per-namespace isolation'); + const name=n=>'radroots.indexeddb.v1.'+n.toString(16).padStart(2,'0').repeat(32); + const rawOpen=(n,version,upgrade)=>new Promise((resolve,reject)=>{ + const request=indexedDB.open(name(n),version); + request.onupgradeneeded=()=>upgrade?.(request.result); + request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(Error('raw fixture open failed')); + }); + const foreign=await rawOpen(14,1,db=>db.createObjectStore('records',{autoIncrement:true}));foreign.close(); + await rejects(()=>Fixture.open(14,false),'incompatible_schema'); + const future=await rawOpen(15,2,db=>db.createObjectStore('records'));future.close(); + await rejects(()=>Fixture.open(15,false),'incompatible_schema');passed('foreign key schema and future version refusal'); + const changed=await Fixture.open(16,true); + const upgraded=await rawOpen(16,2);await rejects(()=>changed.read(1),'closed');upgraded.close();await changed.close(); + passed('version change closes owned connection'); + const corrupt=await Fixture.open(17,true); + const raw=await rawOpen(17,1); + await new Promise((resolve,reject)=>{const tx=raw.transaction('records','readwrite');tx.objectStore('records').put('foreign record',new Uint8Array(32).fill(1));tx.oncomplete=resolve;tx.onabort=reject;}); + raw.close();await rejects(()=>corrupt.read(1),'corrupt_record');await corrupt.close();passed('foreign record representation refusal'); + const oversized=await Fixture.open(19,true); + const largeRaw=await rawOpen(19,1); + await new Promise((resolve,reject)=>{const tx=largeRaw.transaction('records','readwrite');tx.objectStore('records').put(new Uint8Array(65537),new Uint8Array(32).fill(1));tx.oncomplete=resolve;tx.onabort=reject;}); + largeRaw.close();await rejects(()=>oversized.read(1),'corrupt_record');await oversized.close();passed('stored record bound before Rust byte copying'); + const evicted=await Fixture.open(18,true); + await new Promise((resolve,reject)=>{const request=indexedDB.deleteDatabase(name(18));request.onsuccess=resolve;request.onerror=reject;}); + await rejects(()=>evicted.read(1),'closed');await evicted.close(); + await rejects(()=>Fixture.open(18,false),'missing_namespace');passed('actual namespace deletion cannot silently recreate'); + const workerResult=await new Promise((resolve,reject)=>{const worker=new Worker('./worker.js',{type:'module'});worker.onmessage=e=>{if(e.data.ready){worker.postMessage('run');return;}worker.terminate();resolve(e.data);};worker.onerror=e=>{worker.terminate();reject(Error(e.message));};}); + same(workerResult,{value:[77]});passed('dedicated worker actual WASM and IndexedDB reopen'); + return {tests,events:events.reduce((all,event)=>(all[event]=(all[event]??0)+1,all),{})}; + } finally {IDBDatabase.prototype.transaction=nativeTransaction;} + }); + console.log(JSON.stringify({engine,version:browser.version(),...result})); +} finally { + clearTimeout(deadline); + await browser?.close();await new Promise(resolve=>server.close(resolve)); +} diff --git a/crates/storage_indexeddb/tests/browser/src/lib.rs b/crates/storage_indexeddb/tests/browser/src/lib.rs @@ -0,0 +1,105 @@ +use futures::FutureExt; +use radroots_storage::event::SourceGeneration; +use radroots_storage_indexeddb::{ + Batch, Database, Error, Mutation, Namespace, OpenMode, RecordKey, +}; +use wasm_bindgen::prelude::*; + +fn failure(error: Error) -> JsValue { + JsValue::from_str(error.code()) +} +fn key(n: u8) -> RecordKey { + RecordKey::new([n; 32]) +} +fn batch(n: u8, old: Option<Vec<u8>>, new: Option<Vec<u8>>) -> Result<Batch, JsValue> { + Batch::new(vec![Mutation::new(key(n), old, new).map_err(failure)?]).map_err(failure) +} +#[wasm_bindgen] +pub struct Fixture { + db: Database, +} +#[wasm_bindgen] +impl Fixture { + #[wasm_bindgen(js_name = open)] + pub async fn open(n: u8, create: bool) -> Result<Fixture, JsValue> { + let namespace = Namespace::new( + SourceGeneration::new([n; 32]).map_err(|_| JsValue::from_str("invalid_generation"))?, + ); + Ok(Self { + db: Database::open( + namespace, + if create { + OpenMode::CreateNew + } else { + OpenMode::Existing + }, + ) + .await + .map_err(failure)?, + }) + } + pub async fn write( + &self, + n: u8, + old: Option<Vec<u8>>, + new: Option<Vec<u8>>, + ) -> Result<usize, JsValue> { + Ok(self + .db + .compare_exchange(batch(n, old, new)?) + .await + .map_err(failure)? + .records()) + } + pub async fn read(&self, n: u8) -> Result<JsValue, JsValue> { + Ok(self + .db + .get(key(n)) + .await + .map_err(failure)? + .map(|bytes| js_sys::Uint8Array::from(bytes.as_slice()).into()) + .unwrap_or(JsValue::UNDEFINED)) + } + pub async fn atomic_pair(&self, second_expected: u8) -> Result<usize, JsValue> { + let entries = vec![ + Mutation::new(key(1), Some(vec![1]), Some(vec![3])).map_err(failure)?, + Mutation::new(key(2), Some(vec![second_expected]), Some(vec![4])).map_err(failure)?, + ]; + Ok(self + .db + .compare_exchange(Batch::new(entries).map_err(failure)?) + .await + .map_err(failure)? + .records()) + } + pub fn abandon_write(&self, n: u8) -> Result<(), JsValue> { + let result = self + .db + .compare_exchange(batch(n, None, Some(vec![n]))?) + .now_or_never(); + if result.is_some() { + return Err(JsValue::from_str("unexpected_immediate_completion")); + } + Ok(()) + } + pub fn abandon_reads(&self, count: usize) -> Result<usize, JsValue> { + for index in 0..count { + if let Some(result) = self.db.get(key(1)).now_or_never() { + return match result { + Err(Error::Capacity) => Ok(index), + _ => Err(JsValue::from_str("unexpected_admission_result")), + }; + } + } + Ok(count) + } + pub fn abandon_close(&self) -> Result<(), JsValue> { + if self.db.close().now_or_never().is_some() { + return Err(JsValue::from_str("unexpected_immediate_close")); + } + Ok(()) + } + pub async fn close(&self) -> Result<(), JsValue> { + self.db.close().await.map_err(failure) + } +}