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/tauri cache backend (#4774)
Sean Aye0ac6018b1834
diff --git a/.config/hakari.toml b/.config/hakari.tomlindex 325f27f483..d6cb13147d 100644--- a/.config/hakari.toml+++ b/.config/hakari.toml@@ -56,11 +56,17 @@ workspace-members = ["macro_sync_service_jwt","sync_service","sync_service_bebop_schema",- # client/*: browser/Tauri cache crates (cache-core compiles to wasm32 via- # cache-wasm; cache-sqlite ships in the Tauri app, not services). They- # must stay wasm-safe and out of the deploy dependency layers.- "cache-core",- "cache-idb",- "cache-sqlite",- "cache-wasm",+ # maybe_send: zero-dep marker traits used by cache-core; must stay+ # wasm-safe (workspace-hack pulls native-only deps like mio into wasm32).+ "maybe_send",]++# Xtask extension (the hakari engine ignores this table; `cargo x deps` in+# tooling/xtask/crates/xtask_deps expands it into traversal excludes).+# Entries are workspace-relative member-path prefixes ending in `*`.+[xtask]+# crates/client/*: browser/Tauri cache crates (cache-core compiles to wasm32+# via cache-wasm; cache-sqlite ships in the Tauri app, not services). They+# must stay wasm-safe and out of the deploy dependency layers — the glob+# keeps future client crates from silently gaining the workspace-hack dep.+traversal-exclude-globs = ["crates/client/*"]diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex cece19d4a4..c8709cd951 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -529,20 +529,24 @@"crates/workspace-hack"],"cache-core": [- "crates/client/cache-core"+ "crates/client/cache-core",+ "crates/maybe_send"],"cache-idb": ["crates/client/cache-core",- "crates/client/cache-idb"+ "crates/client/cache-idb",+ "crates/maybe_send"],"cache-sqlite": ["crates/client/cache-core",- "crates/client/cache-sqlite"+ "crates/client/cache-sqlite",+ "crates/maybe_send"],"cache-wasm": ["crates/client/cache-core","crates/client/cache-idb",- "crates/client/cache-wasm"+ "crates/client/cache-wasm",+ "crates/maybe_send"],"cal": ["crates/analytics_client",@@ -3331,6 +3335,9 @@"crates/macro_uuid","crates/workspace-hack"],+ "maybe_send": [+ "crates/maybe_send"+ ],"mcp_auth_proxy": ["crates/cowlike","crates/fusionauth",diff --git a/Cargo.lock b/Cargo.lockindex 6fb638ef1d..2acb30fd59 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2247,6 +2247,7 @@ dependencies = ["apollo-compiler","apollo-parser","lru",+ "maybe_send","pollster","postcard","serde",@@ -8570,6 +8571,10 @@ dependencies = ["rayon",]+[[package]]+name = "maybe_send"+version = "0.1.0"+[[package]]name = "mcp_auth_proxy"version = "0.1.0"@@ -16177,7 +16182,9 @@ dependencies = ["anyhow","guppy","hakari",+ "serde","serde_json",+ "toml","xtask_graph",]diff --git a/Cargo.toml b/Cargo.tomlindex bf51d4ed65..88cc3088f0 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -30,6 +30,7 @@ members = ["crates/macro_event_topics","crates/macro_queues","crates/macro_sync_service_jwt",+ "crates/maybe_send","crates/memory","crates/prompt","crates/properties_service",diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.mdindex 7500b231af..cb5a72cefe 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -197,8 +197,9 @@ Topology:`Storage` trait (async): `get_batch`, `put_batch`, `delete_batch`,`scan_prefix`, `approx_size`. Records serialized with `postcard` (stored as`Uint8Array` values in IDB / blobs in SQLite). Note: wasm futures are not-`Send`, so the trait must be `?Send` (e.g. `async_trait(?Send)` or a-maybe-send abstraction) to be implementable by both `idb` and native SQLite.+`Send`, so the 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`.### 4.4 Data model@@ -232,11 +233,16 @@ soup entities from the normy config as they migrate.## 5. Repo layout```-crates/client/ # new cargo workspace (or members of an existing one)- cache-core/ # pure engine, native tests- cache-schema-codegen/ # schema.graphql → type metadata (build.rs or CLI)+crates/client/ # members of the root cargo workspace+ cache-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-wasm/ # wasm-bindgen shell (web)- cache-tauri/ # tauri plugin/commands wrapping cache-core+apps/web/tauri/graphql_cache_plugin/ # tauri commands + engine thread wrapping+ # cache-core over cache-sqlite. Lives in the+ # tauri workspace (not crates/client): it+ # depends on the patched tauri fork pinned+ # there, path-deps back to crates/client.apps/web/src/lib/graphql-cache/ # JS gluehost/ # CacheHost interface + worker & tauri transportsexchange/ # urql normalizedCacheExchange@@ -280,7 +286,7 @@ apps/web/src/lib/graphql-cache/ # JS glue- Deferred: stale-namespace DB cleanup (browser), `scan_prefix`/`approx_size` for GC (hardening phase).-**Phase 3 — hosts + JS glue** *(browser path done; Tauri host pending)*+**Phase 3 — hosts + JS glue** *(done)*- ~~`cache-wasm`~~: wasm-bindgen shell (async-mutex engine, string op-idinterning `"{clientId}:{urqlKey}"`), browser-verified viawasm-bindgen-test. Build: `just build-cache-wasm` →@@ -291,8 +297,20 @@ apps/web/src/lib/graphql-cache/ # JS glueBroadcastChannel fanout in the fallback topology), `createWorkerCacheHost`implementing `CacheHost`. Type-checked; end-to-end browser exercisehappens with the Phase 4 exchange integration.-- **Pending:** `cache-tauri` plugin (commands + change events) + Tauri- `CacheHost` transport; `isTauri` → native selection.+- ~~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+ on the tauri runtime (`Storage` futures are `MaybeSend` → `Send` native;+ SQLite completes immediately), commands mirroring the worker protocol+ registered app-level in `src-tauri` (bundle-updater pattern, no+ capability plumbing), changed ops broadcast to every webview via the+ `graphql-cache://ops-affected` event. One native engine per app process = SharedWorker topology: no Web+ Locks / BroadcastChannel machinery. DB at+ `{app_data_dir}/graphql-cache/cache.sqlite`.+ JS side: `createTauriCacheHost` (`host/tauri-host.ts`) — invoke-based+ RPC with the same 10s timeout + Error-normalized rejections, event+ subscription filtered by clientId prefix; `isTauri()` selects it in+ `graphql-soup.ts`.**Phase 4 — urql exchange, behind flag** *(done — needs manual smoke test)*- `normalizedCacheExchange`@@ -302,8 +320,8 @@ apps/web/src/lib/graphql-cache/ # JS glue`cache-first`, write-through of network results, cache errors degrade tonetwork. 8 vitest cases against a scripted fake host.- Wired into `graphql-soup.ts` behind `ENABLE_GRAPHQL_SOUP` override- (browser only, `isTauri` → plain client): lazily builds the cached client- scoped to the current `userId`; `fetchGraphqlSoup` uses+ (browser: worker host; Tauri: native host): lazily builds the cached+ client; `fetchGraphqlSoup` uses`cache-and-network` (`.toPromise()` skips stale emissions → identicalfresh semantics today) and falls back to a `cache-only` re-read onnetwork errors → offline replay of previously-seen pages.diff --git a/apps/web/src-tauri/.well-known/apple-app-site-association b/apps/web/src-tauri/.well-known/apple-app-site-associationdeleted file mode 100644index 51b4ba8ba1..0000000000--- a/apps/web/src-tauri/.well-known/apple-app-site-association+++ /dev/null@@ -1,15 +0,0 @@-{- "applinks": {- "details": [- {- "appIDs": ["TY74Q77JBD.com.macro.app.prod"],- "components": [- {- "/": "/app/*",- "comment": "Matches any URL whose path starts with /app/"- }- ]- }- ]- }-}diff --git a/apps/web/src-tauri/.well-known/assetlinks.json b/apps/web/src-tauri/.well-known/assetlinks.jsondeleted file mode 100644index 963f4ac955..0000000000--- a/apps/web/src-tauri/.well-known/assetlinks.json+++ /dev/null@@ -1,14 +0,0 @@-[- {- "relation": [- "delegate_permission/common.handle_all_urls"- ],- "target": {- "namespace": "android_app",- "package_name": "com.tauri.dev",- "sha256_cert_fingerprints": [- "30:5B:31:07:B9:52:A7:97:80:4C:BA:50:0C:12:9F:97:2F:53:36:25:D8:66:B2:41:0E:88:AE:60:48:F1:0B:7C"- ]- }- }-]\ No newline at end of filediff --git a/apps/web/src-tauri/justfile b/apps/web/src-tauri/justfiledeleted file mode 100644index ba917a033a..0000000000--- a/apps/web/src-tauri/justfile+++ /dev/null@@ -1,9 +0,0 @@-bucket := "macro-oidc-prod"--# Download .well-known contents from S3-download-well-known:- aws s3 sync s3://{{bucket}}/.well-known .well-known--# Upload .well-known contents to S3-upload-well-known:- aws s3 sync .well-known s3://{{bucket}}/.well-knowndiff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.tsnew file mode 100644index 0000000000..4a21fbe77b--- /dev/null+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts@@ -0,0 +1,208 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const invokeMock = vi.hoisted(() => vi.fn());+const listenMock = vi.hoisted(() => vi.fn());++vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));+vi.mock('@tauri-apps/api/event', () => ({ listen: listenMock }));++import { createTauriCacheHost } from './tauri-host';++type OpsAffectedPayload = { opIds: string[]; keys: string[] };+type EventCallback = (event: { payload: OpsAffectedPayload }) => void;++describe('createTauriCacheHost', () => {+ let eventCallback: EventCallback | undefined;+ const unlisten = vi.fn();++ beforeEach(() => {+ vi.clearAllMocks();+ eventCallback = undefined;+ invokeMock.mockResolvedValue(null);+ listenMock.mockImplementation((_event: string, cb: EventCallback) => {+ eventCallback = cb;+ return Promise.resolve(unlisten);+ });+ });++ it('initializes the native cache once and prefixes op ids', async () => {+ invokeMock.mockImplementation((command: string) =>+ Promise.resolve(+ command === 'graphql_cache_read' ? { kind: 'miss' } : null+ )+ );+ const host = createTauriCacheHost({ scope: 'scope-1', hotCapacity: 42 });++ const result = await host.readQuery({ opKey: 7, query: '{ x }' });+ expect(result).toEqual({ kind: 'miss' });++ expect(invokeMock).toHaveBeenCalledWith('graphql_cache_init', {+ scope: 'scope-1',+ hotCapacity: 42,+ });+ expect(invokeMock).toHaveBeenCalledWith('graphql_cache_read', {+ opId: `${host.clientId}:7`,+ query: '{ x }',+ operationName: undefined,+ variables: undefined,+ });+ });++ it('sends writes with origin op id and identity', async () => {+ const host = createTauriCacheHost({ scope: 'scope-1' });+ const writeResult = { changed: ['A:1'], affectedOps: [], reset: false };+ invokeMock.mockImplementation((command: string) =>+ Promise.resolve(command === 'graphql_cache_write' ? writeResult : null)+ );++ const result = await host.writeQuery({+ opKey: 3,+ query: '{ x }',+ data: { x: 1 },+ identity: 'user-1',+ });+ expect(result).toEqual(writeResult);+ expect(invokeMock).toHaveBeenCalledWith('graphql_cache_write', {+ originOpId: `${host.clientId}:3`,+ query: '{ x }',+ operationName: undefined,+ variables: undefined,+ data: { x: 1 },+ identity: 'user-1',+ });+ });++ it('settles optimistic writes through the dedicated commands', async () => {+ const host = createTauriCacheHost({ scope: 'scope-1' });+ const optimistic = {+ transactionId: '1',+ changed: ['A:1'],+ affectedOps: [],+ reset: false,+ };+ invokeMock.mockImplementation((command: string) => {+ if (command === 'graphql_cache_begin_optimistic_write') {+ return Promise.resolve(optimistic);+ }+ if (+ command === 'graphql_cache_commit_optimistic_write' ||+ command === 'graphql_cache_rollback_optimistic_write'+ ) {+ return Promise.resolve({ changed: [], affectedOps: [], reset: false });+ }+ return Promise.resolve(null);+ });++ const begun = await host.beginOptimisticWrite({+ query: 'mutation { m }',+ data: { m: 1 },+ });+ expect(begun).toEqual(optimistic);++ await host.commitOptimisticWrite('1', {+ query: 'mutation { m }',+ data: { m: 2 },+ });+ expect(invokeMock).toHaveBeenCalledWith(+ 'graphql_cache_commit_optimistic_write',+ expect.objectContaining({ transactionId: '1', data: { m: 2 } })+ );++ await host.rollbackOptimisticWrite('1');+ expect(invokeMock).toHaveBeenCalledWith(+ 'graphql_cache_rollback_optimistic_write',+ { transactionId: '1' }+ );+ });++ it('delivers only own-client op keys from the broadcast event', async () => {+ const host = createTauriCacheHost({ scope: 'scope-1' });+ const seen: number[][] = [];+ host.onOpsAffected((opKeys) => seen.push(opKeys));+ // listen() resolves asynchronously; wait for registration.+ await Promise.resolve();+ expect(listenMock).toHaveBeenCalledWith(+ 'graphql-cache://ops-affected',+ expect.any(Function)+ );++ eventCallback?.({+ payload: {+ opIds: [`${host.clientId}:5`, 'other-client:9', `${host.clientId}:8`],+ keys: ['A:1'],+ },+ });+ expect(seen).toEqual([[5, 8]]);++ // No delivery when nothing matches this client.+ eventCallback?.({+ payload: { opIds: ['other-client:9'], keys: ['A:1'] },+ });+ expect(seen).toEqual([[5, 8]]);+ });++ it('normalizes string command errors to Error rejections', async () => {+ const host = createTauriCacheHost({ scope: 'scope-1' });+ invokeMock.mockImplementation((command: string) =>+ command === 'graphql_cache_read'+ ? Promise.reject('engine exploded')+ : Promise.resolve(null)+ );++ await expect(host.readQuery({ query: '{ x }' })).rejects.toThrow(+ 'engine exploded'+ );+ });++ it('rejects hung requests after the timeout', async () => {+ vi.useFakeTimers();+ try {+ const host = createTauriCacheHost({+ scope: 'scope-1',+ requestTimeoutMs: 50,+ });+ invokeMock.mockImplementation((command: string) =>+ command === 'graphql_cache_init'+ ? Promise.resolve(null)+ : new Promise(() => {})+ );++ const read = host.readQuery({ query: '{ x }' });+ const assertion = expect(read).rejects.toThrow(+ 'graphql cache ipc timeout: graphql_cache_read'+ );+ await vi.advanceTimersByTimeAsync(60);+ await assertion;+ } finally {+ vi.useRealTimers();+ }+ });++ it('tolerates a failed listener setup (no unhandled rejection)', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ listenMock.mockRejectedValue(new Error('listen exploded'));+ const host = createTauriCacheHost({ scope: 'scope-1' });+ // Flush the rejection through the catch handler.+ await Promise.resolve();+ await Promise.resolve();+ expect(warn).toHaveBeenCalledWith(+ 'graphql cache ops-affected listener failed',+ expect.any(Error)+ );+ // dispose must not throw or re-reject.+ host.dispose();+ await Promise.resolve();+ } finally {+ warn.mockRestore();+ }+ });++ it('unsubscribes the event listener on dispose', async () => {+ const host = createTauriCacheHost({ scope: 'scope-1' });+ await Promise.resolve();+ host.dispose();+ await Promise.resolve();+ expect(unlisten).toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.tsnew file mode 100644index 0000000000..59cfe7e0fa--- /dev/null+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts@@ -0,0 +1,186 @@+/**+ * Tauri CacheHost: talks to the native cache engine living in the Tauri+ * host process (graphql_cache_plugin) over invoke commands. The host+ * process is the single shared engine instance across all webviews/windows+ * (SharedWorker semantics); change pushes arrive as a broadcast tauri event+ * that every webview filters by its own clientId prefix — mirroring+ * worker-host.ts.+ */++import { invoke } from '@tauri-apps/api/core';+import { listen, type UnlistenFn } from '@tauri-apps/api/event';+import type {+ OptimisticWriteResult,+ ReadResult,+ WriteResult,+} from '../protocol';+import type { CacheHost, CacheReadArgs, CacheWriteArgs } from './types';++/** Keep in sync with `OPS_AFFECTED_EVENT` in graphql_cache_plugin. */+const OPS_AFFECTED_EVENT = 'graphql-cache://ops-affected';++/** Payload of the ops-affected event (graphql_cache_plugin `OpsAffectedEvent`). */+type OpsAffectedPayload = {+ opIds: string[];+ keys: string[];+};++export interface TauriHostOptions {+ scope: string;+ hotCapacity?: number;+ /**+ * Per-request timeout in ms (default 10s, matching worker-host). A hung+ * IPC call rejects; the exchange degrades rejected reads to the network.+ */+ requestTimeoutMs?: number;+}++const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;++export function createTauriCacheHost(options: TauriHostOptions): CacheHost {+ const clientId = crypto.randomUUID();+ const affectedSubscribers = new Set<(opKeys: number[]) => void>();+ const requestTimeoutMs =+ options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;++ function request<T>(+ command: string,+ args: Record<string, unknown>+ ): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ reject(new Error(`graphql cache ipc timeout: ${command}`));+ }, requestTimeoutMs);+ invoke<T>(command, args).then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (error) => {+ clearTimeout(timer);+ // Command errors cross the boundary as strings; normalize to+ // Error for parity with worker-host rejections.+ reject(error instanceof Error ? error : new Error(String(error)));+ }+ );+ });+ }++ // Failure tolerated: reads/writes still work, only push-driven+ // re-execution is lost — same degradation as a broken worker port.+ const unlisten: Promise<UnlistenFn | undefined> = listen<OpsAffectedPayload>(+ OPS_AFFECTED_EVENT,+ (event) => {+ const prefix = `${clientId}:`;+ const opKeys = event.payload.opIds+ .filter((id) => id.startsWith(prefix))+ .map((id) => Number(id.slice(prefix.length)))+ .filter((n) => Number.isFinite(n));+ if (opKeys.length > 0) {+ for (const cb of affectedSubscribers) cb(opKeys);+ }+ }+ ).catch((error) => {+ console.warn('graphql cache ops-affected listener failed', error);+ return undefined;+ });++ const ready = request('graphql_cache_init', {+ scope: options.scope,+ hotCapacity: options.hotCapacity,+ });++ const opId = (opKey: number) => `${clientId}:${opKey}`;++ return {+ clientId,++ async readQuery(args: CacheReadArgs): Promise<ReadResult> {+ await ready;+ return await request<ReadResult>('graphql_cache_read', {+ opId: args.opKey === undefined ? undefined : opId(args.opKey),+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ });+ },++ async writeQuery(args: CacheWriteArgs): Promise<WriteResult> {+ await ready;+ return await request<WriteResult>('graphql_cache_write', {+ originOpId: args.opKey === undefined ? undefined : opId(args.opKey),+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ data: args.data,+ identity: args.identity,+ });+ },++ async beginOptimisticWrite(+ args: CacheWriteArgs+ ): Promise<OptimisticWriteResult> {+ await ready;+ return await request<OptimisticWriteResult>(+ 'graphql_cache_begin_optimistic_write',+ {+ originOpId: args.opKey === undefined ? undefined : opId(args.opKey),+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ data: args.data,+ }+ );+ },++ async commitOptimisticWrite(+ transactionId: string,+ args: CacheWriteArgs+ ): Promise<WriteResult> {+ await ready;+ return await request<WriteResult>(+ 'graphql_cache_commit_optimistic_write',+ {+ transactionId,+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ data: args.data,+ }+ );+ },++ async rollbackOptimisticWrite(transactionId: string): Promise<WriteResult> {+ await ready;+ return await request<WriteResult>(+ 'graphql_cache_rollback_optimistic_write',+ { transactionId }+ );+ },++ async invalidate(keys: string[]): Promise<string[]> {+ await ready;+ return await request<string[]>('graphql_cache_invalidate', { keys });+ },++ async teardown(opKey: number): Promise<void> {+ await ready;+ await request('graphql_cache_teardown', { opId: opId(opKey) });+ },++ async clear(): Promise<void> {+ await ready;+ await request('graphql_cache_clear', {});+ },++ onOpsAffected(cb: (opKeys: number[]) => void): () => void {+ affectedSubscribers.add(cb);+ return () => affectedSubscribers.delete(cb);+ },++ dispose() {+ affectedSubscribers.clear();+ void unlisten.then((fn) => fn?.());+ },+ };+}diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.tsindex 3f7da95a48..5abe5876cf 100644--- a/apps/web/src/lib/graphql-cache/index.ts+++ b/apps/web/src/lib/graphql-cache/index.ts@@ -7,6 +7,7 @@ export {executeOptimisticMutation,type OptimisticMutationContext,} from './exchange/optimistic';+export { createTauriCacheHost } from './host/tauri-host';export type {CacheHost,CacheReadArgs,diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.tsindex 895d30006c..41385b0a2b 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts@@ -7,7 +7,10 @@ import { fetchToken } from '@core/util/fetchWithToken';import { isTauri } from '@core/util/platform';import { platformFetch } from '@core/util/platformFetch';import { normalizedCacheExchange } from '@graphql-cache/exchange/normalized-cache-exchange';-import { createWorkerCacheHost } from '@graphql-cache/index';+import {+ createTauriCacheHost,+ createWorkerCacheHost,+} from '@graphql-cache/index';import { getOrCreateCacheScope } from '@graphql-cache/scope';import { getMacroApiToken } from '@service-auth/fetch';import { type Client, createClient, fetchExchange } from '@urql/core';@@ -65,11 +68,12 @@ const graphqlSoupClient = createClient({});/**- * Whether the normalized wasm cache is active for soup GraphQL queries.- * Browser only for now — Tauri will use a native host (see design doc).+ * Whether the normalized cache is active for soup GraphQL queries.+ * Browser: wasm engine in a worker. Tauri: native engine in the host+ * process (graphql_cache_plugin).*/function graphqlCacheEnabled(): boolean {- return ENABLE_GRAPHQL_SOUP() && !isTauri();+ return ENABLE_GRAPHQL_SOUP();}let cachedClient: Client | undefined;@@ -86,7 +90,10 @@ export function getGraphqlSoupClient(): Client {if (!graphqlCacheEnabled()) return graphqlSoupClient;cachedClient ??= (() => {try {- const host = createWorkerCacheHost({ scope: getOrCreateCacheScope() });+ const scope = getOrCreateCacheScope();+ const host = isTauri()+ ? createTauriCacheHost({ scope })+ : createWorkerCacheHost({ scope });return createClient({url: `${dssHost}/items/soup/graphql`,exchanges: [diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lockindex f05564fea8..c589bc999f 100644--- a/apps/web/tauri/Cargo.lock+++ b/apps/web/tauri/Cargo.lock@@ -30,6 +30,19 @@ dependencies = ["version_check",]+[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "getrandom 0.3.4",+ "once_cell",+ "version_check",+ "zerocopy",+]+[[package]]name = "aho-corasick"version = "1.1.4"@@ -54,6 +67,12 @@ dependencies = ["alloc-no-stdlib",]+[[package]]+name = "allocator-api2"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"+[[package]]name = "android_log-sys"version = "0.3.2"@@ -86,10 +105,41 @@ version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+[[package]]+name = "apollo-compiler"+version = "1.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b877306ffde4d3cc428bbc8f506fdd67b99255298ae92b919954c0c52f530504"+dependencies = [+ "ahash 0.8.12",+ "apollo-parser",+ "ariadne",+ "futures",+ "indexmap 2.14.0",+ "rowan",+ "serde",+ "serde_json_bytes",+ "thiserror 2.0.18",+ "triomphe",+ "typed-arena",+]++[[package]]+name = "apollo-parser"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11f6e2be4b3474e5890d34d3e483d49ec9b5cbf9e358bc62c9cc5423376df54b"+dependencies = [+ "memchr",+ "rowan",+ "thiserror 2.0.18",+]+[[package]]name = "app"version = "0.1.0"dependencies = [+ "graphql_cache_plugin","http","log","logger",@@ -144,6 +194,17 @@ dependencies = ["derive_arbitrary",]+[[package]]+name = "ariadne"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8454c8a44ce2cb9cc7e7fae67fc6128465b343b92c6631e94beca3c8d1524ea5"+dependencies = [+ "concolor",+ "unicode-width",+ "yansi",+]+[[package]]name = "arrayvec"version = "0.7.6"@@ -304,6 +365,15 @@ dependencies = ["system-deps",]+[[package]]+name = "atomic-polyfill"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4"+dependencies = [+ "critical-section",+]+[[package]]name = "atomic-waker"version = "1.1.2"@@ -555,6 +625,30 @@ dependencies = ["libbz2-rs-sys",]+[[package]]+name = "cache-core"+version = "0.1.0"+dependencies = [+ "apollo-compiler",+ "apollo-parser",+ "lru",+ "maybe_send",+ "postcard",+ "serde",+ "serde_json",+ "sha2",+ "thiserror 2.0.18",+]++[[package]]+name = "cache-sqlite"+version = "0.1.0"+dependencies = [+ "cache-core",+ "rusqlite",+ "thiserror 2.0.18",+]+[[package]]name = "cairo-rs"version = "0.18.5"@@ -704,6 +798,15 @@ dependencies = ["cc",]+[[package]]+name = "cobs"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"+dependencies = [+ "thiserror 2.0.18",+]+[[package]]name = "combine"version = "4.6.7"@@ -714,6 +817,26 @@ dependencies = ["memchr",]+[[package]]+name = "concolor"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b946244a988c390a94667ae0e3958411fa40cc46ea496a929b263d883f5f9c3"+dependencies = [+ "bitflags 1.3.2",+ "concolor-query",+ "is-terminal",+]++[[package]]+name = "concolor-query"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88d11d52c3d7ca2e6d0040212be9e4dbbcd78b6447f535b6b561f449427944cf"+dependencies = [+ "windows-sys 0.45.0",+]+[[package]]name = "concurrent-queue"version = "2.5.0"@@ -850,6 +973,12 @@ dependencies = ["libc",]+[[package]]+name = "countme"+version = "3.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636"+[[package]]name = "cpufeatures"version = "0.2.17"@@ -883,6 +1012,12 @@ dependencies = ["cfg-if",]+[[package]]+name = "critical-section"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"+[[package]]name = "crossbeam-channel"version = "0.5.15"@@ -1370,6 +1505,18 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"+[[package]]+name = "embedded-io"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"++[[package]]+name = "embedded-io"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"+[[package]]name = "encoding_rs"version = "0.8.35"@@ -1464,6 +1611,18 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "fallible-iterator"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"++[[package]]+name = "fallible-streaming-iterator"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+[[package]]name = "fastrand"version = "2.4.1"@@ -1979,6 +2138,21 @@ dependencies = ["system-deps",]+[[package]]+name = "graphql_cache_plugin"+version = "0.1.0"+dependencies = [+ "cache-core",+ "cache-sqlite",+ "pollster",+ "serde",+ "serde_json",+ "tauri",+ "tempfile",+ "tokio",+ "tracing",+]+[[package]]name = "gtk"version = "0.18.2"@@ -2050,13 +2224,22 @@ dependencies = ["tracing",]+[[package]]+name = "hash32"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"+dependencies = [+ "byteorder",+]+[[package]]name = "hashbrown"version = "0.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"dependencies = [- "ahash",+ "ahash 0.7.8",][[package]]@@ -2064,6 +2247,9 @@ 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"@@ -2079,6 +2265,11 @@ name = "hashbrown"version = "0.16.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash 0.2.0",+][[package]]name = "hashbrown"@@ -2086,6 +2277,29 @@ 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"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f"+dependencies = [+ "atomic-polyfill",+ "hash32",+ "rustc_version",+ "serde",+ "spin",+ "stable_deref_trait",+]+[[package]]name = "heck"version = "0.4.1"@@ -2259,7 +2473,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.58.0",+ "windows-core 0.61.2",][[package]]@@ -2462,6 +2676,17 @@ dependencies = ["once_cell",]+[[package]]+name = "is-terminal"+version = "0.4.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"+dependencies = [+ "hermit-abi",+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "is-wsl"version = "0.4.0"@@ -2579,6 +2804,19 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "jsonpath-rust"+version = "0.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06cc127b7c3d270be504572364f9569761a180b981919dd0d87693a7f5fb7829"+dependencies = [+ "pest",+ "pest_derive",+ "regex",+ "serde_json",+ "thiserror 1.0.69",+]+[[package]]name = "jsonptr"version = "0.6.3"@@ -2694,6 +2932,17 @@ dependencies = ["libc",]+[[package]]+name = "libsqlite3-sys"+version = "0.30.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"+dependencies = [+ "cc",+ "pkg-config",+ "vcpkg",+]+[[package]]name = "linux-raw-sys"version = "0.12.1"@@ -2748,6 +2997,15 @@ dependencies = ["tracing",]+[[package]]+name = "lru"+version = "0.16.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39"+dependencies = [+ "hashbrown 0.16.1",+]+[[package]]name = "lru-slab"version = "0.1.2"@@ -2867,6 +3125,10 @@ version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5"+[[package]]+name = "maybe_send"+version = "0.1.0"+[[package]]name = "memalloc"version = "0.1.0"@@ -3553,6 +3815,48 @@ version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "pest"+version = "2.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47627dd7305c6a2d6c8c6bcd24c5a4c17dbbf425f4f9c5313e724b38fc9782e9"+dependencies = [+ "memchr",+ "ucd-trie",+]++[[package]]+name = "pest_derive"+version = "2.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b4254325ecad416ab689e27ba51da03ba01a9632bc6e108f5fe7c3c4ad29d58"+dependencies = [+ "pest",+ "pest_generator",+]++[[package]]+name = "pest_generator"+version = "2.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c4c0e91ead7a8f7acecbca6f003fc2e8282b1dbe2dd9c9d2f16aba42995e0a7"+dependencies = [+ "pest",+ "pest_meta",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "pest_meta"+version = "2.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9744bc48116fee06334924bb5f2bad41eed5e89bd26e29b0b799f9a3f82c210"+dependencies = [+ "pest",+]+[[package]]name = "phf"version = "0.8.0"@@ -3816,6 +4120,25 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "pollster"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"++[[package]]+name = "postcard"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"+dependencies = [+ "cobs",+ "embedded-io 0.4.0",+ "embedded-io 0.6.1",+ "heapless",+ "serde",+]+[[package]]name = "potential_utf"version = "0.1.5"@@ -4017,7 +4340,7 @@ dependencies = ["pin-project-lite","quinn-proto","quinn-udp",- "rustc-hash",+ "rustc-hash 2.1.2","rustls","socket2","thiserror 2.0.18",@@ -4038,7 +4361,7 @@ dependencies = ["lru-slab","rand 0.9.4","ring",- "rustc-hash",+ "rustc-hash 2.1.2","rustls","rustls-pki-types","slab",@@ -4380,7 +4703,7 @@ dependencies = ["hashbrown 0.16.1","indexmap 2.14.0","rootcause-internals",- "rustc-hash",+ "rustc-hash 2.1.2","triomphe",]@@ -4393,6 +4716,32 @@ dependencies = ["triomphe",]+[[package]]+name = "rowan"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "417a3a9f582e349834051b8a10c8d71ca88da4211e4093528e36b9845f6b5f21"+dependencies = [+ "countme",+ "hashbrown 0.14.5",+ "rustc-hash 1.1.0",+ "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"@@ -4420,6 +4769,12 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"+[[package]]name = "rustc-hash"version = "2.1.2"@@ -4665,7 +5020,7 @@ dependencies = ["phf 0.13.1","phf_codegen 0.13.1","precomputed-hash",- "rustc-hash",+ "rustc-hash 2.1.2","servo_arc 0.4.3","smallvec",]@@ -4746,6 +5101,21 @@ dependencies = ["zmij",]+[[package]]+name = "serde_json_bytes"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6a27c10711f94d1042b4c96d483556ec84371864e25d0e1cf3dc1024b0880b1"+dependencies = [+ "ahash 0.8.12",+ "bytes",+ "indexmap 2.14.0",+ "jsonpath-rust",+ "regex",+ "serde",+ "serde_json",+]+[[package]]name = "serde_qs"version = "0.15.0"@@ -4999,6 +5369,15 @@ dependencies = ["system-deps",]+[[package]]+name = "spin"+version = "0.9.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"+dependencies = [+ "lock_api",+]+[[package]]name = "stable_deref_trait"version = "1.2.1"@@ -5856,6 +6235,12 @@ dependencies = ["utf-8",]+[[package]]+name = "text-size"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233"+[[package]]name = "thiserror"version = "1.0.69"@@ -6304,6 +6689,10 @@ name = "triomphe"version = "0.1.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dd69c5aa8f924c7519d6372789a74eac5b94fb0f8fcf0d4a97eb0bfc3e785f39"+dependencies = [+ "serde",+ "stable_deref_trait",+][[package]]name = "try-lock"@@ -6329,6 +6718,12 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "typed-arena"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"+[[package]]name = "typeid"version = "1.0.3"@@ -6341,6 +6736,12 @@ version = "1.20.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"+[[package]]+name = "ucd-trie"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"+[[package]]name = "uds_windows"version = "1.2.1"@@ -6411,6 +6812,12 @@ version = "1.13.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"+[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"+[[package]]name = "unicode-xid"version = "0.2.6"@@ -6506,6 +6913,12 @@ 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"@@ -7651,6 +8064,12 @@ dependencies = ["pkg-config",]+[[package]]+name = "yansi"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"+[[package]]name = "yoke"version = "0.8.2"diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.tomlindex 1b051fa9b4..03539839b5 100644--- a/apps/web/tauri/Cargo.toml+++ b/apps/web/tauri/Cargo.toml@@ -1,6 +1,7 @@[workspace]members = ["callkit_plugin",+ "graphql_cache_plugin","input_accessory_plugin","logger","macro_bundle_updater_plugin",diff --git a/apps/web/tauri/graphql_cache_plugin/Cargo.toml b/apps/web/tauri/graphql_cache_plugin/Cargo.tomlnew file mode 100644index 0000000000..7cb76958ad--- /dev/null+++ b/apps/web/tauri/graphql_cache_plugin/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "graphql_cache_plugin"+version = "0.1.0"+edition.workspace = true++[dependencies]+cache-core = { path = "../../../../crates/client/cache-core" }+cache-sqlite = { path = "../../../../crates/client/cache-sqlite" }+serde = { workspace = true, features = ["derive"] }+serde_json = "1"+tauri = { workspace = true }+tokio = { workspace = true, features = ["sync"] }+tracing = { workspace = true }++[dev-dependencies]+pollster = "0.4"+tempfile = "3"diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rsnew file mode 100644index 0000000000..1c0cfd22e1--- /dev/null+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs@@ -0,0 +1,199 @@+//! Tauri command handlers — the IPC surface consumed by the webview+//! `CacheHost` (`apps/web/src/lib/graphql-cache/host/tauri-host.ts`).+//!+//! Lives in its own module because `#[tauri::command]` emits a+//! `#[macro_export]` helper macro whose crate-root re-import collides with+//! the function item when the command is defined directly in `lib.rs`.+//!+//! Errors cross the boundary as strings (the host rejects the pending call;+//! the exchange degrades to the network) — same contract as the browser+//! worker's `{ok: false, error}` responses.++use crate::engine::{EngineHandle, OptimisticWriteResultWire, ReadResultWire, WriteResultWire};+use crate::{CacheState, InitializedCache, emit_ops_affected};+use cache_sqlite::SqliteStorage;+use tauri::{AppHandle, Manager, Runtime, State};++type Variables = serde_json::Map<String, serde_json::Value>;++fn engine_handle(state: &State<'_, CacheState>) -> Result<EngineHandle, String> {+ state+ .0+ .lock()+ .map_err(|_| "graphql cache state poisoned".to_string())?+ .as_ref()+ .map(|cache| cache.handle.clone())+ .ok_or_else(|| "graphql cache not initialized (call graphql_cache_init first)".to_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`; the+/// namespace check inside `cache-sqlite` (scope + schema hash + format+/// version) wipes and rebuilds on mismatch — the cache is disposable.+#[tauri::command]+pub async fn graphql_cache_init<R: Runtime>(+ app: AppHandle<R>,+ state: State<'_, CacheState>,+ scope: String,+ hot_capacity: Option<u32>,+) -> Result<(), String> {+ let mut guard = state+ .0+ .lock()+ .map_err(|_| "graphql cache state poisoned".to_string())?;+ if let Some(existing) = guard.as_ref() {+ if existing.scope == scope {+ return Ok(());+ }+ return Err(format!(+ "graphql cache already initialized for scope {}, got {}",+ existing.scope, scope+ ));+ }+ let dir = app+ .path()+ .app_data_dir()+ .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 handle = EngineHandle::new(storage, hot_capacity);+ *guard = Some(InitializedCache { scope, handle });+ Ok(())+}++/// Attempts a cache read; registers `op_id` as active when given.+#[tauri::command]+pub async fn graphql_cache_read(+ state: State<'_, CacheState>,+ op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: Option<Variables>,+) -> Result<ReadResultWire, String> {+ engine_handle(&state)?+ .read(op_id, query, operation_name, variables.unwrap_or_default())+ .await+}++/// Normalizes and stores a network response; broadcasts affected operations+/// to every webview.+#[tauri::command]+pub async fn graphql_cache_write<R: Runtime>(+ app: AppHandle<R>,+ state: State<'_, CacheState>,+ origin_op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: Option<Variables>,+ data: serde_json::Value,+ identity: Option<String>,+) -> Result<WriteResultWire, String> {+ let result = engine_handle(&state)?+ .write(+ origin_op_id,+ query,+ operation_name,+ variables.unwrap_or_default(),+ data,+ identity,+ )+ .await?;+ emit_ops_affected(&app, &result.affected_ops, &result.changed);+ Ok(result)+}++/// Installs an in-memory optimistic layer from a mutation's optimistic+/// response. The one engine is shared by all webviews (SharedWorker+/// semantics), so visible changes are broadcast too.+#[tauri::command]+pub async fn graphql_cache_begin_optimistic_write<R: Runtime>(+ app: AppHandle<R>,+ state: State<'_, CacheState>,+ origin_op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: Option<Variables>,+ data: serde_json::Value,+) -> Result<OptimisticWriteResultWire, String> {+ let result = engine_handle(&state)?+ .begin_optimistic_write(+ origin_op_id,+ query,+ operation_name,+ variables.unwrap_or_default(),+ data,+ )+ .await?;+ emit_ops_affected(&app, &result.result.affected_ops, &result.result.changed);+ Ok(result)+}++/// Atomically replaces a pending optimistic layer with the real network+/// response and flushes contiguous settled layers durably.+#[tauri::command]+pub async fn graphql_cache_commit_optimistic_write<R: Runtime>(+ app: AppHandle<R>,+ state: State<'_, CacheState>,+ transaction_id: String,+ query: String,+ operation_name: Option<String>,+ variables: Option<Variables>,+ data: serde_json::Value,+) -> Result<WriteResultWire, String> {+ let result = engine_handle(&state)?+ .commit_optimistic_write(+ transaction_id,+ query,+ operation_name,+ variables.unwrap_or_default(),+ data,+ )+ .await?;+ emit_ops_affected(&app, &result.affected_ops, &result.changed);+ Ok(result)+}++/// Drops a pending optimistic layer's contribution (mutation failed).+#[tauri::command]+pub async fn graphql_cache_rollback_optimistic_write<R: Runtime>(+ app: AppHandle<R>,+ state: State<'_, CacheState>,+ transaction_id: String,+) -> Result<WriteResultWire, String> {+ let result = engine_handle(&state)?+ .rollback_optimistic_write(transaction_id)+ .await?;+ emit_ops_affected(&app, &result.affected_ops, &result.changed);+ Ok(result)+}++/// External invalidation (e.g. websocket push): evicts records and returns+/// (and broadcasts) the affected registered operation ids.+#[tauri::command]+pub async fn graphql_cache_invalidate<R: Runtime>(+ app: AppHandle<R>,+ state: State<'_, CacheState>,+ keys: Vec<String>,+) -> Result<Vec<String>, String> {+ let affected = engine_handle(&state)?.invalidate(keys.clone()).await?;+ emit_ops_affected(&app, &affected, &keys);+ Ok(affected)+}++/// Unregisters an operation (urql teardown).+#[tauri::command]+pub async fn graphql_cache_teardown(+ state: State<'_, CacheState>,+ op_id: String,+) -> Result<(), String> {+ engine_handle(&state)?.teardown(op_id).await+}++/// Wipes all cached state (logout).+#[tauri::command]+pub async fn graphql_cache_clear(state: State<'_, CacheState>) -> Result<(), String> {+ engine_handle(&state)?.clear().await+}diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rsnew file mode 100644index 0000000000..c32baa0e41--- /dev/null+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs@@ -0,0 +1,277 @@+//! Engine host: the cache engine + SQLite 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.+//!+//! Operation ids cross the IPC boundary as strings (`"{clientId}:{urqlKey}"`)+//! so multiple webviews can register operations against the one shared+//! engine without collisions; they're interned to the engine's `u64` ids+//! internally — the same scheme as the `cache-wasm` shell.++use cache_core::deps::OpId;+use cache_core::engine::{Engine, ReadResult, WriteResult};+use cache_core::value::EntityKey;+use cache_sqlite::SqliteStorage;+use serde::Serialize;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::sync::Mutex;++/// Mirrors `ReadResult` in `apps/web/src/lib/graphql-cache/protocol.ts`.+#[derive(Debug, Serialize)]+#[serde(tag = "kind", rename_all = "camelCase")]+pub enum ReadResultWire {+ /// Fully answerable from cache.+ Hit {+ /// Denormalized response data.+ data: serde_json::Value,+ },+ /// Not answerable; the exchange forwards to the network.+ Miss,+}++/// Mirrors `WriteResult` in `apps/web/src/lib/graphql-cache/protocol.ts`.+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WriteResultWire {+ /// Entity keys whose records changed.+ pub changed: Vec<String>,+ /// Registered operation ids affected by the change (origin excluded).+ pub affected_ops: Vec<String>,+ /// True when the identity witness wiped and rebound the cache before+ /// this write (silent restart).+ pub reset: bool,+}++/// Mirrors `OptimisticWriteResult` in+/// `apps/web/src/lib/graphql-cache/protocol.ts`.+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct OptimisticWriteResultWire {+ /// Engine-assigned id; settle with commit/rollback. A string because JS+ /// numbers lose precision past 2^53 (same as the wasm shell).+ pub transaction_id: String,+ /// Visible (composed-view) changes — nothing is durable until commit.+ #[serde(flatten)]+ pub result: WriteResultWire,+}++/// Interns host-side string operation ids to engine `u64` ids.+#[derive(Default)]+struct OpInterner {+ by_name: HashMap<String, OpId>,+ by_id: HashMap<OpId, String>,+ next: OpId,+}++impl OpInterner {+ fn intern(&mut self, name: &str) -> OpId {+ if let Some(id) = self.by_name.get(name) {+ return *id;+ }+ self.next += 1;+ let id = self.next;+ self.by_name.insert(name.to_string(), id);+ self.by_id.insert(id, name.to_string());+ id+ }++ fn remove(&mut self, name: &str) -> Option<OpId> {+ let id = self.by_name.remove(name)?;+ self.by_id.remove(&id);+ Some(id)+ }++ fn names(&self, ids: impl IntoIterator<Item = OpId>) -> Vec<String> {+ ids.into_iter()+ .filter_map(|id| self.by_id.get(&id).cloned())+ .collect()+ }+}++type Variables = serde_json::Map<String, serde_json::Value>;++struct EngineState {+ engine: Engine<SqliteStorage>,+ ops: OpInterner,+}++/// Cheaply-clonable handle to the shared engine. All methods serialize+/// through the async mutex; errors are stringified for the IPC boundary+/// (the JS host rejects the pending call, and the exchange degrades to the+/// network).+#[derive(Clone)]+pub struct EngineHandle {+ inner: Arc<Mutex<EngineState>>,+}++fn wire_write_result(ops: &OpInterner, result: WriteResult) -> WriteResultWire {+ WriteResultWire {+ changed: result.changed.into_iter().map(|k| k.0).collect(),+ affected_ops: ops.names(result.affected_ops),+ reset: result.reset,+ }+}++fn parse_transaction_id(id: &str) -> Result<u64, String> {+ id.parse::<u64>()+ .map_err(|_| format!("invalid optimistic transaction id `{id}`"))+}++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 {+ let engine = match hot_capacity.filter(|c| *c > 0) {+ Some(cap) => Engine::with_capacity(storage, cap as usize),+ None => Engine::new(storage),+ };+ EngineHandle {+ inner: Arc::new(Mutex::new(EngineState {+ engine,+ ops: OpInterner::default(),+ })),+ }+ }++ /// Cache read; registers `op_id` as active when given.+ pub async fn read(+ &self,+ op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: Variables,+ ) -> Result<ReadResultWire, String> {+ let mut state = self.inner.lock().await;+ let EngineState { engine, ops } = &mut *state;+ let op = op_id.map(|name| ops.intern(&name));+ engine+ .read_query(op, &query, operation_name.as_deref(), &variables)+ .await+ .map(|result| match result {+ ReadResult::Hit { data } => ReadResultWire::Hit { data },+ ReadResult::Miss => ReadResultWire::Miss,+ })+ .map_err(|e| e.to_string())+ }++ /// Normalizes and stores a network response.+ pub async fn write(+ &self,+ origin_op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: Variables,+ data: serde_json::Value,+ identity: Option<String>,+ ) -> Result<WriteResultWire, String> {+ let mut state = self.inner.lock().await;+ let EngineState { engine, ops } = &mut *state;+ let origin = origin_op_id.map(|name| ops.intern(&name));+ engine+ .write_query(+ origin,+ &query,+ operation_name.as_deref(),+ &variables,+ &data,+ identity.as_deref(),+ )+ .await+ .map(|result| wire_write_result(ops, result))+ .map_err(|e| e.to_string())+ }++ /// Installs an in-memory optimistic layer (persists nothing).+ pub async fn begin_optimistic_write(+ &self,+ origin_op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: Variables,+ data: serde_json::Value,+ ) -> Result<OptimisticWriteResultWire, String> {+ let mut state = self.inner.lock().await;+ let EngineState { engine, ops } = &mut *state;+ let origin = origin_op_id.map(|name| ops.intern(&name));+ engine+ .begin_optimistic_write(origin, &query, operation_name.as_deref(), &variables, &data)+ .await+ .map(|(transaction, result)| OptimisticWriteResultWire {+ transaction_id: transaction.to_string(),+ result: wire_write_result(ops, result),+ })+ .map_err(|e| e.to_string())+ }++ /// Replaces a pending optimistic layer with the real network response.+ pub async fn commit_optimistic_write(+ &self,+ transaction_id: String,+ query: String,+ operation_name: Option<String>,+ variables: Variables,+ data: serde_json::Value,+ ) -> Result<WriteResultWire, String> {+ let transaction = parse_transaction_id(&transaction_id)?;+ let mut state = self.inner.lock().await;+ let EngineState { engine, ops } = &mut *state;+ engine+ .commit_optimistic_write(+ transaction,+ &query,+ operation_name.as_deref(),+ &variables,+ &data,+ )+ .await+ .map(|result| wire_write_result(ops, result))+ .map_err(|e| e.to_string())+ }++ /// Drops a pending optimistic layer's contribution (mutation failed).+ pub async fn rollback_optimistic_write(+ &self,+ transaction_id: String,+ ) -> Result<WriteResultWire, String> {+ let transaction = parse_transaction_id(&transaction_id)?;+ let mut state = self.inner.lock().await;+ let EngineState { engine, ops } = &mut *state;+ engine+ .rollback_optimistic_write(transaction)+ .await+ .map(|result| wire_write_result(ops, result))+ .map_err(|e| e.to_string())+ }++ /// Evicts records by entity key; returns the affected registered op ids.+ pub async fn invalidate(&self, keys: Vec<String>) -> Result<Vec<String>, String> {+ let keys: Vec<EntityKey> = keys.into_iter().map(EntityKey).collect();+ let mut state = self.inner.lock().await;+ let EngineState { engine, ops } = &mut *state;+ let affected = engine.invalidate_keys(keys.iter());+ Ok(ops.names(affected))+ }++ /// Unregisters an operation (urql teardown).+ pub async fn teardown(&self, op_id: String) -> Result<(), String> {+ let mut state = self.inner.lock().await;+ let EngineState { engine, ops } = &mut *state;+ if let Some(id) = ops.remove(&op_id) {+ engine.teardown_operation(id);+ }+ Ok(())+ }++ /// Drops all cached state (logout).+ pub async fn clear(&self) -> Result<(), String> {+ let mut state = self.inner.lock().await;+ state.engine.clear().await.map_err(|e| e.to_string())+ }+}++#[cfg(test)]+mod test;diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rsnew file mode 100644index 0000000000..b5020c2e5e--- /dev/null+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs@@ -0,0 +1,185 @@+use super::*;+use pollster::block_on;++const QUERY: &str = r#"query Soup($input: SoupInput!) {+ user { id soup(input: $input) { nextCursor hasMore items { id } } }+}"#;++fn variables() -> Variables {+ let serde_json::Value::Object(vars) = serde_json::json!({"input": {"limit": 1}}) else {+ unreachable!()+ };+ vars+}++fn soup_data(has_more: bool) -> serde_json::Value {+ serde_json::json!({+ "user": {+ "id": "user-1",+ "soup": {+ "nextCursor": null,+ "hasMore": has_more,+ "items": [{"id": "doc-1"}]+ }+ }+ })+}++fn spawn_handle() -> EngineHandle {+ let storage = SqliteStorage::open_in_memory("scope-1").unwrap();+ EngineHandle::new(storage, None)+}++fn write(+ handle: &EngineHandle,+ origin: Option<&str>,+ data: serde_json::Value,+ identity: Option<&str>,+) -> WriteResultWire {+ block_on(handle.write(+ origin.map(str::to_string),+ QUERY.to_string(),+ Some("Soup".to_string()),+ variables(),+ data,+ identity.map(str::to_string),+ ))+ .unwrap()+}++fn read(handle: &EngineHandle, op_id: Option<&str>) -> ReadResultWire {+ block_on(handle.read(+ op_id.map(str::to_string),+ QUERY.to_string(),+ Some("Soup".to_string()),+ variables(),+ ))+ .unwrap()+}++#[test]+fn write_then_read_round_trips() {+ let handle = spawn_handle();+ assert!(matches!(read(&handle, None), ReadResultWire::Miss));++ let result = write(&handle, None, soup_data(false), None);+ assert!(!result.changed.is_empty());+ assert!(!result.reset);++ let ReadResultWire::Hit { data } = read(&handle, None) else {+ panic!("expected hit");+ };+ assert_eq!(data, soup_data(false));+}++#[test]+fn registered_op_is_affected_by_later_writes() {+ let handle = spawn_handle();+ write(&handle, None, soup_data(false), None);++ // Register an active operation, then change its data from another op.+ read(&handle, Some("client:1"));+ let result = write(&handle, Some("client:2"), soup_data(true), None);+ assert_eq!(result.affected_ops, vec!["client:1".to_string()]);++ // Torn-down operations stop being reported.+ block_on(handle.teardown("client:1".to_string())).unwrap();+ let result = write(&handle, Some("client:2"), soup_data(false), None);+ assert!(result.affected_ops.is_empty());+}++#[test]+fn identity_mismatch_resets() {+ let handle = spawn_handle();+ let result = write(&handle, None, soup_data(false), Some("user-1"));+ assert!(!result.reset);++ read(&handle, Some("client:1"));+ let result = write(&handle, Some("client:2"), soup_data(true), Some("user-2"));+ assert!(result.reset);+ assert_eq!(result.affected_ops, vec!["client:1".to_string()]);+}++#[test]+fn optimistic_layer_commits_durably() {+ let handle = spawn_handle();+ write(&handle, None, soup_data(false), None);+ read(&handle, Some("client:1"));++ let optimistic = block_on(handle.begin_optimistic_write(+ Some("client:2".to_string()),+ QUERY.to_string(),+ Some("Soup".to_string()),+ variables(),+ soup_data(true),+ ))+ .unwrap();+ assert_eq!(optimistic.result.affected_ops, vec!["client:1".to_string()]);++ // The optimistic view answers reads.+ let ReadResultWire::Hit { data } = read(&handle, None) else {+ panic!("expected hit");+ };+ assert_eq!(data, soup_data(true));++ let committed = block_on(handle.commit_optimistic_write(+ optimistic.transaction_id,+ QUERY.to_string(),+ Some("Soup".to_string()),+ variables(),+ soup_data(true),+ ))+ .unwrap();+ assert!(!committed.changed.is_empty());++ let ReadResultWire::Hit { data } = read(&handle, None) else {+ panic!("expected hit");+ };+ assert_eq!(data, soup_data(true));+}++#[test]+fn rollback_drops_optimistic_contribution() {+ let handle = spawn_handle();+ write(&handle, None, soup_data(false), None);++ let optimistic = block_on(handle.begin_optimistic_write(+ None,+ QUERY.to_string(),+ Some("Soup".to_string()),+ variables(),+ soup_data(true),+ ))+ .unwrap();++ block_on(handle.rollback_optimistic_write(optimistic.transaction_id)).unwrap();+ let ReadResultWire::Hit { data } = read(&handle, None) else {+ panic!("expected hit");+ };+ assert_eq!(data, soup_data(false));+}++#[test]+fn invalidate_reports_dependent_ops() {+ let handle = spawn_handle();+ let written = write(&handle, None, soup_data(false), None);+ read(&handle, Some("client:1"));++ let affected = block_on(handle.invalidate(written.changed)).unwrap();+ assert_eq!(affected, vec!["client:1".to_string()]);+}++#[test]+fn clear_wipes_everything() {+ let handle = spawn_handle();+ write(&handle, None, soup_data(false), None);+ block_on(handle.clear()).unwrap();+ assert!(matches!(read(&handle, None), ReadResultWire::Miss));+}++#[test]+fn bad_transaction_id_is_an_error() {+ let handle = spawn_handle();+ let error = block_on(handle.rollback_optimistic_write("not-a-number".to_string())).unwrap_err();+ assert!(error.contains("invalid optimistic transaction id"));+}diff --git a/apps/web/tauri/graphql_cache_plugin/src/lib.rs b/apps/web/tauri/graphql_cache_plugin/src/lib.rsnew file mode 100644index 0000000000..8a84213820--- /dev/null+++ b/apps/web/tauri/graphql_cache_plugin/src/lib.rs@@ -0,0 +1,67 @@+//! Tauri-native host for the normalized GraphQL cache.+//!+//! 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+//! (`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+//! app-level in `src-tauri`, like the bundle updater plugin) and receive+//! change notifications via the [`OPS_AFFECTED_EVENT`] broadcast event,+//! mirroring the worker `ops-affected` push: each webview's `CacheHost`+//! filters op ids by its own client prefix.+//!+//! Design doc: `apps/web/docs/graphql-normalized-cache-plan.md`.++#![deny(missing_docs)]++use serde::Serialize;+use std::sync::Mutex;+use tauri::{AppHandle, Emitter, Runtime};++pub mod commands;+mod engine;++pub use engine::{EngineHandle, OptimisticWriteResultWire, ReadResultWire, WriteResultWire};++/// Broadcast event carrying [`OpsAffectedEvent`]: operations whose+/// underlying records changed. Emitted to every webview; hosts filter by+/// their own client-id prefix (the origin operation is already excluded by+/// the engine).+pub const OPS_AFFECTED_EVENT: &str = "graphql-cache://ops-affected";++/// Payload of [`OPS_AFFECTED_EVENT`] — mirrors the worker `CachePush`+/// message in `apps/web/src/lib/graphql-cache/protocol.ts`.+#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct OpsAffectedEvent {+ /// Registered operation ids (`"{clientId}:{urqlKey}"`) to re-execute.+ pub op_ids: Vec<String>,+ /// Changed entity keys, for diagnostics/advanced consumers.+ pub keys: Vec<String>,+}++struct InitializedCache {+ scope: String,+ handle: EngineHandle,+}++/// Managed state holding the lazily-initialized engine handle. Register+/// with `.manage(CacheState::default())` in the app builder.+#[derive(Default)]+pub struct CacheState(Mutex<Option<InitializedCache>>);++fn emit_ops_affected<R: Runtime>(app: &AppHandle<R>, op_ids: &[String], keys: &[String]) {+ if op_ids.is_empty() {+ return;+ }+ app.emit(+ OPS_AFFECTED_EVENT,+ OpsAffectedEvent {+ op_ids: op_ids.to_vec(),+ keys: keys.to_vec(),+ },+ )+ .inspect_err(|e| tracing::error!(error=?e, "failed to emit graphql cache change event"))+ .ok();+}diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.tomlindex 13cec2273c..32f4111f0a 100644--- a/apps/web/tauri/src-tauri/Cargo.toml+++ b/apps/web/tauri/src-tauri/Cargo.toml@@ -61,6 +61,7 @@ uuid = { version = "1.18.1", features = ["v4"] }# system notifications for when the app is opentauri-plugin-notification = "2"# push notifications for mobile (when app is closed)+graphql_cache_plugin = { path = "../graphql_cache_plugin" }macro_bundle_updater_plugin = { path = "../macro_bundle_updater_plugin" }navigation_plugin = { path = "../navigation_plugin" }tauri-plugin-device-info = "1.0.1"diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rsindex c123c2bffe..42d5710201 100644--- a/apps/web/tauri/src-tauri/src/lib.rs+++ b/apps/web/tauri/src-tauri/src/lib.rs@@ -224,7 +224,17 @@ pub fn run() {}}).manage(PendingShareFilesState::default())+ .manage(graphql_cache_plugin::CacheState::default()).invoke_handler(tauri::generate_handler![+ graphql_cache_plugin::commands::graphql_cache_init,+ graphql_cache_plugin::commands::graphql_cache_read,+ graphql_cache_plugin::commands::graphql_cache_write,+ graphql_cache_plugin::commands::graphql_cache_begin_optimistic_write,+ graphql_cache_plugin::commands::graphql_cache_commit_optimistic_write,+ graphql_cache_plugin::commands::graphql_cache_rollback_optimistic_write,+ graphql_cache_plugin::commands::graphql_cache_invalidate,+ graphql_cache_plugin::commands::graphql_cache_teardown,+ graphql_cache_plugin::commands::graphql_cache_clear,macro_bundle_updater_plugin::inbound::plugin::grant_bundle_update,macro_bundle_updater_plugin::inbound::plugin::perform_update,macro_bundle_updater_plugin::inbound::plugin::ack_bundle_update_reload,diff --git a/bun.lock b/bun.lockindex 1198cc35f6..080e43e1dc 100644--- a/bun.lock+++ b/bun.lock@@ -874,7 +874,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],"@inquirer/ansi": ["@inquirer/[email protected]", "", {}, "sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q=="],@@ -2614,7 +2614,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/crates/client/README.md b/crates/client/README.mdindex 37dd43d8fa..87cea93753 100644--- a/crates/client/README.md+++ b/crates/client/README.md@@ -10,9 +10,13 @@ Normalized GraphQL cache with disk-backed persistence for urql. Design doc:| `cache-core` | Pure engine: schema-metadata codegen (build.rs from `static_assets/schema.graphql`), normalize/denormalize, LRU hot tier, dependency index, async `Storage` trait || `cache-sqlite` | `Storage` over SQLite — Tauri native host || `cache-idb` | `Storage` over IndexedDB via the `idb` crate — browser wasm host (wasm32-only; empty shell elsewhere) |+| `cache-wasm` | wasm-bindgen shell exposing the engine to the browser worker glue (`apps/web/src/lib/graphql-cache/`) |-Planned (Phase 3): `cache-wasm` (wasm-bindgen shell + worker RPC), `cache-tauri`-(Tauri plugin) — see the design doc.+The Tauri host lives in the tauri workspace (it needs the patched tauri fork+pinned there): `apps/web/tauri/graphql_cache_plugin`, path-depending on+`cache-core`/`cache-sqlite`. Test it from `apps/web/tauri` with+`cargo test -p graphql_cache_plugin` (on NixOS use the `js-app` dev shell —+tauri's Linux desktop stack needs its webkitgtk/dbus system libs).## Testsdiff --git a/crates/client/cache-core/Cargo.toml b/crates/client/cache-core/Cargo.tomlindex aad7f3a75c..e4449f1cc7 100644--- a/crates/client/cache-core/Cargo.toml+++ b/crates/client/cache-core/Cargo.toml@@ -7,6 +7,7 @@ version = "0.1.0"[dependencies]apollo-parser = { workspace = true }lru = { workspace = true }+maybe_send = { path = "../../maybe_send" }postcard = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }diff --git a/crates/client/cache-core/src/store.rs b/crates/client/cache-core/src/store.rsindex 5aebf9a923..4606ccfc65 100644--- a/crates/client/cache-core/src/store.rs+++ b/crates/client/cache-core/src/store.rs@@ -1,30 +1,41 @@//! Storage abstraction: the cold tier behind the in-memory hot tier.//!//! Implementations: in-memory (tests, Phase 1), IndexedDB via the `idb`-//! crate (browser, Phase 2), SQLite (Tauri native, Phase 2). Futures are not-//! required to be `Send` — wasm futures aren't.+//! crate (browser, Phase 2), SQLite (Tauri native, Phase 2). 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`.use crate::value::{EntityKey, Record};+use maybe_send::MaybeSend;use std::collections::HashMap;use std::convert::Infallible;/// Async KV over normalized records. Batch-oriented by design: the engine/// issues one `get_batch` per denormalization round, never per record.-#[allow(async_fn_in_trait)] // deliberately ?Send; single-threaded hosts-pub trait Storage {- type Error: std::error::Error + 'static;+pub trait Storage: MaybeSend {+ type Error: std::error::Error + MaybeSend + 'static;/// Fetches records; result is aligned with `keys` (`None` = absent).- async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error>;+ fn get_batch(+ &self,+ keys: &[EntityKey],+ ) -> impl Future<Output = Result<Vec<Option<Record>>, Self::Error>> + MaybeSend;/// Upserts records atomically (all-or-nothing per batch).- async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error>;+ fn put_batch(+ &mut self,+ entries: Vec<(EntityKey, Record)>,+ ) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;/// Deletes records (absent keys are ignored).- async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error>;+ fn delete_batch(+ &mut self,+ keys: &[EntityKey],+ ) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;/// Drops everything (logout / corruption rebuild).- async fn clear(&mut self) -> Result<(), Self::Error>;+ fn clear(&mut self) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;}/// Hash-map storage for tests and as the Phase 1 default.diff --git a/crates/client/cache-sqlite/src/lib.rs b/crates/client/cache-sqlite/src/lib.rsindex a345c2568a..56a8c00cae 100644--- a/crates/client/cache-sqlite/src/lib.rs+++ b/crates/client/cache-sqlite/src/lib.rs@@ -6,8 +6,10 @@//! and rebuilt — the cache is disposable by design, never migrated.//!//! rusqlite is synchronous; the async [`Storage`] methods complete-//! immediately. That's fine for the Tauri host, which runs the engine on a-//! dedicated thread (blocking IO is the point of the native host).+//! 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)]@@ -16,6 +18,7 @@ use cache_core::store::Storage;use cache_core::value::{EntityKey, Record};use rusqlite::{Connection, OptionalExtension, params};use std::path::Path;+use std::sync::{Mutex, MutexGuard};use thiserror::Error;/// Errors produced by the SQLite storage backend.@@ -31,7 +34,10 @@ pub enum SqliteStorageError {/// [`Storage`] backend over a SQLite database (Tauri native host).pub struct SqliteStorage {- conn: Connection,+ /// `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 {@@ -70,13 +76,21 @@ impl SqliteStorage {params![expected],)?;}- Ok(SqliteStorage { conn })+ 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+ .conn().query_row("SELECT COUNT(*) FROM records", [], |row| row.get(0))?)}}@@ -85,9 +99,8 @@ impl Storage for SqliteStorage {type Error = SqliteStorageError;async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error> {- let mut stmt = self- .conn- .prepare_cached("SELECT value FROM records WHERE key = ?1")?;+ 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@@ -102,7 +115,8 @@ impl Storage for SqliteStorage {}async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error> {- let tx = self.conn.transaction()?;+ let mut conn = self.conn();+ let tx = conn.transaction()?;{let mut stmt = tx.prepare_cached("INSERT INTO records (key, value) VALUES (?1, ?2)@@ -117,7 +131,8 @@ impl Storage for SqliteStorage {}async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {- let tx = self.conn.transaction()?;+ let mut conn = self.conn();+ let tx = conn.transaction()?;{let mut stmt = tx.prepare_cached("DELETE FROM records WHERE key = ?1")?;for key in keys {@@ -129,7 +144,7 @@ impl Storage for SqliteStorage {}async fn clear(&mut self) -> Result<(), Self::Error> {- self.conn.execute("DELETE FROM records", [])?;+ self.conn().execute("DELETE FROM records", [])?;Ok(())}}diff --git a/crates/maybe_send/Cargo.toml b/crates/maybe_send/Cargo.tomlnew file mode 100644index 0000000000..d81609d643--- /dev/null+++ b/crates/maybe_send/Cargo.toml@@ -0,0 +1,7 @@+[package]+edition = "2024"+name = "maybe_send"+publish = false+version = "0.1.0"++[dependencies]diff --git a/crates/maybe_send/src/lib.rs b/crates/maybe_send/src/lib.rsnew file mode 100644index 0000000000..31df019b25--- /dev/null+++ b/crates/maybe_send/src/lib.rs@@ -0,0 +1,31 @@+#![deny(missing_docs)]++//! This crate implements the commen [MaybeSend] and [MaybeSync] patterns for async rust code which must compile for both wasm and native targets.++/// Maybe send on non-wasm32 targets requires the Send bound+#[cfg(not(target_arch = "wasm32"))]+pub trait MaybeSend: Send {}++/// Maybe send on wasm32 targets does not required the send bound+#[cfg(target_arch = "wasm32")]+pub trait MaybeSend {}++#[cfg(not(target_arch = "wasm32"))]+impl<T: Send> MaybeSend for T {}++#[cfg(target_arch = "wasm32")]+impl<T> MaybeSend for T {}++/// Maybe Sync on non-wasm32 targets requires the Sync bound+#[cfg(not(target_arch = "wasm32"))]+pub trait MaybeSync: Sync {}++/// Maybe Sync on wasm32 targets does not required the sync bound+#[cfg(target_arch = "wasm32")]+pub trait MaybeSync {}++#[cfg(not(target_arch = "wasm32"))]+impl<T: Sync> MaybeSync for T {}++#[cfg(target_arch = "wasm32")]+impl<T> MaybeSync for T {}diff --git a/tooling/xtask/crates/xtask_deps/Cargo.toml b/tooling/xtask/crates/xtask_deps/Cargo.tomlindex 6fa809d897..952230a014 100644--- a/tooling/xtask/crates/xtask_deps/Cargo.toml+++ b/tooling/xtask/crates/xtask_deps/Cargo.toml@@ -11,8 +11,12 @@ path = "src/main.rs"[dependencies]anyhow = { workspace = true }+serde = { workspace = true, features = ["derive"] }serde_json = { workspace = true }guppy = { workspace = true }+# For the [xtask] extension table in .config/hakari.toml (path-glob+# traversal excludes); the hakari engine ignores that table.+toml = "0.5"# Pinned engine for the generated dependency artifacts. This version lives in# Cargo.lock, so dev machines and CI always run the identical generator —# upgrading it is an explicit, reviewed lock change.diff --git a/tooling/xtask/crates/xtask_deps/src/hakari_ops.rs b/tooling/xtask/crates/xtask_deps/src/hakari_ops.rsindex 37b36719d4..43d8a18f77 100644--- a/tooling/xtask/crates/xtask_deps/src/hakari_ops.rs+++ b/tooling/xtask/crates/xtask_deps/src/hakari_ops.rs@@ -2,9 +2,55 @@//! the `cargo hakari` CLI wraps, minus the CLI (and its version skew).use anyhow::{Context, Result, anyhow};+use guppy::PackageId;use guppy::graph::PackageGraph;use hakari::HakariBuilder;use hakari::summaries::{DEFAULT_CONFIG_PATH, HakariConfig};+use serde::Deserialize;++/// Xtask-only extension to `.config/hakari.toml`: the hakari engine only+/// accepts exact member names in `workspace-members`, so path globs live in+/// an `[xtask]` table it ignores and are expanded here.+#[derive(Debug, Default, Deserialize)]+struct XtaskConfig {+ #[serde(default)]+ xtask: XtaskSection,+}++#[derive(Debug, Default, Deserialize)]+#[serde(rename_all = "kebab-case")]+struct XtaskSection {+ /// Workspace-relative member-path globs, a literal prefix ending in a+ /// single `*` (e.g. `crates/client/*`). Every matched member becomes a+ /// traversal exclude: not unified into workspace-hack and never given+ /// the workspace-hack dependency by manage-deps.+ #[serde(default)]+ traversal_exclude_globs: Vec<String>,+}++/// Expands the path globs against workspace member paths. A glob matching+/// nothing is an error — it is either a typo or a stale entry.+fn glob_excludes<'g>(graph: &'g PackageGraph, globs: &[String]) -> Result<Vec<&'g PackageId>> {+ let mut ids = Vec::new();+ for glob in globs {+ let prefix = glob.strip_suffix('*').ok_or_else(|| {+ anyhow!("[xtask] traversal-exclude-globs entry `{glob}` must end with `*`")+ })?;+ let matched: Vec<_> = graph+ .workspace()+ .iter_by_path()+ .filter(|(path, _)| path.as_str().starts_with(prefix))+ .map(|(_, package)| package.id())+ .collect();+ if matched.is_empty() {+ return Err(anyhow!(+ "[xtask] traversal-exclude-globs entry `{glob}` matched no workspace members"+ ));+ }+ ids.extend(matched);+ }+ Ok(ids)+}/// Regenerates (or, in check mode, diffs) the workspace-hack crate:/// the generated section of its Cargo.toml, plus the `workspace-hack`@@ -17,11 +63,18 @@ pub fn run(graph: &PackageGraph, check: bool, drift: &mut Vec<String>) -> Resultlet config: HakariConfig = contents.parse().map_err(|e| anyhow!("parsing {config_path}: {e}"))?;+ let xtask_config: XtaskConfig = toml::from_str(&contents)+ .map_err(|e| anyhow!("parsing [xtask] section of {config_path}: {e}"))?;+ let extra_excludes = glob_excludes(graph, &xtask_config.xtask.traversal_exclude_globs)?;let make_builder = || -> Result<HakariBuilder<'_>> {- config+ let mut builder = config.builder.to_hakari_builder(graph)- .map_err(|e| anyhow!("resolving {config_path}: {e}"))+ .map_err(|e| anyhow!("resolving {config_path}: {e}"))?;+ builder+ .add_traversal_excludes(extra_excludes.iter().copied())+ .map_err(|e| anyhow!("applying [xtask] traversal-exclude-globs: {e}"))?;+ Ok(builder)};let mut changed = false;