Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Seanaye/feat/replace tauri cache (#5724)
Sean Ayeab9f0be3df6d
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex a1591dc8e8..02a0573edf 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -595,11 +595,6 @@"crates/client/cache-core","crates/maybe_send"],- "cache-sqlite": [- "crates/client/cache-core",- "crates/client/cache-sqlite",- "crates/maybe_send"- ],"cache-turso": ["crates/client/cache-core","crates/client/cache-turso",diff --git a/Cargo.lock b/Cargo.lockindex 6481dc2c83..782d448b2a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2574,27 +2574,15 @@ dependencies = ["thiserror 2.0.18",]-[[package]]-name = "cache-sqlite"-version = "0.1.0"-dependencies = [- "cache-core",- "pollster",- "rusqlite",- "serde_json",- "tempfile",- "thiserror 2.0.18",-]-[[package]]name = "cache-turso"version = "0.1.0"dependencies = ["cache-core",- "cache-sqlite","maybe_send","pollster","serde_json",+ "tempfile","thiserror 2.0.18","turso-opfs","turso_core",@@ -5757,12 +5745,6 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"-[[package]]-name = "fallible-streaming-iterator"-version = "0.1.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"-[[package]]name = "fancy-regex"version = "0.12.0"@@ -6897,15 +6879,6 @@ dependencies = ["foldhash 0.2.0",]-[[package]]-name = "hashlink"-version = "0.9.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"-dependencies = [- "hashbrown 0.14.5",-]-[[package]]name = "hashlink"version = "0.10.0"@@ -8435,7 +8408,6 @@ version = "0.30.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"dependencies = [- "cc","pkg-config","vcpkg",]@@ -13026,20 +12998,6 @@ dependencies = ["zeroize",]-[[package]]-name = "rusqlite"-version = "0.32.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"-dependencies = [- "bitflags 2.11.1",- "fallible-iterator 0.3.0",- "fallible-streaming-iterator",- "hashlink 0.9.1",- "libsqlite3-sys",- "smallvec",-]-[[package]]name = "rust-embed"version = "8.11.0"@@ -14574,7 +14532,7 @@ dependencies = ["futures-io","futures-util","hashbrown 0.15.5",- "hashlink 0.10.0",+ "hashlink","indexmap 2.14.0","log","memchr",diff --git a/Cargo.toml b/Cargo.tomlindex 47f8738e38..f7f39393f7 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -13,7 +13,6 @@ members = ["crates/calendar_events","crates/channel_bots","crates/client/cache-core",- "crates/client/cache-sqlite","crates/client/cache-turso","crates/client/cache-wasm","crates/client/turso-opfs",diff --git a/apps/web/docs/graphql-cache-optimistic-enqueue-claim-plan.md b/apps/web/docs/graphql-cache-optimistic-enqueue-claim-plan.mdindex 32b8599318..abf9e03a75 100644--- a/apps/web/docs/graphql-cache-optimistic-enqueue-claim-plan.md+++ b/apps/web/docs/graphql-cache-optimistic-enqueue-claim-plan.md@@ -380,7 +380,7 @@ Run from the repository root in the project development environment:```bashcargo fmt --check-cargo test -p cache-core -p cache-idb -p cache-sqlite -p cache-wasm+cargo test -p cache-core -p cache-turso -p cache-wasmjust build-cache-wasmbun type-check```diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.mdindex e018ea7c60..299d998709 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -59,7 +59,7 @@ entire cache in browser memory. With 10s of thousands of cached objectsanonymous client-generated uuid** (localStorage), *not* user identity:construction is synchronousand offline-capable (no identity waterfall), and no PII appears in- enumerable storage metadata (IDB database names / SQLite filenames).+ enumerable storage metadata (OPFS or native database filenames).User↔cache consistency is enforced by **identity witnessing**, splitinto two halves: *extraction* lives in the urql exchange(`extractIdentity: (data) => data.user.id` — the schema exposes@@ -106,7 +106,8 @@ entire cache in browser memory. With 10s of thousands of cached objects### Open questions- Encryption-at-rest for cached content (email bodies/snippets will flow- through this). IDB/SQLite are origin-/app-scoped but plaintext on disk.+ through this). Browser OPFS and native Turso files are origin-/app-scoped+ but plaintext on disk.- Disk budget (proposal: 256 MB default, configurable).- Memory hot-tier budget (proposal: 32 MB default).@@ -144,12 +145,12 @@ One Rust core engine, two hosts:┌───────────────────────────────┐ ┌─────────────────────────────────┐│ BROWSER ONLY: wasm-bindgen │ │ TAURI: native engine in the ││ module in a worker; │ │ Tauri host process (Rust); │-│ IndexedDB via the `idb` crate │ │ no webview storage ever │+│ Turso over OPFS │ │ no webview storage ever ││ (storage entirely in Rust) │ │ • naturally shared across ALL │-│ • SharedWorker: one engine │ │ webviews/windows │-│ shared by every browser tab │ │ • SQLite (or fs) storage │-│ • no SharedWorker: storage- │ │ • glue over invoke + channels/ │-│ free no-op cache host │ │ events │+│ • one coordinated engine │ │ webviews/windows │+│ owner across browser tabs │ │ • Turso filesystem storage │+│ • unsupported browsers use │ │ • glue over invoke + channels/ │+│ a storage-free no-op host │ │ events ││ │ │ │└───────────────┬───────────────┘ └────────────────┬────────────────┘└──────────────────┬──────────────────────┘@@ -171,56 +172,30 @@ One Rust core engine, two hosts:support is inconsistent across WKWebView/WebView2/Android WebView, andwebviews can't share a SharedWorker across windows. The Tauri host processis the shared singleton: it gets us the multi-webview requirement for- free, with real SQLite instead of webview storage. The wasm/worker path is- **browser-only**.+ free, with native Turso filesystem storage instead of webview storage. The+ wasm/worker path is **browser-only**.### 4.2 Multi-consumer strategy (browser only)-**Decision: IndexedDB-backed persistence via the [`idb`-crate](https://docs.rs/idb/latest/idb/), with one engine in a SharedWorker.-Browsers without SharedWorker support use a storage-free no-op cache host.-OPFS is dropped.**--Rationale (see Appendix A):--- OPFS sync access handles are unusable from SharedWorker on Chromium (no- sync handles, no nested `Worker` to delegate to), forcing a- leader-election topology with failover — significant complexity.-- IDB point-reads measured *faster* than OPFS sync 4 KiB reads in the probe- (0.35 ms vs 2 ms avg), and batched writes (119 ms / 1000 records / txn)- are fine for our write rates.-- IDB is available in SharedWorker on supported browsers.-- Using the `idb` Rust crate keeps the entire storage layer inside the wasm- module (no JS-callback storage shim; JS glue is transport only).--Topology:--- **Browser: SharedWorker** hosting the wasm engine — one instance across- tabs, no election or cross-engine coordination.-- **No SharedWorker:** return a no-op `CacheHost` that always misses, ignores- writes, and does not initialize wasm or persistent storage. Mutations pass- through the exchange without durable optimism.-- Selection at startup: Tauri detection (`isTauri`) → native transport;- otherwise SharedWorker support selects either the browser cache or no-op- host. All paths sit behind the same `CacheHost` interface.+**Decision: Turso-backed persistence over OPFS, with one coordinated engine+owner across tabs.** The coordinator routes every request to the current+engine worker and replaces that owner after abrupt loss. Browsers missing the+required worker, lock, or OPFS capabilities use a storage-free no-op cache+host. Tauri detection selects the native transport before browser capability+checks. All paths remain behind the same `CacheHost` interface.### 4.3 Storage backends-| Backend | Host | Notes |-|------------|--------------|------------------------------------------------|-| SQLite | Tauri native | records, mutation queue, optimistic layers, and meta; WAL mode |-| IndexedDB | browser | via the `idb` crate; stable per-scope DB with object stores for records, mutation queue, optimistic layers, and meta |--Normalized records are serialized with `postcard`. SQLite stores the bytes in-`records.value`; IndexedDB stores the bytes directly in the records object-store. Both backends implement schema-neutral, entity-key-ordered record scans.-`Storage::scan_records` selects concrete normalized types by their key ranges;-`Engine::read_records` applies a validated named fragment, loads linked records-in batches, includes optimistic layers, and omits incomplete projections.-Note: wasm futures are not `Send`, so the `Storage` trait's futures-are bound by `MaybeSend` (`crates/maybe_send`):-`Send` on native targets — the Tauri host drives the engine directly from its-multi-threaded runtime — and unbounded on wasm, implementable by `idb`.+| Backend | Host | Notes |+|---------|------|-------|+| Turso over filesystem IO | Tauri native | records, search projection, mutation queue, optimistic layers, and metadata; WAL mode |+| Turso over OPFS | browser | the same frozen schema behind the OPFS IO adapter and coordinated worker lifecycle |++Normalized records are serialized with `postcard` into `records.value`.+Both hosts use the same `Storage` implementation and compound entity keys.+Wasm futures are not `Send`, so the `Storage` trait's futures are bound by+`MaybeSend` (`crates/maybe_send`): `Send` on native targets, where Tauri drives+the engine directly from its multi-threaded runtime, and unbounded on wasm.### 4.4 Data model@@ -256,11 +231,11 @@ soup entities from the normy config as they migrate.```crates/client/ # members of the root cargo workspacecache-core/ # pure engine, native tests (schema codegen in build.rs)- cache-sqlite/ # Storage over SQLite (Tauri native host)- cache-idb/ # Storage over IndexedDB (browser wasm host)+ cache-turso/ # Turso Storage (browser OPFS + Tauri filesystem)+ turso-opfs/ # browser OPFS adapter for Tursocache-wasm/ # wasm-bindgen shell (web)apps/web/tauri/graphql_cache_plugin/ # tauri commands + engine thread wrapping- # cache-core over cache-sqlite. Lives in the+ # cache-core over cache-turso. Lives in the# tauri workspace (not crates/client): it# depends on the patched tauri fork pinned# there, path-deps back to crates/client.@@ -273,10 +248,10 @@ apps/web/src/lib/graphql-cache/ # JS glue## 6. Phases**Phase 0 — spike** *(closed)*-- Browser probe harness built; Chromium results in Appendix A. **Decision- made: IDB-backed persistence via the `idb` crate in a SharedWorker, with- caching disabled when SharedWorker is unavailable (§4.2).** Safari/Firefox- probe runs and the Tauri IPC benchmark were deliberately skipped.+- Browser probe harness built; Chromium results in Appendix A. Its original+ IDB decision was later superseded by the Turso-over-OPFS architecture in+ §4.2. Safari/Firefox probe runs and the Tauri IPC benchmark were deliberately+ skipped.- Wire protocol delivered in Phase 3 (`src/lib/graphql-cache/protocol.ts`).- The probe harness (`spikes/graphql-cache-probe/`) and the soup payloadmeasurement script (`scripts/measure-soup-payloads.ts`) were removed@@ -294,14 +269,12 @@ apps/web/src/lib/graphql-cache/ # JS glue- Deferred: nullability-based partial results (metadata already generated),byte-based LRU budgets, proptest round-trips, staleness metadata.-**Phase 2 — persistence** *(done — `cache-sqlite`, `cache-idb`)*+**Phase 2 — persistence** *(done — `cache-turso`)*- Shared postcard record codec + `cache_namespace(scope)` embeddingschema compatibility epoch + format version.-- SQLite backend (Tauri native): WAL mode, batch txns, namespace- wipe-on-mismatch; tested natively incl. engine integration.-- IndexedDB backend via the `idb` crate: one DB per namespace, atomic- batch txns; tested in headless Chromium via wasm-bindgen-test incl.- engine-over-IDB round trip.+- Turso backend for both Tauri native filesystem storage and browser OPFS:+ WAL mode, batch transactions, and physical reset on incompatible storage;+ tested natively and in headless Chromium.- Deferred: stale-namespace DB cleanup (browser), `scan_prefix`/`approx_size` for GC (hardening phase).@@ -317,14 +290,14 @@ apps/web/src/lib/graphql-cache/ # JS gluehappens with the Phase 4 exchange integration.- ~~Tauri host~~ (`apps/web/tauri/graphql_cache_plugin`, in the *tauri*workspace — it needs the patched tauri fork pinned there; path-deps on- `crates/client/{cache-core,cache-sqlite}`): engine behind an async mutex+ `crates/client/{cache-core,cache-turso}`): engine behind an async mutexon the tauri runtime (`Storage` futures are `MaybeSend` → `Send` native;- SQLite completes immediately), commands mirroring the worker protocol+ Turso uses its synchronous native IO driver), commands mirroring the worker protocolregistered app-level in `src-tauri` (bundle-updater pattern, nocapability plumbing), changed ops broadcast to every webview via the`graphql-cache://ops-affected` event. One native engine per app process = SharedWorker topology: no WebLocks / BroadcastChannel machinery. DB at- `{app_data_dir}/graphql-cache/cache.sqlite`.+ `{app_data_dir}/graphql-cache/cache.turso`.JS side: `createTauriCacheHost` (`host/tauri-host.ts`) — invoke-basedRPC with the same 10s timeout + Error-normalized rejections, eventsubscription filtered by clientId prefix; `isTauri()` selects it in@@ -372,13 +345,13 @@ apps/web/src/lib/graphql-cache/ # JS glue## 7. Risks-- **Browser storage quirks** (Safari IDB edge cases/private mode, storage- eviction under pressure) — mitigated by the disposable-cache design- (detect → discard → rebuild from network). Browsers without SharedWorker- use the storage-free no-op host. Tauri is unaffected (native host only).-- **`idb` crate dependency** — maintained third-party wasm bindings; if it- stalls, the `Storage` trait isolates us (swap for hand-rolled- `web-sys`-based bindings).+- **Browser storage quirks** (OPFS capability differences, private mode, and+ storage eviction under pressure) — mitigated by the disposable-cache design+ and explicit owner/reset lifecycle (detect → discard → rebuild from network).+ Unsupported browsers use the storage-free no-op host. Tauri is unaffected+ because it uses native filesystem IO.+- **Pinned Turso dependency** — both hosts use the same storage engine, while+ the `IO` boundary isolates browser OPFS from native filesystem behavior.- **RPC latency on hot paths** — reads are one round-trip to a worker/host;Chromium probe shows ≤1 ms for 64 KiB payloads. Batch reads peroperation, not per record. Tauri IPC assumed adequate (benchmark skipped);diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex 301d11f10a..c87fe1d784 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -8,6 +8,26 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]+name = "aead"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"+dependencies = [+ "crypto-common",+ "generic-array",+]++[[package]]+name = "aegis"+version = "0.9.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "58541132f980da31e9aa99f7bdee69bc84bf1e168b9b91ef2dbe8abb7b4ce5dd"+dependencies = [+ "cc",+ "softaes",+]+[[package]]name = "aes"version = "0.8.4"@@ -19,6 +39,20 @@ dependencies = ["cpufeatures",]+[[package]]+name = "aes-gcm"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"+dependencies = [+ "aead",+ "aes",+ "cipher",+ "ctr",+ "ghash",+ "subtle",+]+[[package]]name = "ahash"version = "0.7.8"@@ -73,6 +107,12 @@ version = "0.2.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"+[[package]]+name = "allocator-api2"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880"+[[package]]name = "android_log-sys"version = "0.3.2"@@ -99,6 +139,22 @@ dependencies = ["libc",]+[[package]]+name = "antithesis_sdk"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08410fcac93669a476c006cd6c4512ac1e2b30fd117231a5d55d8a2c76599b82"+dependencies = [+ "libc",+ "libloading 0.8.9",+ "linkme",+ "once_cell",+ "rand 0.8.6",+ "rustc_version_runtime",+ "serde",+ "serde_json",+]+[[package]]name = "anyhow"version = "1.0.102"@@ -194,6 +250,15 @@ dependencies = ["derive_arbitrary",]+[[package]]+name = "arc-swap"+version = "1.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"+dependencies = [+ "rustversion",+]+[[package]]name = "ariadne"version = "0.6.0"@@ -201,16 +266,42 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8454c8a44ce2cb9cc7e7fae67fc6128465b343b92c6631e94beca3c8d1524ea5"dependencies = ["concolor",- "unicode-width",+ "unicode-width 0.2.2","yansi",]+[[package]]+name = "aristo"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fcdeefa800110050103e2459a2f8dbdbd560ad046e30f1f87e24ce19c2cb8bde"+dependencies = [+ "aristo-macros",+]++[[package]]+name = "aristo-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d64a66d21a80182b35b1741997a6d2456911f54b7eb1918aa4e2382fc205268d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "arrayvec"version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+[[package]]+name = "assoc"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfdc70193dadb9d7287fa4b633f15f90c876915b31f6af17da307fc59c9859a8"+[[package]]name = "async-broadcast"version = "0.7.2"@@ -437,6 +528,19 @@ dependencies = ["winapi",]+[[package]]+name = "bigdecimal"+version = "0.4.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d6867f1565b3aad85681f1015055b087fcfd840d6aeee6eee7f2da317603695"+dependencies = [+ "autocfg",+ "libm",+ "num-bigint",+ "num-integer",+ "num-traits",+]+[[package]]name = "bit-set"version = "0.8.0"@@ -534,6 +638,15 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "branches"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8fba76cd916045514e3064707df9ed5282b94419444c2753a6c62ecaf458e56"+dependencies = [+ "rustc_version",+]+[[package]]name = "brotli"version = "8.0.2"@@ -606,9 +719,23 @@ dependencies = [[[package]]name = "bytemuck"-version = "1.25.0"+version = "1.25.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+][[package]]name = "byteorder"@@ -651,12 +778,14 @@ dependencies = [][[package]]-name = "cache-sqlite"+name = "cache-turso"version = "0.1.0"dependencies = ["cache-core",- "rusqlite",+ "maybe_send","thiserror 2.0.18",+ "turso-opfs",+ "turso_core",][[package]]@@ -728,9 +857,9 @@ dependencies = [[[package]]name = "cc"-version = "1.2.60"+version = "1.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20"+checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d"dependencies = ["find-msvc-tools","jobserver",@@ -777,6 +906,12 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+[[package]]+name = "cfg_block"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18758054972164c3264f7c8386f5fc6da6114cb46b619fd365d4e3b2dc3ae487"+[[package]]name = "chrono"version = "0.4.44"@@ -1015,6 +1150,15 @@ version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"+[[package]]+name = "crc32c"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47"+dependencies = [+ "rustc_version",+]+[[package]]name = "crc32fast"version = "1.5.0"@@ -1039,6 +1183,15 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]+[[package]]name = "crossbeam-utils"version = "0.8.21"@@ -1058,6 +1211,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"dependencies = ["generic-array",+ "rand_core 0.6.4","typenum",]@@ -1117,6 +1271,15 @@ version = "0.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"+[[package]]+name = "ctr"+version = "0.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"+dependencies = [+ "cipher",+]+[[package]]name = "darling"version = "0.20.11"@@ -1630,10 +1793,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"[[package]]-name = "fallible-streaming-iterator"-version = "0.1.9"+name = "fastbloom"+version = "0.14.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+checksum = "4e7f34442dbe69c60fe8eaf58a8cafff81a1f278816d8ab4db255b3bef4ac3c4"+dependencies = [+ "getrandom 0.3.4",+ "libm",+ "siphasher 1.0.2",+][[package]]name = "fastrand"@@ -1671,9 +1839,9 @@ dependencies = [[[package]]name = "find-msvc-tools"-version = "0.1.9"+version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"+checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"[[package]]name = "flate2"@@ -1971,6 +2139,21 @@ dependencies = ["x11",]+[[package]]+name = "generator"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3b854b0e584ead1a33f18b2fcad7cf7be18b3875c78816b753639aa501513ae"+dependencies = [+ "cc",+ "cfg-if",+ "libc",+ "log",+ "rustversion",+ "windows-link 0.2.1",+ "windows-result 0.3.4",+]+[[package]]name = "generic-array"version = "0.14.7"@@ -2036,10 +2219,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"dependencies = ["cfg-if",+ "js-sys","libc","r-efi 6.0.0","wasip2","wasip3",+ "wasm-bindgen",][[package]]@@ -2054,6 +2239,16 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "ghash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"+dependencies = [+ "opaque-debug",+ "polyval",+]+[[package]]name = "gio"version = "0.18.4"@@ -2155,7 +2350,7 @@ name = "graphql_cache_plugin"version = "0.1.0"dependencies = ["cache-core",- "cache-sqlite",+ "cache-turso","pollster","serde","serde_json",@@ -2259,9 +2454,6 @@ name = "hashbrown"version = "0.14.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"-dependencies = [- "ahash 0.8.12",-][[package]]name = "hashbrown"@@ -2278,7 +2470,7 @@ version = "0.16.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"dependencies = [- "allocator-api2",+ "allocator-api2 0.2.21","equivalent","foldhash 0.2.0",]@@ -2289,15 +2481,6 @@ version = "0.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51"-[[package]]-name = "hashlink"-version = "0.9.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"-dependencies = [- "hashbrown 0.14.5",-]-[[package]]name = "heapless"version = "0.7.17"@@ -2485,7 +2668,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.58.0",+ "windows-core 0.61.2",][[package]]@@ -2507,11 +2690,36 @@ dependencies = ["png 0.17.16",]+[[package]]+name = "icu_collator"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59eea194d189ca897bcb960fd2130f9e7d53998460d4d32e85a60b10d5507cf4"+dependencies = [+ "icu_collator_data",+ "icu_collections",+ "icu_locale_core",+ "icu_locale_fallback",+ "icu_normalizer",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "utf16_iter",+ "utf8_iter",+ "zerovec",+]++[[package]]+name = "icu_collator_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368"+[[package]]name = "icu_collections"-version = "2.2.0"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"dependencies = ["displaydoc","potential_utf",@@ -2521,45 +2729,91 @@ dependencies = ["zerovec",]+[[package]]+name = "icu_locale"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "250ec6d4ac288584d1d0ba29dbfad7737635b7b0e822441f4026a523e3fdb147"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_locale_data",+ "icu_locale_fallback",+ "icu_provider",+ "tinystr",+ "zerovec",+]+[[package]]name = "icu_locale_core"-version = "2.2.0"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"dependencies = ["displaydoc","litemap",+ "serde","tinystr","writeable","zerovec",]+[[package]]+name = "icu_locale_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d37d91460e362a5cf58907cd7ce871411775ee6294e49a5cc8e6cec16dfa75ea"++[[package]]+name = "icu_locale_fallback"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"+dependencies = [+ "icu_locale_core",+ "icu_locale_fallback_data",+ "icu_provider",+ "potential_utf",+ "tinystr",+ "zerovec",+]++[[package]]+name = "icu_locale_fallback_data"+version = "2.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"+[[package]]name = "icu_normalizer"-version = "2.2.0"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"dependencies = ["icu_collections","icu_normalizer_data","icu_properties","icu_provider","smallvec",+ "utf16_iter",+ "utf8_iter",+ "write16","zerovec",][[package]]name = "icu_normalizer_data"-version = "2.2.0"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"[[package]]name = "icu_properties"-version = "2.2.0"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"dependencies = [+ "displaydoc","icu_collections","icu_locale_core","icu_properties_data",@@ -2570,18 +2824,20 @@ dependencies = [[[package]]name = "icu_properties_data"-version = "2.2.0"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"[[package]]name = "icu_provider"-version = "2.2.0"+version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"+checksum = "92a7ed671a6aad807a8651a2e1782a6598fda9ce5185dd8158549e95a91c6428"dependencies = ["displaydoc","icu_locale_core",+ "serde",+ "stable_deref_trait","writeable","yoke","zerofrom",@@ -2663,6 +2919,15 @@ dependencies = ["generic-array",]+[[package]]+name = "intrusive-collections"+version = "0.9.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86"+dependencies = [+ "memoffset",+]+[[package]]name = "ipnet"version = "2.12.0"@@ -2794,13 +3059,12 @@ dependencies = [[[package]]name = "js-sys"-version = "0.3.95"+version = "0.3.104"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2964e92d1d9dc3364cae4d718d93f227e3abb088e747d92e0395bfdedf1c12ca"+checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"dependencies = ["cfg-if","futures-util",- "once_cell","wasm-bindgen",]@@ -2900,7 +3164,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"dependencies = ["gtk-sys",- "libloading",+ "libloading 0.7.4","once_cell",]@@ -2935,6 +3199,22 @@ dependencies = ["winapi",]+[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link 0.2.1",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+[[package]]name = "libredox"version = "0.1.16"@@ -2945,14 +3225,23 @@ dependencies = [][[package]]-name = "libsqlite3-sys"-version = "0.30.1"+name = "linkme"+version = "0.3.37"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"+checksum = "3045e122bd98aef8ec3ad58ce84f0791f64e70163d1a02710af4aa11a4d54cc5"dependencies = [- "cc",- "pkg-config",- "vcpkg",+ "linkme-impl",+]++[[package]]+name = "linkme-impl"+version = "0.3.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77060ebe535362c3da75682cd17b0431017b6e7c5661e714fc69a7ad017d1301"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",][[package]]@@ -3009,6 +3298,19 @@ dependencies = ["tracing",]+[[package]]+name = "loom"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "419e0dc8046cb947daa77eb95ae174acfbddb7673b4151f56d1eed8e93fbfaca"+dependencies = [+ "cfg-if",+ "generator",+ "scoped-tls",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "lru"version = "0.16.4"@@ -3076,7 +3378,7 @@ dependencies = ["serde","serde_json","sha2",- "strum",+ "strum 0.27.2","tauri","tauri-plugin-device-info","thiserror 2.0.18",@@ -3162,6 +3464,28 @@ dependencies = ["autocfg",]+[[package]]+name = "miette"+version = "7.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"+dependencies = [+ "cfg-if",+ "miette-derive",+ "unicode-width 0.1.14",+]++[[package]]+name = "miette-derive"+version = "7.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "mime"version = "0.3.17"@@ -3421,12 +3745,31 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]+[[package]]name = "num-conv"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"+[[package]]+name = "num-integer"+version = "0.1.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"+dependencies = [+ "num-traits",+]+[[package]]name = "num-traits"version = "0.2.19"@@ -3685,6 +4028,12 @@ version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"+[[package]]+name = "opaque-debug"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"+[[package]]name = "open"version = "5.3.4"@@ -3745,6 +4094,21 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "owo-colors"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"++[[package]]+name = "pack1"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3b7bb0ecf2e447b1f20ee94ee79ef6eed1e9d4b3c36ce1903b9dea3bf205523"+dependencies = [+ "bytemuck",+]+[[package]]name = "pango"version = "0.18.3"@@ -3805,6 +4169,12 @@ version = "1.0.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"+[[package]]+name = "pastey"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"+[[package]]name = "pathdiff"version = "0.2.3"@@ -4138,6 +4508,18 @@ version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"+[[package]]+name = "polyval"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "opaque-debug",+ "universal-hash",+]+[[package]]name = "postcard"version = "1.1.3"@@ -4157,6 +4539,8 @@ version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"dependencies = [+ "serde_core",+ "writeable","zerovec",]@@ -4435,7 +4819,7 @@ dependencies = ["rand_chacha 0.2.2","rand_core 0.5.1","rand_hc",- "rand_pcg",+ "rand_pcg 0.2.1",][[package]]@@ -4534,6 +4918,24 @@ dependencies = ["rand_core 0.5.1",]+[[package]]+name = "rand_pcg"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59cad018caf63deb318e5a4586d99a24424a364f40f1e5778c29aca23f4fc73e"+dependencies = [+ "rand_core 0.6.4",+]++[[package]]+name = "rapidhash"+version = "4.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e"+dependencies = [+ "rustversion",+]+[[package]]name = "raw-window-handle"version = "0.6.2"@@ -4706,6 +5108,16 @@ dependencies = ["syn 1.0.109",]+[[package]]+name = "roaring"+version = "0.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18bd8a37d17a58532776dcdf6041ce64929adca78e8489d5cacbafe99229d3e1"+dependencies = [+ "bytemuck",+ "byteorder",+]+[[package]]name = "rootcause"version = "0.12.1"@@ -4740,20 +5152,6 @@ dependencies = ["text-size",]-[[package]]-name = "rusqlite"-version = "0.32.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"-dependencies = [- "bitflags 2.11.1",- "fallible-iterator",- "fallible-streaming-iterator",- "hashlink",- "libsqlite3-sys",- "smallvec",-]-[[package]]name = "rust-ini"version = "0.21.3"@@ -4802,6 +5200,16 @@ dependencies = ["semver",]+[[package]]+name = "rustc_version_runtime"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2dd18cd2bae1820af0b6ad5e54f4a51d0f3fcc53b05f845675074efcc7af071d"+dependencies = [+ "rustc_version",+ "semver",+]+[[package]]name = "rustix"version = "1.1.4"@@ -4896,6 +5304,12 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]name = "same-file"version = "1.0.6"@@ -4965,6 +5379,12 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"+[[package]]name = "scopeguard"version = "1.2.0"@@ -5252,6 +5672,12 @@ dependencies = ["digest",]+[[package]]+name = "sha1_smol"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"+[[package]]name = "sha2"version = "0.10.9"@@ -5274,9 +5700,29 @@ dependencies = [[[package]]name = "shlex"-version = "1.3.0"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "shuttle"+version = "0.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+checksum = "2ab17edba38d63047f46780cf7360acf7467fec2c048928689a5c1dd1c2b4e31"+dependencies = [+ "assoc",+ "bitvec",+ "cfg-if",+ "generator",+ "hex",+ "owo-colors",+ "rand 0.8.6",+ "rand_core 0.6.4",+ "rand_pcg 0.3.1",+ "scoped-tls",+ "smallvec",+ "tracing",+][[package]]name = "signal-hook-registry"@@ -5300,6 +5746,15 @@ version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"+[[package]]+name = "simsimd"+version = "6.5.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4fb3bc3cdce07a7d7d4caa4c54f8aa967f6be41690482b54b24100a2253fa70"+dependencies = [+ "cc",+]+[[package]]name = "siphasher"version = "0.3.11"@@ -5334,6 +5789,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "softaes"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45e14297decde697ddf377c25752aead0927d5cfc89c2684d2af96901a4ceeea"+[[package]]name = "softbuffer"version = "0.4.8"@@ -5456,13 +5917,35 @@ version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]+name = "strum"+version = "0.26.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"+dependencies = [+ "strum_macros 0.26.4",+]+[[package]]name = "strum"version = "0.27.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"dependencies = [- "strum_macros",+ "strum_macros 0.27.2",+]++[[package]]+name = "strum_macros"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "rustversion",+ "syn 2.0.117",][[package]]@@ -5516,6 +5999,17 @@ dependencies = ["unicode-ident",]+[[package]]+name = "syn"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]+[[package]]name = "sync_wrapper"version = "1.0.2"@@ -6347,11 +6841,12 @@ dependencies = [[[package]]name = "tinystr"-version = "0.8.3"+version = "0.8.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"dependencies = ["displaydoc",+ "serde_core","zerovec",]@@ -6731,6 +7226,131 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "turso-opfs"+version = "0.1.0"+dependencies = [+ "js-sys",+ "turso_core",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "turso_core"+version = "0.8.0-pre.3"+source = "git+https://github.com/seanaye/turso?rev=be9acfe9e5e6efb17911af84047e4855cace53a3#be9acfe9e5e6efb17911af84047e4855cace53a3"+dependencies = [+ "aegis",+ "aes",+ "aes-gcm",+ "allocator-api2 0.4.0",+ "antithesis_sdk",+ "arc-swap",+ "aristo",+ "bigdecimal",+ "bitflags 2.11.1",+ "branches",+ "bumpalo",+ "bytemuck",+ "cfg_aliases",+ "cfg_block",+ "chrono",+ "crc32c",+ "crossbeam-epoch",+ "crossbeam-utils",+ "either",+ "fallible-iterator",+ "fastbloom",+ "getrandom 0.2.17",+ "getrandom 0.3.4",+ "hex",+ "icu_collator",+ "icu_locale",+ "intrusive-collections",+ "libc",+ "libloading 0.8.9",+ "libm",+ "loom",+ "miette",+ "num-bigint",+ "num-traits",+ "pack1",+ "parking_lot",+ "pastey",+ "polling",+ "rand 0.9.4",+ "rapidhash",+ "regex",+ "regex-syntax",+ "roaring",+ "rustc-hash 2.1.2",+ "rustix",+ "ryu",+ "serde_json",+ "shuttle",+ "simdutf8",+ "simsimd",+ "smallvec",+ "strum 0.26.3",+ "strum_macros 0.26.4",+ "tempfile",+ "thiserror 2.0.18",+ "tracing",+ "tracing-subscriber",+ "turso_ext",+ "turso_macros",+ "turso_parser",+ "twox-hash",+ "uncased",+ "uuid",+ "windows-sys 0.61.2",+]++[[package]]+name = "turso_ext"+version = "0.8.0-pre.3"+source = "git+https://github.com/seanaye/turso?rev=be9acfe9e5e6efb17911af84047e4855cace53a3#be9acfe9e5e6efb17911af84047e4855cace53a3"+dependencies = [+ "chrono",+ "getrandom 0.4.2",+ "turso_macros",+]++[[package]]+name = "turso_macros"+version = "0.8.0-pre.3"+source = "git+https://github.com/seanaye/turso?rev=be9acfe9e5e6efb17911af84047e4855cace53a3#be9acfe9e5e6efb17911af84047e4855cace53a3"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "turso_parser"+version = "0.8.0-pre.3"+source = "git+https://github.com/seanaye/turso?rev=be9acfe9e5e6efb17911af84047e4855cace53a3#be9acfe9e5e6efb17911af84047e4855cace53a3"+dependencies = [+ "bitflags 2.11.1",+ "memchr",+ "miette",+ "strum 0.26.3",+ "strum_macros 0.26.4",+ "thiserror 2.0.18",+ "turso_macros",+]++[[package]]+name = "twox-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8464ec13c3691491391d9fce00f6416c9a48e46972f72d7865688be2080192c9"+dependencies = [+ "rand 0.9.4",+]+[[package]]name = "typed-arena"version = "2.0.2"@@ -6766,6 +7386,15 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "uncased"+version = "0.9.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697"+dependencies = [+ "version_check",+]+[[package]]name = "unic-char-property"version = "0.9.0"@@ -6825,6 +7454,12 @@ version = "1.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"+[[package]]+name = "unicode-width"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"+[[package]]name = "unicode-width"version = "0.2.2"@@ -6837,6 +7472,16 @@ version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+[[package]]+name = "universal-hash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"+dependencies = [+ "crypto-common",+ "subtle",+]+[[package]]name = "untrusted"version = "0.9.0"@@ -6890,6 +7535,12 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"+[[package]]+name = "utf16_iter"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246"+[[package]]name = "utf8-width"version = "0.1.8"@@ -6911,6 +7562,7 @@ dependencies = ["getrandom 0.4.2","js-sys","serde_core",+ "sha1_smol","wasm-bindgen",]@@ -6926,12 +7578,6 @@ version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"-[[package]]-name = "vcpkg"-version = "0.2.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"-[[package]]name = "version-compare"version = "0.2.1"@@ -7015,9 +7661,9 @@ dependencies = [[[package]]name = "wasm-bindgen"-version = "0.2.118"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0bf938a0bacb0469e83c1e148908bd7d5a6010354cf4fb73279b7447422e3a89"+checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70"dependencies = ["cfg-if","once_cell",@@ -7028,9 +7674,9 @@ dependencies = [[[package]]name = "wasm-bindgen-futures"-version = "0.4.68"+version = "0.4.77"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f371d383f2fb139252e0bfac3b81b265689bf45b6874af544ffa4c975ac1ebf8"+checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950"dependencies = ["js-sys","wasm-bindgen",@@ -7038,9 +7684,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro"-version = "0.2.118"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eeff24f84126c0ec2db7a449f0c2ec963c6a49efe0698c4242929da037ca28ed"+checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1"dependencies = ["quote","wasm-bindgen-macro-support",@@ -7048,9 +7694,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro-support"-version = "0.2.118"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d08065faf983b2b80a79fd87d8254c409281cf7de75fc4b773019824196c904"+checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284"dependencies = ["bumpalo","proc-macro2",@@ -7061,9 +7707,9 @@ dependencies = [[[package]]name = "wasm-bindgen-shared"-version = "0.2.118"+version = "0.2.127"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5fd04d9e306f1907bd13c6361b5c6bfc7b3b3c095ed3f8a9246390f8dbdee129"+checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf"dependencies = ["unicode-ident",]@@ -7117,9 +7763,9 @@ dependencies = [[[package]]name = "web-sys"-version = "0.3.95"+version = "0.3.104"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4f2dfbb17949fa2088e5d39408c48368947b86f7834484e87b73de55bc14d97d"+checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30"dependencies = ["js-sys","wasm-bindgen",@@ -7997,11 +8643,17 @@ dependencies = ["windows-core 0.58.0",]+[[package]]+name = "write16"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"+[[package]]name = "writeable"-version = "0.6.3"+version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"[[package]]name = "wry"@@ -8085,9 +8737,9 @@ checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"[[package]]name = "yoke"-version = "0.8.2"+version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"dependencies = ["stable_deref_trait","yoke-derive",@@ -8230,21 +8882,23 @@ dependencies = [[[package]]name = "zerotrie"-version = "0.2.4"+version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"dependencies = ["displaydoc","yoke","zerofrom",+ "zerovec",][[package]]name = "zerovec"-version = "0.11.6"+version = "0.11.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"+checksum = "94b5c6b5976d66c1d703c4fd17d3f5e43c8cedaacf604961b171adc7130896d8"dependencies = [+ "serde","yoke","zerofrom","zerovec-derive",@@ -8252,13 +8906,13 @@ dependencies = [[[package]]name = "zerovec-derive"-version = "0.11.3"+version = "0.11.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"+checksum = "9f212a141d820099d57ffafb9569be9617a6f27d3dc881fbee8fb56642f917a9"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 3.0.3",][[package]]diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.tomlindex 03539839b5..3441531052 100644--- a/apps/web/tauri/Cargo.toml+++ b/apps/web/tauri/Cargo.toml@@ -15,6 +15,7 @@ package.edition = "2024"resolver = "2"[workspace.dependencies]+pollster = "0.4"reqwest = "0.13"rootcause = "0.12"semver = "1"diff --git a/apps/web/tauri/graphql_cache_plugin/Cargo.toml b/apps/web/tauri/graphql_cache_plugin/Cargo.tomlindex 7df20cfd00..b38bdaa17c 100644--- a/apps/web/tauri/graphql_cache_plugin/Cargo.toml+++ b/apps/web/tauri/graphql_cache_plugin/Cargo.toml@@ -5,7 +5,7 @@ edition.workspace = true[dependencies]cache-core = { path = "../../../../crates/client/cache-core" }-cache-sqlite = { path = "../../../../crates/client/cache-sqlite" }+cache-turso = { path = "../../../../crates/client/cache-turso" }serde = { workspace = true, features = ["derive"] }serde_json = "1"tauri = { workspace = true }diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rsindex 2fdc3684cb..4a031e78b2 100644--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs@@ -21,7 +21,7 @@ use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};use cache_core::query_inspection::{CachedQueryInstance, CachedQueryVariant};use cache_core::record_selection::SelectedRecord;use cache_core::search::{SearchPage, SearchRequest};-use cache_sqlite::SqliteStorage;+use cache_turso::TursoFileDatabase;use serde::Deserialize;use tauri::{AppHandle, Manager, Runtime, State};@@ -39,10 +39,8 @@ fn engine_handle(state: &State<'_, CacheState>) -> Result<EngineHandle, String>/// Opens (or creates) the cache for `scope`. Idempotent for the same scope;/// errors on a scope mismatch (parity with the browser worker `init`). The-/// database lives at `{app_data_dir}/graphql-cache/cache.sqlite`. A scope-/// change clears all cache state; for the same scope, a schema compatibility-/// epoch or format mismatch clears disposable records but retains queued user-/// intent.+/// database lives at `{app_data_dir}/graphql-cache/cache.turso`. Incompatible+/// or uncertain storage is physically replaced before opening.#[tauri::command]pub async fn graphql_cache_init<R: Runtime>(app: AppHandle<R>,@@ -69,8 +67,11 @@ pub async fn graphql_cache_init<R: Runtime>(.map_err(|e| e.to_string())?.join("graphql-cache");std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;- let storage =- SqliteStorage::open(dir.join("cache.sqlite"), &scope).map_err(|e| e.to_string())?;+ let database =+ TursoFileDatabase::new(dir.join("cache.turso")).map_err(|error| error.to_string())?;+ let storage = database+ .open_or_reset(&scope)+ .map_err(|error| error.to_string())?;let handle = EngineHandle::new(storage, hot_capacity);*guard = Some(InitializedCache { scope, handle });Ok(())diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rsindex d92337a192..e22d66e74c 100644--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs@@ -1,10 +1,10 @@-//! Engine host: the cache engine + SQLite storage behind an async mutex.+//! Engine host: the cache engine + Turso storage behind an async mutex.//!//! `cache-core`'s `Storage` futures are `MaybeSend` — `Send` on native//! targets — so the engine is driven directly from the tauri/tokio runtime;//! the async mutex serializes commands the same way the browser worker's-//! queue does. SQLite work completes immediately (blocking IO is the point-//! of the native host), so holding a runtime thread through it is fine.+//! queue does. Turso work completes immediately on its native synchronous IO+//! driver, so holding a runtime thread through it is fine.//!//! Operation ids cross the IPC boundary as strings (`"{clientId}:{urqlKey}"`)//! so multiple webviews can register operations against the one shared@@ -22,7 +22,7 @@ use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimTokeuse cache_core::record_selection::RecordSelection;use cache_core::search::{SearchPage, SearchRequest};use cache_core::value::EntityKey;-use cache_sqlite::SqliteStorage;+use cache_turso::{TursoStorage, TursoStorageCloseOutcome};use serde::Serialize;use std::collections::HashMap;use std::sync::Arc;@@ -162,7 +162,7 @@ impl OpInterner {type Variables = serde_json::Map<String, serde_json::Value>;struct EngineState {- engine: Engine<SqliteStorage>,+ engine: Engine<TursoStorage>,ops: OpInterner,}@@ -201,7 +201,7 @@ fn parse_transaction_id(id: &str) -> Result<u64, String> {impl EngineHandle {/// Wraps an opened storage backend. A `hot_capacity` of 0 is treated as/// unset (engine default).- pub fn new(storage: SqliteStorage, hot_capacity: Option<u32>) -> Self {+ pub fn new(storage: TursoStorage, hot_capacity: Option<u32>) -> Self {let engine = match hot_capacity.filter(|c| *c > 0) {Some(cap) => Engine::with_capacity(storage, cap as usize),None => Engine::new(storage),@@ -214,6 +214,23 @@ impl EngineHandle {}}+ /// Consumes the sole handle and explicitly closes native Turso storage.+ pub fn shutdown(self) -> Result<(), String> {+ let mutex = Arc::try_unwrap(self.inner)+ .map_err(|_| "graphql cache still has active command handles".to_string())?;+ let state = mutex.into_inner();+ let outcome = state+ .engine+ .into_storage()+ .try_close()+ .map_err(|error| error.to_string())?;+ match outcome {+ TursoStorageCloseOutcome::Healthy | TursoStorageCloseOutcome::ResetRequired(_) => {+ Ok(())+ }+ }+ }+/// Cache read; registers `op_id` as active when given.pub async fn read(&self,@@ -251,10 +268,7 @@ impl EngineHandle {) -> Result<Vec<cache_core::record_selection::SelectedRecord>, String> {let selection =RecordSelection::parse(&document, &fragment_name).map_err(|error| error.to_string())?;- let keys: Vec<_> = keys- .into_iter()- .map(|key| EntityKey(key.into()))- .collect();+ let keys: Vec<_> = keys.into_iter().map(|key| EntityKey(key.into())).collect();self.inner.lock().awaitdiff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rsindex f85b90cf3e..2a93b0e2ac 100644--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs@@ -25,7 +25,7 @@ fn soup_data(has_next_page: bool) -> serde_json::Value {}fn spawn_handle() -> EngineHandle {- let storage = SqliteStorage::open_in_memory("scope-1").unwrap();+ let storage = TursoStorage::open_in_memory("scope-1").unwrap();EngineHandle::new(storage, None)}@@ -420,6 +420,11 @@ fn clear_wipes_everything() {assert!(matches!(read(&handle, None), ReadResultWire::Miss));}+#[test]+fn sole_engine_handle_shuts_turso_down_explicitly() {+ spawn_handle().shutdown().unwrap();+}+#[test]fn bad_transaction_id_is_an_error() {let handle = spawn_handle();diff --git a/apps/web/tauri/graphql_cache_plugin/src/lib.rs b/apps/web/tauri/graphql_cache_plugin/src/lib.rsindex 953d265784..89015a7724 100644--- a/apps/web/tauri/graphql_cache_plugin/src/lib.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/lib.rs@@ -2,7 +2,7 @@//!//! The webview counterpart of the browser worker glue in//! `apps/web/src/lib/graphql-cache/`: the engine (`cache-core` over-//! `cache-sqlite`) lives in the Tauri host process behind an async mutex+//! `cache-turso`) lives in the Tauri host process behind an async mutex//! (`Storage` futures are `MaybeSend`, so `Send` on native) — one shared//! instance across all webviews/windows, never webview storage.//! Webviews talk to it through the commands in [`commands`] (registered@@ -74,6 +74,18 @@ struct InitializedCache {#[derive(Default)]pub struct CacheState(Mutex<Option<InitializedCache>>);+impl CacheState {+ /// Takes the initialized cache and explicitly closes its Turso connection.+ pub fn shutdown(&self) -> Result<(), String> {+ let cache = self+ .0+ .lock()+ .map_err(|_| "graphql cache state poisoned".to_string())?+ .take();+ cache.map_or(Ok(()), |cache| cache.handle.shutdown())+ }+}+fn emit_ops_affected<R: Runtime>(app: &AppHandle<R>, op_ids: &[String], keys: &[String]) {if op_ids.is_empty() {return;diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex 2fb6a5f5e5..a60354c624 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -345,6 +345,16 @@ pub fn run() {});}}+ RunEvent::Exit => {+ if let Some(state) = app_handle.try_state::<graphql_cache_plugin::CacheState>() {+ state+ .shutdown()+ .inspect_err(+ |error| tracing::error!(error=?error, "failed to close graphql cache"),+ )+ .ok();+ }+ }_ => {}});}diff --git a/crates/client/README.md b/crates/client/README.mdindex 8c43b7afcf..b2e450a34f 100644--- a/crates/client/README.md+++ b/crates/client/README.md@@ -8,14 +8,13 @@ Normalized GraphQL cache with disk-backed persistence for urql. Design doc:| Crate | Purpose ||---|---|| `cache-core` | Pure engine: normalize/denormalize, LRU hot tier, dependency index, durable ordered optimistic-mutation queue, async `Storage` trait |-| `cache-sqlite` | `Storage` over SQLite — Tauri native host |-| `cache-turso` | `Storage` over Turso core — browser WASM host |+| `cache-turso` | `Storage` over Turso core — browser WASM and Tauri native hosts || `turso-opfs` | Browser OPFS `IO`/`File` adapter for the dedicated Turso engine worker || `cache-wasm` | wasm-bindgen shell combining the engine, Turso storage, and OPFS adapter for browser worker glue (`apps/web/src/lib/graphql-cache/`) |The Tauri host lives in the tauri workspace (it needs the patched tauri forkpinned there): `apps/web/tauri/graphql_cache_plugin`, path-depending on-`cache-core`/`cache-sqlite`. Test it from `apps/web/tauri` with+`cache-core`/`cache-turso`. Test it from `apps/web/tauri` with`cargo test -p graphql_cache_plugin` (on NixOS use the `tauri-linux` dev shell —Tauri's Linux desktop stack needs its WebKitGTK/DBus system libraries).@@ -24,7 +23,7 @@ Tauri's Linux desktop stack needs its WebKitGTK/DBus system libraries).Run from the repository root:```sh-cargo test -p cache-core -p cache-sqlite -p cache-turso -p turso-opfs+cargo test -p cache-core -p cache-turso -p turso-opfscargo check --target wasm32-unknown-unknown -p cache-turso -p turso-opfs -p cache-wasm --all-targetswasm-pack test --headless --chrome crates/client/cache-tursowasm-pack test --headless --chrome crates/client/turso-opfsdiff --git a/crates/client/cache-core/src/codec.rs b/crates/client/cache-core/src/codec.rsindex 71d9757fa4..ba04fc10b4 100644--- a/crates/client/cache-core/src/codec.rs+++ b/crates/client/cache-core/src/codec.rs@@ -1,5 +1,5 @@-//! Binary record codec shared by all persistent backends (browser Turso and-//! native SQLite). Records are stored as postcard bytes; the logical namespace+//! Binary record codec shared by all persistent Turso backends (browser and+//! native hosts). Records are stored as postcard bytes; the logical namespace//! embeds [`CACHE_FORMAT_VERSION`] and [`CACHE_SCHEMA_COMPATIBILITY_EPOCH`].//! A healthy, graceful browser reopen with matching versions preserves records,//! queued mutations, and optimistic layers. A compatibility/format mismatch ordiff --git a/crates/client/cache-core/src/store.rs b/crates/client/cache-core/src/store.rsindex 7124e0dac9..cc9554f24f 100644--- a/crates/client/cache-core/src/store.rs+++ b/crates/client/cache-core/src/store.rs@@ -1,7 +1,7 @@//! Storage abstraction: the cold tier behind the in-memory hot tier.//!-//! Implementations: in-memory (tests), Turso over OPFS (browser), and SQLite-//! (Tauri native). Futures are [`MaybeSend`]: `Send` on native targets (so+//! Implementations: in-memory (tests) and Turso over OPFS (browser) or native+//! filesystem IO (Tauri). Futures are [`MaybeSend`]: `Send` on native targets (so//! hosts can drive the engine from a multi-threaded runtime), unbounded on//! wasm — wasm futures aren't//! `Send`.diff --git a/crates/client/cache-sqlite/Cargo.toml b/crates/client/cache-sqlite/Cargo.tomldeleted file mode 100644index 5f3ed89f1d..0000000000--- a/crates/client/cache-sqlite/Cargo.toml+++ /dev/null@@ -1,17 +0,0 @@-[package]-edition = "2024"-name = "cache-sqlite"-publish = false-version = "0.1.0"--[dependencies]-cache-core = { path = "../cache-core" }-# 0.32 pins libsqlite3-sys 0.30, matching the workspace sqlx-sqlite pin-# (libsqlite3-sys has `links = "sqlite3"` — only one version may exist).-rusqlite = { version = "0.32", features = ["bundled"] }-thiserror = { workspace = true }--[dev-dependencies]-pollster = { workspace = true }-serde_json = { workspace = true }-tempfile = "3"diff --git a/crates/client/cache-sqlite/src/lib.rs b/crates/client/cache-sqlite/src/lib.rsdeleted file mode 100644index dfc26befcb..0000000000--- a/crates/client/cache-sqlite/src/lib.rs+++ /dev/null@@ -1,1100 +0,0 @@-//! SQLite [`Storage`] backend for the Tauri native host.-//!-//! One database file per cache; the `meta` table pins the cache namespace-//! (scope + schema compatibility epoch + format version, see-//! [`cache_core::codec::cache_namespace`]). On mismatch the store is wiped-//! and rebuilt — the cache is disposable by design, never migrated.-//!-//! rusqlite is synchronous; the async [`Storage`] methods complete-//! immediately (blocking IO is the point of the native host). The-//! connection sits behind a `Mutex` so `&self` futures are `Send`-//! (`Storage` futures are `MaybeSend`), letting the Tauri host drive the-//! engine directly from its multi-threaded runtime.--#![deny(missing_docs)]--use cache_core::codec::{- cache_namespace, decode_record, decode_record_updates, encode_record, encode_record_updates,-};-use cache_core::queue::{- ClaimedMutation, MutationClaimRequest, MutationClaimToken, MutationId, MutationRequest,- NewQueuedMutation, PersistedOptimisticLayer, QueuedMutation, StoredMutation,-};-use cache_core::search::{SearchCursor, SearchDocument, SearchProfile, project_search_documents};-use cache_core::store::{QueueDiagnostics, QueueDiagnosticsAvailability, Storage};-use cache_core::value::{EntityKey, Record};-use rusqlite::{Connection, OptionalExtension, Transaction, params};-use std::path::Path;-use std::sync::{Mutex, MutexGuard};-use thiserror::Error;--/// Version of the disposable native search projection schema.-const NATIVE_SEARCH_SCHEMA_VERSION: u32 = 4;--/// Errors produced by the SQLite storage backend.-#[derive(Debug, Error)]-pub enum SqliteStorageError {- /// Underlying SQLite failure.- #[error("sqlite: {0}")]- Sqlite(#[from] rusqlite::Error),- /// A stored cache value failed to decode.- #[error(transparent)]- Codec(#[from] cache_core::codec::CodecError),- /// Durable queue metadata violated an invariant.- #[error("invalid mutation queue state: {0}")]- QueueInvariant(String),- /// A search cursor did not contain a canonical entity key.- #[error("invalid search cursor")]- InvalidSearchCursor,-}--/// [`Storage`] backend over a SQLite database (Tauri native host).-pub struct SqliteStorage {- /// `Connection` is `Send` but not `Sync`; the mutex makes the storage- /// `Sync` so borrowing futures are `Send`. Never contended in practice —- /// the engine serializes storage access.- conn: Mutex<Connection>,-}--impl SqliteStorage {- /// Opens (or wipes and rebuilds) the cache database at `path` for- /// `scope` (user/workspace identifier).- pub fn open(path: impl AsRef<Path>, scope: &str) -> Result<Self, SqliteStorageError> {- let conn = Connection::open(path)?;- Self::init(conn, scope)- }-- /// In-memory database (tests).- pub fn open_in_memory(scope: &str) -> Result<Self, SqliteStorageError> {- Self::init(Connection::open_in_memory()?, scope)- }-- fn init(mut conn: Connection, scope: &str) -> Result<Self, SqliteStorageError> {- conn.pragma_update(None, "journal_mode", "WAL")?;- conn.pragma_update(None, "synchronous", "NORMAL")?;- conn.pragma_update(None, "foreign_keys", "ON")?;- conn.execute_batch(- "CREATE TABLE IF NOT EXISTS meta (- k TEXT PRIMARY KEY,- v TEXT NOT NULL- );- CREATE TABLE IF NOT EXISTS records (- key TEXT PRIMARY KEY,- value BLOB NOT NULL- );- CREATE TABLE IF NOT EXISTS search_documents (- profile TEXT NOT NULL,- __typename TEXT NOT NULL,- id TEXT NOT NULL,- bucket TEXT NOT NULL,- search_text TEXT NOT NULL,- timestamp_ms INTEGER NOT NULL,- source_hash TEXT NOT NULL,- PRIMARY KEY(profile, __typename, id)- );- CREATE INDEX IF NOT EXISTS search_documents_browse_idx- ON search_documents(- profile, bucket, timestamp_ms DESC, __typename ASC, id ASC- );- CREATE TABLE IF NOT EXISTS mutation_queue (- id INTEGER PRIMARY KEY AUTOINCREMENT,- query TEXT NOT NULL,- operation_name TEXT,- variables_json TEXT NOT NULL,- identity TEXT,- attempt_count INTEGER NOT NULL DEFAULT 0,- next_attempt_at_ms INTEGER,- lease_owner TEXT,- lease_generation INTEGER NOT NULL DEFAULT 0,- lease_expires_at_ms INTEGER,- last_error TEXT,- created_at_ms INTEGER NOT NULL- );- CREATE INDEX IF NOT EXISTS mutation_queue_created_at_ms_idx- ON mutation_queue(created_at_ms);- CREATE TABLE IF NOT EXISTS optimistic_layers (- mutation_id INTEGER PRIMARY KEY,- optimistic_data_json TEXT NOT NULL,- normalized_updates BLOB NOT NULL,- FOREIGN KEY(mutation_id) REFERENCES mutation_queue(id) ON DELETE CASCADE- );",- )?;-- let expected_namespace = cache_namespace(scope);- let stored_scope: Option<String> = conn- .query_row("SELECT v FROM meta WHERE k = 'scope'", [], |row| row.get(0))- .optional()?;- let stored_namespace: Option<String> = conn- .query_row("SELECT v FROM meta WHERE k = 'namespace'", [], |row| {- row.get(0)- })- .optional()?;- let stored_search_version: Option<String> = conn- .query_row(- "SELECT v FROM meta WHERE k = 'search_schema_version'",- [],- |row| row.get(0),- )- .optional()?;-- let expected_search_version = NATIVE_SEARCH_SCHEMA_VERSION.to_string();- let search_schema_changed =- stored_search_version.as_deref() != Some(expected_search_version.as_str());- let tx = conn.transaction()?;- // Existing projection schemas must be physically replaced before the- // version marker advances. The cache is disposable and intentionally- // does not backfill by scanning record blobs.- if stored_search_version.is_some() && search_schema_changed {- tx.execute_batch(- "DROP TABLE search_documents;- CREATE TABLE search_documents (- profile TEXT NOT NULL,- __typename TEXT NOT NULL,- id TEXT NOT NULL,- bucket TEXT NOT NULL,- search_text TEXT NOT NULL,- timestamp_ms INTEGER NOT NULL,- source_hash TEXT NOT NULL,- PRIMARY KEY(profile, __typename, id)- );- CREATE INDEX search_documents_browse_idx- ON search_documents(- profile, bucket, timestamp_ms DESC, __typename ASC, id ASC- );",- )?;- }- if stored_scope.as_deref() != Some(scope) {- // Scope changes are identity changes: queued user intent must not- // cross the boundary. `None` is the one-time upgrade from the- // pre-queue schema, where no durable mutations existed.- tx.execute("DELETE FROM optimistic_layers", [])?;- tx.execute("DELETE FROM mutation_queue", [])?;- tx.execute("DELETE FROM search_documents", [])?;- tx.execute("DELETE FROM records", [])?;- } else if stored_namespace.as_deref() != Some(expected_namespace.as_str()) {- // Incompatible schema/cache-format changes only invalidate- // disposable records. The queue retains source GraphQL +- // optimistic JSON so the engine can re-normalize it against the- // current schema.- tx.execute("DELETE FROM search_documents", [])?;- tx.execute("DELETE FROM records", [])?;- } else if search_schema_changed {- // The projection is derived from complete records, so a profile- // change discards both rather than backfilling by blob scan.- tx.execute("DELETE FROM search_documents", [])?;- tx.execute("DELETE FROM records", [])?;- }- tx.execute(- "INSERT INTO meta (k, v) VALUES ('scope', ?1)- ON CONFLICT(k) DO UPDATE SET v = excluded.v",- params![scope],- )?;- tx.execute(- "INSERT INTO meta (k, v) VALUES ('namespace', ?1)- ON CONFLICT(k) DO UPDATE SET v = excluded.v",- params![expected_namespace],- )?;- tx.execute(- "INSERT INTO meta (k, v) VALUES ('search_schema_version', ?1)- ON CONFLICT(k) DO UPDATE SET v = excluded.v",- params![expected_search_version],- )?;- tx.commit()?;-- Ok(SqliteStorage {- conn: Mutex::new(conn),- })- }-- /// A poisoned mutex means a panic mid-statement; SQLite rolls back- /// interrupted transactions on drop, so the connection stays usable.- fn conn(&self) -> MutexGuard<'_, Connection> {- self.conn.lock().unwrap_or_else(|e| e.into_inner())- }-- /// Total number of stored records (diagnostics/GC).- pub fn record_count(&self) -> Result<u64, SqliteStorageError> {- Ok(self- .conn()- .query_row("SELECT COUNT(*) FROM records", [], |row| row.get(0))?)- }-- /// Number of compact search documents.- pub fn search_document_count(&self) -> Result<u64, SqliteStorageError> {- Ok(self- .conn()- .query_row("SELECT COUNT(*) FROM search_documents", [], |row| {- row.get(0)- })?)- }-- /// Number of mutations waiting for settlement.- pub fn mutation_count(&self) -> Result<u64, SqliteStorageError> {- Ok(self- .conn()- .query_row("SELECT COUNT(*) FROM mutation_queue", [], |row| row.get(0))?)- }-}--fn mutation_id_from_sql(id: i64) -> Result<MutationId, SqliteStorageError> {- id.try_into()- .map_err(|_| SqliteStorageError::QueueInvariant(format!("negative mutation id {id}")))-}--fn mutation_id_to_sql(id: MutationId) -> Result<i64, SqliteStorageError> {- id.try_into().map_err(|_| {- SqliteStorageError::QueueInvariant(format!("mutation id {id} exceeds SQLite INTEGER"))- })-}--fn row_stored_mutation(row: &rusqlite::Row<'_>, offset: usize) -> rusqlite::Result<StoredMutation> {- let attempt_count: i64 = row.get(offset + 4)?;- let lease_generation: i64 = row.get(offset + 7)?;- Ok(StoredMutation {- request: MutationRequest {- query: row.get(offset)?,- operation_name: row.get(offset + 1)?,- variables_json: row.get(offset + 2)?,- identity: row.get(offset + 3)?,- },- attempt_count: attempt_count.try_into().map_err(|e| {- rusqlite::Error::FromSqlConversionFailure(- offset + 4,- rusqlite::types::Type::Integer,- Box::new(e),- )- })?,- next_attempt_at_ms: row.get(offset + 5)?,- lease_owner: row.get(offset + 6)?,- lease_generation: lease_generation.try_into().map_err(|e| {- rusqlite::Error::FromSqlConversionFailure(- offset + 7,- rusqlite::types::Type::Integer,- Box::new(e),- )- })?,- lease_expires_at_ms: row.get(offset + 8)?,- last_error: row.get(offset + 9)?,- created_at_ms: row.get(offset + 10)?,- })-}--fn entity_key_parts<'a>(key: &'a EntityKey<'_>) -> Option<(&'a str, &'a str)> {- key.as_ref()- .split_once(':')- .filter(|(typename, _)| !typename.is_empty())-}--fn write_search_documents(- tx: &Transaction<'_>,- entries: &[(EntityKey<'static>, Record)],-) -> Result<(), rusqlite::Error> {- let mut delete =- tx.prepare_cached("DELETE FROM search_documents WHERE __typename = ?1 AND id = ?2")?;- let mut upsert = tx.prepare_cached(- "INSERT INTO search_documents (- profile, __typename, id, bucket, search_text, timestamp_ms, source_hash- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)- ON CONFLICT(profile, __typename, id) DO UPDATE SET- bucket = excluded.bucket,- search_text = excluded.search_text,- timestamp_ms = excluded.timestamp_ms,- source_hash = excluded.source_hash",- )?;- for (key, record) in entries {- let Some((typename, id)) = entity_key_parts(key) else {- continue;- };- delete.execute(params![typename, id])?;- for document in project_search_documents(key, record) {- upsert.execute(params![- document.profile.as_str(),- typename,- id,- document.bucket,- document.search_text,- document.timestamp_ms,- document.source_hash,- ])?;- }- }- Ok(())-}--fn row_search_document(- row: &rusqlite::Row<'_>,- profile: SearchProfile,-) -> rusqlite::Result<SearchDocument> {- let typename: String = row.get(0)?;- let id: String = row.get(1)?;- Ok(SearchDocument {- profile,- record_key: EntityKey::entity(&typename, &[&id]),- bucket: row.get(2)?,- search_text: row.get(3)?,- timestamp_ms: row.get(4)?,- source_hash: row.get(5)?,- })-}--fn claim_is_current(- tx: &Transaction<'_>,- id: i64,- claim: &MutationClaimToken,-) -> Result<bool, rusqlite::Error> {- let current: Option<(Option<String>, i64)> = tx- .query_row(- "SELECT lease_owner, lease_generation FROM mutation_queue WHERE id = ?1",- params![id],- |row| Ok((row.get(0)?, row.get(1)?)),- )- .optional()?;- Ok(current.is_some_and(|(owner, generation)| {- owner.as_deref() == Some(&claim.owner)- && u64::try_from(generation).ok() == Some(claim.generation)- }))-}--impl Storage for SqliteStorage {- type Error = SqliteStorageError;-- async fn get_batch(&self, keys: &[EntityKey<'_>]) -> Result<Vec<Option<Record>>, Self::Error> {- let conn = self.conn();- let mut stmt = conn.prepare_cached("SELECT value FROM records WHERE key = ?1")?;- let mut out = Vec::with_capacity(keys.len());- for key in keys {- let bytes: Option<Vec<u8>> = stmt- .query_row(params![key.0.as_ref()], |row| row.get(0))- .optional()?;- out.push(match bytes {- Some(b) => Some(decode_record(&b)?),- None => None,- });- }- Ok(out)- }-- async fn put_batch(- &mut self,- entries: Vec<(EntityKey<'static>, Record)>,- ) -> Result<(), Self::Error> {- let mut conn = self.conn();- let tx = conn.transaction()?;- {- let mut stmt = tx.prepare_cached(- "INSERT INTO records (key, value) VALUES (?1, ?2)- ON CONFLICT(key) DO UPDATE SET value = excluded.value",- )?;- for (key, record) in &entries {- stmt.execute(params![key.0.as_ref(), encode_record(record)])?;- }- }- write_search_documents(&tx, &entries)?;- tx.commit()?;- Ok(())- }-- async fn delete_batch(&mut self, keys: &[EntityKey<'static>]) -> Result<(), Self::Error> {- let mut conn = self.conn();- let tx = conn.transaction()?;- {- let mut record_stmt = tx.prepare_cached("DELETE FROM records WHERE key = ?1")?;- let mut search_stmt = tx- .prepare_cached("DELETE FROM search_documents WHERE __typename = ?1 AND id = ?2")?;- for key in keys {- record_stmt.execute(params![key.0.as_ref()])?;- if let Some((typename, id)) = entity_key_parts(key) {- search_stmt.execute(params![typename, id])?;- }- }- }- tx.commit()?;- Ok(())- }-- async fn load_search_documents(- &self,- profile: SearchProfile,- ) -> Result<Vec<SearchDocument>, Self::Error> {- let conn = self.conn();- let mut statement = conn.prepare_cached(- "SELECT __typename, id, bucket, search_text, timestamp_ms, source_hash- FROM search_documents WHERE profile = ?1",- )?;- let rows = statement.query_map(params![profile.as_str()], |row| {- row_search_document(row, profile)- })?;- rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)- }-- async fn browse_search_documents(- &self,- profile: SearchProfile,- bucket: &str,- after: Option<&SearchCursor>,- limit: usize,- ) -> Result<Vec<SearchDocument>, Self::Error> {- let conn = self.conn();- let limit = i64::try_from(limit).unwrap_or(i64::MAX);- let mut documents = Vec::new();- if let Some(cursor) = after {- let (cursor_typename, cursor_id) = entity_key_parts(&cursor.record_key)- .ok_or(SqliteStorageError::InvalidSearchCursor)?;- let mut statement = conn.prepare_cached(- "SELECT __typename, id, bucket, search_text, timestamp_ms, source_hash- FROM search_documents- WHERE profile = ?1 AND bucket = ?2- AND (- timestamp_ms < ?3- OR (timestamp_ms = ?3 AND (- __typename > ?4 OR (__typename = ?4 AND id > ?5)- ))- )- ORDER BY timestamp_ms DESC, __typename ASC, id ASC LIMIT ?6",- )?;- let rows = statement.query_map(- params![- profile.as_str(),- bucket,- cursor.timestamp_ms,- cursor_typename,- cursor_id,- limit- ],- |row| row_search_document(row, profile),- )?;- for row in rows {- documents.push(row?);- }- } else {- let mut statement = conn.prepare_cached(- "SELECT __typename, id, bucket, search_text, timestamp_ms, source_hash- FROM search_documents- WHERE profile = ?1 AND bucket = ?2- ORDER BY timestamp_ms DESC, __typename ASC, id ASC LIMIT ?3",- )?;- let rows = statement.query_map(params![profile.as_str(), bucket, limit], |row| {- row_search_document(row, profile)- })?;- for row in rows {- documents.push(row?);- }- }- Ok(documents)- }-- async fn enqueue_mutation(- &mut self,- entry: NewQueuedMutation,- ) -> Result<MutationId, Self::Error> {- let mut conn = self.conn();- let tx = conn.transaction()?;- let mutation = &entry.mutation;- tx.execute(- "INSERT INTO mutation_queue (- query, operation_name, variables_json, identity,- attempt_count, next_attempt_at_ms, lease_owner,- lease_generation, lease_expires_at_ms, last_error, created_at_ms- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",- params![- mutation.request.query,- mutation.request.operation_name,- mutation.request.variables_json,- mutation.request.identity,- i64::from(mutation.attempt_count),- mutation.next_attempt_at_ms,- mutation.lease_owner,- i64::try_from(mutation.lease_generation).map_err(|_| {- SqliteStorageError::QueueInvariant(- "lease generation exceeds SQLite INTEGER".to_string(),- )- })?,- mutation.lease_expires_at_ms,- mutation.last_error,- mutation.created_at_ms,- ],- )?;- let sql_id = tx.last_insert_rowid();- tx.execute(- "INSERT INTO optimistic_layers (- mutation_id, optimistic_data_json, normalized_updates- ) VALUES (?1, ?2, ?3)",- params![- sql_id,- entry.optimistic.optimistic_data_json,- encode_record_updates(&entry.optimistic.normalized_updates),- ],- )?;- tx.commit()?;- mutation_id_from_sql(sql_id)- }-- async fn load_mutation_queue(&self) -> Result<Vec<QueuedMutation>, Self::Error> {- let conn = self.conn();- let mut stmt = conn.prepare_cached(- "SELECT- m.id, m.query, m.operation_name, m.variables_json, m.identity,- m.attempt_count, m.next_attempt_at_ms, m.lease_owner,- m.lease_generation, m.lease_expires_at_ms, m.last_error,- m.created_at_ms, o.optimistic_data_json, o.normalized_updates- FROM mutation_queue m- INNER JOIN optimistic_layers o ON o.mutation_id = m.id- ORDER BY m.id ASC",- )?;- let mut rows = stmt.query([])?;- let mut out = Vec::new();- while let Some(row) = rows.next()? {- let id: i64 = row.get(0)?;- let updates: Vec<u8> = row.get(13)?;- out.push(QueuedMutation {- id: mutation_id_from_sql(id)?,- mutation: row_stored_mutation(row, 1)?,- optimistic: PersistedOptimisticLayer {- optimistic_data_json: row.get(12)?,- normalized_updates: decode_record_updates(&updates)?,- },- });- }- Ok(out)- }-- async fn queue_diagnostics(&self) -> Result<QueueDiagnostics, Self::Error> {- let (depth, oldest_created_at_ms): (i64, Option<i64>) = self.conn().query_row(- "SELECT COUNT(*), MIN(created_at_ms) FROM mutation_queue",- [],- |row| Ok((row.get(0)?, row.get(1)?)),- )?;- let depth = u64::try_from(depth).map_err(|_| {- SqliteStorageError::QueueInvariant("negative mutation queue depth".to_string())- })?;- if (depth == 0) != oldest_created_at_ms.is_none() {- return Err(SqliteStorageError::QueueInvariant(- "queue depth and oldest timestamp disagree".to_string(),- ));- }- Ok(QueueDiagnostics {- availability: QueueDiagnosticsAvailability::Available,- depth,- oldest_created_at_ms,- })- }-- async fn claim_next_mutation(- &mut self,- request: MutationClaimRequest,- ) -> Result<Option<ClaimedMutation>, Self::Error> {- let mut conn = self.conn();- let tx = conn.transaction()?;- let head: Option<(i64, StoredMutation)> = tx- .query_row(- "SELECT- id, query, operation_name, variables_json, identity,- attempt_count, next_attempt_at_ms, lease_owner,- lease_generation, lease_expires_at_ms, last_error,- created_at_ms- FROM mutation_queue- ORDER BY id ASC- LIMIT 1",- [],- |row| Ok((row.get(0)?, row_stored_mutation(row, 1)?)),- )- .optional()?;- let Some((sql_id, mut mutation)) = head else {- tx.commit()?;- return Ok(None);- };- if mutation- .next_attempt_at_ms- .is_some_and(|next| next > request.now_ms)- || mutation- .lease_expires_at_ms- .is_some_and(|expiry| expiry > request.now_ms)- {- tx.commit()?;- return Ok(None);- }-- mutation.attempt_count = mutation.attempt_count.saturating_add(1);- mutation.lease_generation = mutation.lease_generation.saturating_add(1);- mutation.lease_owner = Some(request.owner.clone());- mutation.lease_expires_at_ms = Some(request.lease_expires_at_ms);- mutation.next_attempt_at_ms = None;- tx.execute(- "UPDATE mutation_queue SET- attempt_count = ?2,- next_attempt_at_ms = NULL,- lease_owner = ?3,- lease_generation = ?4,- lease_expires_at_ms = ?5- WHERE id = ?1",- params![- sql_id,- i64::from(mutation.attempt_count),- mutation.lease_owner,- i64::try_from(mutation.lease_generation).map_err(|_| {- SqliteStorageError::QueueInvariant(- "lease generation exceeds SQLite INTEGER".to_string(),- )- })?,- mutation.lease_expires_at_ms,- ],- )?;- let (optimistic_data_json, updates): (String, Vec<u8>) = tx.query_row(- "SELECT optimistic_data_json, normalized_updates- FROM optimistic_layers WHERE mutation_id = ?1",- params![sql_id],- |row| Ok((row.get(0)?, row.get(1)?)),- )?;- let generation = mutation.lease_generation;- let queued = QueuedMutation {- id: mutation_id_from_sql(sql_id)?,- mutation,- optimistic: PersistedOptimisticLayer {- optimistic_data_json,- normalized_updates: decode_record_updates(&updates)?,- },- };- tx.commit()?;- Ok(Some(ClaimedMutation {- queued,- lease_generation: generation,- }))- }-- async fn defer_mutation(- &mut self,- id: MutationId,- claim: MutationClaimToken,- next_attempt_at_ms: i64,- error: String,- ) -> Result<bool, Self::Error> {- let sql_id = mutation_id_to_sql(id)?;- let mut conn = self.conn();- let tx = conn.transaction()?;- if !claim_is_current(&tx, sql_id, &claim)? {- tx.commit()?;- return Ok(false);- }- tx.execute(- "UPDATE mutation_queue SET- next_attempt_at_ms = ?2,- lease_owner = NULL,- lease_expires_at_ms = NULL,- last_error = ?3- WHERE id = ?1",- params![sql_id, next_attempt_at_ms, error],- )?;- tx.commit()?;- Ok(true)- }-- async fn complete_mutation(- &mut self,- id: MutationId,- claim: MutationClaimToken,- entries: Vec<(EntityKey<'static>, Record)>,- ) -> Result<bool, Self::Error> {- let sql_id = mutation_id_to_sql(id)?;- let mut conn = self.conn();- let tx = conn.transaction()?;- if !claim_is_current(&tx, sql_id, &claim)? {- tx.commit()?;- return Ok(false);- }- {- let mut stmt = tx.prepare_cached(- "INSERT INTO records (key, value) VALUES (?1, ?2)- ON CONFLICT(key) DO UPDATE SET value = excluded.value",- )?;- for (key, record) in &entries {- stmt.execute(params![key.0.as_ref(), encode_record(record)])?;- }- }- write_search_documents(&tx, &entries)?;- tx.execute("DELETE FROM mutation_queue WHERE id = ?1", params![sql_id])?;- tx.commit()?;- Ok(true)- }-- async fn discard_mutation(- &mut self,- id: MutationId,- claim: MutationClaimToken,- ) -> Result<bool, Self::Error> {- let sql_id = mutation_id_to_sql(id)?;- let mut conn = self.conn();- let tx = conn.transaction()?;- if !claim_is_current(&tx, sql_id, &claim)? {- tx.commit()?;- return Ok(false);- }- tx.execute("DELETE FROM mutation_queue WHERE id = ?1", params![sql_id])?;- tx.commit()?;- Ok(true)- }-- async fn clear(&mut self) -> Result<(), Self::Error> {- let mut conn = self.conn();- let tx = conn.transaction()?;- tx.execute("DELETE FROM optimistic_layers", [])?;- tx.execute("DELETE FROM mutation_queue", [])?;- tx.execute("DELETE FROM search_documents", [])?;- tx.execute("DELETE FROM records", [])?;- tx.commit()?;- Ok(())- }-}--#[cfg(test)]-mod tests {- use super::*;- use cache_core::value::CacheValue;- use pollster::block_on;-- fn record(name: &str) -> Record {- let mut r = Record::default();- r.fields- .insert("name".into(), CacheValue::String(name.into()));- r- }-- fn key(s: &str) -> EntityKey<'static> {- EntityKey(s.to_string().into())- }-- #[test]- fn put_get_delete_roundtrip() {- block_on(async {- let mut s = SqliteStorage::open_in_memory("user-1").unwrap();- s.put_batch(vec![(key("A:1"), record("a")), (key("B:2"), record("b"))])- .await- .unwrap();-- let got = s- .get_batch(&[key("A:1"), key("C:3"), key("B:2")])- .await- .unwrap();- assert_eq!(got[0].as_ref().unwrap(), &record("a"));- assert!(got[1].is_none());- assert_eq!(got[2].as_ref().unwrap(), &record("b"));-- // Upsert overwrites.- s.put_batch(vec![(key("A:1"), record("a2"))]).await.unwrap();- let got = s.get_batch(&[key("A:1")]).await.unwrap();- assert_eq!(got[0].as_ref().unwrap(), &record("a2"));-- s.delete_batch(&[key("A:1")]).await.unwrap();- assert!(s.get_batch(&[key("A:1")]).await.unwrap()[0].is_none());-- s.clear().await.unwrap();- assert_eq!(s.record_count().unwrap(), 0);- });- }-- #[test]- fn search_projection_is_write_through_and_browse_uses_covering_order_index() {- block_on(async {- let mut storage = SqliteStorage::open_in_memory("search").unwrap();- let mut document = Record::default();- document.fields.insert(- "__typename".into(),- CacheValue::String("GraphqlSoupDocument".into()),- );- document- .fields- .insert("name".into(), CacheValue::String("Quarterly Plan".into()));- document.fields.insert(- "updatedAt".into(),- CacheValue::Number(cache_core::value::CacheNumber::PosInt(123)),- );- storage- .put_batch(vec![- (key("GraphqlSoupDocument:d1"), document.clone()),- (key("GraphqlSoupDocument:d2"), document),- ])- .await- .unwrap();-- let columns = {- let conn = storage.conn();- let mut statement = conn- .prepare("PRAGMA table_info('search_documents')")- .unwrap();- statement- .query_map([], |row| row.get::<_, String>(1))- .unwrap()- .collect::<Result<Vec<_>, _>>()- .unwrap()- };- assert_eq!(- columns,- [- "profile",- "__typename",- "id",- "bucket",- "search_text",- "timestamp_ms",- "source_hash",- ]- );-- let loaded = storage- .load_search_documents(SearchProfile::QuickAccessV1)- .await- .unwrap();- assert_eq!(loaded.len(), 2);- assert!(- loaded- .iter()- .all(|document| document.search_text == "quarterly plan")- );- let first = storage- .browse_search_documents(SearchProfile::QuickAccessV1, "document", None, 1)- .await- .unwrap();- assert_eq!(first[0].record_key.as_ref(), "GraphqlSoupDocument:d1");- let cursor = SearchCursor {- timestamp_ms: first[0].timestamp_ms,- record_key: first[0].record_key.clone(),- };- let second = storage- .browse_search_documents(SearchProfile::QuickAccessV1, "document", Some(&cursor), 1)- .await- .unwrap();- assert_eq!(second[0].record_key.as_ref(), "GraphqlSoupDocument:d2");-- let details = {- let conn = storage.conn();- let mut plan = conn- .prepare(- "EXPLAIN QUERY PLAN SELECT __typename, id, bucket, search_text, timestamp_ms, source_hash FROM search_documents WHERE profile = 'quick-access-v1' AND bucket = 'document' ORDER BY timestamp_ms DESC, __typename ASC, id ASC LIMIT 25",- )- .unwrap();- plan.query_map([], |row| row.get::<_, String>(3))- .unwrap()- .collect::<Result<Vec<_>, _>>()- .unwrap()- .join(" ")- };- assert!(- details.contains("search_documents_browse_idx"),- "browse query did not use projection index: {details}"- );- assert!(!details.contains("records"));-- storage- .delete_batch(&[key("GraphqlSoupDocument:d2")])- .await- .unwrap();- // Replacing the same base key with an unsearchable record deletes- // the stale derived row in the same transaction.- storage- .put_batch(vec![(key("GraphqlSoupDocument:d1"), Record::default())])- .await- .unwrap();- assert_eq!(storage.search_document_count().unwrap(), 0);- });- }-- #[test]- fn previous_search_schema_is_replaced_without_blob_backfill() {- let file = tempfile::NamedTempFile::new().unwrap();- let path = file.path();- {- let storage = SqliteStorage::open(path, "search-upgrade").unwrap();- let conn = storage.conn();- conn.execute_batch(- "DROP TABLE search_documents;- CREATE TABLE search_documents (- profile TEXT NOT NULL,- __typename TEXT NOT NULL,- id TEXT NOT NULL,- entity_type TEXT NOT NULL,- bucket TEXT NOT NULL,- search_text TEXT NOT NULL,- timestamp_ms INTEGER NOT NULL,- source_hash TEXT NOT NULL,- PRIMARY KEY(profile, __typename, id)- );- CREATE INDEX search_documents_browse_idx- ON search_documents(- profile, bucket, timestamp_ms DESC, __typename ASC, id ASC- );- UPDATE meta SET v = '2' WHERE k = 'search_schema_version';- INSERT INTO records(key, value) VALUES ('Thing:stale', X'00');",- )- .unwrap();- }-- let storage = SqliteStorage::open(path, "search-upgrade").unwrap();- assert_eq!(storage.record_count().unwrap(), 0);- let columns = {- let conn = storage.conn();- let mut statement = conn- .prepare("PRAGMA table_info('search_documents')")- .unwrap();- statement- .query_map([], |row| row.get::<_, String>(1))- .unwrap()- .collect::<Result<Vec<_>, _>>()- .unwrap()- };- assert!(columns.iter().all(|column| column != "record_key"));- assert!(columns.iter().all(|column| column != "entity_type"));- assert!(columns.iter().any(|column| column == "__typename"));- assert!(columns.iter().any(|column| column == "id"));- }-- #[test]- fn queue_diagnostics_return_only_depth_and_oldest_timestamp() {- block_on(async {- let storage = SqliteStorage::open_in_memory("user-1").unwrap();- assert_eq!(- storage.queue_diagnostics().await.unwrap(),- QueueDiagnostics {- availability: QueueDiagnosticsAvailability::Available,- depth: 0,- oldest_created_at_ms: None,- }- );- storage- .conn()- .execute(- "INSERT INTO mutation_queue (query, variables_json, created_at_ms) VALUES ('mutation A { a }', '{}', 9), ('mutation B { b }', '{}', 4)",- [],- )- .unwrap();- assert_eq!(- storage.queue_diagnostics().await.unwrap(),- QueueDiagnostics {- availability: QueueDiagnosticsAvailability::Available,- depth: 2,- oldest_created_at_ms: Some(4),- }- );- });- }-- #[test]- fn queue_diagnostics_query_uses_covering_index_at_scale() {- block_on(async {- let storage = SqliteStorage::open_in_memory("queue-plan").unwrap();- storage- .conn()- .execute(- "WITH RECURSIVE values_to_insert(value) AS (VALUES(1) UNION ALL SELECT value + 1 FROM values_to_insert WHERE value < 10000) INSERT INTO mutation_queue (query, variables_json, created_at_ms) SELECT 'mutation Scale { scale }', '{}', 10001 - value FROM values_to_insert",- [],- )- .unwrap();- let details = {- let conn = storage.conn();- let mut plan = conn- .prepare(- "EXPLAIN QUERY PLAN SELECT COUNT(*), MIN(created_at_ms) FROM mutation_queue",- )- .unwrap();- plan.query_map([], |row| row.get::<_, String>(3))- .unwrap()- .collect::<Result<Vec<_>, _>>()- .unwrap()- .join(" ")- };- assert!(- details.contains("mutation_queue_created_at_ms_idx"),- "diagnostics query did not use the timestamp index: {details}"- );- assert_eq!(- storage.queue_diagnostics().await.unwrap(),- QueueDiagnostics {- availability: QueueDiagnosticsAvailability::Available,- depth: 10_000,- oldest_created_at_ms: Some(1),- }- );- });- }-- #[test]- fn persists_across_reopen_same_namespace() {- block_on(async {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("cache.db");-- let mut s = SqliteStorage::open(&path, "user-1").unwrap();- s.put_batch(vec![(key("A:1"), record("a"))]).await.unwrap();- drop(s);-- let s = SqliteStorage::open(&path, "user-1").unwrap();- let got = s.get_batch(&[key("A:1")]).await.unwrap();- assert_eq!(got[0].as_ref().unwrap(), &record("a"));- });- }-- #[test]- fn compatibility_epoch_change_wipes_records() {- block_on(async {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("cache.db");-- let mut s = SqliteStorage::open(&path, "user-1").unwrap();- s.put_batch(vec![(key("A:1"), record("a"))]).await.unwrap();- s.conn()- .execute(- "UPDATE meta SET v = 'graphql-cache:user-1:s0:v2' WHERE k = 'namespace'",- [],- )- .unwrap();- drop(s);-- let s = SqliteStorage::open(&path, "user-1").unwrap();- assert_eq!(s.record_count().unwrap(), 0);- });- }-- #[test]- fn scope_change_wipes() {- block_on(async {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("cache.db");-- let mut s = SqliteStorage::open(&path, "user-1").unwrap();- s.put_batch(vec![(key("A:1"), record("a"))]).await.unwrap();- drop(s);-- // Different user → wiped.- let s = SqliteStorage::open(&path, "user-2").unwrap();- assert_eq!(s.record_count().unwrap(), 0);- });- }-- #[test]- fn works_with_engine() {- use cache_core::engine::{Engine, ReadResult};- block_on(async {- let storage = SqliteStorage::open_in_memory("user-1").unwrap();- let mut engine = Engine::new(storage);- let query = r#"query Soup($input: SoupInput!) {- user { id soup(input: $input) { nextCursor items { __typename id } } }- }"#;- let serde_json::Value::Object(vars) = serde_json::json!({"input": {"limit": 1}}) else {- unreachable!()- };- let data = serde_json::json!({- "user": { "id": "user-1", "soup": { "nextCursor": null, "items": [{"__typename": "GraphqlSoupDocument", "id": "doc-1"}] } }- });- engine- .write_query(None, query, Some("Soup"), &vars, &data, None)- .await- .unwrap();- let ReadResult::Hit { data: cached } = engine- .read_query(None, query, Some("Soup"), &vars)- .await- .unwrap()- else {- panic!("expected hit");- };- assert_eq!(cached, data);- });- }-}diff --git a/crates/client/cache-sqlite/tests/mutation_queue.rs b/crates/client/cache-sqlite/tests/mutation_queue.rsdeleted file mode 100644index 668fdb214b..0000000000--- a/crates/client/cache-sqlite/tests/mutation_queue.rs+++ /dev/null@@ -1,214 +0,0 @@-use cache_core::queue::{- MutationClaimRequest, MutationClaimToken, MutationRequest, NewQueuedMutation,- PersistedOptimisticLayer, StoredMutation,-};-use cache_core::store::Storage;-use cache_core::value::{CacheValue, EntityKey, Record};-use cache_sqlite::SqliteStorage;-use pollster::block_on;--const CACHE_QUERY: &str = r#"-query Soup($input: SoupInput!) {- user {- id- soup(input: $input) {- items {- __typename- id- ... on GraphqlSoupDocument {- properties { id displayName }- }- }- nextCursor- }- }-}-"#;--const CACHE_MUTATION: &str = r#"-mutation SetEntityProperty($input: SetEntityPropertyInput!) {- setEntityProperty(input: $input) { id displayName }-}-"#;--fn queued(value: &str) -> NewQueuedMutation {- let mut update = Record::default();- update- .fields- .insert("name".into(), CacheValue::String(value.into()));- NewQueuedMutation {- mutation: StoredMutation::new(- MutationRequest {- query: "mutation Rename { rename { id } }".into(),- operation_name: Some("Rename".into()),- variables_json: format!(r#"{{"name":"{value}"}}"#),- identity: Some("user-1".into()),- },- 10,- ),- optimistic: PersistedOptimisticLayer {- optimistic_data_json: format!(r#"{{"rename":{{"name":"{value}"}}}}"#),- normalized_updates: [(EntityKey("Thing:1".into()), update)].into(),- },- }-}--#[test]-fn queue_and_optimistic_layer_survive_reopen() {- block_on(async {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("cache.db");- let mut storage = SqliteStorage::open(&path, "scope-1").unwrap();- let id = storage- .enqueue_mutation(queued("optimistic"))- .await- .unwrap();- drop(storage);-- let mut storage = SqliteStorage::open(&path, "scope-1").unwrap();- let loaded = storage.load_mutation_queue().await.unwrap();- assert_eq!(loaded.len(), 1);- assert_eq!(loaded[0].id, id);- assert_eq!(- loaded[0].optimistic.optimistic_data_json,- r#"{"rename":{"name":"optimistic"}}"#- );-- let claimed = storage- .claim_next_mutation(MutationClaimRequest {- owner: "runner".into(),- now_ms: 20,- lease_expires_at_ms: 100,- })- .await- .unwrap()- .unwrap();- let mut real = Record::default();- real.fields- .insert("name".into(), CacheValue::String("server".into()));- assert!(- storage- .complete_mutation(- id,- MutationClaimToken {- owner: "runner".into(),- generation: claimed.lease_generation,- },- vec![(EntityKey("Thing:1".into()), real.clone())],- )- .await- .unwrap()- );- drop(storage);-- let storage = SqliteStorage::open(&path, "scope-1").unwrap();- assert!(storage.load_mutation_queue().await.unwrap().is_empty());- assert_eq!(- storage- .get_batch(&[EntityKey("Thing:1".into())])- .await- .unwrap()[0],- Some(real)- );- });-}--#[test]-fn restart_hydration_preserves_legacy_json_with_envelope_keys() {- use cache_core::engine::{Engine, ReadResult};- use serde_json::json;-- block_on(async {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("cache.db");- let serde_json::Value::Object(query_vars) = json!({"input": {"limit": 1}}) else {- unreachable!()- };- let serde_json::Value::Object(mutation_vars) = json!({"input": {- "entityType": "DOCUMENT",- "entityId": "doc-1",- "propertyDefinitionId": "def-1",- "value": {"string": "x"}- }}) else {- unreachable!()- };- let base = json!({"user": {"id": "user-1", "soup": {- "items": [{- "__typename": "GraphqlSoupDocument",- "id": "doc-1",- "properties": [{"id": "prop-1", "displayName": "Status"}]- }],- "nextCursor": null- }}});- let optimistic = json!({- "version": 2,- "mutationData": {"colliding": true},- "setEntityProperty": {- "id": "prop-1",- "displayName": "Stage"- }- });-- let mut engine = Engine::new(SqliteStorage::open(&path, "scope-1").unwrap());- engine- .write_query(- None,- CACHE_QUERY,- Some("Soup"),- &query_vars,- &base,- Some("user-1"),- )- .await- .unwrap();- drop(engine);-- let mut storage = SqliteStorage::open(&path, "scope-1").unwrap();- storage- .enqueue_mutation(NewQueuedMutation {- mutation: StoredMutation::new(- MutationRequest {- query: CACHE_MUTATION.to_string(),- operation_name: Some("SetEntityProperty".to_string()),- variables_json: serde_json::to_string(&mutation_vars).unwrap(),- identity: Some("user-1".to_string()),- },- 10,- ),- optimistic: PersistedOptimisticLayer {- optimistic_data_json: serde_json::to_string(&optimistic).unwrap(),- normalized_updates: Default::default(),- },- })- .await- .unwrap();- drop(storage);-- let mut reopened = Engine::new(SqliteStorage::open(&path, "scope-1").unwrap());- let ReadResult::Hit { data } = reopened- .read_query(None, CACHE_QUERY, Some("Soup"), &query_vars)- .await- .unwrap()- else {- panic!("expected hydrated hit");- };- assert_eq!(- data["user"]["soup"]["items"][0]["properties"][0]["displayName"],- json!("Stage")- );- });-}--#[test]-fn scope_change_clears_queued_user_intent() {- block_on(async {- let dir = tempfile::tempdir().unwrap();- let path = dir.path().join("cache.db");- let mut storage = SqliteStorage::open(&path, "scope-1").unwrap();- storage.enqueue_mutation(queued("a")).await.unwrap();- drop(storage);-- let storage = SqliteStorage::open(&path, "scope-2").unwrap();- assert!(storage.load_mutation_queue().await.unwrap().is_empty());- });-}diff --git a/crates/client/cache-turso/Cargo.toml b/crates/client/cache-turso/Cargo.tomlindex 9d6888af4a..f23bf59032 100644--- a/crates/client/cache-turso/Cargo.toml+++ b/crates/client/cache-turso/Cargo.toml@@ -25,7 +25,7 @@ pollster = { workspace = true }serde_json = { workspace = true }[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]-cache-sqlite = { path = "../cache-sqlite" }+tempfile = "3"[target.'cfg(target_arch = "wasm32")'.dev-dependencies]wasm-bindgen-test = { workspace = true }diff --git a/crates/client/cache-turso/src/error.rs b/crates/client/cache-turso/src/error.rsindex ea0733e840..e98a6bf966 100644--- a/crates/client/cache-turso/src/error.rs+++ b/crates/client/cache-turso/src/error.rs@@ -14,8 +14,8 @@ pub enum PhysicalResetReason {/// Queue, key, numeric, or relational state violated the frozen schema contract.#[error("invalid durable cache state")]Invariant,- /// The browser storage quota is full.- #[error("browser storage is full")]+ /// The browser quota or native filesystem is full.+ #[error("cache storage is full")]StorageFull,/// A commit, rollback, or statement cleanup left transaction durability uncertain.#[error("transaction outcome is uncertain")]diff --git a/crates/client/cache-turso/src/lib.rs b/crates/client/cache-turso/src/lib.rsindex 0784814675..1b1ee01e75 100644--- a/crates/client/cache-turso/src/lib.rs+++ b/crates/client/cache-turso/src/lib.rs@@ -16,13 +16,13 @@ mod storage;pub use error::{PhysicalResetReason, TursoStorageError};pub use storage::{- BROWSER_STORAGE_SCHEMA_VERSION, TursoStorage, TursoStorageCloseOutcome, TursoStorageOpenOutcome,+ STORAGE_SCHEMA_VERSION, TursoStorage, TursoStorageCloseOutcome, TursoStorageOpenOutcome,};-#[cfg(not(target_arch = "wasm32"))]-pub use storage::TursoMemoryDatabase;#[cfg(target_arch = "wasm32")]pub use storage::{HealthyTursoStorageClosed, ResetRequiredTursoStorageClosed, TursoStorageCloseFailure,TursoStorageOpenFailure, TursoStorageResetFailure,};+#[cfg(not(target_arch = "wasm32"))]+pub use storage::{TursoFileDatabase, TursoMemoryDatabase};diff --git a/crates/client/cache-turso/src/storage.rs b/crates/client/cache-turso/src/storage.rsindex c25688457b..b7d4d1c5da 100644--- a/crates/client/cache-turso/src/storage.rs+++ b/crates/client/cache-turso/src/storage.rs@@ -15,22 +15,26 @@ use std::sync::Arc;use std::sync::atomic::{AtomicU8, Ordering};use turso_core::{Connection, Numeric, Value};+#[cfg(not(target_arch = "wasm32"))]+use std::io::ErrorKind;+#[cfg(not(target_arch = "wasm32"))]+use std::path::{Path, PathBuf};#[cfg(not(target_arch = "wasm32"))]use std::sync::Mutex;#[cfg(not(target_arch = "wasm32"))]use std::sync::atomic::AtomicU64;#[cfg(not(target_arch = "wasm32"))]-use turso_core::{Database, IO, MemoryIO, OpenOptions, SqliteDialect};+use turso_core::{Database, IO, MemoryIO, OpenOptions, PlatformIO, SqliteDialect};#[cfg(target_arch = "wasm32")]use turso_opfs::{CloseFailure, ClosedSession, ConnectedOpfsSession, OpenDisposition, OpfsError, OpfsOwner,ResetFailure,};-/// Frozen browser-storage schema version, independent of cache postcard versions.-pub const BROWSER_STORAGE_SCHEMA_VERSION: u32 = 6;+/// Frozen storage schema version, independent of cache postcard versions.+pub const STORAGE_SCHEMA_VERSION: u32 = 6;-/// Coarse outcome of validating an OPFS Turso session.+/// Coarse outcome of validating a Turso database.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum TursoStorageOpenOutcome {/// Existing compatible storage was validated and preserved.@@ -71,7 +75,8 @@ const QUEUE_DIAGNOSTICS_SELECT: &str = "SELECT COUNT(*), MIN(created_at_ms) FROM/// On `wasm32` this value owns the consuming/// `turso_opfs::ConnectedOpfsSession` capability. It must be consumed with/// [`Self::try_close`] before OPFS preservation or reset.-/// Native builds own a Turso `MemoryIO` database solely for conformance tests.+/// Native builds own either a filesystem-backed Turso database or a `MemoryIO`+/// database used by conformance tests.pub struct TursoStorage {health: AtomicU8,#[cfg(target_arch = "wasm32")]@@ -443,6 +448,94 @@ impl std::fmt::Display for TursoStorageOpenFailure {#[cfg(target_arch = "wasm32")]impl std::error::Error for TursoStorageOpenFailure {}+/// Reopenable filesystem-backed Turso database for native hosts.+#[cfg(not(target_arch = "wasm32"))]+#[derive(Clone, Debug)]+pub struct TursoFileDatabase {+ path: PathBuf,+ turso_path: String,+}++#[cfg(not(target_arch = "wasm32"))]+impl TursoFileDatabase {+ /// Creates a native database owner for `path`.+ pub fn new(path: impl AsRef<Path>) -> Result<Self, TursoStorageError> {+ let path = path.as_ref().to_path_buf();+ let turso_path = path+ .to_str()+ .ok_or(TursoStorageError::InvalidInput)?+ .to_owned();+ Ok(Self { path, turso_path })+ }++ /// Opens and initializes or validates this database for `scope`.+ pub fn open(&self, scope: &str) -> Result<TursoStorage, TursoStorageError> {+ let fresh = !self.path.exists();+ let io: Arc<dyn IO> = Arc::new(PlatformIO::new().map_err(TursoStorageError::turso)?);+ open_native_database(io, &self.turso_path, scope, fresh)+ }++ /// Opens this database, physically replacing incompatible or uncertain+ /// storage before retrying once.+ pub fn open_or_reset(&self, scope: &str) -> Result<TursoStorage, TursoStorageError> {+ match self.open(scope) {+ Ok(storage) => Ok(storage),+ Err(error) if error.requires_physical_reset() => {+ self.physical_reset()?;+ self.open(scope)+ }+ Err(error) => Err(error),+ }+ }++ /// Deletes the native main and WAL files after all connections are closed.+ pub fn physical_reset(&self) -> Result<(), TursoStorageError> {+ remove_native_file(&self.path)?;+ let wal_path = PathBuf::from(format!("{}-wal", self.turso_path));+ remove_native_file(&wal_path)+ }+}++#[cfg(not(target_arch = "wasm32"))]+fn remove_native_file(path: &Path) -> Result<(), TursoStorageError> {+ match std::fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),+ Err(_) => Err(TursoStorageError::reset(PhysicalResetReason::Io)),+ }+}++#[cfg(not(target_arch = "wasm32"))]+fn open_native_database(+ io: Arc<dyn IO>,+ path: &str,+ scope: &str,+ fresh: bool,+) -> Result<TursoStorage, TursoStorageError> {+ let database = Database::open(io, path, OpenOptions::new(Arc::new(SqliteDialect)))+ .map_err(TursoStorageError::turso)+ .map_err(|error| if fresh { error } else { error.initialization() })?;+ let connection = database+ .connect()+ .map_err(TursoStorageError::turso)+ .map_err(|error| if fresh { error } else { error.initialization() })?;+ if let Err(error) = initialize(&connection, scope, fresh) {+ if connection.close().is_err() {+ return Err(TursoStorageError::reset(+ PhysicalResetReason::TransactionOutcomeUncertain,+ ));+ }+ return Err(error);+ }+ Ok(TursoStorage {+ health: AtomicU8::new(0),+ database,+ connection,+ #[cfg(all(test, not(target_arch = "wasm32")))]+ fault: Mutex::new(None),+ })+}+/// Reopenable Turso `MemoryIO` database used by native conformance tests.#[cfg(not(target_arch = "wasm32"))]pub struct TursoMemoryDatabase {@@ -476,38 +569,14 @@ impl TursoMemoryDatabase {(state.io.clone(), !state.initialized)};let io_trait: Arc<dyn IO> = io;- let database = Database::open(- io_trait,- &self.path,- OpenOptions::new(Arc::new(SqliteDialect)),- )- .map_err(TursoStorageError::turso)- .map_err(|error| if fresh { error } else { error.initialization() })?;- let connection = database- .connect()- .map_err(TursoStorageError::turso)- .map_err(|error| if fresh { error } else { error.initialization() })?;- if let Err(error) = initialize(&connection, scope, fresh) {- if connection.close().is_err() {- return Err(TursoStorageError::reset(- PhysicalResetReason::TransactionOutcomeUncertain,- ));- }- return Err(error);- }+ let storage = open_native_database(io_trait, &self.path, scope, fresh)?;if fresh {self.state.lock().unwrap_or_else(|error| error.into_inner()).initialized = true;}- Ok(TursoStorage {- health: AtomicU8::new(0),- database,- connection,- #[cfg(all(test, not(target_arch = "wasm32")))]- fault: Mutex::new(None),- })+ Ok(storage)}/// Replaces the complete in-memory main/WAL store with a fresh one.@@ -1058,7 +1127,7 @@ fn initialize(driver::execute(connection,"INSERT INTO meta (key, value) VALUES ('storage_schema_version', ?1)",- vec![text(&BROWSER_STORAGE_SCHEMA_VERSION.to_string())],+ vec![text(&STORAGE_SCHEMA_VERSION.to_string())],)?;Ok(())})@@ -1079,10 +1148,7 @@ fn initialize(let expected = [("namespace", cache_namespace(scope)),("scope", scope.to_owned()),- (- "storage_schema_version",- BROWSER_STORAGE_SCHEMA_VERSION.to_string(),- ),+ ("storage_schema_version", STORAGE_SCHEMA_VERSION.to_string()),];if metadata.len() != expected.len() {return Err(TursoStorageError::reset(PhysicalResetReason::Compatibility));diff --git a/crates/client/cache-turso/tests/native_file.rs b/crates/client/cache-turso/tests/native_file.rsnew file mode 100644index 0000000000..b0743aa0b2--- /dev/null+++ b/crates/client/cache-turso/tests/native_file.rs@@ -0,0 +1,145 @@+#![cfg(not(target_arch = "wasm32"))]++use cache_core::normalize::RecordUpdates;+use cache_core::queue::{+ MutationRequest, NewQueuedMutation, PersistedOptimisticLayer, StoredMutation,+};+use cache_core::store::Storage;+use cache_core::value::{CacheValue, EntityKey, Record};+use cache_turso::{TursoFileDatabase, TursoStorageCloseOutcome};+use pollster::block_on;++fn key(value: &str) -> EntityKey<'static> {+ EntityKey(value.to_owned().into())+}++fn record(value: &str) -> Record {+ let mut record = Record::default();+ record+ .fields+ .insert("value".into(), CacheValue::String(value.into()));+ record+}++#[test]+fn filesystem_database_persists_across_close_and_reopen() {+ block_on(async {+ let directory = tempfile::tempdir().unwrap();+ let database = TursoFileDatabase::new(directory.path().join("cache.turso")).unwrap();++ let mut storage = database.open("scope-1").unwrap();+ storage+ .put_batch(vec![(key("Document:1"), record("persisted"))])+ .await+ .unwrap();+ assert_eq!(+ storage.try_close().unwrap(),+ TursoStorageCloseOutcome::Healthy+ );++ let storage = database.open("scope-1").unwrap();+ assert_eq!(+ storage.get_batch(&[key("Document:1")]).await.unwrap(),+ vec![Some(record("persisted"))]+ );+ assert_eq!(+ storage.try_close().unwrap(),+ TursoStorageCloseOutcome::Healthy+ );+ });+}++#[test]+fn filesystem_database_preserves_the_mutation_queue() {+ block_on(async {+ let directory = tempfile::tempdir().unwrap();+ let database = TursoFileDatabase::new(directory.path().join("cache.turso")).unwrap();++ let mut storage = database.open("scope-1").unwrap();+ let mutation_id = storage+ .enqueue_mutation(NewQueuedMutation {+ mutation: StoredMutation::new(+ MutationRequest {+ query: "mutation Persist { persist }".into(),+ operation_name: Some("Persist".into()),+ variables_json: r#"{"value":1}"#.into(),+ identity: Some("identity".into()),+ },+ 42,+ ),+ optimistic: PersistedOptimisticLayer {+ optimistic_data_json: r#"{"persist":true}"#.into(),+ normalized_updates: RecordUpdates::default(),+ },+ })+ .await+ .unwrap();+ assert_eq!(+ storage.try_close().unwrap(),+ TursoStorageCloseOutcome::Healthy+ );++ let storage = database.open("scope-1").unwrap();+ let queue = storage.load_mutation_queue().await.unwrap();+ assert_eq!(queue.len(), 1);+ assert_eq!(queue[0].id, mutation_id);+ assert_eq!(+ queue[0].mutation.request.operation_name.as_deref(),+ Some("Persist")+ );+ assert_eq!(queue[0].mutation.created_at_ms, 42);+ assert_eq!(+ queue[0].optimistic.optimistic_data_json,+ r#"{"persist":true}"#+ );+ assert_eq!(+ storage.try_close().unwrap(),+ TursoStorageCloseOutcome::Healthy+ );+ });+}++#[test]+fn open_or_reset_replaces_an_incompatible_scope() {+ block_on(async {+ let directory = tempfile::tempdir().unwrap();+ let database = TursoFileDatabase::new(directory.path().join("cache.turso")).unwrap();++ let mut storage = database.open("scope-1").unwrap();+ storage+ .put_batch(vec![(key("Document:1"), record("old-scope"))])+ .await+ .unwrap();+ assert_eq!(+ storage.try_close().unwrap(),+ TursoStorageCloseOutcome::Healthy+ );++ let error = database.open("scope-2").unwrap_err();+ assert!(error.requires_physical_reset());++ let storage = database.open_or_reset("scope-2").unwrap();+ assert_eq!(+ storage.get_batch(&[key("Document:1")]).await.unwrap(),+ vec![None]+ );+ assert_eq!(+ storage.try_close().unwrap(),+ TursoStorageCloseOutcome::Healthy+ );+ });+}++#[test]+fn open_or_reset_replaces_invalid_database_bytes() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("cache.turso");+ std::fs::write(&path, b"not a sqlite database").unwrap();+ let database = TursoFileDatabase::new(path).unwrap();++ let storage = database.open_or_reset("scope-1").unwrap();+ assert_eq!(+ storage.try_close().unwrap(),+ TursoStorageCloseOutcome::Healthy+ );+}diff --git a/crates/client/cache-turso/tests/shared_conformance.rs b/crates/client/cache-turso/tests/shared_conformance.rsindex 8b64d094e0..04a826ce48 100644--- a/crates/client/cache-turso/tests/shared_conformance.rs+++ b/crates/client/cache-turso/tests/shared_conformance.rs@@ -8,11 +8,8 @@ use cache_core::queue::{use cache_core::search::{SearchProfile, project_search_documents};use cache_core::store::{InMemoryStorage, Storage};use cache_core::value::{CacheValue, EntityKey, Record};-use cache_sqlite::SqliteStorage;use cache_turso::{TursoMemoryDatabase, TursoStorage, TursoStorageCloseOutcome};use pollster::block_on;-use std::path::PathBuf;-use std::sync::atomic::{AtomicU64, Ordering};trait BackendFactory: Sized {type Backend: Storage;@@ -38,36 +35,6 @@ impl BackendFactory for InMemoryFactory {fn finish(self, _: Self::Backend) {}}-struct SqliteFactory {- path: PathBuf,-}--impl BackendFactory for SqliteFactory {- type Backend = SqliteStorage;-- fn create() -> (Self, Self::Backend) {- static NEXT_DATABASE: AtomicU64 = AtomicU64::new(1);- let id = NEXT_DATABASE.fetch_add(1, Ordering::Relaxed);- let path = std::env::temp_dir().join(format!(- "cache-turso-shared-conformance-{}-{id}.db",- std::process::id()- ));- let _ = std::fs::remove_file(&path);- let storage = SqliteStorage::open(&path, "shared-conformance").unwrap();- (Self { path }, storage)- }-- fn reopen(&mut self, storage: Self::Backend) -> Self::Backend {- drop(storage);- SqliteStorage::open(&self.path, "shared-conformance").unwrap()- }-- fn finish(self, storage: Self::Backend) {- drop(storage);- std::fs::remove_file(self.path).unwrap();- }-}-struct TursoFactory {database: TursoMemoryDatabase,}@@ -616,11 +583,6 @@ fn in_memory_storage_satisfies_shared_contract() {run::<InMemoryFactory>();}-#[test]-fn sqlite_storage_satisfies_shared_contract() {- run::<SqliteFactory>();-}-#[test]fn turso_storage_satisfies_shared_contract() {run::<TursoFactory>();diff --git a/nix-support/root-cargo-output-hashes.nix b/nix-support/root-cargo-output-hashes.nixindex 8fadc6a399..fe5a2fec6e 100644--- a/nix-support/root-cargo-output-hashes.nix+++ b/nix-support/root-cargo-output-hashes.nix@@ -1,4 +1,6 @@{+ "git+https://github.com/seanaye/turso?rev=be9acfe9e5e6efb17911af84047e4855cace53a3#be9acfe9e5e6efb17911af84047e4855cace53a3" =+ "sha256-BTS0ypmcVWne+m0BQp/VT2O6mOFB/cc9F1TgQMo48aM=";"git+https://github.com/whutchinson98/jsonwebtoken#c8c0d19511a0e7ba9d456e21437a79d321e99f16" ="sha256-jllT52SAIiNpTPg7Vm3wmT79w/CIz9NnVKM81oQq8dM=";"git+https://github.com/macro-inc/rig?branch=feat/responses-api-non-strict-tools#6deadfc6f9b432c849ea79733a549f46407530b7" =diff --git a/nix/tauri-desktop.nix b/nix/tauri-desktop.nixindex 823fa27aa3..d36fec5e7e 100644--- a/nix/tauri-desktop.nix+++ b/nix/tauri-desktop.nix@@ -145,10 +145,12 @@src = ../apps/web/tauri;cargoLock = ../apps/web/tauri/Cargo.lock;outputHashes = {- "git+https://github.com/macro-inc/tauri-plugins?rev=26537c8a46bb8424f9cf4021d08aa76aa7cd66ef#26537c8a46bb8424f9cf4021d08aa76aa7cd66ef" =- "sha256-v0Pn8kiRXaczNrFNjXct7yZUQ50qP68l8ivQDumu7Hw=";+ "git+https://github.com/macro-inc/tauri-plugins?rev=6ddd6600e20436388f169e936b610fe93944b7b0#6ddd6600e20436388f169e936b610fe93944b7b0" =+ "sha256-5ErLW2po5ZlTTuJjsCExwC//rHYcQo2tKXiyz3w/0kQ=";"git+https://github.com/macro-inc/plugins-workspace?rev=06474e4c446600627cf37a11f0c22c27bcf764ca#06474e4c446600627cf37a11f0c22c27bcf764ca" ="sha256-ngH5sltERe8DlP/zjsin9jmlGOZFeABk8SxJ5AnZG18=";+ "git+https://github.com/seanaye/turso?rev=be9acfe9e5e6efb17911af84047e4855cace53a3#be9acfe9e5e6efb17911af84047e4855cace53a3" =+ "sha256-BTS0ypmcVWne+m0BQp/VT2O6mOFB/cc9F1TgQMo48aM=";"git+https://github.com/seanaye/tauri?rev=95a7521b#95a7521b8c565cfba568319ddd8ba79c9ce244e2" ="sha256-5HamTWAZPtUSWOfP3TgtiqFJvunlPXy9/C0TLHQpXlU=";"git+https://github.com/voxelbee/tauri-plugin-virtual-keyboard?branch=main#70e8e8325b5ff7d681ef5f3b996ac083d4fc5a01" =@@ -161,7 +163,7 @@version = appVersion;binaryName = "app";src = ../apps/web/tauri;- # The native GraphQL cache plugin depends on cache-core/cache-sqlite+ # The native GraphQL cache plugin depends on cache-core/cache-turso# at the repository root, so preserve those relative paths in the# filtered Cargo source used by crane.cargoRoot = ../.;