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/normalized lru cache exchange (#4488)
Sean Aye19eb8b502300
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex ed117df5b8..0901d82f2b 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -503,6 +503,22 @@"user_quota","workspace-hack"],+ "cache-core": [+ "client/cache-core"+ ],+ "cache-idb": [+ "client/cache-core",+ "client/cache-idb"+ ],+ "cache-sqlite": [+ "client/cache-core",+ "client/cache-sqlite"+ ],+ "cache-wasm": [+ "client/cache-core",+ "client/cache-idb",+ "client/cache-wasm"+ ],"cal": ["analytics_client","cal",diff --git a/js/app/biome.jsonc b/js/app/biome.jsoncindex 74b3dedd95..976b2edd50 100644--- a/js/app/biome.jsonc+++ b/js/app/biome.jsonc@@ -15,6 +15,8 @@"!infra/web-app/output","!scripts","packages/service-clients/**/generated/**",+ // graphql-codegen output; regenerated wholesale by `bun gen-graphql`+ "!packages/service-clients/service-storage/graphql/generated","!packages/filesystem","!packages/_app-mobile","!../loro-mirror/packages",diff --git a/js/app/docs/graphql-normalized-cache-plan.md b/js/app/docs/graphql-normalized-cache-plan.mdnew file mode 100644index 0000000000..e28083b2bb--- /dev/null+++ b/js/app/docs/graphql-normalized-cache-plan.md@@ -0,0 +1,390 @@+# GraphQL Normalized Cache — Design & Plan++Status: **draft / pre-implementation**++## 1. Problem++We are migrating data fetching from REST to GraphQL (urql). We need normalized+caching with graphcache-like semantics, but graphcache hydrates and keeps the+entire cache in browser memory. With 10s of thousands of cached objects+(documents, email threads, channels, properties, …) that is not acceptable.++## 2. Requirements++### Hard requirements++1. **Normalized caching** — entities keyed by `__typename:id`, stored once,+ shared across queries; queries stored as link graphs over entity records+ (graphcache/Apollo-style).+2. **Bounded memory** — hot tier in memory (LRU, size-budgeted); everything+ else on disk. WASM linear memory is still browser memory, so the disk tier+ is the actual fix — Rust gives us a compact record format, deterministic+ eviction, and a portable engine.+3. **Persistence & offline** — cache survives restarts; previously-seen+ queries must be answerable fully offline. This means we persist not just+ entity records but also *operation root links* (query + variables →+ root selection links), plus staleness metadata.+4. **Both Tauri and web** — same core engine; Tauri **always** uses the+ native host (never OPFS/SharedWorker/webview storage), browser uses WASM+ in a worker.+5. **Shared cache across consumers** — multiple Tauri webviews and multiple+ browser tabs must observe one cache (single writer, shared invalidation).+6. **urql integration** — a custom exchange replacing `cacheExchange`.+ Components will eventually move to reactive urql queries, so the exchange+ must support the full operation lifecycle: active-operation registry,+ dependency-triggered re-execution, `cache-first` / `cache-and-network` /+ `network-only` policies, stale-flagged emissions.++### Derived / secondary requirements++7. **Async reads** — a disk-backed cache cannot offer graphcache's+ synchronous `readQuery`. urql's exchange model (wonka streams) tolerates+ async reads fine; imperative consumers get a Promise-based API.+8. **Schema awareness** — `GraphqlSoupEntity` is a 9-variant union; the cache+ needs possible-types metadata and per-type key config (e.g.+ `GraphqlSoupChannelMessage.messageId`, embedded non-keyable types like+ `GraphqlSoupPropertyValue`). Schema lives in-repo+ (`rust/cloud-storage/schema.graphql`) → embed metadata at build time, no+ runtime introspection.+9. **External write API** — no GraphQL subscriptions exist; updates arrive+ via websocket-service. Expose `writeFragment` / `invalidate(entityKey)` so+ websocket handlers can patch records and trigger re-execution.+10. **Eviction & GC** — active operations pin their dependencies; memory tier+ is LRU with a byte budget; disk tier has a byte budget with orphan sweep+ (records unreachable from any persisted operation root).+11. **Cache identity & lifecycle** — namespace by `scope + schemaHash ++ cacheFormatVersion`, where **scope is an anonymous client-generated+ uuid** (localStorage), *not* user identity: construction is synchronous+ and offline-capable (no identity waterfall), and no PII appears in+ enumerable storage metadata (IDB database names / SQLite filenames).+ User↔cache consistency is enforced by **identity witnessing**, split+ into two halves: *extraction* lives in the urql exchange+ (`extractIdentity: (data) => data.user.id` — the schema exposes+ `QueryRoot → user: GraphqlUser!`, viewer pattern), and *enforcement*+ lives in the engine as a schema-agnostic mechanism — writes carry an+ opaque session tag compared against the binding stored in the same+ database (`__meta:identity`), so compare-and-wipe is atomic with the+ triggering write (no stale-in-flight-write races). A mismatch wipes and+ rebinds (“silent restart”), all active operations re-execute, and other+ engine instances get a `reset` broadcast. Eager path: clear on logout.+ Discard on schema/format mismatch (cache is disposable, rebuild from+ network).++ **Key policy — presence-of-id convention**: no client-side key config.+ An output object type with `id: ID!` is keyed by `__typename:id`; no+ `id` field → embedded. The SDL is the policy (schema authors must only+ name a field `id` when it is a global identity — hence+ `GraphqlSoupProperty.propertyDefinitionId` and+ `GraphqlSoupChannelMessage.id`); the build fails on malformed shapes.+12. **Native-testable core** — the Rust engine is a pure crate (`cargo test`,+ no wasm) with storage/clock behind traits.+13. **Future** — mutations don't exist in the schema yet; design leaves room+ for optimistic updates, mutation-driven invalidation, and an offline+ mutation queue, but none of that is in scope now.++### 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.+- Disk budget (proposal: 256 MB default, configurable).+- Memory hot-tier budget (proposal: 32 MB default).++## 3. Current state (as of writing)++- urql usage is imperative-only: `@urql/core` + `fetchExchange`, called via+ `fetchGraphqlSoup()` (`packages/service-clients/service-storage/graphql-soup.ts`),+ results mapped to REST `SoupApiItem` shapes and fed into TanStack+ solid-query infinite queries (`packages/queries/soup/items.ts`), gated by+ `ENABLE_GRAPHQL_SOUP` with REST fallback.+- A separate normalization layer exists at the tanstack level:+ `@normy/query-core` (`packages/queries/soup/normalized-cache/`).+- WASM precedent: loro-crdt via `vite-plugin-wasm`; note the documented+ dual-instantiation pitfall in `packages/app/vite.base.ts` — the cache wasm+ module must be instantiated exactly once per JS context.+- IndexedDB (`idb`) and OPFS utilities are already used elsewhere+ (loro WAL/snapshot stores, `service-storage/util/opfs.ts`).++## 4. Architecture++One Rust core engine, two hosts:++```+ ┌──────────────────────────────────────────┐+ │ cache-core (pure Rust crate) │+ │ • GraphQL doc parsing (apollo-rs) │+ │ • schema metadata (build-time codegen) │+ │ • normalize / denormalize │+ │ • dependency index (op ↔ record keys) │+ │ • hot tier: LRU record store │+ │ • Storage trait (async KV + scans) │+ └───────────────┬──────────────────────────┘+ ┌─────────────────────┴──────────────────────┐+ ▼ ▼+┌───────────────────────────────┐ ┌─────────────────────────────────┐+│ 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 │+│ (storage entirely in Rust) │ │ • naturally shared across ALL │+│ • SharedWorker where available│ │ webviews/windows │+│ (single engine instance) │ │ • SQLite (or fs) storage │+│ • fallback: worker-per-tab + │ │ • glue over invoke + channels/ │+│ Web Locks write serializing │ │ events │+│ + BroadcastChannel fanout │ │ │+└───────────────┬───────────────┘ └────────────────┬────────────────┘+ └──────────────────┬──────────────────────┘+ ▼+ ┌────────────────────────────────────┐+ │ JS glue: transport-agnostic async │+ │ RPC client (`CacheHost` interface) │+ │ • normalizedCacheExchange (urql) │+ │ • imperative read/write/invalidate │+ └────────────────────────────────────┘+```++### 4.1 Why the engine lives outside the page++- Keeps main thread free (normalization of large pages off-thread).+- A worker is the natural place for a shared single engine instance+ (SharedWorker) and keeps wasm out of every page context.+- On Tauri we do **not** use SharedWorker or webview storage at all —+ support is inconsistent across WKWebView/WebView2/Android WebView, and+ webviews can't share a SharedWorker across windows. The Tauri host process+ is 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**.++### 4.2 Multi-consumer strategy (browser only)++**Decision: IndexedDB-backed persistence via the [`idb`+crate](https://docs.rs/idb/latest/idb/), engine in a worker that may or may+not be a SharedWorker. 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 window, dedicated workers and SharedWorker, and+ tolerates concurrent instances — so the same backend works in every+ topology.+- 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:++- **Preferred: SharedWorker** hosting the wasm engine — single instance,+ no election, trivial routing. (Chromium probe: IDB, Web Locks and+ BroadcastChannel all available in SharedWorker.)+- **Fallback (no SharedWorker): dedicated worker per tab**, each with its+ own engine instance over the same IDB database. Web Locks serialize+ writes/GC (single writer at a time); BroadcastChannel broadcasts+ changed-keys so every tab's exchange re-executes affected operations.+ Cost: N copies of the hot tier — acceptable.+- Selection at startup: Tauri detection (`isTauri`) → native transport;+ otherwise `typeof SharedWorker === 'function'` picks the worker kind. All+ paths sit behind the same `Storage` trait and `CacheHost` RPC interface.++### 4.3 Storage backends++| Backend | Host | Notes |+|------------|--------------|------------------------------------------------|+| SQLite | Tauri native | records + links + meta tables; WAL mode |+| IndexedDB | browser | via the `idb` crate inside the wasm module; one DB, object stores for records / operation roots / meta |++`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.++### 4.4 Data model++- **Record** = normalized entity: `key → { fields, embedded objects, links,+ staleness/lastWritten metadata }`.+- **Operation root** = `hash(query, variables) → root links + lastFetched ++ ttl`. Persisted → offline replay of previously-seen queries.+- **Dependency index** = record key → active operation ids (in-memory only)+ and record key → persisted operation hashes (disk, for GC).++### 4.5 urql exchange semantics++- On operation: RPC `readQuery` → full hit: emit (stale-flagged if+ `cache-and-network`, then forward to network); partial/miss: forward.+- On network result: RPC `writeQuery`; engine returns the set of changed+ record keys; exchange re-executes affected active operations (mirrors+ graphcache `cache-and-network` re-emission behavior).+- On teardown: unregister operation (unpins dependencies).+- Cross-context: engine broadcasts changed-keys; every context's exchange+ re-executes its own affected active operations.++### 4.6 Coexistence with normy / tanstack++Near term the exchange sits under `fetchGraphqlSoup` unchanged (tanstack stays+the component-facing layer; it benefits from offline + dedup immediately). As+components move to reactive urql queries, the corresponding soup queries drop+out of the normy layer. The wasm cache is the source of truth for+GraphQL-fetched data; do not double-normalize the same data in normy — remove+soup entities from the normy config as they migrate.++## 5. Repo layout++```+rust/cloud-storage/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)+ cache-wasm/ # wasm-bindgen shell (web)+ cache-tauri/ # tauri plugin/commands wrapping cache-core+js/app/packages/graphql-cache/ # JS glue+ host/ # CacheHost interface + worker & tauri transports+ exchange/ # urql normalizedCacheExchange+ worker/ # SharedWorker/dedicated-worker entries+```++## 6. Phases++**Phase 0 — spike** *(closed)*+- Browser probe harness built; Chromium results in Appendix A. **Decision+ made: IDB-backed persistence via the `idb` crate, SharedWorker preferred+ with dedicated-worker fallback (§4.2).** Safari/Firefox probe runs and+ the Tauri IPC benchmark were deliberately skipped — the IDB + worker+ approach is the lowest common denominator and doesn't depend on their+ results.+- Wire protocol delivered in Phase 3 (`packages/graphql-cache/protocol.ts`).+- The probe harness (`spikes/graphql-cache-probe/`) and the soup payload+ measurement script (`scripts/measure-soup-payloads.ts`) were removed+ after the decisions landed — recover them from history (`jj`/git) if+ re-measurement is ever needed; the results live in Appendix A.++**Phase 1 — cache-core (native, no wasm)** *(done — `rust/cloud-storage/client/cache-core`)*+- Schema metadata codegen from `rust/cloud-storage/schema.graphql`+ (`build.rs`; key policy derived via the presence-of-id convention, build+ fails on malformed shapes).+- Normalize/denormalize for the real `Soup` query shape, union + fragment+ handling, alias-aware storage, canonical-args field keys.+- Dependency index, LRU hot tier, in-memory Storage impl, engine with+ batch-fetch read loop and changed-key/affected-ops write results.+- 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`)*+- Shared postcard record codec + `cache_namespace(scope)` embedding+ schema hash + 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.+- 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)*+- ~~`cache-wasm`~~: wasm-bindgen shell (async-mutex engine, string op-id+ interning `"{clientId}:{urqlKey}"`), browser-verified via+ wasm-bindgen-test. Build: `just build-cache-wasm` →+ `packages/graphql-cache/wasm/` (gitignored), ~460 KiB pre-gzip.+- ~~JS glue~~ (`js/app/packages/graphql-cache/`, alias `@graphql-cache/*`):+ wire protocol (`protocol.ts`), `CacheWorkerCore` ++ SharedWorker/dedicated-worker entries (Web Locks write serialization ++ BroadcastChannel fanout in the fallback topology), `createWorkerCacheHost`+ implementing `CacheHost`. Type-checked; end-to-end browser exercise+ happens with the Phase 4 exchange integration.+- **Pending:** `cache-tauri` plugin (commands + change events) + Tauri+ `CacheHost` transport; `isTauri` → native selection.++**Phase 4 — urql exchange, behind flag** *(done — needs manual smoke test)*+- `normalizedCacheExchange`+ (`packages/graphql-cache/exchange/`): async cache reads with a+ forward-queue re-injection (cache is off-thread, unlike graphcache's sync+ reads), all four request policies, push-driven re-execution downgraded to+ `cache-first`, write-through of network results, cache errors degrade to+ network. 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+ `cache-and-network` (`.toPromise()` skips stale emissions → identical+ fresh semantics today) and falls back to a `cache-only` re-read on+ network errors → offline replay of previously-seen pages.+- Production build verified: worker chunks + `cache_wasm_bg.wasm` emitted+ as hashed assets (explicit `module_or_path` URL — vite copies the+ wasm-pack JS as an opaque asset, so its internal relative wasm URL had to+ be resolved at the caller).+- **Manual smoke test pending**: dev-server run with the override enabled+ (localStorage `ENABLE_GRAPHQL_SOUP=true`), verify hit/miss + offline+ behavior in the browser.++**Phase 5 — write path & coexistence**+- `writeFragment`/`invalidate` from websocket handlers.+- Define normy retirement path per entity type as components move to+ reactive urql queries.++**Phase 6 — hardening**+- Eviction budgets, disk GC, telemetry (hit rate, tier sizes, read latency,+ re-execution counts), multi-tab soak tests, schema-change invalidation test.++## 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) and the dedicated-worker+ fallback topology. 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).+- **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 per+ operation, not per record. Tauri IPC assumed adequate (benchmark skipped);+ revisit only if Phase 4 integration shows latency problems.+- **Two normalization layers during migration** — consistency hazard;+ mitigated by per-entity-type ownership rule (§4.6).+- **wasm dual-instantiation** (known loro pitfall) — single worker entry owns+ the module; never import the wasm package from page code.+- **Offline correctness** — staleness semantics must be explicit+ (`stale: true` emissions) so UI can indicate offline data.++## Appendix A — Phase 0 probe results++Harness: `spikes/graphql-cache-probe/` — removed after the §4.2 decision+landed; recover from history if needed.++### Chromium 149 (headless, Linux) — 2026-07-03++| Capability | Window | Dedicated worker | SharedWorker | Nested worker in SharedWorker |+|---|---|---|---|---|+| SharedWorker constructor | ✅ | — | — | — |+| Worker constructor (nested spawn) | — | ✅ | ❌ | — |+| OPFS root (getDirectory) | ✅ | ✅ | ✅ | — |+| createSyncAccessHandle (working) | ❌ (expected) | ✅ | ❌ | — (`Worker is not defined`) |+| Web Locks | ✅ | ✅ | ✅ | — |+| BroadcastChannel | ✅ | ✅ | ✅ | — |++Benchmarks (headless chromium on dev machine — order of magnitude only):++| Metric | Result |+|---|---|+| OPFS sync write 4 KiB | avg 2.0 ms, p50 1.0 ms, p95 5.3 ms (n=1000) |+| OPFS sync read 4 KiB (random) | avg 2.0 ms, p50 1.9 ms, p95 3.6 ms (n=1000) |+| OPFS flush after 1000 writes | 0.1 ms |+| IDB batched put ×1000 (≈1 KiB records, one txn) | 119 ms total |+| IDB individual get | avg 0.35 ms, p95 0.5 ms (n=1000) |+| IDB getAll ×1000 | 24 ms |+| postMessage RTT tiny (window↔dedicated) | avg 0.10 ms |+| postMessage RTT 64 KiB clone (window↔dedicated) | avg 0.85 ms, p95 3.0 ms |+| postMessage RTT 64 KiB clone (window↔shared) | avg 0.22 ms |++Takeaways:++1. **SharedWorker + OPFS is not viable on Chromium** (no sync handles in+ SharedWorker, no nested `Worker`).+2. **IDB point-reads (0.35 ms) beat OPFS sync 4 KiB reads (2 ms)** in this+ environment — sync-handle IO still pays a per-call cost.+3. RTT is a non-issue: ≤1 ms for 64 KiB payloads, well within the read+ budget.++These takeaways drove the §4.2 decision (IDB via the `idb` crate, engine in+a worker that may or may not be a SharedWorker). Firefox/Safari probe runs+and the Tauri IPC benchmark were **skipped by decision** — the chosen+approach relies only on APIs universally available (IndexedDB, dedicated+workers, Web Locks, BroadcastChannel).diff --git a/js/app/justfile b/js/app/justfileindex 19c3faf710..a944515264 100644--- a/js/app/justfile+++ b/js/app/justfile@@ -23,7 +23,7 @@ ios-prepare-tauri-api:# Tauri build hook (run automatically via beforeDevCommand) — not meant to be run directly[private]-dev-tauri:+dev-tauri: ensure-cache-wasmprintf development > tauri/src-tauri/.macro-tauri-envcd packages/app && bun run --bun dev@@ -48,24 +48,27 @@ local-dcs:local-dss:cd packages/app && VITE_LOCAL_SERVERS='document-storage-service' bun run --bun dev-local-search:+local-search: ensure-cache-wasmcd packages/app && VITE_LOCAL_SERVERS='search-service' bun run --bun dev-local-email:+local-email: ensure-cache-wasmcd packages/app && VITE_LOCAL_SERVERS='email-service' bun run --bun dev-build-dev:+# All app builds need the gitignored wasm pkg (packages/graphql-cache/wasm):+# without it the cache worker's dynamic import 404s at runtime and the+# normalized cache silently degrades to network-only.+build-dev: build-cache-wasmcd packages/app && MODE=development NODE_ENV=production bun run --bun build-build-staging:+build-staging: build-cache-wasmcd packages/app && MODE=staging NODE_ENV=production bun run --bun build-build-prod:+build-prod: build-cache-wasmcd packages/app && MODE=production NODE_ENV=production bun run --bun build# Tauri build hook (run automatically via beforeBuildCommand) — not meant to be run directly[private]-build-tauri:+build-tauri: build-cache-wasmprintf production > tauri/src-tauri/.macro-tauri-envcd packages/app && MODE=production NODE_ENV=production bun run --bun build@@ -150,3 +153,15 @@ cycles:cycles-ci:bunx --bun biome lint --changed --only=nursery/noImportCycles++# Build the GraphQL cache wasm module into packages/graphql-cache/wasm+# (gitignored). Unconditional — CI app builds must never skip it (schema or+# engine changes alter the wasm without a cache-wasm version bump).+build-cache-wasm:+ wasm-pack build {{justfile_directory()}}/../../rust/cloud-storage/client/cache-wasm --target web --release --out-dir {{justfile_directory()}}/packages/graphql-cache/wasm++# Dev fast path: build the wasm pkg only when missing or its version drifts+# from client/cache-wasm/Cargo.toml (bump that version to push a rebuild to+# dev machines). See rust/cloud-storage/tools/xtask/src/cache_wasm.rs.+ensure-cache-wasm:+ cd {{justfile_directory()}}/../../rust/cloud-storage && SQLX_OFFLINE=true cargo run -q -p xtask -- cache-wasmdiff --git a/js/app/package.json b/js/app/package.jsonindex 9b83a33156..0f28045d12 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -3,7 +3,7 @@"private": true,"type": "module","scripts": {- "dev": "cd packages/app && bun run --bun dev",+ "dev": "just ensure-cache-wasm && cd packages/app && bun run --bun dev","build": "cd packages/app && MODE=development NODE_ENV=production bun run --bun build","test": "bunx vitest run","local:e2e": "LOCAL_E2E=true bunx playwright test",@@ -116,6 +116,7 @@"uuid": "^10.0.0","virtua": "0.48.8","vite-plugin-wasm": "^3.5.0",+ "wonka": "^6.3.2","zod": "^4.3.6"},"devDependencies": {diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 384e84f0c5..d9771e48cd 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -414,6 +414,20 @@ export const ENABLE_GRAPHQL_SOUP_OVERRIDE = getFeatureFlagOverride('ENABLE_GRAPHQL_SOUP');+/**+ * Non-reactive check for imperative call sites (e.g. the soup GraphQL+ * client's normalized-cache gate). Env override first (dev), else the same+ * PostHog flag that gates the GraphQL transport — so cache and transport+ * activate together in previews/production.+ */+export function ENABLE_GRAPHQL_SOUP(): boolean {+ if (ENABLE_GRAPHQL_SOUP_OVERRIDE !== undefined) {+ return ENABLE_GRAPHQL_SOUP_OVERRIDE;+ }++ return analytics.posthog.isFeatureEnabled(ENABLE_GRAPHQL_SOUP_FLAG) ?? false;+}+export const DISABLE_AUTO_UPDATE_UI_FLAG = 'disable-auto-update-ui';export const ENABLE_AUTO_UPDATE_UI_OVERRIDE = getFeatureFlagOverride('ENABLE_AUTO_UPDATE_UI'diff --git a/js/app/packages/graphql-cache/.gitignore b/js/app/packages/graphql-cache/.gitignorenew file mode 100644index 0000000000..7d601c9b0d--- /dev/null+++ b/js/app/packages/graphql-cache/.gitignore@@ -0,0 +1,2 @@+# Generated by `just build-cache-wasm` (wasm-pack over rust/graphql-cache/cache-wasm)+wasm/diff --git a/js/app/packages/graphql-cache/exchange/normalized-cache-exchange.test.ts b/js/app/packages/graphql-cache/exchange/normalized-cache-exchange.test.tsnew file mode 100644index 0000000000..7db424ca42--- /dev/null+++ b/js/app/packages/graphql-cache/exchange/normalized-cache-exchange.test.ts@@ -0,0 +1,331 @@+import {+ type Client,+ gql,+ makeOperation,+ type Operation,+ type OperationResult,+} from '@urql/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { makeSubject, map, pipe, type Source, subscribe } from 'wonka';+import type { CacheHost } from '../host/types';+import type { ReadResult, WriteResult } from '../protocol';+import { normalizedCacheExchange } from './normalized-cache-exchange';++const QUERY = gql`+ query Soup($input: SoupInput!) {+ soup(input: $input) {+ nextCursor+ hasMore+ }+ }+`;++type FakeHost = CacheHost & {+ reads: Array<{ opKey?: number; query: string; variables?: object }>;+ writes: Array<{ opKey?: number; data: unknown; identity?: string }>;+ teardowns: number[];+ scriptRead: (result: ReadResult) => void;+ pushAffected: (opKeys: number[]) => void;+};++function makeFakeHost(): FakeHost {+ let readResult: ReadResult = { kind: 'miss' };+ const subscribers = new Set<(opKeys: number[]) => void>();+ const host: FakeHost = {+ clientId: 'test-client',+ reads: [],+ writes: [],+ teardowns: [],+ scriptRead: (r) => {+ readResult = r;+ },+ pushAffected: (opKeys) => {+ for (const cb of subscribers) cb(opKeys);+ },+ async readQuery(args) {+ host.reads.push({+ opKey: args.opKey,+ query: args.query,+ variables: args.variables,+ });+ return readResult;+ },+ async writeQuery(args): Promise<WriteResult> {+ host.writes.push({+ opKey: args.opKey,+ data: args.data,+ identity: args.identity,+ });+ return { changed: [], affectedOps: [], reset: false };+ },+ async invalidate() {+ return [];+ },+ async teardown(opKey) {+ host.teardowns.push(opKey);+ },+ async clear() {},+ onOpsAffected(cb) {+ subscribers.add(cb);+ return () => subscribers.delete(cb);+ },+ dispose() {},+ };+ return host;+}++function makeOp(+ key: number,+ requestPolicy:+ | 'cache-first'+ | 'cache-and-network'+ | 'network-only'+ | 'cache-only' = 'cache-first'+): Operation {+ return makeOperation(+ 'query',+ { key, query: QUERY, variables: { input: { limit: 2 } } },+ { requestPolicy, url: 'http://test', suspense: false } as never+ );+}++function teardownOf(op: Operation): Operation {+ return makeOperation('teardown', op, op.context);+}++/** Runs the exchange over a manual operation stream. */+function harness(host: CacheHost) {+ const client = { reexecuteOperation: vi.fn() } as unknown as Client;+ const ops = makeSubject<Operation>();+ const forwarded: Operation[] = [];+ const forward = (ops$: Source<Operation>): Source<OperationResult> =>+ pipe(+ ops$,+ map((op) => {+ forwarded.push(op);+ return {+ operation: op,+ data: op.kind === 'query' ? { from: 'network' } : undefined,+ error: undefined,+ extensions: undefined,+ stale: false,+ hasNext: false,+ };+ })+ );++ const results: OperationResult[] = [];+ const exchangeIo = normalizedCacheExchange(host)({+ forward,+ client,+ dispatchDebug: () => undefined,+ });+ pipe(+ exchangeIo(ops.source),+ subscribe((r) => results.push(r))+ );+ return { ops, results, forwarded, client };+}++const tick = () => new Promise((r) => setTimeout(r, 0));++describe('normalizedCacheExchange', () => {+ let host: FakeHost;++ beforeEach(() => {+ host = makeFakeHost();+ });++ it('cache-first miss forwards to network and writes through', async () => {+ const { ops, results, forwarded } = harness(host);+ ops.next(makeOp(1));+ await tick();++ expect(host.reads).toHaveLength(1);+ expect(host.reads[0]?.opKey).toBe(1);+ expect(forwarded.map((op) => op.key)).toEqual([1]);+ expect(results).toHaveLength(1);+ expect(results[0]?.data).toEqual({ from: 'network' });+ expect(host.writes).toHaveLength(1);+ expect(host.writes[0]?.data).toEqual({ from: 'network' });+ });++ it('cache-first hit emits without network', async () => {+ host.scriptRead({ kind: 'hit', data: { from: 'cache' } });+ const { ops, results, forwarded } = harness(host);+ ops.next(makeOp(1));+ await tick();++ expect(results).toHaveLength(1);+ expect(results[0]?.data).toEqual({ from: 'cache' });+ expect(results[0]?.stale).toBe(false);+ expect(forwarded).toHaveLength(0);+ expect(host.writes).toHaveLength(0);+ });++ it('cache-and-network hit emits stale then network result', async () => {+ host.scriptRead({ kind: 'hit', data: { from: 'cache' } });+ const { ops, results, forwarded } = harness(host);+ ops.next(makeOp(1, 'cache-and-network'));+ await tick();++ expect(results.map((r) => [r.data, r.stale])).toEqual([+ [{ from: 'cache' }, true],+ [{ from: 'network' }, false],+ ]);+ expect(forwarded.map((op) => op.key)).toEqual([1]);+ expect(host.writes).toHaveLength(1);+ });++ it('network-only skips the read but writes the response', async () => {+ const { ops, results } = harness(host);+ ops.next(makeOp(1, 'network-only'));+ await tick();++ expect(host.reads).toHaveLength(0);+ expect(results[0]?.data).toEqual({ from: 'network' });+ expect(host.writes).toHaveLength(1);+ });++ it('cache-only miss emits empty data and never touches the network', async () => {+ const { ops, results, forwarded } = harness(host);+ ops.next(makeOp(1, 'cache-only'));+ await tick();++ expect(results).toHaveLength(1);+ expect(results[0]?.data).toBeUndefined();+ expect(forwarded).toHaveLength(0);+ });++ it('cache read errors degrade to the network', async () => {+ host.readQuery = async () => {+ throw new Error('idb exploded');+ };+ const onCacheError = vi.fn();+ const client = { reexecuteOperation: vi.fn() } as unknown as Client;+ const ops = makeSubject<Operation>();+ const results: OperationResult[] = [];+ const forward = (ops$: Source<Operation>): Source<OperationResult> =>+ pipe(+ ops$,+ map((op) => ({+ operation: op,+ data: { from: 'network' },+ error: undefined,+ extensions: undefined,+ stale: false,+ hasNext: false,+ }))+ );+ pipe(+ normalizedCacheExchange(host, { onCacheError })({+ forward,+ client,+ dispatchDebug: () => undefined,+ })(ops.source),+ subscribe((r) => results.push(r))+ );+ ops.next(makeOp(1));+ await tick();++ expect(onCacheError).toHaveBeenCalledOnce();+ expect(results[0]?.data).toEqual({ from: 'network' });+ });++ it('cache-only never touches the network, even when the cache read throws', async () => {+ host.readQuery = async () => {+ throw new Error('idb exploded');+ };+ const onCacheError = vi.fn();+ const client = { reexecuteOperation: vi.fn() } as unknown as Client;+ const ops = makeSubject<Operation>();+ const results: OperationResult[] = [];+ const forwarded: Operation[] = [];+ const forward = (ops$: Source<Operation>): Source<OperationResult> =>+ pipe(+ ops$,+ map((op) => {+ forwarded.push(op);+ return {+ operation: op,+ data: { from: 'network' },+ error: undefined,+ extensions: undefined,+ stale: false,+ hasNext: false,+ };+ })+ );+ pipe(+ normalizedCacheExchange(host, { onCacheError })({+ forward,+ client,+ dispatchDebug: () => undefined,+ })(ops.source),+ subscribe((r) => results.push(r))+ );+ ops.next(makeOp(1, 'cache-only'));+ await tick();++ expect(onCacheError).toHaveBeenCalledOnce();+ expect(forwarded).toHaveLength(0);+ expect(results).toHaveLength(1);+ expect(results[0]?.data).toBeUndefined();+ });++ it('passes the extracted identity tag on write-through', async () => {+ const client = { reexecuteOperation: vi.fn() } as unknown as Client;+ const ops = makeSubject<Operation>();+ const forward = (ops$: Source<Operation>): Source<OperationResult> =>+ pipe(+ ops$,+ map((op) => ({+ operation: op,+ data: { user: { id: 'macro|[email protected]' } },+ error: undefined,+ extensions: undefined,+ stale: false,+ hasNext: false,+ }))+ );+ pipe(+ normalizedCacheExchange(host, {+ extractIdentity: (data) =>+ (data as { user?: { id?: string } })?.user?.id,+ })({ forward, client, dispatchDebug: () => undefined })(ops.source),+ subscribe(() => undefined)+ );+ ops.next(makeOp(1));+ await tick();++ expect(host.writes).toHaveLength(1);+ expect(host.writes[0]?.identity).toBe('macro|[email protected]');+ });++ it('re-executes affected active operations as cache-first', async () => {+ const { ops, client } = harness(host);+ const op = makeOp(7, 'cache-and-network');+ ops.next(op);+ await tick();++ host.pushAffected([7, 999]); // 999 is not active → ignored+ const reexec = vi.mocked(client.reexecuteOperation);+ expect(reexec).toHaveBeenCalledOnce();+ const reissued = reexec.mock.calls[0]?.[0] as Operation;+ expect(reissued.key).toBe(7);+ expect(reissued.context.requestPolicy).toBe('cache-first');+ });++ it('teardown unregisters the op with the host and stops re-execution', async () => {+ const { ops, client } = harness(host);+ const op = makeOp(7);+ ops.next(op);+ await tick();+ ops.next(teardownOf(op));+ await tick();++ expect(host.teardowns).toEqual([7]);+ host.pushAffected([7]);+ expect(vi.mocked(client.reexecuteOperation)).not.toHaveBeenCalled();+ });+});diff --git a/js/app/packages/graphql-cache/exchange/normalized-cache-exchange.ts b/js/app/packages/graphql-cache/exchange/normalized-cache-exchange.tsnew file mode 100644index 0000000000..7e4acd7b6a--- /dev/null+++ b/js/app/packages/graphql-cache/exchange/normalized-cache-exchange.ts@@ -0,0 +1,217 @@+/**+ * urql exchange backed by the normalized wasm cache (via a `CacheHost`).+ *+ * Differences from `@urql/exchange-graphcache`:+ * - cache reads are **async** (the cache is disk-backed, possibly in another+ * worker/process), so operations needing the network are re-injected into+ * the forward pipeline through a queue after the read resolves;+ * - invalidation is push-based: the host emits "these operation keys must+ * re-execute" (local sibling writes, other tabs/webviews, external+ * invalidations) and the exchange re-executes them as `cache-first`.+ *+ * Request policies:+ * - `cache-first` (default): hit → emit; miss → network.+ * - `cache-and-network`: hit → emit with `stale: true`, then network.+ * (`toPromise()` ignores stale results, so imperative callers keep+ * network-fresh semantics for free.)+ * - `network-only`: skip read; response still written to cache.+ * - `cache-only`: hit → emit; miss → emit `data: undefined`, no network.+ *+ * Cache failures are never fatal: any host error degrades to the network.+ */++import {+ type Exchange,+ makeOperation,+ type Operation,+ type OperationResult,+ stringifyDocument,+} from '@urql/core';+import { Kind, type OperationDefinitionNode } from 'graphql';+import {+ empty,+ filter,+ fromPromise,+ fromValue,+ makeSubject,+ merge,+ mergeMap,+ pipe,+ type Source,+ share,+ tap,+} from 'wonka';+import type { CacheHost } from '../host/types';++const queryTextCache = new WeakMap<object, string>();++function queryText(op: Operation): string {+ const doc = op.query;+ let text = queryTextCache.get(doc);+ if (text === undefined) {+ text = stringifyDocument(doc);+ queryTextCache.set(doc, text);+ }+ return text;+}++function operationName(op: Operation): string | undefined {+ for (const def of op.query.definitions) {+ if (def.kind === Kind.OPERATION_DEFINITION) {+ return (def as OperationDefinitionNode).name?.value;+ }+ }+ return undefined;+}++function cacheResult(+ op: Operation,+ data: unknown,+ stale: boolean+): OperationResult {+ return {+ operation: op,+ data,+ error: undefined,+ extensions: undefined,+ stale,+ hasNext: false,+ };+}++export interface NormalizedCacheExchangeOptions {+ /** Called when a cache read/write fails (diagnostics; flow already degraded to network). */+ onCacheError?: (error: unknown, op: Operation) => void;+ /**+ * Extracts the session identity (e.g. viewer id, `data.user.id`) from a+ * response. The extracted value is passed to the cache as an opaque tag;+ * a write tagged with a different identity than the one bound to the+ * cache wipes and rebinds it atomically (silent restart), and every+ * active operation re-executes. Schema knowledge lives here — the cache+ * layer itself is identity-agnostic.+ */+ extractIdentity?: (data: unknown) => string | undefined;+}++export function normalizedCacheExchange(+ host: CacheHost,+ options: NormalizedCacheExchangeOptions = {}+): Exchange {+ return ({ forward, client }) => {+ /** Operations registered with the host, for push-driven re-execution. */+ const activeOps = new Map<number, Operation>();++ const unsubscribePush = host.onOpsAffected((opKeys) => {+ for (const key of opKeys) {+ const op = activeOps.get(key);+ if (!op) continue;+ // Re-read from cache; do not stampede the network (graphcache does+ // the same downgrade on dependency-driven re-execution).+ client.reexecuteOperation(+ makeOperation(op.kind, op, {+ ...op.context,+ requestPolicy: 'cache-first',+ })+ );+ }+ });++ return (ops$) => {+ const shared = pipe(ops$, share);++ // Async cache reads re-inject network-bound operations here.+ const { source: forwardQueue$, next: enqueueForward } =+ makeSubject<Operation>();++ async function readThenRoute(+ op: Operation+ ): Promise<OperationResult | undefined> {+ const policy = op.context.requestPolicy;+ if (policy === 'network-only') {+ enqueueForward(op);+ return undefined;+ }+ try {+ const read = await host.readQuery({+ opKey: op.key,+ query: queryText(op),+ operationName: operationName(op),+ variables: op.variables as Record<string, unknown> | undefined,+ });+ if (read.kind === 'hit') {+ const stale = policy === 'cache-and-network';+ if (stale) enqueueForward(op);+ return cacheResult(op, read.data, stale);+ }+ if (policy === 'cache-only') {+ return cacheResult(op, undefined, false);+ }+ } catch (error) {+ options.onCacheError?.(error, op);+ // `cache-only` must never touch the network, even when the cache+ // itself fails — degrade to an empty result instead.+ if (policy === 'cache-only') {+ return cacheResult(op, undefined, false);+ }+ }+ enqueueForward(op);+ return undefined;+ }++ async function writeThrough(+ result: OperationResult+ ): Promise<OperationResult> {+ const op = result.operation;+ if (op.kind === 'query' && result.data != null) {+ try {+ await host.writeQuery({+ opKey: op.key,+ query: queryText(op),+ operationName: operationName(op),+ variables: op.variables as Record<string, unknown> | undefined,+ data: result.data,+ identity: options.extractIdentity?.(result.data),+ });+ } catch (error) {+ options.onCacheError?.(error, op);+ }+ }+ return result;+ }++ const cacheResults$ = pipe(+ shared,+ filter((op) => op.kind === 'query'),+ mergeMap((op) => {+ activeOps.set(op.key, op);+ return pipe(+ fromPromise(readThenRoute(op)),+ mergeMap((result) =>+ result ? fromValue(result) : (empty as Source<OperationResult>)+ )+ );+ })+ );++ const passthrough$ = pipe(+ shared,+ filter((op) => op.kind !== 'query'),+ tap((op) => {+ if (op.kind === 'teardown') {+ activeOps.delete(op.key);+ host.teardown(op.key).catch(() => undefined);+ }+ })+ );++ const forwarded$ = pipe(+ merge([forwardQueue$, passthrough$]),+ forward,+ mergeMap((result) => fromPromise(writeThrough(result)))+ );++ void unsubscribePush;+ return merge([cacheResults$, forwarded$]);+ };+ };+}diff --git a/js/app/packages/graphql-cache/host/types.ts b/js/app/packages/graphql-cache/host/types.tsnew file mode 100644index 0000000000..3fc7fc248a--- /dev/null+++ b/js/app/packages/graphql-cache/host/types.ts@@ -0,0 +1,45 @@+/**+ * Transport-agnostic cache host interface consumed by the urql exchange and+ * imperative writers (websocket handlers). Implementations:+ * - worker-host.ts: browser (SharedWorker / dedicated worker + wasm engine)+ * - tauri-host.ts (Phase 3b): Tauri IPC to the native engine+ */++import type { ReadResult, WriteResult } from '../protocol';++export interface CacheReadArgs {+ /** urql operation key; registers the op for re-execution when set. */+ opKey?: number;+ query: string;+ operationName?: string;+ variables?: Record<string, unknown>;+}++export interface CacheWriteArgs extends CacheReadArgs {+ data: unknown;+ /** Opaque session tag; see protocol.ts `identity`. */+ identity?: string;+}++export interface CacheHost {+ /** Stable id of this context; used to namespace operation ids. */+ readonly clientId: string;++ readQuery(args: CacheReadArgs): Promise<ReadResult>;+ writeQuery(args: CacheWriteArgs): Promise<WriteResult>;+ /** Evict records by entity key (external/push updates); returns affected local op ids. */+ invalidate(keys: string[]): Promise<string[]>;+ /** urql teardown for an operation key. */+ teardown(opKey: number): Promise<void>;+ /** Wipe all cached state (logout). */+ clear(): Promise<void>;++ /**+ * Subscribes to "these urql operation keys must re-execute" pushes+ * (local writes from other operations, other tabs, push invalidation).+ * Only keys belonging to this client are delivered. Returns unsubscribe.+ */+ onOpsAffected(cb: (opKeys: number[]) => void): () => void;++ dispose(): void;+}diff --git a/js/app/packages/graphql-cache/host/worker-host.ts b/js/app/packages/graphql-cache/host/worker-host.tsnew file mode 100644index 0000000000..5bf1cb9185--- /dev/null+++ b/js/app/packages/graphql-cache/host/worker-host.ts@@ -0,0 +1,186 @@+/**+ * Browser CacheHost: talks the RPC protocol to the cache worker.+ * Prefers SharedWorker (single engine across tabs); falls back to a+ * dedicated worker per tab (engines converge via IndexedDB + Web Locks ++ * BroadcastChannel — see worker-core.ts).+ */++import {+ type CacheNotice,+ type CacheRequest,+ isCachePush,+ type ReadResult,+ type WorkerMessage,+ type WriteResult,+} from '../protocol';+import type { CacheHost, CacheReadArgs, CacheWriteArgs } from './types';++type Pending = {+ resolve: (value: unknown) => void;+ reject: (error: Error) => void;+};++/** `Omit` that distributes over union members. */+type DistributiveOmit<T, K extends PropertyKey> = T extends unknown+ ? Omit<T, K>+ : never;++export interface WorkerHostOptions {+ scope: string;+ hotCapacity?: number;+ /** Force a topology (tests/diagnostics). */+ forceDedicatedWorker?: boolean;+ /**+ * Per-request timeout in ms (default 10s). A hung worker rejects the+ * pending call; the exchange degrades rejected reads to the network.+ */+ requestTimeoutMs?: number;+}++const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;++export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {+ const clientId = crypto.randomUUID();+ const pending = new Map<+ number,+ Pending & { timer: ReturnType<typeof setTimeout> }+ >();+ const affectedSubscribers = new Set<(opKeys: number[]) => void>();+ const requestTimeoutMs =+ options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;+ let nextRequestId = 1;++ const useShared =+ typeof SharedWorker === 'function' && !options.forceDedicatedWorker;++ let post: (msg: CacheRequest) => void;+ let dispose: () => void;++ const onMessage = (event: MessageEvent<WorkerMessage>) => {+ const msg = event.data;+ if (isCachePush(msg)) {+ const prefix = `${clientId}:`;+ const opKeys = msg.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);+ }+ return;+ }+ const entry = pending.get(msg.id);+ if (!entry) return;+ pending.delete(msg.id);+ clearTimeout(entry.timer);+ if (msg.ok) {+ entry.resolve(msg.result);+ } else {+ entry.reject(new Error(msg.error));+ }+ };++ if (useShared) {+ const worker = new SharedWorker(+ new URL('../worker/cache.shared-worker.ts', import.meta.url),+ { type: 'module', name: `graphql-cache:${options.scope}` }+ );+ worker.port.onmessage = onMessage;+ worker.port.start();+ post = (msg) => worker.port.postMessage(msg);+ dispose = () => {+ // Tell the SharedWorker to drop our port — there is no platform+ // disconnect event, and stale ports would otherwise accumulate.+ const notice: CacheNotice = { kind: 'disconnect' };+ worker.port.postMessage(notice);+ worker.port.close();+ };+ } else {+ const worker = new Worker(+ new URL('../worker/cache.worker.ts', import.meta.url),+ { type: 'module', name: `graphql-cache:${options.scope}` }+ );+ worker.onmessage = onMessage;+ post = (msg) => worker.postMessage(msg);+ dispose = () => worker.terminate();+ }++ // Best-effort cleanup when the page goes away (bfcache-safe: a restored+ // page gets a fresh host on next use anyway).+ if (typeof addEventListener === 'function') {+ addEventListener('pagehide', dispose, { once: true });+ }++ function request(+ msg: DistributiveOmit<CacheRequest, 'id'>+ ): Promise<unknown> {+ const id = nextRequestId++;+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ if (pending.delete(id)) {+ reject(new Error(`cache worker timeout: ${msg.kind}`));+ }+ }, requestTimeoutMs);+ pending.set(id, { resolve, reject, timer });+ post({ ...msg, id } as CacheRequest);+ });+ }++ const ready = request({+ kind: '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({+ kind: 'read',+ opId: args.opKey === undefined ? undefined : opId(args.opKey),+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ })) as ReadResult;+ },++ async writeQuery(args: CacheWriteArgs): Promise<WriteResult> {+ await ready;+ return (await request({+ kind: 'write',+ originOpId: args.opKey === undefined ? undefined : opId(args.opKey),+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ data: args.data,+ identity: args.identity,+ })) as WriteResult;+ },++ async invalidate(keys: string[]): Promise<string[]> {+ await ready;+ return (await request({ kind: 'invalidate', keys })) as string[];+ },++ async teardown(opKey: number): Promise<void> {+ await ready;+ await request({ kind: 'teardown', opId: opId(opKey) });+ },++ async clear(): Promise<void> {+ await ready;+ await request({ kind: 'clear' });+ },++ onOpsAffected(cb: (opKeys: number[]) => void): () => void {+ affectedSubscribers.add(cb);+ return () => affectedSubscribers.delete(cb);+ },++ dispose,+ };+}diff --git a/js/app/packages/graphql-cache/index.ts b/js/app/packages/graphql-cache/index.tsnew file mode 100644index 0000000000..c87531bb2a--- /dev/null+++ b/js/app/packages/graphql-cache/index.ts@@ -0,0 +1,19 @@+/**+ * Normalized GraphQL cache — JS glue.+ * Design doc: js/app/docs/graphql-normalized-cache-plan.md+ */++export type {+ CacheHost,+ CacheReadArgs,+ CacheWriteArgs,+} from './host/types';+export { createWorkerCacheHost } from './host/worker-host';+export type {+ CacheBroadcast,+ CachePush,+ CacheRequest,+ CacheResponse,+ ReadResult,+ WriteResult,+} from './protocol';diff --git a/js/app/packages/graphql-cache/protocol.ts b/js/app/packages/graphql-cache/protocol.tsnew file mode 100644index 0000000000..c116f8f0f0--- /dev/null+++ b/js/app/packages/graphql-cache/protocol.ts@@ -0,0 +1,117 @@+/**+ * Wire protocol between page contexts and the cache worker (the `CacheHost`+ * RPC from the design doc, js/app/docs/graphql-normalized-cache-plan.md §4).+ *+ * Topologies:+ * - SharedWorker: one engine, many ports. Invalidations fan out over the+ * ports directly.+ * - Dedicated worker per tab (fallback): one engine per tab over the same+ * IndexedDB database. Writes are serialized with Web Locks; changed keys+ * fan out across tabs via BroadcastChannel, and each tab's worker+ * translates them into locally-affected operation ids.+ *+ * Operation ids are strings of the form `"{clientId}:{urqlOperationKey}"` so+ * one shared engine can track operations from many tabs without collisions.+ */++export type ReadResult = { kind: 'hit'; data: unknown } | { kind: 'miss' };++export type WriteResult = {+ /** Entity keys whose records changed. */+ changed: string[];+ /** Registered operation ids affected by the change (origin excluded). */+ affectedOps: string[];+ /**+ * True when the identity witness observed a different user and the cache+ * silently restarted (wiped + rebound) before this write. `affectedOps`+ * then contains every registered operation except the origin.+ */+ reset: boolean;+};++export type CacheRequest = { id: number } & (+ | { kind: 'init'; scope: string; hotCapacity?: number }+ | {+ kind: 'read';+ opId?: string;+ query: string;+ operationName?: string;+ variables?: Record<string, unknown>;+ }+ | {+ kind: 'write';+ originOpId?: string;+ query: string;+ operationName?: string;+ variables?: Record<string, unknown>;+ data: unknown;+ /**+ * Opaque session tag (e.g. viewer id extracted from the response). A+ * write tagged with a different identity than the cache's bound one+ * wipes and rebinds the cache atomically (silent restart).+ */+ identity?: string;+ }+ | { kind: 'teardown'; opId: string }+ /** External invalidation (e.g. websocket push): evict + report ops. */+ | { kind: 'invalidate'; keys: string[] }+ | { kind: 'clear' }+);++export type CacheResponse =+ | { id: number; ok: true; result: unknown }+ | { id: number; ok: false; error: string };++/**+ * Fire-and-forget notice from a client to the worker (no id/response).+ * `disconnect` lets a SharedWorker drop the sender's port — there is no+ * platform event for client disconnection, so hosts send this on dispose+ * and pagehide.+ */+export type CacheNotice = { kind: 'disconnect' };++export function isCacheNotice(+ msg: CacheRequest | CacheNotice+): msg is CacheNotice {+ return msg.kind === 'disconnect';+}++/**+ * Pushed (not request/response) messages from worker to its client(s):+ * operations whose underlying records changed. The host filters by its own+ * clientId prefix and re-executes.+ */+export type CachePush = {+ kind: 'ops-affected';+ opIds: string[];+ /** Changed entity keys, for diagnostics/advanced consumers. */+ keys: string[];+};++export type WorkerMessage = CacheResponse | CachePush;++/** Cross-tab broadcast (fallback topology), channel `graphql-cache:{scope}`. */+export type CacheBroadcast =+ | {+ kind: 'changed';+ keys: string[];+ /** Random id of the emitting worker, to ignore own broadcasts. */+ source: string;+ }+ | {+ /** The shared storage was wiped (identity change silent restart). */+ kind: 'reset';+ source: string;+ };++export function broadcastChannelName(scope: string): string {+ return `graphql-cache:${scope}`;+}++export function writeLockName(scope: string): string {+ return `graphql-cache:write:${scope}`;+}++export function isCachePush(msg: WorkerMessage): msg is CachePush {+ return 'kind' in msg && msg.kind === 'ops-affected';+}diff --git a/js/app/packages/graphql-cache/scope.ts b/js/app/packages/graphql-cache/scope.tsnew file mode 100644index 0000000000..1c246d1d7c--- /dev/null+++ b/js/app/packages/graphql-cache/scope.ts@@ -0,0 +1,34 @@+/**+ * Cache scope: an anonymous, client-generated uuid naming the local cache+ * storage (IndexedDB database). Deliberately NOT derived from user identity:+ *+ * - construction is synchronous and works offline (no identity waterfall);+ * - no PII leaks into enumerable storage metadata (database names);+ * - user↔cache consistency is enforced *inside* the cache by the identity+ * witness (`QueryRoot.user.id` observed on every write): a response for a+ * different user than the one bound to the cache wipes and rebinds it+ * (silent restart). See the design doc and cache-core `identity_witness`.+ *+ * The uuid is stable for the browser profile; identity changes rotate the+ * cache *contents*, not the scope.+ */++const SCOPE_STORAGE_KEY = 'graphql-cache:scope';++export function getOrCreateCacheScope(): string {+ let scope: string | null = null;+ try {+ scope = localStorage.getItem(SCOPE_STORAGE_KEY);+ } catch {+ // Storage access denied (privacy mode edge cases): session-only scope.+ }+ if (!scope) {+ scope = crypto.randomUUID();+ try {+ localStorage.setItem(SCOPE_STORAGE_KEY, scope);+ } catch {+ // Non-persistent scope is fine; the cache is disposable.+ }+ }+ return scope;+}diff --git a/js/app/packages/graphql-cache/worker/cache.shared-worker.ts b/js/app/packages/graphql-cache/worker/cache.shared-worker.tsnew file mode 100644index 0000000000..f99bcfe0a1--- /dev/null+++ b/js/app/packages/graphql-cache/worker/cache.shared-worker.ts@@ -0,0 +1,31 @@+/**+ * SharedWorker entry: one engine shared by every tab (preferred topology).+ */++import {+ type CacheNotice,+ type CacheRequest,+ isCacheNotice,+} from '../protocol';+import { CacheWorkerCore } from './worker-core';++declare const self: SharedWorkerGlobalScope;++const core = new CacheWorkerCore({ multiEngine: false });++self.onconnect = (event: MessageEvent) => {+ const port = event.ports[0];+ if (!port) return;+ core.addPort(port);+ port.onmessage = (msg: MessageEvent<CacheRequest | CacheNotice>) => {+ // Clients announce disconnection (dispose/pagehide) — there is no+ // platform event for it, and unpruned ports would accumulate.+ if (isCacheNotice(msg.data)) {+ core.removePort(port);+ port.close();+ return;+ }+ void core.handleRequest(port, msg.data);+ };+ port.start();+};diff --git a/js/app/packages/graphql-cache/worker/cache.worker.ts b/js/app/packages/graphql-cache/worker/cache.worker.tsnew file mode 100644index 0000000000..a9f1025a9d--- /dev/null+++ b/js/app/packages/graphql-cache/worker/cache.worker.ts@@ -0,0 +1,18 @@+/**+ * Dedicated-worker entry: fallback topology when SharedWorker is+ * unavailable. One engine per tab over the shared IndexedDB database;+ * writes serialized via Web Locks; cross-tab invalidation over+ * BroadcastChannel (handled inside CacheWorkerCore).+ */++import type { CacheRequest } from '../protocol';+import { CacheWorkerCore } from './worker-core';++declare const self: DedicatedWorkerGlobalScope;++const core = new CacheWorkerCore({ multiEngine: true });+core.addPort(self);++self.onmessage = (msg: MessageEvent<CacheRequest>) => {+ void core.handleRequest(self, msg.data);+};diff --git a/js/app/packages/graphql-cache/worker/wasm-module.ts b/js/app/packages/graphql-cache/worker/wasm-module.tsnew file mode 100644index 0000000000..f82e65e553--- /dev/null+++ b/js/app/packages/graphql-cache/worker/wasm-module.ts@@ -0,0 +1,61 @@+/**+ * Typed surface of the generated wasm package (`cache-wasm`), loaded+ * dynamically so the repo type-checks without the generated artifacts.+ *+ * Build the package with:+ * just build-cache-wasm+ * which runs wasm-pack over rust/cloud-storage/client/cache-wasm into+ * packages/graphql-cache/wasm/ (gitignored).+ */++import type { ReadResult, WriteResult } from '../protocol';++export interface CacheEngine {+ readQuery(+ opId: string | undefined,+ query: string,+ operationName: string | undefined,+ variables: Record<string, unknown> | undefined+ ): Promise<ReadResult>;+ writeQuery(+ originOpId: string | undefined,+ query: string,+ operationName: string | undefined,+ variables: Record<string, unknown> | undefined,+ data: unknown,+ identity: string | undefined+ ): Promise<WriteResult>;+ invalidateKeys(keys: string[]): Promise<string[]>;+ externalReset(): Promise<string[]>;+ teardownOperation(opId: string): Promise<void>;+ clear(): Promise<void>;+ /** Close the IndexedDB connection; call before destroyCache. */+ close(): Promise<void>;+}++export interface CacheWasmModule {+ default: (input?: { module_or_path?: unknown }) => Promise<unknown>;+ openCache(scope: string, hotCapacity?: number): Promise<CacheEngine>;+ destroyCache(scope: string): Promise<void>;+ schemaHash(): string;+}++let modulePromise: Promise<CacheWasmModule> | undefined;++/** Loads and initializes the wasm module exactly once per worker context. */+export function loadCacheWasm(): Promise<CacheWasmModule> {+ if (!modulePromise) {+ modulePromise = (async () => {+ const url = new URL('../wasm/cache_wasm.js', import.meta.url).href;+ const mod = (await import(/* @vite-ignore */ url)) as CacheWasmModule;+ // Resolve the wasm binary explicitly: vite copies the generated JS as+ // an opaque asset, so its internal relative `cache_wasm_bg.wasm` URL+ // would 404 in production. This `new URL` pattern is statically+ // analyzable, so vite emits the binary as an asset and rewrites it.+ const wasmUrl = new URL('../wasm/cache_wasm_bg.wasm', import.meta.url);+ await mod.default({ module_or_path: wasmUrl });+ return mod;+ })();+ }+ return modulePromise;+}diff --git a/js/app/packages/graphql-cache/worker/worker-core.ts b/js/app/packages/graphql-cache/worker/worker-core.tsnew file mode 100644index 0000000000..9910680a70--- /dev/null+++ b/js/app/packages/graphql-cache/worker/worker-core.ts@@ -0,0 +1,203 @@+/**+ * Topology-agnostic worker core: owns the wasm engine, serves the RPC+ * protocol on one or more ports, and fans out invalidations.+ *+ * Used by both entries:+ * - cache.shared-worker.ts (SharedWorker, many ports, one engine)+ * - cache.worker.ts (dedicated worker per tab + BroadcastChannel + Web Locks)+ */++import {+ broadcastChannelName,+ type CacheBroadcast,+ type CachePush,+ type CacheRequest,+ type CacheResponse,+ type ReadResult,+ type WriteResult,+ writeLockName,+} from '../protocol';+import { type CacheEngine, loadCacheWasm } from './wasm-module';++type PortLike = {+ postMessage(msg: unknown): void;+};++export class CacheWorkerCore {+ private engine: CacheEngine | undefined;+ private initPromise: Promise<void> | undefined;+ private scope: string | undefined;+ /** Serializes engine calls (defense in depth; the engine also locks). */+ private queue: Promise<unknown> = Promise.resolve();+ private readonly ports = new Set<PortLike>();+ private broadcast: BroadcastChannel | undefined;+ private readonly workerId = crypto.randomUUID();++ constructor(+ private readonly options: {+ /**+ * Fallback topology (dedicated worker per tab): serialize writes via+ * Web Locks and exchange changed keys over BroadcastChannel.+ */+ multiEngine: boolean;+ }+ ) {}++ addPort(port: PortLike): void {+ this.ports.add(port);+ }++ removePort(port: PortLike): void {+ this.ports.delete(port);+ }++ async handleRequest(port: PortLike, request: CacheRequest): Promise<void> {+ const respond = (response: CacheResponse) => port.postMessage(response);+ try {+ const result = await this.enqueue(() => this.dispatch(request));+ respond({ id: request.id, ok: true, result });+ } catch (error) {+ respond({+ id: request.id,+ ok: false,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ private enqueue<T>(task: () => Promise<T>): Promise<T> {+ const next = this.queue.then(task, task);+ this.queue = next.catch(() => undefined);+ return next;+ }++ private async dispatch(request: CacheRequest): Promise<unknown> {+ switch (request.kind) {+ case 'init': {+ await this.init(request.scope, request.hotCapacity);+ return null;+ }+ case 'read': {+ const engine = this.requireEngine();+ const result: ReadResult = await engine.readQuery(+ request.opId,+ request.query,+ request.operationName,+ request.variables+ );+ return result;+ }+ case 'write': {+ const engine = this.requireEngine();+ const write = async (): Promise<WriteResult> =>+ await engine.writeQuery(+ request.originOpId,+ request.query,+ request.operationName,+ request.variables,+ request.data,+ request.identity+ );+ const result =+ this.options.multiEngine && this.scope+ ? await navigator.locks.request(writeLockName(this.scope), write)+ : await write();+ this.fanOut(result);+ return result;+ }+ case 'invalidate': {+ const engine = this.requireEngine();+ const affectedOps = await engine.invalidateKeys(request.keys);+ this.fanOut({ changed: request.keys, affectedOps, reset: false });+ return affectedOps;+ }+ case 'teardown': {+ await this.requireEngine().teardownOperation(request.opId);+ return null;+ }+ case 'clear': {+ await this.requireEngine().clear();+ return null;+ }+ default: {+ // Compile-time exhaustiveness: a new request kind fails here.+ return request satisfies never;+ }+ }+ }++ private async init(scope: string, hotCapacity?: number): Promise<void> {+ if (this.initPromise) {+ // Subsequent tabs connecting to the SharedWorker re-init idempotently.+ await this.initPromise;+ if (this.scope !== scope) {+ throw new Error(+ `cache worker already initialized for scope ${this.scope}, got ${scope}`+ );+ }+ return;+ }+ this.scope = scope;+ this.initPromise = (async () => {+ const wasm = await loadCacheWasm();+ this.engine = await wasm.openCache(scope, hotCapacity);+ if (this.options.multiEngine) {+ this.broadcast = new BroadcastChannel(broadcastChannelName(scope));+ this.broadcast.onmessage = (event: MessageEvent<CacheBroadcast>) => {+ void this.onBroadcast(event.data);+ };+ }+ })();+ await this.initPromise;+ }++ /** Broadcasts from other tabs' engines sharing our storage. */+ private async onBroadcast(msg: CacheBroadcast): Promise<void> {+ if (msg.source === this.workerId) return;+ const engine = this.engine;+ if (!engine) return;+ if (msg.kind === 'reset') {+ // Another engine wiped the shared storage (identity change): drop+ // local in-memory state and re-execute everything we track.+ const affectedOps = await this.enqueue(() => engine.externalReset());+ this.push({ kind: 'ops-affected', opIds: affectedOps, keys: [] });+ return;+ }+ const affectedOps = await this.enqueue(() =>+ engine.invalidateKeys(msg.keys)+ );+ this.push({ kind: 'ops-affected', opIds: affectedOps, keys: msg.keys });+ }++ /** After a local change: notify connected clients + other tabs. */+ private fanOut(result: WriteResult): void {+ if (result.changed.length === 0 && !result.reset) return;+ if (result.affectedOps.length > 0) {+ this.push({+ kind: 'ops-affected',+ opIds: result.affectedOps,+ keys: result.changed,+ });+ }+ if (this.options.multiEngine && this.broadcast) {+ const msg: CacheBroadcast = result.reset+ ? { kind: 'reset', source: this.workerId }+ : { kind: 'changed', keys: result.changed, source: this.workerId };+ this.broadcast.postMessage(msg);+ }+ }++ private push(msg: CachePush): void {+ if (msg.opIds.length === 0) return;+ for (const port of this.ports) {+ port.postMessage(msg);+ }+ }++ private requireEngine(): CacheEngine {+ if (!this.engine) {+ throw new Error('cache worker not initialized (send init first)');+ }+ return this.engine;+ }+}diff --git a/js/app/packages/service-clients/service-storage/graphql-soup.ts b/js/app/packages/service-clients/service-storage/graphql-soup.tsindex bf77c1c484..f6c5c7bf76 100644--- a/js/app/packages/service-clients/service-storage/graphql-soup.ts+++ b/js/app/packages/service-clients/service-storage/graphql-soup.ts@@ -1,9 +1,16 @@-import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';+import {+ ENABLE_BEARER_TOKEN_AUTH,+ ENABLE_GRAPHQL_SOUP,+} from '@core/constant/featureFlags';import { SERVER_HOSTS } from '@core/constant/servers';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 { getOrCreateCacheScope } from '@graphql-cache/scope';import { getMacroApiToken } from '@service-auth/fetch';-import { createClient, fetchExchange } from '@urql/core';+import { type Client, createClient, fetchExchange } from '@urql/core';import { match } from 'ts-pattern';import type { SoupApiItem, SoupPage } from './generated/schemas';import {@@ -57,9 +64,54 @@ const graphqlSoupClient = createClient({fetch: dssGraphqlFetch,});+/**+ * Whether the normalized wasm cache is active for soup GraphQL queries.+ * Browser only for now — Tauri will use a native host (see design doc).+ */+function graphqlCacheEnabled(): boolean {+ return ENABLE_GRAPHQL_SOUP() && !isTauri();+}++let cachedClient: Client | undefined;++/**+ * Resolves the urql client, lazily assembling the cached client on first+ * use. The cache scope is an anonymous client uuid — no identity lookup is+ * needed (or wanted) here: user↔cache consistency is enforced inside the+ * engine by the identity witness on `QueryRoot.user.id` (a response for a+ * different user wipes and rebinds the cache). See @graphql-cache/scope.+ * Any failure falls back to the plain fetch client for the session.+ */+function getGraphqlSoupClient(): Client {+ if (!graphqlCacheEnabled()) return graphqlSoupClient;+ cachedClient ??= (() => {+ try {+ const host = createWorkerCacheHost({ scope: getOrCreateCacheScope() });+ return createClient({+ url: `${dssHost}/items/soup/graphql`,+ exchanges: [+ normalizedCacheExchange(host, {+ // Session identity witness: the viewer id present on every soup+ // response. A response for a different user silently wipes and+ // rebinds the cache (see @graphql-cache/scope).+ extractIdentity: (data) =>+ (data as Partial<SoupQuery> | undefined)?.user?.id,+ }),+ fetchExchange,+ ],+ fetch: dssGraphqlFetch,+ });+ } catch (error) {+ console.warn('graphql cache init failed; using uncached client', error);+ return graphqlSoupClient;+ }+ })();+ return cachedClient;+}+export type GraphqlSoupInput = SoupInput;-type GraphqlSoupItem = SoupQuery['soup']['items'][number];+type GraphqlSoupItem = SoupQuery['user']['soup']['items'][number];type GraphqlSoupEntity = GraphqlSoupItem['entity'];type GraphqlSoupProperty = Extract<GraphqlSoupEntity,@@ -139,7 +191,7 @@ function mapGraphqlPropertyValue(function mapGraphqlProperties(properties: GraphqlSoupProperty[]) {return properties.map((property) => ({definition: {- id: property.id,+ id: property.propertyDefinitionId,display_name: property.displayName,data_type: property.dataType,is_multi_select: property.isMultiSelect,@@ -172,7 +224,7 @@ function mapChannelMessage() {if (!message) return message;return {- message_id: message.messageId,+ message_id: message.id,thread_id: message.threadId ?? undefined,sender_id: message.senderId,content: message.content,@@ -456,11 +508,38 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {export async function fetchGraphqlSoup(input: GraphqlSoupInput): Promise<SoupPage> {- const result = await graphqlSoupClient- .query<SoupQuery, SoupQueryVariables>(SoupQueryDocument, { input })+ const client = getGraphqlSoupClient();+ const useCache = graphqlCacheEnabled();++ // `cache-and-network` writes responses through the normalized cache;+ // `.toPromise()` skips the stale cache emission, so callers keep+ // network-fresh semantics. Reactive urql consumers will see the+ // stale-then-fresh stream once components migrate.+ const result = await client+ .query<SoupQuery, SoupQueryVariables>(+ SoupQueryDocument,+ { input },+ useCache ? { requestPolicy: 'cache-and-network' } : {}+ ).toPromise();if (result.error) {+ // Offline replay: a network failure falls back to the last cached page.+ if (useCache && result.error.networkError) {+ const cached = await client+ .query<SoupQuery, SoupQueryVariables>(+ SoupQueryDocument,+ { input },+ { requestPolicy: 'cache-only' }+ )+ .toPromise();+ if (cached.data) {+ return {+ items: cached.data.user.soup.items.map(mapGraphqlSoupItem),+ next_cursor: cached.data.user.soup.nextCursor ?? undefined,+ };+ }+ }throw result.error;}@@ -470,7 +549,7 @@ export async function fetchGraphqlSoup(}return {- items: data.soup.items.map(mapGraphqlSoupItem),- next_cursor: data.soup.nextCursor ?? undefined,+ items: data.user.soup.items.map(mapGraphqlSoupItem),+ next_cursor: data.user.soup.nextCursor ?? undefined,};}diff --git a/js/app/packages/service-clients/service-storage/graphql/generated/graphql.ts b/js/app/packages/service-clients/service-storage/graphql/generated/graphql.tsindex 68fa067758..882c7cf614 100644--- a/js/app/packages/service-clients/service-storage/graphql/generated/graphql.ts+++ b/js/app/packages/service-clients/service-storage/graphql/generated/graphql.ts@@ -1,12 +1,7 @@/** Internal type. DO NOT USE DIRECTLY. */type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };/** Internal type. DO NOT USE DIRECTLY. */-export type Incremental<T> =- | T- | {- [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never;- };-+export type Incremental<T> = T | { [P in keyof T]?: P extends ' $fragmentName' | '__typename' ? T[P] : never };import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';export type GraphqlCallBinaryExpr = {left: GraphqlCallExpr;@@ -14,49 +9,22 @@ export type GraphqlCallBinaryExpr = {};export type GraphqlCallExpr =- | { and: GraphqlCallBinaryExpr; literal?: never; not?: never; or?: never }- | { and?: never; literal: GraphqlCallLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlCallExpr; or?: never }- | { and?: never; literal?: never; not?: never; or: GraphqlCallBinaryExpr };+ { and: GraphqlCallBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlCallLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlCallExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlCallBinaryExpr; };export type GraphqlCallLiteral =- | {- attended: boolean;- callId?: never;- channelId?: never;- speaker?: never;- status?: never;- }- | {- attended?: never;- callId: string | number;- channelId?: never;- speaker?: never;- status?: never;- }- | {- attended?: never;- callId?: never;- channelId: string | number;- speaker?: never;- status?: never;- }- | {- attended?: never;- callId?: never;- channelId?: never;- speaker: string;- status?: never;- }- | {- attended?: never;- callId?: never;- channelId?: never;- speaker?: never;- status: GraphqlCallStatus;- };+ { attended: boolean; callId?: never; channelId?: never; speaker?: never; status?: never; }+ | { attended?: never; callId: string | number; channelId?: never; speaker?: never; status?: never; }+ | { attended?: never; callId?: never; channelId: string | number; speaker?: never; status?: never; }+ | { attended?: never; callId?: never; channelId?: never; speaker: string; status?: never; }+ | { attended?: never; callId?: never; channelId?: never; speaker?: never; status: GraphqlCallStatus; };-export type GraphqlCallStatus = 'ATTENDED' | 'MISSED' | 'UNATTENDED';+export type GraphqlCallStatus =+ | 'ATTENDED'+ | 'MISSED'+ | 'UNATTENDED';export type GraphqlChannelBinaryExpr = {left: GraphqlChannelExpr;@@ -64,132 +32,22 @@ export type GraphqlChannelBinaryExpr = {};export type GraphqlChannelExpr =- | { and: GraphqlChannelBinaryExpr; literal?: never; not?: never; or?: never }- | { and?: never; literal: GraphqlChannelLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlChannelExpr; or?: never }- | { and?: never; literal?: never; not?: never; or: GraphqlChannelBinaryExpr };+ { and: GraphqlChannelBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlChannelLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlChannelExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlChannelBinaryExpr; };export type GraphqlChannelLiteral =- | {- channelId: string | number;- channelType?: never;- importance?: never;- mention?: never;- notificationDone?: never;- notificationSeen?: never;- organizationId?: never;- sender?: never;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType: GraphqlChannelTypeFilter;- importance?: never;- mention?: never;- notificationDone?: never;- notificationSeen?: never;- organizationId?: never;- sender?: never;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance: boolean;- mention?: never;- notificationDone?: never;- notificationSeen?: never;- organizationId?: never;- sender?: never;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance?: never;- mention: string;- notificationDone?: never;- notificationSeen?: never;- organizationId?: never;- sender?: never;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance?: never;- mention?: never;- notificationDone: boolean;- notificationSeen?: never;- organizationId?: never;- sender?: never;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance?: never;- mention?: never;- notificationDone?: never;- notificationSeen: boolean;- organizationId?: never;- sender?: never;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance?: never;- mention?: never;- notificationDone?: never;- notificationSeen?: never;- organizationId: number;- sender?: never;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance?: never;- mention?: never;- notificationDone?: never;- notificationSeen?: never;- organizationId?: never;- sender: string;- teamId?: never;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance?: never;- mention?: never;- notificationDone?: never;- notificationSeen?: never;- organizationId?: never;- sender?: never;- teamId: string | number;- threadId?: never;- }- | {- channelId?: never;- channelType?: never;- importance?: never;- mention?: never;- notificationDone?: never;- notificationSeen?: never;- organizationId?: never;- sender?: never;- teamId?: never;- threadId: string | number;- };+ { channelId: string | number; channelType?: never; importance?: never; mention?: never; notificationDone?: never; notificationSeen?: never; organizationId?: never; sender?: never; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType: GraphqlChannelTypeFilter; importance?: never; mention?: never; notificationDone?: never; notificationSeen?: never; organizationId?: never; sender?: never; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType?: never; importance: boolean; mention?: never; notificationDone?: never; notificationSeen?: never; organizationId?: never; sender?: never; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType?: never; importance?: never; mention: string; notificationDone?: never; notificationSeen?: never; organizationId?: never; sender?: never; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType?: never; importance?: never; mention?: never; notificationDone: boolean; notificationSeen?: never; organizationId?: never; sender?: never; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType?: never; importance?: never; mention?: never; notificationDone?: never; notificationSeen: boolean; organizationId?: never; sender?: never; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType?: never; importance?: never; mention?: never; notificationDone?: never; notificationSeen?: never; organizationId: number; sender?: never; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType?: never; importance?: never; mention?: never; notificationDone?: never; notificationSeen?: never; organizationId?: never; sender: string; teamId?: never; threadId?: never; }+ | { channelId?: never; channelType?: never; importance?: never; mention?: never; notificationDone?: never; notificationSeen?: never; organizationId?: never; sender?: never; teamId: string | number; threadId?: never; }+ | { channelId?: never; channelType?: never; importance?: never; mention?: never; notificationDone?: never; notificationSeen?: never; organizationId?: never; sender?: never; teamId?: never; threadId: string | number; };export type GraphqlChannelThreadBinaryExpr = {left: GraphqlChannelThreadExpr;@@ -197,75 +55,18 @@ export type GraphqlChannelThreadBinaryExpr = {};export type GraphqlChannelThreadExpr =- | {- and: GraphqlChannelThreadBinaryExpr;- literal?: never;- not?: never;- or?: never;- }- | {- and?: never;- literal: GraphqlChannelThreadLiteral;- not?: never;- or?: never;- }- | { and?: never; literal?: never; not: GraphqlChannelThreadExpr; or?: never }- | {- and?: never;- literal?: never;- not?: never;- or: GraphqlChannelThreadBinaryExpr;- };+ { and: GraphqlChannelThreadBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlChannelThreadLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlChannelThreadExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlChannelThreadBinaryExpr; };export type GraphqlChannelThreadLiteral =- | {- channelId: string | number;- notificationDone?: never;- notificationSeen?: never;- participant?: never;- rootSender?: never;- threadId?: never;- }- | {- channelId?: never;- notificationDone: boolean;- notificationSeen?: never;- participant?: never;- rootSender?: never;- threadId?: never;- }- | {- channelId?: never;- notificationDone?: never;- notificationSeen: boolean;- participant?: never;- rootSender?: never;- threadId?: never;- }- | {- channelId?: never;- notificationDone?: never;- notificationSeen?: never;- participant: string;- rootSender?: never;- threadId?: never;- }- | {- channelId?: never;- notificationDone?: never;- notificationSeen?: never;- participant?: never;- rootSender: string;- threadId?: never;- }- | {- channelId?: never;- notificationDone?: never;- notificationSeen?: never;- participant?: never;- rootSender?: never;- threadId: string | number;- };+ { channelId: string | number; notificationDone?: never; notificationSeen?: never; participant?: never; rootSender?: never; threadId?: never; }+ | { channelId?: never; notificationDone: boolean; notificationSeen?: never; participant?: never; rootSender?: never; threadId?: never; }+ | { channelId?: never; notificationDone?: never; notificationSeen: boolean; participant?: never; rootSender?: never; threadId?: never; }+ | { channelId?: never; notificationDone?: never; notificationSeen?: never; participant: string; rootSender?: never; threadId?: never; }+ | { channelId?: never; notificationDone?: never; notificationSeen?: never; participant?: never; rootSender: string; threadId?: never; }+ | { channelId?: never; notificationDone?: never; notificationSeen?: never; participant?: never; rootSender?: never; threadId: string | number; };export type GraphqlChannelTypeFilter =| 'DIRECT_MESSAGE'@@ -279,113 +80,26 @@ export type GraphqlChatBinaryExpr = {};export type GraphqlChatExpr =- | { and: GraphqlChatBinaryExpr; literal?: never; not?: never; or?: never }- | { and?: never; literal: GraphqlChatLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlChatExpr; or?: never }- | { and?: never; literal?: never; not?: never; or: GraphqlChatBinaryExpr };+ { and: GraphqlChatBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlChatLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlChatExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlChatBinaryExpr; };export type GraphqlChatLiteral =- | {- chatId: string | number;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- role?: never;- updatedAt?: never;- }- | {- chatId?: never;- createdAt: GraphqlDateLiteral;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- role?: never;- updatedAt?: never;- }- | {- chatId?: never;- createdAt?: never;- importance: boolean;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- role?: never;- updatedAt?: never;- }- | {- chatId?: never;- createdAt?: never;- importance?: never;- notificationDone: boolean;- notificationSeen?: never;- owner?: never;- projectId?: never;- role?: never;- updatedAt?: never;- }- | {- chatId?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen: boolean;- owner?: never;- projectId?: never;- role?: never;- updatedAt?: never;- }- | {- chatId?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner: string;- projectId?: never;- role?: never;- updatedAt?: never;- }- | {- chatId?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId: string | number;- role?: never;- updatedAt?: never;- }- | {- chatId?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- role: GraphqlChatRole;- updatedAt?: never;- }- | {- chatId?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- role?: never;- updatedAt: GraphqlDateLiteral;- };--export type GraphqlChatRole = 'ASSISTANT' | 'SYSTEM' | 'USER';+ { chatId: string | number; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; role?: never; updatedAt?: never; }+ | { chatId?: never; createdAt: GraphqlDateLiteral; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; role?: never; updatedAt?: never; }+ | { chatId?: never; createdAt?: never; importance: boolean; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; role?: never; updatedAt?: never; }+ | { chatId?: never; createdAt?: never; importance?: never; notificationDone: boolean; notificationSeen?: never; owner?: never; projectId?: never; role?: never; updatedAt?: never; }+ | { chatId?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen: boolean; owner?: never; projectId?: never; role?: never; updatedAt?: never; }+ | { chatId?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner: string; projectId?: never; role?: never; updatedAt?: never; }+ | { chatId?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId: string | number; role?: never; updatedAt?: never; }+ | { chatId?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; role: GraphqlChatRole; updatedAt?: never; }+ | { chatId?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; role?: never; updatedAt: GraphqlDateLiteral; };++export type GraphqlChatRole =+ | 'ASSISTANT'+ | 'SYSTEM'+ | 'USER';export type GraphqlCrmCompanyBinaryExpr = {left: GraphqlCrmCompanyExpr;@@ -393,34 +107,24 @@ export type GraphqlCrmCompanyBinaryExpr = {};export type GraphqlCrmCompanyExpr =- | {- and: GraphqlCrmCompanyBinaryExpr;- literal?: never;- not?: never;- or?: never;- }- | { and?: never; literal: GraphqlCrmCompanyLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlCrmCompanyExpr; or?: never }- | {- and?: never;- literal?: never;- not?: never;- or: GraphqlCrmCompanyBinaryExpr;- };+ { and: GraphqlCrmCompanyBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlCrmCompanyLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlCrmCompanyExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlCrmCompanyBinaryExpr; };export type GraphqlCrmCompanyLiteral =- | { hidden: boolean; id?: never }- | { hidden?: never; id: string | number };+ { hidden: boolean; id?: never; }+ | { hidden?: never; id: string | number; };export type GraphqlCrmScope =- | { addresses: Array<string>; domains?: never }- | { addresses?: never; domains: Array<string> };+ { addresses: Array<string>; domains?: never; }+ | { addresses?: never; domains: Array<string>; };export type GraphqlDateLiteral =- | { gt: string; gte?: never; lt?: never; lte?: never }- | { gt?: never; gte: string; lt?: never; lte?: never }- | { gt?: never; gte?: never; lt: string; lte?: never }- | { gt?: never; gte?: never; lt?: never; lte: string };+ { gt: string; gte?: never; lt?: never; lte?: never; }+ | { gt?: never; gte: string; lt?: never; lte?: never; }+ | { gt?: never; gte?: never; lt: string; lte?: never; }+ | { gt?: never; gte?: never; lt?: never; lte: string; };export type GraphqlDocumentBinaryExpr = {left: GraphqlDocumentExpr;@@ -428,214 +132,29 @@ export type GraphqlDocumentBinaryExpr = {};export type GraphqlDocumentExpr =- | { and: GraphqlDocumentBinaryExpr; literal?: never; not?: never; or?: never }- | { and?: never; literal: GraphqlDocumentLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlDocumentExpr; or?: never }- | {- and?: never;- literal?: never;- not?: never;- or: GraphqlDocumentBinaryExpr;- };+ { and: GraphqlDocumentBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlDocumentLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlDocumentExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlDocumentBinaryExpr; };export type GraphqlDocumentLiteral =- | {- createdAt: GraphqlDateLiteral;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc: string;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType: string;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id: string | number;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance: boolean;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc: boolean;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment: boolean;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone: boolean;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen: boolean;- owner?: never;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner: string;- projectId?: never;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId: string | number;- subType?: never;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType: GraphqlDocumentSubType;- updatedAt?: never;- }- | {- createdAt?: never;- fileAssoc?: never;- fileType?: never;- id?: never;- importance?: never;- includeCbmAtmNc?: never;- isEmailAttachment?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- subType?: never;- updatedAt: GraphqlDateLiteral;- };--export type GraphqlDocumentSubType = 'SNIPPET' | 'TASK';+ { createdAt: GraphqlDateLiteral; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc: string; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType: string; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id: string | number; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance: boolean; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc: boolean; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment: boolean; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone: boolean; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen: boolean; owner?: never; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner: string; projectId?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId: string | number; subType?: never; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType: GraphqlDocumentSubType; updatedAt?: never; }+ | { createdAt?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; subType?: never; updatedAt: GraphqlDateLiteral; };++export type GraphqlDocumentSubType =+ | 'SNIPPET'+ | 'TASK';export type GraphqlEmailBinaryExpr = {left: GraphqlEmailExpr;@@ -643,10 +162,10 @@ export type GraphqlEmailBinaryExpr = {};export type GraphqlEmailExpr =- | { and: GraphqlEmailBinaryExpr; literal?: never; not?: never; or?: never }- | { and?: never; literal: GraphqlEmailLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlEmailExpr; or?: never }- | { and?: never; literal?: never; not?: never; or: GraphqlEmailBinaryExpr };+ { and: GraphqlEmailBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlEmailLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlEmailExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlEmailBinaryExpr; };export type GraphqlEmailFilterAst = {crmScope?: GraphqlCrmScope | null | undefined;@@ -654,235 +173,25 @@ export type GraphqlEmailFilterAst = {};export type GraphqlEmailLiteral =- | {- bcc: GraphqlEmailValue;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly: boolean;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc: GraphqlEmailValue;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt: GraphqlDateLiteral;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance: boolean;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone: boolean;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen: boolean;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner: string | number;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId: string;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient: GraphqlEmailValue;- sender?: never;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender: GraphqlEmailValue;- shared?: never;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared: GraphqlSharedEmailFilter;- threadId?: never;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId: string | number;- updatedAt?: never;- }- | {- bcc?: never;- calendarOnly?: never;- cc?: never;- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- recipient?: never;- sender?: never;- shared?: never;- threadId?: never;- updatedAt: GraphqlDateLiteral;- };+ { bcc: GraphqlEmailValue; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly: boolean; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc: GraphqlEmailValue; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt: GraphqlDateLiteral; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance: boolean; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone: boolean; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen: boolean; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner: string | number; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId: string; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient: GraphqlEmailValue; sender?: never; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender: GraphqlEmailValue; shared?: never; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared: GraphqlSharedEmailFilter; threadId?: never; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId: string | number; updatedAt?: never; }+ | { bcc?: never; calendarOnly?: never; cc?: never; createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; recipient?: never; sender?: never; shared?: never; threadId?: never; updatedAt: GraphqlDateLiteral; };export type GraphqlEmailValue =- | { complete: string; domain?: never; partial?: never }- | { complete?: never; domain: string; partial?: never }- | { complete?: never; domain?: never; partial: string };+ { complete: string; domain?: never; partial?: never; }+ | { complete?: never; domain: string; partial?: never; }+ | { complete?: never; domain?: never; partial: string; };export type GraphqlEmailView =| 'ALL'@@ -913,75 +222,18 @@ export type GraphqlForeignEntityBinaryExpr = {};export type GraphqlForeignEntityExpr =- | {- and: GraphqlForeignEntityBinaryExpr;- literal?: never;- not?: never;- or?: never;- }- | {- and?: never;- literal: GraphqlForeignEntityLiteral;- not?: never;- or?: never;- }- | { and?: never; literal?: never; not: GraphqlForeignEntityExpr; or?: never }- | {- and?: never;- literal?: never;- not?: never;- or: GraphqlForeignEntityBinaryExpr;- };+ { and: GraphqlForeignEntityBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlForeignEntityLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlForeignEntityExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlForeignEntityBinaryExpr; };export type GraphqlForeignEntityLiteral =- | {- foreignEntityId: string;- foreignEntitySource?: never;- id?: never;- includesMe?: never;- notificationDone?: never;- notificationSeen?: never;- }- | {- foreignEntityId?: never;- foreignEntitySource: string;- id?: never;- includesMe?: never;- notificationDone?: never;- notificationSeen?: never;- }- | {- foreignEntityId?: never;- foreignEntitySource?: never;- id: string | number;- includesMe?: never;- notificationDone?: never;- notificationSeen?: never;- }- | {- foreignEntityId?: never;- foreignEntitySource?: never;- id?: never;- includesMe: boolean;- notificationDone?: never;- notificationSeen?: never;- }- | {- foreignEntityId?: never;- foreignEntitySource?: never;- id?: never;- includesMe?: never;- notificationDone: boolean;- notificationSeen?: never;- }- | {- foreignEntityId?: never;- foreignEntitySource?: never;- id?: never;- includesMe?: never;- notificationDone?: never;- notificationSeen: boolean;- };+ { foreignEntityId: string; foreignEntitySource?: never; id?: never; includesMe?: never; notificationDone?: never; notificationSeen?: never; }+ | { foreignEntityId?: never; foreignEntitySource: string; id?: never; includesMe?: never; notificationDone?: never; notificationSeen?: never; }+ | { foreignEntityId?: never; foreignEntitySource?: never; id: string | number; includesMe?: never; notificationDone?: never; notificationSeen?: never; }+ | { foreignEntityId?: never; foreignEntitySource?: never; id?: never; includesMe: boolean; notificationDone?: never; notificationSeen?: never; }+ | { foreignEntityId?: never; foreignEntitySource?: never; id?: never; includesMe?: never; notificationDone: boolean; notificationSeen?: never; }+ | { foreignEntityId?: never; foreignEntitySource?: never; id?: never; includesMe?: never; notificationDone?: never; notificationSeen: boolean; };export type GraphqlProjectBinaryExpr = {left: GraphqlProjectExpr;@@ -989,92 +241,20 @@ export type GraphqlProjectBinaryExpr = {};export type GraphqlProjectExpr =- | { and: GraphqlProjectBinaryExpr; literal?: never; not?: never; or?: never }- | { and?: never; literal: GraphqlProjectLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlProjectExpr; or?: never }- | { and?: never; literal?: never; not?: never; or: GraphqlProjectBinaryExpr };+ { and: GraphqlProjectBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlProjectLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlProjectExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlProjectBinaryExpr; };export type GraphqlProjectLiteral =- | {- createdAt: GraphqlDateLiteral;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- projectIdSelf?: never;- updatedAt?: never;- }- | {- createdAt?: never;- importance: boolean;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- projectIdSelf?: never;- updatedAt?: never;- }- | {- createdAt?: never;- importance?: never;- notificationDone: boolean;- notificationSeen?: never;- owner?: never;- projectId?: never;- projectIdSelf?: never;- updatedAt?: never;- }- | {- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen: boolean;- owner?: never;- projectId?: never;- projectIdSelf?: never;- updatedAt?: never;- }- | {- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner: string;- projectId?: never;- projectIdSelf?: never;- updatedAt?: never;- }- | {- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId: string | number;- projectIdSelf?: never;- updatedAt?: never;- }- | {- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- projectIdSelf: string | number;- updatedAt?: never;- }- | {- createdAt?: never;- importance?: never;- notificationDone?: never;- notificationSeen?: never;- owner?: never;- projectId?: never;- projectIdSelf?: never;- updatedAt: GraphqlDateLiteral;- };+ { createdAt: GraphqlDateLiteral; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; projectIdSelf?: never; updatedAt?: never; }+ | { createdAt?: never; importance: boolean; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; projectIdSelf?: never; updatedAt?: never; }+ | { createdAt?: never; importance?: never; notificationDone: boolean; notificationSeen?: never; owner?: never; projectId?: never; projectIdSelf?: never; updatedAt?: never; }+ | { createdAt?: never; importance?: never; notificationDone?: never; notificationSeen: boolean; owner?: never; projectId?: never; projectIdSelf?: never; updatedAt?: never; }+ | { createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner: string; projectId?: never; projectIdSelf?: never; updatedAt?: never; }+ | { createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId: string | number; projectIdSelf?: never; updatedAt?: never; }+ | { createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; projectIdSelf: string | number; updatedAt?: never; }+ | { createdAt?: never; importance?: never; notificationDone?: never; notificationSeen?: never; owner?: never; projectId?: never; projectIdSelf?: never; updatedAt: GraphqlDateLiteral; };export type GraphqlPropertiesBinaryExpr = {left: GraphqlPropertiesExpr;@@ -1082,20 +262,10 @@ export type GraphqlPropertiesBinaryExpr = {};export type GraphqlPropertiesExpr =- | {- and: GraphqlPropertiesBinaryExpr;- literal?: never;- not?: never;- or?: never;- }- | { and?: never; literal: GraphqlPropertiesLiteral; not?: never; or?: never }- | { and?: never; literal?: never; not: GraphqlPropertiesExpr; or?: never }- | {- and?: never;- literal?: never;- not?: never;- or: GraphqlPropertiesBinaryExpr;- };+ { and: GraphqlPropertiesBinaryExpr; literal?: never; not?: never; or?: never; }+ | { and?: never; literal: GraphqlPropertiesLiteral; not?: never; or?: never; }+ | { and?: never; literal?: never; not: GraphqlPropertiesExpr; or?: never; }+ | { and?: never; literal?: never; not?: never; or: GraphqlPropertiesBinaryExpr; };export type GraphqlPropertiesLiteral = {entityType?: GraphqlPropertyEntityType | null | undefined;@@ -1114,10 +284,13 @@ export type GraphqlPropertyEntityType =| 'USER';export type GraphqlPropertyMatchValue =- | { entityRef: string; selectOption?: never }- | { entityRef?: never; selectOption: string | number };+ { entityRef: string; selectOption?: never; }+ | { entityRef?: never; selectOption: string | number; };-export type GraphqlSharedEmailFilter = 'EXCLUDE' | 'INCLUDE' | 'ONLY';+export type GraphqlSharedEmailFilter =+ | 'EXCLUDE'+ | 'INCLUDE'+ | 'ONLY';/** GraphQL representation of supported simple Soup sorts. */export type GraphqlSimpleSortMethod =@@ -1176,1515 +349,23 @@ export type SoupQueryVariables = Exact<{input: SoupInput;}>;-export type SoupQuery = {- soup: {- nextCursor: string | null;- hasMore: boolean;- items: Array<{- id: string;- entityType: GraphqlSoupEntityType;- frecencyScore: number;- entity:- | {- __typename: 'GraphqlSoupCall';- id: string;- channelId: string;- channelName: string | null;- createdBy: string;- customName: string | null;- summary: string | null;- startedAt: string;- endedAt: string | null;- durationMs: number | null;- isActive: boolean;- status: string;- attended: boolean;- participants: Array<{- userId: string;- joinedAt: string;- leftAt: string | null;- }>;- }- | {- __typename: 'GraphqlSoupChannel';- id: string;- channelType: string;- ownerId: string;- organizationId: string | null;- createdAt: string;- updatedAt: string;- viewedAt: string | null;- interactedAt: string | null;- channelName: string | null;- channelTeamId: string | null;- participants: Array<{- channelId: string;- userId: string;- role: string;- joinedAt: string;- leftAt: string | null;- }>;- latestMessage: {- messageId: string;- threadId: string | null;- senderId: string;- content: string;- createdAt: string;- updatedAt: string;- deletedAt: string | null;- mentions: Array<string>;- } | null;- latestNonThreadMessage: {- messageId: string;- threadId: string | null;- senderId: string;- content: string;- createdAt: string;- updatedAt: string;- deletedAt: string | null;- mentions: Array<string>;- } | null;- }- | {- __typename: 'GraphqlSoupChannelThread';- id: string;- channelId: string;- senderId: string;- content: string;- createdAt: string;- updatedAt: string;- effectiveUpdatedAt: string;- replyCount: number;- }- | {- __typename: 'GraphqlSoupChat';- id: string;- ownerId: string;- projectId: string | null;- isPersistent: boolean;- createdAt: string;- updatedAt: string;- viewedAt: string | null;- deletedAt: string | null;- chatName: string;- properties: Array<{- id: string;- displayName: string;- dataType: string;- isMultiSelect: boolean;- specificEntityType: string | null;- isSystem: boolean;- isMetadata: boolean;- value: {- kind: string;- boolValue: boolean | null;- numberValue: number | null;- stringValue: string | null;- dateValue: string | null;- selectOptionIds: Array<string>;- links: Array<string>;- entityReferences: Array<{- entityId: string;- entityType: string;- specificMessageId: string | null;- }>;- } | null;- }>;- }- | {- __typename: 'GraphqlSoupCrmCompany';- id: string;- description: string | null;- emailSync: boolean;- hidden: boolean;- createdAt: string;- updatedAt: string;- viewedAt: string | null;- domains: Array<string>;- crmTeamId: string;- crmCompanyName: string | null;- }- | {- __typename: 'GraphqlSoupDocument';- id: string;- ownerId: string;- fileType: string | null;- projectId: string | null;- createdAt: string;- updatedAt: string;- viewedAt: string | null;- deletedAt: string | null;- documentName: string;- subType: { kind: string; isCompleted: boolean | null } | null;- properties: Array<{- id: string;- displayName: string;- dataType: string;- isMultiSelect: boolean;- specificEntityType: string | null;- isSystem: boolean;- isMetadata: boolean;- value: {- kind: string;- boolValue: boolean | null;- numberValue: number | null;- stringValue: string | null;- dateValue: string | null;- selectOptionIds: Array<string>;- links: Array<string>;- entityReferences: Array<{- entityId: string;- entityType: string;- specificMessageId: string | null;- }>;- } | null;- }>;- }- | {- __typename: 'GraphqlSoupEmailThread';- id: string;- providerId: string | null;- ownerId: string;- inboxVisible: boolean;- linkId: string | null;- snippet: string | null;- senderEmail: string | null;- senderName: string | null;- senderPhotoUrl: string | null;- isRead: boolean;- isDraft: boolean;- isImportant: boolean;- projectId: string | null;- sortTs: string;- createdAt: string;- updatedAt: string;- viewedAt: string | null;- emailName: string | null;- participants: Array<{- id: string;- linkId: string;- name: string | null;- email: string | null;- sfsPhotoUrl: string | null;- }>;- attachments: Array<{- id: string;- messageId: string;- providerAttachmentId: string | null;- filename: string | null;- mimeType: string | null;- sizeBytes: number | null;- contentId: string | null;- createdAt: string;- }>;- labels: Array<{- id: string;- linkId: string;- providerLabelId: string;- name: string;- createdAt: string;- messageListVisibility: string;- labelListVisibility: string;- type: string;- }>;- properties: Array<{- id: string;- displayName: string;- dataType: string;- isMultiSelect: boolean;- specificEntityType: string | null;- isSystem: boolean;- isMetadata: boolean;- value: {- kind: string;- boolValue: boolean | null;- numberValue: number | null;- stringValue: string | null;- dateValue: string | null;- selectOptionIds: Array<string>;- links: Array<string>;- entityReferences: Array<{- entityId: string;- entityType: string;- specificMessageId: string | null;- }>;- } | null;- }>;- }- | {- __typename: 'GraphqlSoupForeignEntity';- id: string;- foreignEntityId: string;- foreignEntitySource: string;- storedForId: string;- storedForAuthEntity: string;- metadata: unknown;- createdAt: string;- updatedAt: string;- }- | {- __typename: 'GraphqlSoupProject';- id: string;- ownerId: string;- parentId: string | null;- createdAt: string;- updatedAt: string;- viewedAt: string | null;- deletedAt: string | null;- projectName: string;- properties: Array<{- id: string;- displayName: string;- dataType: string;- isMultiSelect: boolean;- specificEntityType: string | null;- isSystem: boolean;- isMetadata: boolean;- value: {- kind: string;- boolValue: boolean | null;- numberValue: number | null;- stringValue: string | null;- dateValue: string | null;- selectOptionIds: Array<string>;- links: Array<string>;- entityReferences: Array<{- entityId: string;- entityType: string;- specificMessageId: string | null;- }>;- } | null;- }>;- };- }>;- };-};-export type SoupPropertyFieldsFragment = {- id: string;- displayName: string;- dataType: string;- isMultiSelect: boolean;- specificEntityType: string | null;- isSystem: boolean;- isMetadata: boolean;- value: {- kind: string;- boolValue: boolean | null;- numberValue: number | null;- stringValue: string | null;- dateValue: string | null;- selectOptionIds: Array<string>;- links: Array<string>;- entityReferences: Array<{- entityId: string;- entityType: string;- specificMessageId: string | null;- }>;- } | null;-};+export type SoupQuery = { user: { id: string, soup: { nextCursor: string | null, hasMore: boolean, items: Array<{ id: string, entityType: GraphqlSoupEntityType, frecencyScore: number, entity:+ | { __typename: 'GraphqlSoupCall', id: string, channelId: string, channelName: string | null, createdBy: string, customName: string | null, summary: string | null, startedAt: string, endedAt: string | null, durationMs: number | null, isActive: boolean, status: string, attended: boolean, participants: Array<{ userId: string, joinedAt: string, leftAt: string | null }> }+ | { __typename: 'GraphqlSoupChannel', id: string, channelType: string, ownerId: string, organizationId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, interactedAt: string | null, channelName: string | null, channelTeamId: string | null, participants: Array<{ channelId: string, userId: string, role: string, joinedAt: string, leftAt: string | null }>, latestMessage: { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> } | null, latestNonThreadMessage: { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> } | null }+ | { __typename: 'GraphqlSoupChannelThread', id: string, channelId: string, senderId: string, content: string, createdAt: string, updatedAt: string, effectiveUpdatedAt: string, replyCount: number }+ | { __typename: 'GraphqlSoupChat', id: string, ownerId: string, projectId: string | null, isPersistent: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, chatName: string, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: string, isMultiSelect: boolean, specificEntityType: string | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: string, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupCrmCompany', id: string, description: string | null, emailSync: boolean, hidden: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, domains: Array<string>, crmTeamId: string, crmCompanyName: string | null }+ | { __typename: 'GraphqlSoupDocument', id: string, ownerId: string, fileType: string | null, projectId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, documentName: string, subType: { kind: string, isCompleted: boolean | null } | null, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: string, isMultiSelect: boolean, specificEntityType: string | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: string, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupEmailThread', id: string, providerId: string | null, ownerId: string, inboxVisible: boolean, linkId: string | null, snippet: string | null, senderEmail: string | null, senderName: string | null, senderPhotoUrl: string | null, isRead: boolean, isDraft: boolean, isImportant: boolean, projectId: string | null, sortTs: string, createdAt: string, updatedAt: string, viewedAt: string | null, emailName: string | null, participants: Array<{ id: string, linkId: string, name: string | null, email: string | null, sfsPhotoUrl: string | null }>, attachments: Array<{ id: string, messageId: string, providerAttachmentId: string | null, filename: string | null, mimeType: string | null, sizeBytes: number | null, contentId: string | null, createdAt: string }>, labels: Array<{ id: string, linkId: string, providerLabelId: string, name: string, createdAt: string, messageListVisibility: string, labelListVisibility: string, type: string }>, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: string, isMultiSelect: boolean, specificEntityType: string | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: string, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupForeignEntity', id: string, foreignEntityId: string, foreignEntitySource: string, storedForId: string, storedForAuthEntity: string, metadata: unknown, createdAt: string, updatedAt: string }+ | { __typename: 'GraphqlSoupProject', id: string, ownerId: string, parentId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, projectName: string, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: string, isMultiSelect: boolean, specificEntityType: string | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: string, specificMessageId: string | null }> } | null }> }+ }> } } };-export type SoupChannelMessageFieldsFragment = {- messageId: string;- threadId: string | null;- senderId: string;- content: string;- createdAt: string;- updatedAt: string;- deletedAt: string | null;- mentions: Array<string>;-};+export type SoupPropertyFieldsFragment = { propertyDefinitionId: string, displayName: string, dataType: string, isMultiSelect: boolean, specificEntityType: string | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: string, specificMessageId: string | null }> } | null };++export type SoupChannelMessageFieldsFragment = { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> };-export const SoupPropertyFieldsFragmentDoc = {- kind: 'Document',- definitions: [- {- kind: 'FragmentDefinition',- name: { kind: 'Name', value: 'SoupPropertyFields' },- typeCondition: {- kind: 'NamedType',- name: { kind: 'Name', value: 'GraphqlSoupProperty' },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- { kind: 'Field', name: { kind: 'Name', value: 'id' } },- { kind: 'Field', name: { kind: 'Name', value: 'displayName' } },- { kind: 'Field', name: { kind: 'Name', value: 'dataType' } },- { kind: 'Field', name: { kind: 'Name', value: 'isMultiSelect' } },- {- kind: 'Field',- name: { kind: 'Name', value: 'specificEntityType' },- },- { kind: 'Field', name: { kind: 'Name', value: 'isSystem' } },- { kind: 'Field', name: { kind: 'Name', value: 'isMetadata' } },- {- kind: 'Field',- name: { kind: 'Name', value: 'value' },- selectionSet: {- kind: 'SelectionSet',- selections: [- { kind: 'Field', name: { kind: 'Name', value: 'kind' } },- { kind: 'Field', name: { kind: 'Name', value: 'boolValue' } },- { kind: 'Field', name: { kind: 'Name', value: 'numberValue' } },- { kind: 'Field', name: { kind: 'Name', value: 'stringValue' } },- { kind: 'Field', name: { kind: 'Name', value: 'dateValue' } },- {- kind: 'Field',- name: { kind: 'Name', value: 'selectOptionIds' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'entityReferences' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'entityId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'entityType' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'specificMessageId' },- },- ],- },- },- { kind: 'Field', name: { kind: 'Name', value: 'links' } },- ],- },- },- ],- },- },- ],-} as unknown as DocumentNode<SoupPropertyFieldsFragment, unknown>;-export const SoupChannelMessageFieldsFragmentDoc = {- kind: 'Document',- definitions: [- {- kind: 'FragmentDefinition',- name: { kind: 'Name', value: 'SoupChannelMessageFields' },- typeCondition: {- kind: 'NamedType',- name: { kind: 'Name', value: 'GraphqlSoupChannelMessage' },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- { kind: 'Field', name: { kind: 'Name', value: 'messageId' } },- { kind: 'Field', name: { kind: 'Name', value: 'threadId' } },- { kind: 'Field', name: { kind: 'Name', value: 'senderId' } },- { kind: 'Field', name: { kind: 'Name', value: 'content' } },- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },- { kind: 'Field', name: { kind: 'Name', value: 'deletedAt' } },- { kind: 'Field', name: { kind: 'Name', value: 'mentions' } },- ],- },- },- ],-} as unknown as DocumentNode<SoupChannelMessageFieldsFragment, unknown>;-export const SoupDocument = {- kind: 'Document',- definitions: [- {- kind: 'OperationDefinition',- operation: 'query',- name: { kind: 'Name', value: 'Soup' },- variableDefinitions: [- {- kind: 'VariableDefinition',- variable: {- kind: 'Variable',- name: { kind: 'Name', value: 'input' },- },- type: {- kind: 'NonNullType',- type: {- kind: 'NamedType',- name: { kind: 'Name', value: 'SoupInput' },- },- },- },- ],- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'soup' },- arguments: [- {- kind: 'Argument',- name: { kind: 'Name', value: 'input' },- value: {- kind: 'Variable',- name: { kind: 'Name', value: 'input' },- },- },- ],- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'items' },- selectionSet: {- kind: 'SelectionSet',- selections: [- { kind: 'Field', name: { kind: 'Name', value: 'id' } },- {- kind: 'Field',- name: { kind: 'Name', value: 'entityType' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'frecencyScore' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'entity' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: '__typename' },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupDocument',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- alias: {- kind: 'Name',- value: 'documentName',- },- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'ownerId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'fileType' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'projectId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'viewedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'deletedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'subType' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'kind' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'isCompleted',- },- },- ],- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'properties' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'FragmentSpread',- name: {- kind: 'Name',- value: 'SoupPropertyFields',- },- },- ],- },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupChat',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- alias: { kind: 'Name', value: 'chatName' },- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'ownerId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'projectId' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'isPersistent',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'viewedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'deletedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'properties' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'FragmentSpread',- name: {- kind: 'Name',- value: 'SoupPropertyFields',- },- },- ],- },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupProject',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- alias: {- kind: 'Name',- value: 'projectName',- },- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'ownerId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'parentId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'viewedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'deletedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'properties' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'FragmentSpread',- name: {- kind: 'Name',- value: 'SoupPropertyFields',- },- },- ],- },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupEmailThread',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'providerId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'ownerId' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'inboxVisible',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'linkId' },- },- {- kind: 'Field',- alias: { kind: 'Name', value: 'emailName' },- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'snippet' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'senderEmail',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'senderName' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'senderPhotoUrl',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'isRead' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'isDraft' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'isImportant',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'projectId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'sortTs' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'viewedAt' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'participants',- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'linkId',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'email',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'sfsPhotoUrl',- },- },- ],- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'attachments',- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'messageId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'providerAttachmentId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'filename',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'mimeType',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'sizeBytes',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'contentId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'createdAt',- },- },- ],- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'labels' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'linkId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'providerLabelId',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'createdAt',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'messageListVisibility',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'labelListVisibility',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'type' },- },- ],- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'properties' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'FragmentSpread',- name: {- kind: 'Name',- value: 'SoupPropertyFields',- },- },- ],- },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupChannel',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- alias: {- kind: 'Name',- value: 'channelName',- },- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'channelType',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'ownerId' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'organizationId',- },- },- {- kind: 'Field',- alias: {- kind: 'Name',- value: 'channelTeamId',- },- name: { kind: 'Name', value: 'teamId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'viewedAt' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'interactedAt',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'participants',- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: {- kind: 'Name',- value: 'channelId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'userId',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'role' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'joinedAt',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'leftAt',- },- },- ],- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'latestMessage',- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'FragmentSpread',- name: {- kind: 'Name',- value: 'SoupChannelMessageFields',- },- },- ],- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'latestNonThreadMessage',- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'FragmentSpread',- name: {- kind: 'Name',- value: 'SoupChannelMessageFields',- },- },- ],- },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupChannelThread',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'channelId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'senderId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'content' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'effectiveUpdatedAt',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'replyCount' },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupCall',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'channelId' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'channelName',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdBy' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'customName' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'summary' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'startedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'endedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'durationMs' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'isActive' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'status' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'attended' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'participants',- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: {- kind: 'Name',- value: 'userId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'joinedAt',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'leftAt',- },- },- ],- },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupCrmCompany',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- alias: { kind: 'Name', value: 'crmTeamId' },- name: { kind: 'Name', value: 'teamId' },- },- {- kind: 'Field',- alias: {- kind: 'Name',- value: 'crmCompanyName',- },- name: { kind: 'Name', value: 'name' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'description',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'emailSync' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'hidden' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'viewedAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'domains' },- },- ],- },- },- {- kind: 'InlineFragment',- typeCondition: {- kind: 'NamedType',- name: {- kind: 'Name',- value: 'GraphqlSoupForeignEntity',- },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'id' },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'foreignEntityId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'foreignEntitySource',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'storedForId',- },- },- {- kind: 'Field',- name: {- kind: 'Name',- value: 'storedForAuthEntity',- },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'metadata' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'createdAt' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'updatedAt' },- },- ],- },- },- ],- },- },- ],- },- },- { kind: 'Field', name: { kind: 'Name', value: 'nextCursor' } },- { kind: 'Field', name: { kind: 'Name', value: 'hasMore' } },- ],- },- },- ],- },- },- {- kind: 'FragmentDefinition',- name: { kind: 'Name', value: 'SoupPropertyFields' },- typeCondition: {- kind: 'NamedType',- name: { kind: 'Name', value: 'GraphqlSoupProperty' },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- { kind: 'Field', name: { kind: 'Name', value: 'id' } },- { kind: 'Field', name: { kind: 'Name', value: 'displayName' } },- { kind: 'Field', name: { kind: 'Name', value: 'dataType' } },- { kind: 'Field', name: { kind: 'Name', value: 'isMultiSelect' } },- {- kind: 'Field',- name: { kind: 'Name', value: 'specificEntityType' },- },- { kind: 'Field', name: { kind: 'Name', value: 'isSystem' } },- { kind: 'Field', name: { kind: 'Name', value: 'isMetadata' } },- {- kind: 'Field',- name: { kind: 'Name', value: 'value' },- selectionSet: {- kind: 'SelectionSet',- selections: [- { kind: 'Field', name: { kind: 'Name', value: 'kind' } },- { kind: 'Field', name: { kind: 'Name', value: 'boolValue' } },- { kind: 'Field', name: { kind: 'Name', value: 'numberValue' } },- { kind: 'Field', name: { kind: 'Name', value: 'stringValue' } },- { kind: 'Field', name: { kind: 'Name', value: 'dateValue' } },- {- kind: 'Field',- name: { kind: 'Name', value: 'selectOptionIds' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'entityReferences' },- selectionSet: {- kind: 'SelectionSet',- selections: [- {- kind: 'Field',- name: { kind: 'Name', value: 'entityId' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'entityType' },- },- {- kind: 'Field',- name: { kind: 'Name', value: 'specificMessageId' },- },- ],- },- },- { kind: 'Field', name: { kind: 'Name', value: 'links' } },- ],- },- },- ],- },- },- {- kind: 'FragmentDefinition',- name: { kind: 'Name', value: 'SoupChannelMessageFields' },- typeCondition: {- kind: 'NamedType',- name: { kind: 'Name', value: 'GraphqlSoupChannelMessage' },- },- selectionSet: {- kind: 'SelectionSet',- selections: [- { kind: 'Field', name: { kind: 'Name', value: 'messageId' } },- { kind: 'Field', name: { kind: 'Name', value: 'threadId' } },- { kind: 'Field', name: { kind: 'Name', value: 'senderId' } },- { kind: 'Field', name: { kind: 'Name', value: 'content' } },- { kind: 'Field', name: { kind: 'Name', value: 'createdAt' } },- { kind: 'Field', name: { kind: 'Name', value: 'updatedAt' } },- { kind: 'Field', name: { kind: 'Name', value: 'deletedAt' } },- { kind: 'Field', name: { kind: 'Name', value: 'mentions' } },- ],- },- },- ],-} as unknown as DocumentNode<SoupQuery, SoupQueryVariables>;+export const SoupPropertyFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"boolValue"}},{"kind":"Field","name":{"kind":"Name","value":"numberValue"}},{"kind":"Field","name":{"kind":"Name","value":"stringValue"}},{"kind":"Field","name":{"kind":"Name","value":"dateValue"}},{"kind":"Field","name":{"kind":"Name","value":"selectOptionIds"}},{"kind":"Field","name":{"kind":"Name","value":"entityReferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"links"}}]}}]}}]} as unknown as DocumentNode<SoupPropertyFieldsFragment, unknown>;+export const SoupChannelMessageFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupChannelMessageFieldsFragment, unknown>;+export const SoupDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Soup"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasMore"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"boolValue"}},{"kind":"Field","name":{"kind":"Name","value":"numberValue"}},{"kind":"Field","name":{"kind":"Name","value":"stringValue"}},{"kind":"Field","name":{"kind":"Name","value":"dateValue"}},{"kind":"Field","name":{"kind":"Name","value":"selectOptionIds"}},{"kind":"Field","name":{"kind":"Name","value":"entityReferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"links"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupQuery, SoupQueryVariables>;\ No newline at end of filediff --git a/js/app/packages/service-clients/service-storage/graphql/soup.graphql b/js/app/packages/service-clients/service-storage/graphql/soup.graphqlindex a3bee61411..2ade16671a 100644--- a/js/app/packages/service-clients/service-storage/graphql/soup.graphql+++ b/js/app/packages/service-clients/service-storage/graphql/soup.graphql@@ -1,191 +1,194 @@query Soup($input: SoupInput!) {- soup(input: $input) {- items {- id- entityType- frecencyScore- entity {- __typename- ... on GraphqlSoupDocument {- id- documentName: name- ownerId- fileType- projectId- createdAt- updatedAt- viewedAt- deletedAt- subType {- kind- isCompleted- }- properties {- ...SoupPropertyFields- }- }- ... on GraphqlSoupChat {- id- chatName: name- ownerId- projectId- isPersistent- createdAt- updatedAt- viewedAt- deletedAt- properties {- ...SoupPropertyFields- }- }- ... on GraphqlSoupProject {- id- projectName: name- ownerId- parentId- createdAt- updatedAt- viewedAt- deletedAt- properties {- ...SoupPropertyFields+ user {+ id+ soup(input: $input) {+ items {+ id+ entityType+ frecencyScore+ entity {+ __typename+ ... on GraphqlSoupDocument {+ id+ documentName: name+ ownerId+ fileType+ projectId+ createdAt+ updatedAt+ viewedAt+ deletedAt+ subType {+ kind+ isCompleted+ }+ properties {+ ...SoupPropertyFields+ }}- }- ... on GraphqlSoupEmailThread {- id- providerId- ownerId- inboxVisible- linkId- emailName: name- snippet- senderEmail- senderName- senderPhotoUrl- isRead- isDraft- isImportant- projectId- sortTs- createdAt- updatedAt- viewedAt- participants {+ ... on GraphqlSoupChat {id- linkId- name- sfsPhotoUrl+ chatName: name+ ownerId+ projectId+ isPersistent+ createdAt+ updatedAt+ viewedAt+ deletedAt+ properties {+ ...SoupPropertyFields+ }}- attachments {+ ... on GraphqlSoupProject {id- messageId- providerAttachmentId- filename- mimeType- sizeBytes- contentId+ projectName: name+ ownerId+ parentIdcreatedAt+ updatedAt+ viewedAt+ deletedAt+ properties {+ ...SoupPropertyFields+ }}- labels {+ ... on GraphqlSoupEmailThread {id+ providerId+ ownerId+ inboxVisiblelinkId- providerLabelId- name+ emailName: name+ snippet+ senderEmail+ senderName+ senderPhotoUrl+ isRead+ isDraft+ isImportant+ projectId+ sortTscreatedAt- messageListVisibility- labelListVisibility- type+ updatedAt+ viewedAt+ participants {+ id+ linkId+ name+ sfsPhotoUrl+ }+ attachments {+ id+ messageId+ providerAttachmentId+ filename+ mimeType+ sizeBytes+ contentId+ createdAt+ }+ labels {+ id+ linkId+ providerLabelId+ name+ createdAt+ messageListVisibility+ labelListVisibility+ type+ }+ properties {+ ...SoupPropertyFields+ }}- properties {- ...SoupPropertyFields+ ... on GraphqlSoupChannel {+ id+ channelName: name+ channelType+ ownerId+ organizationId+ channelTeamId: teamId+ createdAt+ updatedAt+ viewedAt+ interactedAt+ participants {+ channelId+ userId+ role+ joinedAt+ leftAt+ }+ latestMessage {+ ...SoupChannelMessageFields+ }+ latestNonThreadMessage {+ ...SoupChannelMessageFields+ }}- }- ... on GraphqlSoupChannel {- id- channelName: name- channelType- ownerId- organizationId- channelTeamId: teamId- createdAt- updatedAt- viewedAt- interactedAt- participants {+ ... on GraphqlSoupChannelThread {+ idchannelId- userId- role- joinedAt- leftAt+ senderId+ content+ createdAt+ updatedAt+ effectiveUpdatedAt+ replyCount}- latestMessage {- ...SoupChannelMessageFields+ ... on GraphqlSoupCall {+ id+ channelId+ channelName+ createdBy+ customName+ summary+ startedAt+ endedAt+ durationMs+ isActive+ status+ attended+ participants {+ userId+ joinedAt+ leftAt+ }}- latestNonThreadMessage {- ...SoupChannelMessageFields+ ... on GraphqlSoupCrmCompany {+ id+ crmTeamId: teamId+ crmCompanyName: name+ description+ emailSync+ hidden+ createdAt+ updatedAt+ viewedAt+ domains}- }- ... on GraphqlSoupChannelThread {- id- channelId- senderId- content- createdAt- updatedAt- effectiveUpdatedAt- replyCount- }- ... on GraphqlSoupCall {- id- channelId- channelName- createdBy- customName- summary- startedAt- endedAt- durationMs- isActive- status- attended- participants {- userId- joinedAt- leftAt+ ... on GraphqlSoupForeignEntity {+ id+ foreignEntityId+ foreignEntitySource+ storedForId+ storedForAuthEntity+ metadata+ createdAt+ updatedAt}}- ... on GraphqlSoupCrmCompany {- id- crmTeamId: teamId- crmCompanyName: name- description- emailSync- hidden- createdAt- updatedAt- viewedAt- domains- }- ... on GraphqlSoupForeignEntity {- id- foreignEntityId- foreignEntitySource- storedForId- storedForAuthEntity- metadata- createdAt- updatedAt- }}+ nextCursor+ hasMore}- nextCursor- hasMore}}fragment SoupPropertyFields on GraphqlSoupProperty {- id+ propertyDefinitionIddisplayNamedataTypeisMultiSelect@@ -209,7 +212,7 @@ fragment SoupPropertyFields on GraphqlSoupProperty {}fragment SoupChannelMessageFields on GraphqlSoupChannelMessage {- messageId+ idthreadIdsenderIdcontentdiff --git a/js/app/tsconfig.json b/js/app/tsconfig.jsonindex d9430817f4..2920d56d0f 100644--- a/js/app/tsconfig.json+++ b/js/app/tsconfig.json@@ -60,6 +60,9 @@"loro-crdt/*": ["../node_modules/loro-crdt/*"],+ "@graphql-cache/*": [+ "./packages/graphql-cache/*"+ ],"@filesystem": ["./packages/filesystem/src"],diff --git a/js/app/vitest.config.ts b/js/app/vitest.config.tsindex 6953e8215f..05ba15cd3a 100644--- a/js/app/vitest.config.ts+++ b/js/app/vitest.config.ts@@ -31,6 +31,13 @@ export default defineConfig({name: 'queries',},},+ {+ plugins: [tsconfigPaths()],+ test: {+ include: ['packages/graphql-cache/**/*.{test,spec}.{ts,tsx}'],+ name: 'graphql-cache',+ },+ },{test: {include: ['scripts/**/*.{test,spec}.{ts,tsx}'],diff --git a/js/bun.lock b/js/bun.lockindex fd13fb759d..60583bebf8 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -121,6 +121,7 @@"uuid": "^10.0.0","virtua": "0.48.8","vite-plugin-wasm": "^3.5.0",+ "wonka": "^6.3.2","zod": "^4.3.6",},"devDependencies": {diff --git a/rust/cloud-storage/.config/hakari.toml b/rust/cloud-storage/.config/hakari.tomlindex 0d6de1c49a..bd1bd72c41 100644--- a/rust/cloud-storage/.config/hakari.toml+++ b/rust/cloud-storage/.config/hakari.toml@@ -40,4 +40,14 @@ platforms = [# macro_sync_service_jwt: must stay wasm-safe (the sync service compiles it to# wasm32), so it must not gain the workspace-hack dep, which pulls native-only# features.-workspace-members = ["xtask", "macro_sync_service_jwt"]+workspace-members = [+ "xtask",+ "macro_sync_service_jwt",+ # 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",+]diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 8f9d4560b9..71ce571198 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -425,6 +425,36 @@ version = "1.0.103"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"+[[package]]+name = "apollo-compiler"+version = "1.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b877306ffde4d3cc428bbc8f506fdd67b99255298ae92b919954c0c52f530504"+dependencies = [+ "ahash",+ "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 = "aquamarine"version = "0.6.0"@@ -465,6 +495,17 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "ariadne"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8454c8a44ce2cb9cc7e7fae67fc6128465b343b92c6631e94beca3c8d1524ea5"+dependencies = [+ "concolor",+ "unicode-width 0.2.2",+ "yansi",+]+[[package]]name = "arrayvec"version = "0.5.2"@@ -849,6 +890,15 @@ dependencies = ["num-traits",]+[[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"@@ -2151,6 +2201,63 @@ dependencies = ["pkg-config",]+[[package]]+name = "cache-core"+version = "0.1.0"+dependencies = [+ "apollo-compiler",+ "apollo-parser",+ "lru",+ "pollster",+ "postcard",+ "serde",+ "serde_json",+ "sha2 0.10.9",+ "thiserror 2.0.18",+]++[[package]]+name = "cache-idb"+version = "0.1.0"+dependencies = [+ "cache-core",+ "idb",+ "js-sys",+ "serde_json",+ "thiserror 2.0.18",+ "wasm-bindgen",+ "wasm-bindgen-test",+ "web-sys",+]++[[package]]+name = "cache-sqlite"+version = "0.1.0"+dependencies = [+ "cache-core",+ "pollster",+ "rusqlite",+ "serde_json",+ "tempfile",+ "thiserror 2.0.18",+]++[[package]]+name = "cache-wasm"+version = "0.1.0"+dependencies = [+ "async-lock",+ "cache-core",+ "cache-idb",+ "js-sys",+ "serde",+ "serde-wasm-bindgen",+ "serde_json",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-bindgen-test",+]+[[package]]name = "cached"version = "0.54.0"@@ -2305,6 +2412,12 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "cast"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"+[[package]]name = "cc"version = "1.2.62"@@ -2625,6 +2738,15 @@ version = "0.5.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"+[[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 = "color_quant"version = "1.1.0"@@ -2692,6 +2814,26 @@ version = "0.4.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cc14f565cf027a105f7a44ccf9e5b424348421a1d8952a8fc9d499d313107789"+[[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"@@ -3040,6 +3182,12 @@ version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"+[[package]]+name = "countme"+version = "3.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636"+[[package]]name = "cowlike"version = "0.1.0"@@ -3172,9 +3320,9 @@ dependencies = [[[package]]name = "crossbeam-epoch"-version = "0.9.18"+version = "0.9.20"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"dependencies = ["crossbeam-utils",]@@ -4766,6 +4914,18 @@ dependencies = ["workspace-hack",]+[[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 = "embedding"version = "0.1.0"@@ -4976,6 +5136,18 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7"+[[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 = "fancy-regex"version = "0.12.0"@@ -5784,6 +5956,15 @@ dependencies = ["thiserror 2.0.18",]+[[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"@@ -5833,6 +6014,15 @@ 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"@@ -5866,6 +6056,20 @@ dependencies = ["http 1.4.0",]+[[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 0.9.8",+ "stable_deref_trait",+]+[[package]]name = "heck"version = "0.4.1"@@ -6424,6 +6628,21 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"+[[package]]+name = "idb"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6554f394e990a1af530a528a7fdcad6e01b29cb1b990f89df3ffd62cf15f7828"+dependencies = [+ "indexmap 2.14.0",+ "js-sys",+ "num-traits",+ "thiserror 2.0.18",+ "tokio",+ "wasm-bindgen",+ "web-sys",+]+[[package]]name = "iddqd"version = "0.3.18"@@ -6752,6 +6971,17 @@ dependencies = ["serde",]+[[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_terminal_polyfill"version = "1.70.2"@@ -6929,6 +7159,19 @@ dependencies = ["wasm-bindgen",]+[[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 = "jsonwebtoken"version = "10.3.0"@@ -7166,6 +7409,7 @@ version = "0.30.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"dependencies = [+ "cc","pkg-config","vcpkg",]@@ -8095,6 +8339,16 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "minicov"+version = "0.3.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"+dependencies = [+ "cc",+ "walkdir",+]+[[package]]name = "minimal-lexical"version = "0.2.1"@@ -9205,6 +9459,12 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]+name = "oorandom"+version = "11.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"+[[package]]name = "opaque-debug"version = "0.3.1"@@ -9928,6 +10188,12 @@ 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 = "polyval"version = "0.6.2"@@ -9946,6 +10212,19 @@ version = "1.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"+[[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 = "postgres-protocol"version = "0.6.11"@@ -9955,7 +10234,7 @@ dependencies = ["base64 0.22.1","byteorder","bytes",- "fallible-iterator",+ "fallible-iterator 0.2.0","hmac 0.13.0","md-5 0.11.0","memchr",@@ -9971,7 +10250,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8dc729a129e682e8d24170cd30ae1aa01b336b096cbb56df6d534ffec133d186"dependencies = ["bytes",- "fallible-iterator",+ "fallible-iterator 0.2.0","postgres-protocol",]@@ -11076,6 +11355,18 @@ 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 = "rs-libreoffice-bindings"version = "0.0.7"@@ -11106,6 +11397,20 @@ 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"@@ -11803,6 +12108,17 @@ dependencies = ["serde_derive",]+[[package]]+name = "serde-wasm-bindgen"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b"+dependencies = [+ "js-sys",+ "serde",+ "wasm-bindgen",+]+[[package]]name = "serde_core"version = "1.0.228"@@ -11859,6 +12175,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",+ "bytes",+ "indexmap 2.14.0",+ "jsonpath-rust",+ "regex",+ "serde",+ "serde_json",+]+[[package]]name = "serde_path_to_error"version = "0.1.20"@@ -12427,7 +12758,7 @@ dependencies = ["futures-io","futures-util","hashbrown 0.15.5",- "hashlink",+ "hashlink 0.10.0","indexmap 2.14.0","log","memchr",@@ -13114,6 +13445,12 @@ version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"+[[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"@@ -13698,6 +14035,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"@@ -13753,6 +14094,12 @@ dependencies = ["rand 0.9.4",]+[[package]]+name = "typed-arena"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"+[[package]]name = "typenum"version = "1.20.0"@@ -14301,6 +14648,45 @@ dependencies = ["unicode-ident",]+[[package]]+name = "wasm-bindgen-test"+version = "0.3.71"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af5ec93229ad9ccd0a545a516dec76dc276613f278f6a91aa6b463d5b33d42d0"+dependencies = [+ "async-trait",+ "cast",+ "js-sys",+ "libm",+ "minicov",+ "nu-ansi-term",+ "num-traits",+ "oorandom",+ "serde",+ "serde_json",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-bindgen-test-macro",+ "wasm-bindgen-test-shared",+]++[[package]]+name = "wasm-bindgen-test-macro"+version = "0.3.71"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c81b9fef827e575e0e54431736d1baa0d700315d8c62cfef1f61fa3aad0cbeb"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "wasm-bindgen-test-shared"+version = "0.2.121"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f4d8ae7ad5440360e9799dfd42857d126454a88441ddf72d288ef83fa47f527"+[[package]]name = "wasm-encoder"version = "0.244.0"@@ -15156,6 +15542,12 @@ version = "0.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"+[[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/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex ebbeb0ba4b..e221ab1ae8 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -12,6 +12,10 @@ members = ["bots","call_recording_preview_handler","channel_bots",+ "client/cache-core",+ "client/cache-idb",+ "client/cache-sqlite",+ "client/cache-wasm","connection_gateway","contacts_service","convert_service",@@ -72,6 +76,8 @@ members = [[workspace.dependencies]anyhow = "1.0.100"+apollo-compiler = "1"+apollo-parser = "0.8"askama = "0.14"async-graphql = "7.2.1"async-openai = { version = "0.36.1", features = [@@ -80,6 +86,7 @@ async-openai = { version = "0.36.1", features = ["completions","embedding",] }+async-lock = "3"async-stream = "0.3.6"async-trait = "0.1.86"automod = "1"@@ -120,6 +127,7 @@ jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features"rust_crypto",] }lambda_runtime = "0.13.0"+lru = "0.16"lazy_static = "1.5.0"livekit-api = { version = "0.4.16", default-features = false, features = ["access-token",@@ -167,9 +175,11 @@ rmcp = "1.6.0"rootcause = { version = "0.12" }schemars = { version = "1.0.4", features = ["chrono04", "uuid1"] }semver = { version = "1", features = ["serde"] }+postcard = { version = "1", features = ["use-std"] }serde = { version = "1.0.214", features = ["derive"] }serde_dynamo = { version = "4", features = ["aws-sdk-dynamodb+1"] }serde_json = { version = "1.0.132" }+serde-wasm-bindgen = "0.6"serde_repr = "0.1"serde_with = { version = "3.12.0", features = ["base64"] }sha2 = "0.10.8"@@ -182,6 +192,8 @@ sqlx = { version = "0.8.6", features = [sqlx-core = { version = "0.8.6" }strum = { version = "0.27.1", features = ["derive"] }thiserror = "2.0.0"+wasm-bindgen = "0.2"+wasm-bindgen-futures = "0.4"time = "0.3.37"tokio = { version = "1.43.0", features = ["macros", "rt-multi-thread"] }tokio-stream = { version = "0.1.17" }diff --git a/rust/cloud-storage/client/README.md b/rust/cloud-storage/client/README.mdnew file mode 100644index 0000000000..b1e167861c--- /dev/null+++ b/rust/cloud-storage/client/README.md@@ -0,0 +1,51 @@+# graphql-cache++Normalized GraphQL cache with disk-backed persistence for urql. Design doc:+[`js/app/docs/graphql-normalized-cache-plan.md`](../../../js/app/docs/graphql-normalized-cache-plan.md).++## Crates++| Crate | Purpose |+|---|---|+| `cache-core` | Pure engine: schema-metadata codegen (build.rs from `rust/cloud-storage/schema.graphql` (`../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) |++Planned (Phase 3): `cache-wasm` (wasm-bindgen shell + worker RPC), `cache-tauri`+(Tauri plugin) — see the design doc.++## Tests++From `rust/cloud-storage` (these crates are members of the cloud-storage+workspace; use `SQLX_OFFLINE=true` as usual):++```sh+SQLX_OFFLINE=true cargo test -p cache-core -p cache-sqlite # native+cargo check --target wasm32-unknown-unknown -p cache-idb -p cache-wasm --all-targets+wasm-pack test --headless --chrome client/cache-idb # browser tests (IDB backend)+```++NixOS note: wasm-pack downloads a dynamically-linked chromedriver that won't+run. Work around by invoking the runner directly with a nix chromedriver:++```sh+cd client/cache-idb+CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER=~/.cache/.wasm-pack/wasm-bindgen-*/wasm-bindgen-test-runner \+CHROMEDRIVER=$(command -v chromedriver || echo /nix/store/*undetected-chromedriver*/bin/undetected-chromedriver) \+WASM_BINDGEN_TEST_ONLY_WEB=1 cargo test --target wasm32-unknown-unknown+```++## Key policy++**Presence-of-id convention**: an output object type with an `id: ID!`+field is a normalized entity keyed by `__typename:id`; a type without `id`+is embedded inline in its parent record. The schema itself is the policy —+there is no client-side key config. The build fails on malformed shapes+(nullable/non-ID `id`, `id` on the query root). Consequence for schema+authors: **only expose a field named `id` when it is the object's global+identity** (e.g. `GraphqlSoupProperty` exposes `propertyDefinitionId`+because a property instance's value is per-entity).++Identity is not the cache's concern: the engine accepts an opaque session+tag on writes (extracted by the urql exchange from `data.user.id`) and+wipes + rebinds atomically when the tag changes (silent restart).diff --git a/rust/cloud-storage/client/cache-core/Cargo.toml b/rust/cloud-storage/client/cache-core/Cargo.tomlnew file mode 100644index 0000000000..aad7f3a75c--- /dev/null+++ b/rust/cloud-storage/client/cache-core/Cargo.toml@@ -0,0 +1,21 @@+[package]+edition = "2024"+name = "cache-core"+publish = false+version = "0.1.0"++[dependencies]+apollo-parser = { workspace = true }+lru = { workspace = true }+postcard = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sha2 = { workspace = true }+thiserror = { workspace = true }++[build-dependencies]+apollo-compiler = { workspace = true }+sha2 = { workspace = true }++[dev-dependencies]+pollster = "0.4"diff --git a/rust/cloud-storage/client/cache-core/build.rs b/rust/cloud-storage/client/cache-core/build.rsnew file mode 100644index 0000000000..3fc8981527--- /dev/null+++ b/rust/cloud-storage/client/cache-core/build.rs@@ -0,0 +1,248 @@+//! Build-time schema metadata codegen.+//!+//! Parses the in-repo SDL schema and emits `$OUT_DIR/schema_meta.rs`: static+//! lookup tables consumed by `src/meta.rs`.+//!+//! Key policy is the **presence-of-id convention**: an output object type+//! with an `id: ID!` field is a normalized entity keyed by+//! `__typename:id`; a type without `id` is embedded inline in its parent+//! record. The schema itself is the policy — there is no client-side key+//! config to drift. The build still fails on malformed shapes (e.g. a+//! nullable or non-ID `id`).++// std::env::var is disallowed workspace-wide to force `macro_env_var` for+// service config; build scripts read cargo-provided vars (CARGO_MANIFEST_DIR,+// OUT_DIR), which have nothing to do with app secrets.+#![allow(clippy::disallowed_methods)]++use apollo_compiler::Schema;+use apollo_compiler::schema::ExtendedType;+use sha2::{Digest, Sha256};+use std::collections::{BTreeMap, BTreeSet};+use std::fmt::Write as _;+use std::path::Path;++const SCHEMA_PATH: &str = "../../schema.graphql";++fn main() {+ println!("cargo:rerun-if-changed={SCHEMA_PATH}");++ let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();+ let schema_path = Path::new(&manifest_dir).join(SCHEMA_PATH);+ let schema_text = std::fs::read_to_string(&schema_path)+ .unwrap_or_else(|e| panic!("cannot read {}: {e}", schema_path.display()));++ let schema = Schema::parse_and_validate(&schema_text, "schema.graphql")+ .unwrap_or_else(|e| panic!("schema does not validate: {e:?}"));++ let query_root = schema+ .schema_definition+ .query+ .as_ref()+ .expect("schema has no query root")+ .name+ .to_string();++ // The schema hash namespaces persisted caches; key policy is derived+ // from the schema, so hashing the schema covers it.+ let mut hasher = Sha256::new();+ hasher.update(schema_text.as_bytes());+ let schema_hash = hex_string(&hasher.finalize());++ let mut errors: Vec<String> = Vec::new();+ let mut entries: Vec<(String, String)> = Vec::new(); // (type name, TypeMeta literal)++ // Interface implementors (reverse map).+ let mut implementors: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();+ for (name, ty) in schema.types.iter() {+ if let ExtendedType::Object(obj) = ty {+ for iface in &obj.implements_interfaces {+ implementors+ .entry(iface.name.to_string())+ .or_default()+ .insert(name.to_string());+ }+ }+ }++ for (name, ty) in schema.types.iter() {+ let name = name.to_string();+ if name.starts_with("__") {+ continue; // introspection machinery+ }+ match ty {+ ExtendedType::Object(obj) => {+ let key_literal =+ key_literal(&name, name == query_root, obj.fields.iter(), &mut errors);+ let fields = fields_literal(&schema, obj.fields.iter(), &mut errors);+ entries.push((+ name.clone(),+ type_meta_literal(&name, "Object", &key_literal, &fields, &[]),+ ));+ }+ ExtendedType::Interface(iface) => {+ let key_literal = key_literal(&name, false, iface.fields.iter(), &mut errors);+ let fields = fields_literal(&schema, iface.fields.iter(), &mut errors);+ let possible: Vec<String> = implementors+ .get(&name)+ .map(|s| s.iter().cloned().collect())+ .unwrap_or_default();+ entries.push((+ name.clone(),+ type_meta_literal(&name, "Interface", &key_literal, &fields, &possible),+ ));+ }+ ExtendedType::Union(u) => {+ let possible: Vec<String> = u.members.iter().map(|m| m.name.to_string()).collect();+ entries.push((+ name.clone(),+ type_meta_literal(&name, "Union", "None", "&[]", &possible),+ ));+ }+ // Scalars, enums and input objects need no TypeMeta: field kinds+ // are resolved at codegen and inputs never appear in responses.+ _ => {}+ }+ }++ if !errors.is_empty() {+ panic!(+ "schema shape errors:\n - {}\n(fix the schema — see the presence-of-id convention in this build script's docs)",+ errors.join("\n - ")+ );+ }++ entries.sort_by(|a, b| a.0.cmp(&b.0)); // binary-searchable++ let mut out = String::new();+ writeln!(out, "// @generated by cache-core/build.rs — do not edit.").unwrap();+ writeln!(out, "pub static QUERY_ROOT_TYPE: &str = {query_root:?};").unwrap();+ writeln!(out, "pub static SCHEMA_HASH: &str = {schema_hash:?};").unwrap();+ writeln!(out, "pub static TYPES: &[TypeMeta] = &[").unwrap();+ for (_, literal) in &entries {+ writeln!(out, " {literal},").unwrap();+ }+ writeln!(out, "];").unwrap();++ let out_path = Path::new(&std::env::var("OUT_DIR").unwrap()).join("schema_meta.rs");+ std::fs::write(out_path, out).unwrap();+}++/// Presence-of-id convention: a type with an `id` field is keyed by it; the+/// field must be a non-null, non-list `ID`. Types without `id` are embedded.+fn key_literal<'a>(+ name: &str,+ is_query_root: bool,+ fields: impl Iterator<+ Item = (+ &'a apollo_compiler::Name,+ &'a apollo_compiler::schema::Component<apollo_compiler::ast::FieldDefinition>,+ ),+ >,+ errors: &mut Vec<String>,+) -> String {+ let id_field = fields.into_iter().find(|(fname, _)| fname.as_str() == "id");+ let Some((_, fdef)) = id_field else {+ return "None".into();+ };+ if is_query_root {+ errors.push(format!("query root `{name}` must not expose an `id` field"));+ return "None".into();+ }+ match flatten_type(&fdef.ty) {+ Ok((named, false, false, _)) if named == "ID" => r#"Some(&["id"])"#.into(),+ _ => {+ errors.push(format!(+ "`{name}.id` must be `ID!` (non-null, non-list) to satisfy the presence-of-id convention; rename it if it is not this object's identity"+ ));+ "None".into()+ }+ }+}++fn type_meta_literal(+ name: &str,+ kind: &str,+ key_literal: &str,+ fields_literal: &str,+ possible: &[String],+) -> String {+ let possible_list = possible+ .iter()+ .map(|p| format!("{p:?}"))+ .collect::<Vec<_>>()+ .join(", ");+ format!(+ "TypeMeta {{ name: {name:?}, kind: TypeKind::{kind}, key_fields: {key_literal}, fields: {fields_literal}, possible_types: &[{possible_list}] }}"+ )+}++fn fields_literal<'a>(+ schema: &Schema,+ fields: impl Iterator<+ Item = (+ &'a apollo_compiler::Name,+ &'a apollo_compiler::schema::Component<apollo_compiler::ast::FieldDefinition>,+ ),+ >,+ errors: &mut Vec<String>,+) -> String {+ let mut parts = Vec::new();+ for (fname, fdef) in fields {+ let (named, nullable, list, item_nullable) = match flatten_type(&fdef.ty) {+ Ok(t) => t,+ Err(e) => {+ errors.push(format!("field `{fname}`: {e}"));+ continue;+ }+ };+ let kind = match schema.types.get(named.as_str()) {+ Some(ExtendedType::Object(_))+ | Some(ExtendedType::Interface(_))+ | Some(ExtendedType::Union(_)) => "Composite",+ Some(ExtendedType::Enum(_)) => "Leaf",+ Some(ExtendedType::Scalar(_)) => {+ if matches!(+ named.as_str(),+ "Int" | "Float" | "String" | "Boolean" | "ID"+ ) {+ "Leaf"+ } else {+ "OpaqueScalar" // e.g. JSON+ }+ }+ Some(ExtendedType::InputObject(_)) | None => {+ errors.push(format!("field `{fname}` has non-output type `{named}`"));+ continue;+ }+ };+ parts.push(format!(+ "FieldMeta {{ name: {:?}, ty: FieldType {{ name: {:?}, kind: FieldKind::{kind}, nullable: {nullable}, list: {list}, item_nullable: {item_nullable} }} }}",+ fname.to_string(),+ named,+ ));+ }+ format!("&[{}]", parts.join(", "))+}++/// Flattens GraphQL type wrapping to (named, nullable, list, item_nullable).+/// Nested lists are rejected — extend `FieldType` if the schema ever needs+/// them.+fn flatten_type(ty: &apollo_compiler::ast::Type) -> Result<(String, bool, bool, bool), String> {+ use apollo_compiler::ast::Type;+ let (inner, nullable, list) = match ty {+ Type::Named(n) => return Ok((n.to_string(), true, false, false)),+ Type::NonNullNamed(n) => return Ok((n.to_string(), false, false, false)),+ Type::List(inner) => (inner, true, true),+ Type::NonNullList(inner) => (inner, false, true),+ };+ match inner.as_ref() {+ Type::Named(n) => Ok((n.to_string(), nullable, list, true)),+ Type::NonNullNamed(n) => Ok((n.to_string(), nullable, list, false)),+ Type::List(_) | Type::NonNullList(_) => Err("nested lists are not supported".into()),+ }+}++fn hex_string(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}diff --git a/rust/cloud-storage/client/cache-core/src/codec.rs b/rust/cloud-storage/client/cache-core/src/codec.rsnew file mode 100644index 0000000000..46ed91a52a--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/codec.rs@@ -0,0 +1,84 @@+//! Binary record codec shared by all persistent backends (IndexedDB,+//! SQLite). Records are stored as postcard bytes; the cache namespace embeds+//! [`CACHE_FORMAT_VERSION`] and [`meta::SCHEMA_HASH`](crate::meta) so a+//! format or schema change starts a fresh cache instead of attempting+//! migration (the cache is disposable by design).++use crate::value::Record;+use thiserror::Error;++/// Bump when the stored representation of [`Record`]/[`CacheValue`]+/// (or anything else persisted) changes incompatibly.+pub const CACHE_FORMAT_VERSION: u32 = 1;++#[derive(Debug, Error)]+pub enum CodecError {+ #[error("corrupt record: {0}")]+ Corrupt(#[from] postcard::Error),+}++pub fn encode_record(record: &Record) -> Vec<u8> {+ // Serialization of an in-memory record cannot fail.+ postcard::to_allocvec(record).expect("record serializes")+}++pub fn decode_record(bytes: &[u8]) -> Result<Record, CodecError> {+ Ok(postcard::from_bytes(bytes)?)+}++/// Canonical database/namespace name for a cache instance.+/// `scope` identifies the user/workspace (host-provided).+pub fn cache_namespace(scope: &str) -> String {+ format!(+ "graphql-cache:{scope}:{}:v{CACHE_FORMAT_VERSION}",+ &crate::meta::SCHEMA_HASH[..12]+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::value::{CacheNumber, CacheValue, EntityKey};++ #[test]+ fn round_trips() {+ let mut record = Record::default();+ record.fields.insert(+ "__typename".into(),+ CacheValue::String("GraphqlSoupDocument".into()),+ );+ record.fields.insert(+ "properties".into(),+ CacheValue::List(vec![CacheValue::Object(+ [("kind".to_string(), CacheValue::String("Boolean".into()))].into(),+ )]),+ );+ record.fields.insert(+ "project".into(),+ CacheValue::Ref(EntityKey("GraphqlSoupProject:p1".into())),+ );+ record.fields.insert(+ "metadata".into(),+ CacheValue::opaque(&serde_json::json!({"a": [1, 2.5, null]})),+ );+ record+ .fields+ .insert("count".into(), CacheValue::Number(CacheNumber::PosInt(42)));++ let bytes = encode_record(&record);+ let decoded = decode_record(&bytes).unwrap();+ assert_eq!(decoded, record);+ }++ #[test]+ fn rejects_garbage() {+ assert!(decode_record(&[0xff, 0x00, 0x13, 0x37]).is_err());+ }++ #[test]+ fn namespace_shape() {+ let ns = cache_namespace("user-1");+ assert!(ns.starts_with("graphql-cache:user-1:"));+ assert!(ns.ends_with(":v1"));+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/denormalize.rs b/rust/cloud-storage/client/cache-core/src/denormalize.rsnew file mode 100644index 0000000000..8544d4f09a--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/denormalize.rs@@ -0,0 +1,232 @@+//! Read path: normalized records → response JSON.+//!+//! Pure and synchronous: reads records through a [`RecordSource`] snapshot.+//! When records are absent from the source the walk *continues* and gathers+//! every missing key, so the engine can batch-fetch from storage and retry+//! (see the engine's read loop). A record that exists but lacks a selected+//! field is a cache miss (Phase 1: no partial results — nullability-based+//! partials are a later phase; the metadata is already generated).++use crate::document::{FieldNode, MissingVariable, Operation, Selection, resolve_args_key};+use crate::meta;+use crate::value::{CacheValue, EntityKey, Record, field_key};+use serde_json::Value as Json;+use std::collections::BTreeSet;+use thiserror::Error;++/// Synchronous view over records available right now (hot tier + any+/// batch-fetched records).+pub trait RecordSource {+ fn get(&self, key: &EntityKey) -> Option<&Record>;+}++impl RecordSource for std::collections::BTreeMap<EntityKey, Record> {+ fn get(&self, key: &EntityKey) -> Option<&Record> {+ std::collections::BTreeMap::get(self, key)+ }+}++impl RecordSource for std::collections::HashMap<EntityKey, Record> {+ fn get(&self, key: &EntityKey) -> Option<&Record> {+ std::collections::HashMap::get(self, key)+ }+}++#[derive(Debug, Error)]+pub enum DenormalizeError {+ #[error(transparent)]+ MissingVariable(#[from] MissingVariable),+ #[error("unknown field `{type_name}.{field}` (schema drift?)")]+ UnknownField { type_name: String, field: String },+ #[error("stored value for `{type_name}.{field}` does not match the selection shape")]+ Shape { type_name: String, field: String },+}++/// Outcome of a read attempt.+#[derive(Debug)]+pub enum ReadOutcome {+ /// All selected data present.+ Complete(Json),+ /// Some records weren't in the [`RecordSource`]; fetch these and retry.+ NeedRecords(BTreeSet<EntityKey>),+ /// A record exists but a selected field was never written → miss.+ Miss { entity: EntityKey, field: String },+}++/// Attempts to answer `op` from `source`. `deps` accumulates every entity+/// key touched (for dependency tracking), regardless of outcome.+pub fn denormalize(+ op: &Operation,+ variables: &serde_json::Map<String, Json>,+ source: &impl RecordSource,+ deps: &mut BTreeSet<EntityKey>,+) -> Result<ReadOutcome, DenormalizeError> {+ let mut walk = Walk {+ variables,+ source,+ deps,+ missing_records: BTreeSet::new(),+ miss: None,+ };+ let root_key = EntityKey::root();+ let data = walk.read_record(&root_key, meta::QUERY_ROOT_TYPE, &op.selection_set)?;++ if !walk.missing_records.is_empty() {+ return Ok(ReadOutcome::NeedRecords(walk.missing_records));+ }+ if let Some((entity, field)) = walk.miss {+ return Ok(ReadOutcome::Miss { entity, field });+ }+ match data {+ Some(json) => Ok(ReadOutcome::Complete(json)),+ // Root record itself absent → nothing cached for this operation yet.+ None => Ok(ReadOutcome::Miss {+ entity: root_key,+ field: "(root)".to_string(),+ }),+ }+}++struct Walk<'a, S: RecordSource> {+ variables: &'a serde_json::Map<String, Json>,+ source: &'a S,+ deps: &'a mut BTreeSet<EntityKey>,+ missing_records: BTreeSet<EntityKey>,+ /// First field-level miss encountered.+ miss: Option<(EntityKey, String)>,+}++impl<'a, S: RecordSource> Walk<'a, S> {+ /// Reads a full record by key. Returns `None` when the outcome is+ /// already determined to be incomplete (missing record / miss noted).+ fn read_record(+ &mut self,+ key: &EntityKey,+ type_name: &str,+ selections: &[Selection],+ ) -> Result<Option<Json>, DenormalizeError> {+ self.deps.insert(key.clone());+ let Some(record) = self.source.get(key) else {+ self.missing_records.insert(key.clone());+ return Ok(None);+ };+ // Clone is cheap relative to the walk; keeps borrows simple.+ let record = record.clone();+ let concrete = record.typename().unwrap_or(type_name).to_string();+ self.read_fields(key, &record.fields, &concrete, selections)+ }++ /// Reads selected fields out of a record's or embedded object's map.+ fn read_fields(+ &mut self,+ owner: &EntityKey,+ fields: &std::collections::BTreeMap<String, CacheValue>,+ concrete: &str,+ selections: &[Selection],+ ) -> Result<Option<Json>, DenormalizeError> {+ let mut field_nodes = Vec::new();+ collect_fields(selections, concrete, &mut field_nodes);++ let mut out = serde_json::Map::new();+ for f in field_nodes {+ if f.name == "__typename" {+ out.insert(f.response_key.clone(), Json::String(concrete.to_string()));+ continue;+ }+ // Validate the field exists in the schema (drift protection).+ let fmeta = meta::field_meta(concrete, &f.name).ok_or_else(|| {+ DenormalizeError::UnknownField {+ type_name: concrete.to_string(),+ field: f.name.clone(),+ }+ })?;+ let args = resolve_args_key(f, self.variables)?;+ let storage_key = field_key(&f.name, args.as_deref());++ let Some(value) = fields.get(&storage_key) else {+ if self.miss.is_none() {+ self.miss = Some((owner.clone(), storage_key));+ }+ continue;+ };+ let json = self.read_value(owner, f, fmeta.ty.name, value)?;+ match json {+ Some(j) => {+ out.insert(f.response_key.clone(), j);+ }+ None => continue, // incomplete subtree already noted+ }+ }+ Ok(Some(Json::Object(out)))+ }++ fn read_value(+ &mut self,+ owner: &EntityKey,+ field: &FieldNode,+ named_type: &str,+ value: &CacheValue,+ ) -> Result<Option<Json>, DenormalizeError> {+ Ok(match value {+ CacheValue::Null => Some(Json::Null),+ CacheValue::Bool(b) => Some(Json::Bool(*b)),+ CacheValue::Number(n) => Some(Json::Number(n.to_json())),+ CacheValue::String(s) => Some(Json::String(s.clone())),+ CacheValue::Opaque(j) => {+ Some(+ serde_json::from_str(j).map_err(|_| DenormalizeError::Shape {+ type_name: named_type.to_string(),+ field: field.name.clone(),+ })?,+ )+ }+ CacheValue::List(items) => {+ let mut out = Vec::with_capacity(items.len());+ let mut complete = true;+ for item in items {+ match self.read_value(owner, field, named_type, item)? {+ Some(j) => out.push(j),+ None => complete = false,+ }+ }+ if complete {+ Some(Json::Array(out))+ } else {+ None+ }+ }+ CacheValue::Ref(key) => self.read_record(key, named_type, &field.selection_set)?,+ CacheValue::Object(map) => {+ let concrete = match map.get("__typename") {+ Some(CacheValue::String(t)) => t.clone(),+ _ => named_type.to_string(),+ };+ self.read_fields(owner, map, &concrete, &field.selection_set)?+ }+ })+ }+}++fn collect_fields<'a>(+ selections: &'a [Selection],+ concrete_type: &str,+ out: &mut Vec<&'a FieldNode>,+) {+ for sel in selections {+ match sel {+ Selection::Field(f) => out.push(f),+ Selection::Fragment {+ type_condition,+ selection_set,+ } => {+ let applies = match type_condition {+ None => true,+ Some(cond) => meta::type_matches(concrete_type, cond),+ };+ if applies {+ collect_fields(selection_set, concrete_type, out);+ }+ }+ }+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/deps.rs b/rust/cloud-storage/client/cache-core/src/deps.rsnew file mode 100644index 0000000000..2b45dbb3df--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/deps.rs@@ -0,0 +1,102 @@+//! Dependency index: which active operations depend on which records.+//!+//! Operation ids are assigned by the host (the urql exchange uses urql's+//! operation keys). When a write changes records, the engine reports the+//! affected active operations so the host can re-execute them.++use crate::value::EntityKey;+use std::collections::{BTreeSet, HashMap, HashSet};++pub type OpId = u64;++#[derive(Debug, Default)]+pub struct DepIndex {+ by_op: HashMap<OpId, BTreeSet<EntityKey>>,+ by_key: HashMap<EntityKey, HashSet<OpId>>,+}++impl DepIndex {+ pub fn new() -> Self {+ Self::default()+ }++ /// Replaces the dependency set of an active operation.+ pub fn set_op_deps(&mut self, op: OpId, deps: BTreeSet<EntityKey>) {+ self.remove_op(op);+ for key in &deps {+ self.by_key.entry(key.clone()).or_default().insert(op);+ }+ self.by_op.insert(op, deps);+ }++ /// Unregisters an operation (urql teardown).+ pub fn remove_op(&mut self, op: OpId) {+ if let Some(old) = self.by_op.remove(&op) {+ for key in old {+ if let Some(set) = self.by_key.get_mut(&key) {+ set.remove(&op);+ if set.is_empty() {+ self.by_key.remove(&key);+ }+ }+ }+ }+ }++ /// Active operations depending on any of `keys`.+ pub fn ops_for_keys<'a>(+ &self,+ keys: impl IntoIterator<Item = &'a EntityKey>,+ ) -> BTreeSet<OpId> {+ let mut out = BTreeSet::new();+ for key in keys {+ if let Some(ops) = self.by_key.get(key) {+ out.extend(ops.iter().copied());+ }+ }+ out+ }++ /// Keys pinned by at least one active operation (future: eviction).+ pub fn pinned(&self) -> impl Iterator<Item = &EntityKey> {+ self.by_key.keys()+ }++ pub fn active_ops(&self) -> usize {+ self.by_op.len()+ }++ /// All registered operation ids (cache reset → everything re-executes).+ pub fn all_ops(&self) -> BTreeSet<OpId> {+ self.by_op.keys().copied().collect()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn key(s: &str) -> EntityKey {+ EntityKey(s.to_string())+ }++ #[test]+ fn tracks_and_removes() {+ let mut idx = DepIndex::new();+ idx.set_op_deps(1, [key("A"), key("B")].into());+ idx.set_op_deps(2, [key("B"), key("C")].into());++ assert_eq!(idx.ops_for_keys(&[key("A")]), [1].into());+ assert_eq!(idx.ops_for_keys(&[key("B")]), [1, 2].into());+ assert_eq!(idx.ops_for_keys(&[key("C"), key("A")]), [1, 2].into());++ // Re-registration replaces deps.+ idx.set_op_deps(1, [key("C")].into());+ assert!(idx.ops_for_keys(&[key("A")]).is_empty());++ idx.remove_op(1);+ idx.remove_op(2);+ assert_eq!(idx.active_ops(), 0);+ assert!(idx.ops_for_keys(&[key("B"), key("C")]).is_empty());+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/document.rs b/rust/cloud-storage/client/cache-core/src/document.rsnew file mode 100644index 0000000000..7ed2241e77--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/document.rs@@ -0,0 +1,439 @@+//! Executable-document IR.+//!+//! apollo-parser's CST is lossless but awkward to walk repeatedly; we convert+//! each document once into a compact IR (and memoize by document hash at the+//! engine level). The IR is also where parse-time invariants are enforced so+//! the normalize/denormalize walks can be infallible about shape.++use crate::value::canonical_json;+use apollo_parser::cst;+use apollo_parser::cst::CstNode;+use serde_json::Value as Json;+use std::collections::HashMap;+use thiserror::Error;++#[derive(Debug, Error)]+pub enum DocumentError {+ #[error("GraphQL parse error: {0}")]+ Parse(String),+ #[error("document has no operations")]+ NoOperation,+ #[error("operation `{0}` not found")]+ UnknownOperation(String),+ #[error("only queries are supported (got {0})")]+ UnsupportedOperationType(String),+ #[error("fragment `{0}` is not defined")]+ UnknownFragment(String),+ #[error("malformed document: {0}")]+ Malformed(&'static str),+}++/// Argument value: constant JSON or a variable reference resolved at+/// read/write time.+#[derive(Debug, Clone)]+pub enum ArgValue {+ Const(Json),+ Variable(String),+ List(Vec<ArgValue>),+ Object(Vec<(String, ArgValue)>),+}++#[derive(Debug, Clone)]+pub struct FieldNode {+ /// Response key (alias if present, else name).+ pub response_key: String,+ /// Schema field name.+ pub name: String,+ pub arguments: Vec<(String, ArgValue)>,+ pub selection_set: Vec<Selection>,+}++#[derive(Debug, Clone)]+pub enum Selection {+ Field(FieldNode),+ /// Inline fragment or named-fragment spread, already flattened to a type+ /// condition (None = no condition) plus selections.+ Fragment {+ type_condition: Option<String>,+ selection_set: Vec<Selection>,+ },+}++#[derive(Debug)]+pub struct Operation {+ pub name: Option<String>,+ pub selection_set: Vec<Selection>,+}++#[derive(Debug)]+pub struct Document {+ pub operations: Vec<Operation>,+}++impl Document {+ /// Parses executable document text into the IR. Fragment spreads are+ /// inlined (cycles rejected by the parser's recursion limit; fragments+ /// must be defined in the same document, which urql guarantees).+ pub fn parse(text: &str) -> Result<Document, DocumentError> {+ let tree = apollo_parser::Parser::new(text).parse();+ if tree.errors().len() > 0 {+ let msg = tree+ .errors()+ .map(|e| e.message().to_string())+ .collect::<Vec<_>>()+ .join("; ");+ return Err(DocumentError::Parse(msg));+ }+ let doc = tree.document();++ let mut fragments: HashMap<String, cst::FragmentDefinition> = HashMap::new();+ let mut operations_cst = Vec::new();+ for def in doc.definitions() {+ match def {+ cst::Definition::OperationDefinition(op) => operations_cst.push(op),+ cst::Definition::FragmentDefinition(frag) => {+ let name = frag+ .fragment_name()+ .and_then(|n| n.name())+ .ok_or(DocumentError::Malformed("fragment without name"))?+ .text()+ .to_string();+ fragments.insert(name, frag);+ }+ _ => {+ return Err(DocumentError::Malformed(+ "type-system definition in executable document",+ ));+ }+ }+ }+ if operations_cst.is_empty() {+ return Err(DocumentError::NoOperation);+ }++ let mut operations = Vec::new();+ for op in operations_cst {+ if let Some(ty) = op.operation_type() {+ // Queries only for now; mutations/subscriptions are Phase 5+.+ if ty.query_token().is_none() {+ let label = ty.syntax().text().to_string();+ return Err(DocumentError::UnsupportedOperationType(label));+ }+ }+ let selection_set = convert_selection_set(+ op.selection_set()+ .ok_or(DocumentError::Malformed("operation without selection set"))?,+ &fragments,+ 0,+ )?;+ operations.push(Operation {+ name: op.name().map(|n| n.text().to_string()),+ selection_set,+ });+ }+ Ok(Document { operations })+ }++ /// Selects an operation by name (or the only one when unnamed).+ pub fn operation(&self, name: Option<&str>) -> Result<&Operation, DocumentError> {+ match name {+ None => {+ if self.operations.len() == 1 {+ Ok(&self.operations[0])+ } else {+ Err(DocumentError::Malformed(+ "operation name required for multi-operation documents",+ ))+ }+ }+ Some(n) => self+ .operations+ .iter()+ .find(|o| o.name.as_deref() == Some(n))+ .ok_or_else(|| DocumentError::UnknownOperation(n.to_string())),+ }+ }+}++const MAX_FRAGMENT_DEPTH: usize = 32;++fn convert_selection_set(+ set: cst::SelectionSet,+ fragments: &HashMap<String, cst::FragmentDefinition>,+ depth: usize,+) -> Result<Vec<Selection>, DocumentError> {+ if depth > MAX_FRAGMENT_DEPTH {+ return Err(DocumentError::Malformed(+ "fragment nesting too deep (cycle?)",+ ));+ }+ let mut out = Vec::new();+ for sel in set.selections() {+ match sel {+ cst::Selection::Field(f) => {+ let name = f+ .name()+ .ok_or(DocumentError::Malformed("field without name"))?+ .text()+ .to_string();+ let response_key = f+ .alias()+ .and_then(|a| a.name())+ .map(|n| n.text().to_string())+ .unwrap_or_else(|| name.clone());+ let mut arguments = Vec::new();+ if let Some(args) = f.arguments() {+ for arg in args.arguments() {+ let arg_name = arg+ .name()+ .ok_or(DocumentError::Malformed("argument without name"))?+ .text()+ .to_string();+ let value = arg+ .value()+ .ok_or(DocumentError::Malformed("argument without value"))?;+ arguments.push((arg_name, convert_value(value)?));+ }+ }+ let selection_set = match f.selection_set() {+ Some(s) => convert_selection_set(s, fragments, depth + 1)?,+ None => Vec::new(),+ };+ out.push(Selection::Field(FieldNode {+ response_key,+ name,+ arguments,+ selection_set,+ }));+ }+ cst::Selection::InlineFragment(frag) => {+ let type_condition = frag+ .type_condition()+ .and_then(|tc| tc.named_type())+ .and_then(|nt| nt.name())+ .map(|n| n.text().to_string());+ let selection_set = convert_selection_set(+ frag.selection_set().ok_or(DocumentError::Malformed(+ "inline fragment without selections",+ ))?,+ fragments,+ depth + 1,+ )?;+ out.push(Selection::Fragment {+ type_condition,+ selection_set,+ });+ }+ cst::Selection::FragmentSpread(spread) => {+ let name = spread+ .fragment_name()+ .and_then(|n| n.name())+ .ok_or(DocumentError::Malformed("fragment spread without name"))?+ .text()+ .to_string();+ let def = fragments+ .get(&name)+ .ok_or_else(|| DocumentError::UnknownFragment(name.clone()))?;+ let type_condition = def+ .type_condition()+ .and_then(|tc| tc.named_type())+ .and_then(|nt| nt.name())+ .map(|n| n.text().to_string());+ let selection_set = convert_selection_set(+ def.selection_set()+ .ok_or(DocumentError::Malformed("fragment without selections"))?,+ fragments,+ depth + 1,+ )?;+ out.push(Selection::Fragment {+ type_condition,+ selection_set,+ });+ }+ }+ }+ Ok(out)+}++fn convert_value(value: cst::Value) -> Result<ArgValue, DocumentError> {+ Ok(match value {+ cst::Value::Variable(v) => ArgValue::Variable(v.text().to_string()),+ cst::Value::StringValue(s) => ArgValue::Const(Json::String(String::from(s))),+ cst::Value::IntValue(i) => {+ let text = i.syntax().text().to_string();+ let n: serde_json::Number = text+ .parse::<i64>()+ .map(Into::into)+ .map_err(|_| DocumentError::Malformed("invalid int literal"))?;+ ArgValue::Const(Json::Number(n))+ }+ cst::Value::FloatValue(f) => {+ let text = f.syntax().text().to_string();+ let parsed: f64 = text+ .parse()+ .map_err(|_| DocumentError::Malformed("invalid float literal"))?;+ let n = serde_json::Number::from_f64(parsed)+ .ok_or(DocumentError::Malformed("non-finite float literal"))?;+ ArgValue::Const(Json::Number(n))+ }+ cst::Value::BooleanValue(b) => {+ ArgValue::Const(Json::Bool(b.syntax().text().to_string().trim() == "true"))+ }+ cst::Value::NullValue(_) => ArgValue::Const(Json::Null),+ cst::Value::EnumValue(e) => ArgValue::Const(Json::String(e.text().to_string())),+ cst::Value::ListValue(l) => {+ let mut items = Vec::new();+ for item in l.values() {+ items.push(convert_value(item)?);+ }+ ArgValue::List(items)+ }+ cst::Value::ObjectValue(o) => {+ let mut fields = Vec::new();+ for f in o.object_fields() {+ let name = f+ .name()+ .ok_or(DocumentError::Malformed("object field without name"))?+ .text()+ .to_string();+ let value = f+ .value()+ .ok_or(DocumentError::Malformed("object field without value"))?;+ fields.push((name, convert_value(value)?));+ }+ ArgValue::Object(fields)+ }+ })+}++#[derive(Debug, Error)]+#[error("missing variable `{0}`")]+pub struct MissingVariable(pub String);++/// Resolves an argument value against operation variables into plain JSON.+pub fn resolve_arg(+ value: &ArgValue,+ variables: &serde_json::Map<String, Json>,+) -> Result<Json, MissingVariable> {+ Ok(match value {+ ArgValue::Const(v) => v.clone(),+ ArgValue::Variable(name) => variables+ .get(name)+ .cloned()+ .ok_or_else(|| MissingVariable(name.clone()))?,+ ArgValue::List(items) => Json::Array(+ items+ .iter()+ .map(|i| resolve_arg(i, variables))+ .collect::<Result<_, _>>()?,+ ),+ ArgValue::Object(fields) => {+ let mut map = serde_json::Map::new();+ for (k, v) in fields {+ map.insert(k.clone(), resolve_arg(v, variables)?);+ }+ Json::Object(map)+ }+ })+}++/// Resolves a field's arguments to a canonical string (`None` when the field+/// has no arguments), for use in field storage keys.+pub fn resolve_args_key(+ field: &FieldNode,+ variables: &serde_json::Map<String, Json>,+) -> Result<Option<String>, MissingVariable> {+ if field.arguments.is_empty() {+ return Ok(None);+ }+ let mut map = serde_json::Map::new();+ for (name, value) in &field.arguments {+ map.insert(name.clone(), resolve_arg(value, variables)?);+ }+ Ok(Some(canonical_json(&Json::Object(map))))+}++#[cfg(test)]+mod tests {+ use super::*;++ const DOC: &str = r#"+ query Soup($input: SoupInput!) {+ soup(input: $input) {+ items {+ id+ entity {+ __typename+ ... on GraphqlSoupDocument { id docName: name }+ ...ChatFields+ }+ }+ nextCursor+ }+ }+ fragment ChatFields on GraphqlSoupChat { id chatName: name }+ "#;++ #[test]+ fn parses_real_shape() {+ let doc = Document::parse(DOC).unwrap();+ let op = doc.operation(Some("Soup")).unwrap();+ assert_eq!(op.name.as_deref(), Some("Soup"));+ let Selection::Field(soup) = &op.selection_set[0] else {+ panic!("expected field");+ };+ assert_eq!(soup.name, "soup");+ assert!(matches!(&soup.arguments[0].1, ArgValue::Variable(v) if v == "input"));++ // fragment spread flattened with type condition+ let Selection::Field(items) = &soup.selection_set[0] else {+ panic!()+ };+ let Selection::Field(entity) = &items.selection_set[1] else {+ panic!()+ };+ let conditions: Vec<_> = entity+ .selection_set+ .iter()+ .filter_map(|s| match s {+ Selection::Fragment { type_condition, .. } => type_condition.clone(),+ _ => None,+ })+ .collect();+ assert_eq!(conditions, vec!["GraphqlSoupDocument", "GraphqlSoupChat"]);+ }++ #[test]+ fn alias_and_args_key() {+ let doc = Document::parse(DOC).unwrap();+ let op = doc.operation(Some("Soup")).unwrap();+ let Selection::Field(soup) = &op.selection_set[0] else {+ panic!()+ };+ let mut vars = serde_json::Map::new();+ vars.insert(+ "input".into(),+ serde_json::json!({"limit": 20, "cursor": null}),+ );+ assert_eq!(+ resolve_args_key(soup, &vars).unwrap().unwrap(),+ r#"{"input":{"cursor":null,"limit":20}}"#+ );+ assert!(matches!(+ resolve_args_key(soup, &serde_json::Map::new()),+ Err(MissingVariable(v)) if v == "input"+ ));+ }++ #[test]+ fn rejects_mutations() {+ let err = Document::parse("mutation M { doThing }").unwrap_err();+ assert!(matches!(err, DocumentError::UnsupportedOperationType(_)));+ }++ #[test]+ fn rejects_unknown_fragment() {+ let err = Document::parse("query Q { a { ...Nope } }").unwrap_err();+ assert!(matches!(err, DocumentError::UnknownFragment(_)));+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/engine.rs b/rust/cloud-storage/client/cache-core/src/engine.rsnew file mode 100644index 0000000000..428b20614a--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/engine.rs@@ -0,0 +1,389 @@+//! The cache engine: ties documents, normalization, the hot tier, storage+//! and dependency tracking together behind the API the hosts (wasm worker /+//! Tauri) expose over RPC.++use crate::denormalize::{DenormalizeError, ReadOutcome, RecordSource, denormalize};+use crate::deps::{DepIndex, OpId};+use crate::document::{Document, DocumentError};+use crate::normalize::{NormalizeError, normalize};+use crate::store::Storage;+use crate::value::{EntityKey, Record};+use lru::LruCache;+use serde_json::Value as Json;+use std::collections::{BTreeSet, HashMap};+use std::num::NonZeroUsize;+use thiserror::Error;++#[derive(Debug, Error)]+pub enum EngineError<S: std::error::Error + 'static> {+ #[error(transparent)]+ Document(#[from] DocumentError),+ #[error(transparent)]+ Normalize(#[from] NormalizeError),+ #[error(transparent)]+ Denormalize(#[from] DenormalizeError),+ #[error("storage: {0}")]+ Storage(#[source] S),+}++/// Result of a cache read.+#[derive(Debug)]+pub enum ReadResult {+ /// Fully answerable from cache.+ Hit { data: Json },+ /// Not answerable; forward to the network.+ Miss,+}++/// Result of writing a network response.+#[derive(Debug)]+pub struct WriteResult {+ /// Records whose contents changed.+ pub changed: BTreeSet<EntityKey>,+ /// Active operations depending on changed records (host re-executes+ /// these). Excludes the operation that performed the write. After a+ /// `reset` this is *every* active operation except the origin.+ pub affected_ops: BTreeSet<OpId>,+ /// True when the identity witness observed a different user than the one+ /// bound to this cache: all previous state was wiped (silent restart)+ /// before this response was written. Hosts must broadcast this to other+ /// engine instances sharing the same storage.+ pub reset: bool,+}++/// Reserved storage key holding the identity bound to this cache. The+/// `__meta:` prefix can never collide with entity keys (typenames can't+/// contain `:`).+const IDENTITY_META_KEY: &str = "__meta:identity";+const IDENTITY_FIELD: &str = "userId";++/// Hydration/binding state of the session identity tag for this cache.+#[derive(Debug, Clone, PartialEq, Eq)]+enum IdentityState {+ /// Not yet loaded from storage.+ NotHydrated,+ /// Hydrated: no identity has been bound to this cache yet.+ Missing,+ /// Hydrated: bound to this identity. (Named `Bound` rather than `Some`+ /// to avoid shadowing/confusion with `Option::Some` in matches.)+ Bound(String),+}++/// Default hot-tier capacity (records, not bytes — byte budgets are a+/// hardening-phase refinement).+pub const DEFAULT_HOT_CAPACITY: usize = 10_000;++pub struct Engine<S: Storage> {+ storage: S,+ hot: LruCache<EntityKey, Record>,+ docs: HashMap<String, Document>,+ deps: DepIndex,+ identity: IdentityState,+}++impl<S: Storage> Engine<S> {+ pub fn new(storage: S) -> Self {+ Self::with_capacity(storage, DEFAULT_HOT_CAPACITY)+ }++ pub fn with_capacity(storage: S, hot_capacity: usize) -> Self {+ Engine {+ storage,+ hot: LruCache::new(NonZeroUsize::new(hot_capacity).expect("capacity > 0")),+ docs: HashMap::new(),+ deps: DepIndex::new(),+ identity: IdentityState::NotHydrated,+ }+ }++ /// The identity binding of this cache, hydrating it from storage on+ /// first use. Never returns [`IdentityState::NotHydrated`].+ async fn bound_identity(&mut self) -> Result<IdentityState, EngineError<S::Error>> {+ if self.identity == IdentityState::NotHydrated {+ let key = EntityKey(IDENTITY_META_KEY.to_string());+ let fetched = self+ .storage+ .get_batch(std::slice::from_ref(&key))+ .await+ .map_err(EngineError::Storage)?;+ let stored = fetched.into_iter().next().flatten().and_then(|record| {+ match record.fields.get(IDENTITY_FIELD) {+ Some(crate::value::CacheValue::String(s)) => Some(s.clone()),+ _ => None,+ }+ });+ self.identity = match stored {+ Some(user_id) => IdentityState::Bound(user_id),+ None => IdentityState::Missing,+ };+ }+ Ok(self.identity.clone())+ }++ async fn bind_identity(&mut self, user_id: &str) -> Result<(), EngineError<S::Error>> {+ let mut record = Record::default();+ record.fields.insert(+ IDENTITY_FIELD.to_string(),+ crate::value::CacheValue::String(user_id.to_string()),+ );+ self.storage+ .put_batch(vec![(EntityKey(IDENTITY_META_KEY.to_string()), record)])+ .await+ .map_err(EngineError::Storage)?;+ self.identity = IdentityState::Bound(user_id.to_string());+ Ok(())+ }++ /// Attempts to answer a query from cache. When `op_id` is given the+ /// operation is registered as active with the dependencies it touched+ /// (hit *or* miss — a miss still re-executes when its records change).+ pub async fn read_query(+ &mut self,+ op_id: Option<OpId>,+ query: &str,+ operation_name: Option<&str>,+ variables: &serde_json::Map<String, Json>,+ ) -> Result<ReadResult, EngineError<S::Error>> {+ let doc = Self::document(&mut self.docs, query)?;+ let op = doc.operation(operation_name)?;++ let mut overlay: HashMap<EntityKey, Record> = HashMap::new();+ let mut known_absent: BTreeSet<EntityKey> = BTreeSet::new();+ let mut deps = BTreeSet::new();++ let outcome = loop {+ deps.clear();+ let source = EngineSource {+ hot: &self.hot,+ overlay: &overlay,+ };+ match denormalize(op, variables, &source, &mut deps)? {+ ReadOutcome::Complete(data) => break ReadResult::Hit { data },+ ReadOutcome::Miss { .. } => break ReadResult::Miss,+ ReadOutcome::NeedRecords(missing) => {+ let to_fetch: Vec<EntityKey> = missing+ .into_iter()+ .filter(|k| !known_absent.contains(k) && !overlay.contains_key(k))+ .collect();+ if to_fetch.is_empty() {+ // Everything missing is genuinely absent → miss.+ break ReadResult::Miss;+ }+ let fetched = self+ .storage+ .get_batch(&to_fetch)+ .await+ .map_err(EngineError::Storage)?;+ for (key, record) in to_fetch.into_iter().zip(fetched) {+ match record {+ Some(r) => {+ overlay.insert(key, r);+ }+ None => {+ known_absent.insert(key);+ }+ }+ }+ }+ }+ };++ // Promote overlay records into the hot tier and refresh recency of+ // everything this operation touched.+ for (key, record) in overlay {+ self.hot.put(key, record);+ }+ for key in &deps {+ let _ = self.hot.get(key);+ }+ if let Some(op_id) = op_id {+ self.deps.set_op_deps(op_id, deps);+ }+ Ok(outcome)+ }++ /// Normalizes and stores a network response. Returns changed records and+ /// the affected active operations (excluding `origin_op`).+ ///+ /// `identity` is an opaque session tag extracted by the host (e.g. the+ /// viewer id from the response). The engine knows nothing about its+ /// meaning — only that a write tagged with a different identity than the+ /// one bound to this cache wipes everything before the write proceeds+ /// (silent restart), atomically with this write.+ pub async fn write_query(+ &mut self,+ origin_op: Option<OpId>,+ query: &str,+ operation_name: Option<&str>,+ variables: &serde_json::Map<String, Json>,+ data: &Json,+ identity: Option<&str>,+ ) -> Result<WriteResult, EngineError<S::Error>> {+ let doc = Self::document(&mut self.docs, query)?;+ let op = doc.operation(operation_name)?;+ let updates = normalize(op, variables, data)?;++ let mut reset = false;+ if let Some(observed) = identity {+ match self.bound_identity().await? {+ IdentityState::NotHydrated => unreachable!("bound_identity hydrates"),+ IdentityState::Missing => self.bind_identity(observed).await?,+ IdentityState::Bound(bound) if bound == observed => {}+ IdentityState::Bound(_) => {+ self.hot.clear();+ self.storage.clear().await.map_err(EngineError::Storage)?;+ self.bind_identity(observed).await?;+ reset = true;+ }+ }+ }++ // Load current values (hot tier, then storage) so merges detect real+ // changes. Merges are staged in a plain map, NOT the LRU: a batch+ // larger than the hot capacity would otherwise evict its own+ // records mid-merge and overwrite storage with partial updates.+ let mut staging: HashMap<EntityKey, Record> = HashMap::new();+ let mut missing: Vec<EntityKey> = Vec::new();+ for key in updates.keys() {+ match self.hot.peek(key) {+ Some(record) => {+ staging.insert(key.clone(), record.clone());+ }+ None => missing.push(key.clone()),+ }+ }+ if !missing.is_empty() {+ let fetched = self+ .storage+ .get_batch(&missing)+ .await+ .map_err(EngineError::Storage)?;+ for (key, record) in missing.into_iter().zip(fetched) {+ if let Some(r) = record {+ staging.insert(key, r);+ }+ }+ }++ let mut changed = BTreeSet::new();+ let mut to_persist: Vec<(EntityKey, Record)> = Vec::new();+ for (key, update) in updates {+ let merged = match staging.remove(&key) {+ Some(mut existing) => {+ if existing.merge(update) {+ changed.insert(key.clone());+ }+ existing+ }+ None => {+ changed.insert(key.clone());+ update+ }+ };+ // Refresh the hot tier (eviction here is harmless: storage gets+ // the fully merged record below).+ self.hot.put(key.clone(), merged.clone());+ to_persist.push((key, merged));+ }++ // Persist every touched record (idempotent for unchanged ones —+ // keeps storage authoritative even if the hot tier evicted them+ // between loads).+ self.storage+ .put_batch(to_persist)+ .await+ .map_err(EngineError::Storage)?;++ let mut affected_ops = if reset {+ // Everything anyone had cached is gone: re-execute all ops.+ self.deps.all_ops()+ } else {+ self.deps.ops_for_keys(changed.iter())+ };+ if let Some(origin) = origin_op {+ affected_ops.remove(&origin);+ }+ Ok(WriteResult {+ changed,+ affected_ops,+ reset,+ })+ }++ /// Reacts to a reset performed by *another* engine instance sharing the+ /// same storage (cross-tab broadcast): drops all local in-memory state+ /// and returns every local active operation for re-execution.+ pub fn external_reset(&mut self) -> BTreeSet<OpId> {+ self.hot.clear();+ self.docs.clear();+ // Another engine may have rebound the shared storage → re-hydrate.+ self.identity = IdentityState::NotHydrated;+ self.deps.all_ops()+ }++ /// Unregisters an active operation (urql teardown).+ pub fn teardown_operation(&mut self, op_id: OpId) {+ self.deps.remove_op(op_id);+ }++ /// Handles records changed *outside* this engine instance (another tab's+ /// engine in the dedicated-worker fallback topology, or push-driven+ /// invalidation): evicts them from the hot tier so the next read hits+ /// storage, and returns the local active operations that depend on them.+ pub fn invalidate_keys<'k>(+ &mut self,+ keys: impl IntoIterator<Item = &'k EntityKey>,+ ) -> BTreeSet<OpId> {+ let mut affected = BTreeSet::new();+ for key in keys {+ self.hot.pop(key);+ affected.extend(self.deps.ops_for_keys([key]));+ }+ affected+ }++ /// Drops all cached state (logout, schema-hash mismatch).+ pub async fn clear(&mut self) -> Result<(), EngineError<S::Error>> {+ self.hot.clear();+ self.deps = DepIndex::new();+ // The wipe below removes the binding record too.+ self.identity = IdentityState::Missing;+ self.storage.clear().await.map_err(EngineError::Storage)+ }++ pub fn active_ops(&self) -> usize {+ self.deps.active_ops()+ }++ /// Access to the underlying storage (hosts need it for lifecycle+ /// operations like closing connections before database deletion).+ pub fn storage(&self) -> &S {+ &self.storage+ }++ /// Memoized document parse. Takes the map (not `&mut self`) so callers+ /// can keep the returned borrow while using other engine fields.+ fn document<'d>(+ docs: &'d mut HashMap<String, Document>,+ query: &str,+ ) -> Result<&'d Document, DocumentError> {+ use std::collections::hash_map::Entry;+ match docs.entry(query.to_string()) {+ Entry::Occupied(e) => Ok(e.into_mut()),+ Entry::Vacant(e) => Ok(e.insert(Document::parse(query)?)),+ }+ }+}++/// Read view over hot tier + per-read overlay. Uses `peek` (no recency+/// mutation) — recency is refreshed once per read from the dep set.+struct EngineSource<'a> {+ hot: &'a LruCache<EntityKey, Record>,+ overlay: &'a HashMap<EntityKey, Record>,+}++impl RecordSource for EngineSource<'_> {+ fn get(&self, key: &EntityKey) -> Option<&Record> {+ self.overlay.get(key).or_else(|| self.hot.peek(key))+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/lib.rs b/rust/cloud-storage/client/cache-core/src/lib.rsnew file mode 100644index 0000000000..5b4d26a9f5--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/lib.rs@@ -0,0 +1,13 @@+//! Normalized GraphQL cache engine (Phase 1: pure, native-tested core).+//!+//! Design doc: `js/app/docs/graphql-normalized-cache-plan.md`.++pub mod codec;+pub mod denormalize;+pub mod deps;+pub mod document;+pub mod engine;+pub mod meta;+pub mod normalize;+pub mod store;+pub mod value;diff --git a/rust/cloud-storage/client/cache-core/src/meta.rs b/rust/cloud-storage/client/cache-core/src/meta.rsnew file mode 100644index 0000000000..31609f82ed--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/meta.rs@@ -0,0 +1,168 @@+//! Schema metadata: static tables generated at build time from+//! `rust/cloud-storage/schema.graphql` + `key_config.toml` (see `build.rs`).+//!+//! The cache never parses SDL at runtime — everything type-related is+//! resolved through these tables.++/// Kind of a composite (selectable) type.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TypeKind {+ Object,+ Union,+ Interface,+}++/// What a field's named type resolves to, decided at codegen time.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FieldKind {+ /// Object / union / interface — value is a link (ref) or embedded object.+ Composite,+ /// Built-in scalar or enum — stored as a plain leaf value.+ Leaf,+ /// Custom scalar (e.g. `JSON`) — stored as an opaque JSON blob.+ OpaqueScalar,+}++/// Flattened GraphQL wrapping type. Nested lists are rejected at codegen.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct FieldType {+ /// The named (inner) type.+ pub name: &'static str,+ pub kind: FieldKind,+ /// Nullability of the outermost wrapper.+ pub nullable: bool,+ pub list: bool,+ /// Only meaningful when `list` is true.+ pub item_nullable: bool,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct FieldMeta {+ pub name: &'static str,+ pub ty: FieldType,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct TypeMeta {+ pub name: &'static str,+ pub kind: TypeKind,+ /// `Some(fields)` when the type is a normalized entity; `None` when it is+ /// embedded inline in its parent record. Policy from `key_config.toml`.+ pub key_fields: Option<&'static [&'static str]>,+ /// Field definitions (objects/interfaces only; empty for unions).+ pub fields: &'static [FieldMeta],+ /// Union members / interface implementors (empty for plain objects).+ pub possible_types: &'static [&'static str],+}++include!(concat!(env!("OUT_DIR"), "/schema_meta.rs"));++/// Looks up a composite type by name. `TYPES` is sorted by name at codegen.+pub fn type_meta(name: &str) -> Option<&'static TypeMeta> {+ TYPES+ .binary_search_by(|t| t.name.cmp(name))+ .ok()+ .map(|i| &TYPES[i])+}++/// Looks up a field on a composite type.+pub fn field_meta(type_name: &str, field: &str) -> Option<&'static FieldMeta> {+ let t = type_meta(type_name)?;+ t.fields.iter().find(|f| f.name == field)+}++/// True when an object of concrete type `concrete` matches a fragment type+/// condition `condition` (exact match, union membership, or interface+/// implementation).+pub fn type_matches(concrete: &str, condition: &str) -> bool {+ if concrete == condition {+ return true;+ }+ match type_meta(condition) {+ Some(meta) => meta.possible_types.contains(&concrete),+ None => false,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn query_root_is_present() {+ let root = type_meta(QUERY_ROOT_TYPE).expect("query root type");+ assert_eq!(root.kind, TypeKind::Object);+ assert!(root.key_fields.is_none());+ assert!(root.fields.iter().any(|f| f.name == "user"));++ // The viewer object is keyed by presence-of-id.+ let user = type_meta("GraphqlUser").expect("user type");+ assert_eq!(user.key_fields, Some(&["id"][..]));+ assert!(user.fields.iter().any(|f| f.name == "soup"));+ }++ #[test]+ fn union_possible_types() {+ let entity = type_meta("GraphqlSoupEntity").expect("entity union");+ assert_eq!(entity.kind, TypeKind::Union);+ assert!(entity.possible_types.contains(&"GraphqlSoupDocument"));+ assert!(entity.possible_types.contains(&"GraphqlSoupForeignEntity"));+ assert_eq!(entity.possible_types.len(), 9);+ assert!(type_matches("GraphqlSoupDocument", "GraphqlSoupEntity"));+ assert!(!type_matches("GraphqlSoupItem", "GraphqlSoupEntity"));+ }++ #[test]+ fn presence_of_id_convention_applied() {+ assert_eq!(+ type_meta("GraphqlSoupDocument").unwrap().key_fields,+ Some(&["id"][..])+ );+ // Renamed from `messageId` so the convention keys it.+ assert_eq!(+ type_meta("GraphqlSoupChannelMessage").unwrap().key_fields,+ Some(&["id"][..])+ );+ // Property values are per-entity; the schema exposes the definition+ // id as `propertyDefinitionId` (not `id`) so properties embed.+ assert_eq!(type_meta("GraphqlSoupProperty").unwrap().key_fields, None);+ assert!(field_meta("GraphqlSoupProperty", "propertyDefinitionId").is_some());+ // No id field → embedded.+ assert_eq!(type_meta("SoupPage").unwrap().key_fields, None);+ assert_eq!(+ type_meta("GraphqlSoupChannelParticipant")+ .unwrap()+ .key_fields,+ None+ );+ }++ #[test]+ fn field_shapes() {+ // properties: [GraphqlSoupProperty!]!+ let f = field_meta("GraphqlSoupDocument", "properties").unwrap();+ assert_eq!(f.ty.name, "GraphqlSoupProperty");+ assert_eq!(f.ty.kind, FieldKind::Composite);+ assert!(!f.ty.nullable && f.ty.list && !f.ty.item_nullable);++ // viewedAt: String (nullable leaf)+ let f = field_meta("GraphqlSoupDocument", "viewedAt").unwrap();+ assert_eq!(f.ty.kind, FieldKind::Leaf);+ assert!(f.ty.nullable && !f.ty.list);++ // metadata: JSON! (opaque scalar)+ let f = field_meta("GraphqlSoupForeignEntity", "metadata").unwrap();+ assert_eq!(f.ty.kind, FieldKind::OpaqueScalar);+ assert!(!f.ty.nullable);++ // entity: GraphqlSoupEntity! (composite link to a union)+ let f = field_meta("GraphqlSoupItem", "entity").unwrap();+ assert_eq!(f.ty.kind, FieldKind::Composite);+ assert_eq!(f.ty.name, "GraphqlSoupEntity");+ }++ #[test]+ fn schema_hash_present() {+ assert_eq!(SCHEMA_HASH.len(), 64);+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/normalize.rs b/rust/cloud-storage/client/cache-core/src/normalize.rsnew file mode 100644index 0000000000..52c9d9b3a3--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/normalize.rs@@ -0,0 +1,270 @@+//! Write path: response JSON → normalized records.++use crate::document::{FieldNode, MissingVariable, Operation, Selection, resolve_args_key};+use crate::meta::{self, FieldKind, TypeKind};+use crate::value::{CacheValue, EntityKey, Record, field_key};+use serde_json::Value as Json;+use std::collections::BTreeMap;+use thiserror::Error;++#[derive(Debug, Error)]+pub enum NormalizeError {+ #[error(transparent)]+ MissingVariable(#[from] MissingVariable),+ #[error("unknown type `{0}` (schema drift? rebuild after schema changes)")]+ UnknownType(String),+ #[error("unknown field `{type_name}.{field}`")]+ UnknownField { type_name: String, field: String },+ #[error(+ "`{type_name}` is abstract but the response object has no __typename; add __typename to the selection"+ )]+ MissingTypename { type_name: String },+ #[error(+ "key field `{type_name}.{field}` is missing or not a string/number in the response; every query fetching `{type_name}` must select its key"+ )]+ BadKeyField { type_name: String, field: String },+ #[error("response field `{type_name}.{field}` has unexpected shape: {detail}")]+ Shape {+ type_name: String,+ field: String,+ detail: &'static str,+ },+}++/// Records produced by normalizing one response. Each record contains only+/// the fields this response provided — the store merges them into existing+/// records.+pub type RecordUpdates = BTreeMap<EntityKey, Record>;++/// Normalizes a response's `data` object into record updates rooted at+/// [`ROOT_QUERY`](crate::value::ROOT_QUERY).+pub fn normalize(+ op: &Operation,+ variables: &serde_json::Map<String, Json>,+ data: &Json,+) -> Result<RecordUpdates, NormalizeError> {+ let Json::Object(data) = data else {+ return Err(NormalizeError::Shape {+ type_name: meta::QUERY_ROOT_TYPE.to_string(),+ field: "(data)".to_string(),+ detail: "response data is not an object",+ });+ };+ let mut records = RecordUpdates::new();+ let mut root = Record::default();+ write_object_fields(+ &op.selection_set,+ meta::QUERY_ROOT_TYPE,+ data,+ variables,+ &mut root.fields,+ &mut records,+ )?;+ merge_into(&mut records, EntityKey::root(), root);+ Ok(records)+}++fn merge_into(records: &mut RecordUpdates, key: EntityKey, record: Record) {+ records.entry(key).or_default().merge(record);+}++/// Flattens fragments applicable to `concrete_type` and visits each field.+fn collect_fields<'a>(+ selections: &'a [Selection],+ concrete_type: &str,+ out: &mut Vec<&'a FieldNode>,+) {+ for sel in selections {+ match sel {+ Selection::Field(f) => out.push(f),+ Selection::Fragment {+ type_condition,+ selection_set,+ } => {+ let applies = match type_condition {+ None => true,+ Some(cond) => meta::type_matches(concrete_type, cond),+ };+ if applies {+ collect_fields(selection_set, concrete_type, out);+ }+ }+ }+ }+}++/// Writes the selected fields of one response object into `target` (a+/// record's or embedded object's field map), normalizing children into+/// `records`.+fn write_object_fields(+ selections: &[Selection],+ type_name: &str,+ data: &serde_json::Map<String, Json>,+ variables: &serde_json::Map<String, Json>,+ target: &mut BTreeMap<String, CacheValue>,+ records: &mut RecordUpdates,+) -> Result<(), NormalizeError> {+ // The concrete type: trust __typename in the response when present.+ let concrete = match data.get("__typename") {+ Some(Json::String(t)) => t.as_str(),+ _ => type_name,+ };+ target.insert(+ "__typename".to_string(),+ CacheValue::String(concrete.to_string()),+ );++ let mut fields = Vec::new();+ collect_fields(selections, concrete, &mut fields);++ for f in fields {+ if f.name == "__typename" {+ continue; // handled above+ }+ let fmeta =+ meta::field_meta(concrete, &f.name).ok_or_else(|| NormalizeError::UnknownField {+ type_name: concrete.to_string(),+ field: f.name.clone(),+ })?;+ let args = resolve_args_key(f, variables)?;+ let storage_key = field_key(&f.name, args.as_deref());++ // GraphQL guarantees selected fields are present in data; tolerate+ // absence by skipping (defensive against non-conformant servers).+ let Some(value) = data.get(&f.response_key) else {+ continue;+ };++ let cache_value = write_value(f, fmeta.ty.name, fmeta.ty.kind, value, variables, records)+ .map_err(|detail| NormalizeError::Shape {+ type_name: concrete.to_string(),+ field: f.name.clone(),+ detail,+ })?;+ let cache_value = cache_value?;+ target.insert(storage_key, cache_value);+ }+ Ok(())+}++/// Converts one response value. Outer `Result` is shape errors (with static+/// detail); inner carries nested structured errors.+#[allow(clippy::type_complexity)]+fn write_value(+ field: &FieldNode,+ named_type: &str,+ kind: FieldKind,+ value: &Json,+ variables: &serde_json::Map<String, Json>,+ records: &mut RecordUpdates,+) -> Result<Result<CacheValue, NormalizeError>, &'static str> {+ Ok(match value {+ Json::Null => Ok(CacheValue::Null),+ Json::Array(items) => {+ let mut out = Vec::with_capacity(items.len());+ for item in items {+ match write_value(field, named_type, kind, item, variables, records)? {+ Ok(v) => out.push(v),+ Err(e) => return Ok(Err(e)),+ }+ }+ Ok(CacheValue::List(out))+ }+ Json::Bool(b) => match kind {+ FieldKind::Leaf => Ok(CacheValue::Bool(*b)),+ FieldKind::OpaqueScalar => Ok(CacheValue::opaque(value)),+ FieldKind::Composite => return Err("expected object, got boolean"),+ },+ Json::Number(n) => match kind {+ FieldKind::Leaf => Ok(CacheValue::Number(n.into())),+ FieldKind::OpaqueScalar => Ok(CacheValue::opaque(value)),+ FieldKind::Composite => return Err("expected object, got number"),+ },+ Json::String(s) => match kind {+ FieldKind::Leaf => Ok(CacheValue::String(s.clone())),+ FieldKind::OpaqueScalar => Ok(CacheValue::opaque(value)),+ FieldKind::Composite => return Err("expected object, got string"),+ },+ Json::Object(obj) => match kind {+ FieldKind::OpaqueScalar => Ok(CacheValue::opaque(value)),+ FieldKind::Leaf => return Err("expected scalar, got object"),+ FieldKind::Composite => {+ match normalize_object(field, named_type, obj, variables, records) {+ Ok(v) => Ok(v),+ Err(e) => return Ok(Err(e)),+ }+ }+ },+ })+}++/// Normalizes a composite response object: either into its own record+/// (keyable → `Ref`) or an embedded object value.+fn normalize_object(+ field: &FieldNode,+ named_type: &str,+ obj: &serde_json::Map<String, Json>,+ variables: &serde_json::Map<String, Json>,+ records: &mut RecordUpdates,+) -> Result<CacheValue, NormalizeError> {+ let named_meta = meta::type_meta(named_type)+ .ok_or_else(|| NormalizeError::UnknownType(named_type.to_string()))?;++ let concrete: &str = match obj.get("__typename") {+ Some(Json::String(t)) => t,+ _ if named_meta.kind == TypeKind::Object => named_type,+ _ => {+ return Err(NormalizeError::MissingTypename {+ type_name: named_type.to_string(),+ });+ }+ };+ let concrete_meta = meta::type_meta(concrete)+ .ok_or_else(|| NormalizeError::UnknownType(concrete.to_string()))?;++ match concrete_meta.key_fields {+ Some(key_fields) => {+ let mut key_values = Vec::with_capacity(key_fields.len());+ for kf in key_fields {+ let v = match obj.get(*kf) {+ Some(Json::String(s)) => s.clone(),+ Some(Json::Number(n)) => n.to_string(),+ _ => {+ return Err(NormalizeError::BadKeyField {+ type_name: concrete.to_string(),+ field: kf.to_string(),+ });+ }+ };+ key_values.push(v);+ }+ let key = EntityKey::entity(+ concrete,+ &key_values.iter().map(|s| s.as_str()).collect::<Vec<_>>(),+ );+ let mut record = Record::default();+ write_object_fields(+ &field.selection_set,+ concrete,+ obj,+ variables,+ &mut record.fields,+ records,+ )?;+ merge_into(records, key.clone(), record);+ Ok(CacheValue::Ref(key))+ }+ None => {+ let mut embedded = BTreeMap::new();+ write_object_fields(+ &field.selection_set,+ concrete,+ obj,+ variables,+ &mut embedded,+ records,+ )?;+ Ok(CacheValue::Object(embedded))+ }+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/store.rs b/rust/cloud-storage/client/cache-core/src/store.rsnew file mode 100644index 0000000000..5aebf9a923--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/store.rs@@ -0,0 +1,75 @@+//! 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.++use crate::value::{EntityKey, Record};+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;++ /// Fetches records; result is aligned with `keys` (`None` = absent).+ async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error>;++ /// Upserts records atomically (all-or-nothing per batch).+ async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error>;++ /// Deletes records (absent keys are ignored).+ async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error>;++ /// Drops everything (logout / corruption rebuild).+ async fn clear(&mut self) -> Result<(), Self::Error>;+}++/// Hash-map storage for tests and as the Phase 1 default.+#[derive(Debug, Default)]+pub struct InMemoryStorage {+ records: HashMap<EntityKey, Record>,+}++impl InMemoryStorage {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn len(&self) -> usize {+ self.records.len()+ }++ pub fn is_empty(&self) -> bool {+ self.records.is_empty()+ }+}++impl Storage for InMemoryStorage {+ type Error = Infallible;++ async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error> {+ Ok(keys.iter().map(|k| self.records.get(k).cloned()).collect())+ }++ async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error> {+ for (k, v) in entries {+ self.records.insert(k, v);+ }+ Ok(())+ }++ async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {+ for k in keys {+ self.records.remove(k);+ }+ Ok(())+ }++ async fn clear(&mut self) -> Result<(), Self::Error> {+ self.records.clear();+ Ok(())+ }+}diff --git a/rust/cloud-storage/client/cache-core/src/value.rs b/rust/cloud-storage/client/cache-core/src/value.rsnew file mode 100644index 0000000000..c844ac6bd1--- /dev/null+++ b/rust/cloud-storage/client/cache-core/src/value.rs@@ -0,0 +1,226 @@+//! Stored value representation: entity keys, field keys, records and cache+//! values.++use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use std::fmt;++/// Key of a normalized record: `"Typename:keyValue"`, or [`ROOT_QUERY`].+#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]+pub struct EntityKey(pub String);++/// The singleton record holding root-level query fields (graphcache's+/// `Query` record). Field keys on it embed arguments, e.g.+/// `soup({"input":{...}})`.+pub const ROOT_QUERY: &str = "ROOT_QUERY";++impl EntityKey {+ pub fn root() -> Self {+ EntityKey(ROOT_QUERY.to_string())+ }++ pub fn entity(typename: &str, key_values: &[&str]) -> Self {+ let mut s = String::with_capacity(typename.len() + 16);+ s.push_str(typename);+ for v in key_values {+ s.push(':');+ s.push_str(v);+ }+ EntityKey(s)+ }++ pub fn is_root(&self) -> bool {+ self.0 == ROOT_QUERY+ }+}++impl fmt::Display for EntityKey {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.write_str(&self.0)+ }+}++/// Storage key of a field within a record: `name` or `name({canonicalArgs})`.+pub type FieldKey = String;++/// Builds a field storage key from the field name and resolved, canonical+/// argument JSON (sorted object keys). `args` must already be canonical.+pub fn field_key(name: &str, args: Option<&str>) -> FieldKey {+ match args {+ None => name.to_string(),+ Some(a) => format!("{name}({a})"),+ }+}++/// A JSON number in a postcard-serializable representation+/// (`serde_json::Number` requires self-describing formats).+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]+pub enum CacheNumber {+ PosInt(u64),+ NegInt(i64),+ Float(f64),+}++impl From<&serde_json::Number> for CacheNumber {+ fn from(n: &serde_json::Number) -> Self {+ if let Some(u) = n.as_u64() {+ CacheNumber::PosInt(u)+ } else if let Some(i) = n.as_i64() {+ CacheNumber::NegInt(i)+ } else {+ CacheNumber::Float(n.as_f64().expect("number is u64, i64 or f64"))+ }+ }+}++impl CacheNumber {+ pub fn to_json(self) -> serde_json::Number {+ match self {+ CacheNumber::PosInt(u) => serde_json::Number::from(u),+ CacheNumber::NegInt(i) => serde_json::Number::from(i),+ CacheNumber::Float(f) => {+ serde_json::Number::from_f64(f).expect("stored floats are finite")+ }+ }+ }+}++/// A value stored inside a record.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub enum CacheValue {+ Null,+ Bool(bool),+ Number(CacheNumber),+ String(String),+ /// Link to another normalized record.+ Ref(EntityKey),+ /// Embedded (non-keyable) object. `__typename` is stored as a regular+ /// field when known, for fragment matching on read.+ Object(BTreeMap<FieldKey, CacheValue>),+ List(Vec<CacheValue>),+ /// Opaque custom-scalar blob (e.g. `JSON`) as canonical JSON text+ /// (canonical → comparable; text → postcard-serializable).+ Opaque(String),+}++impl CacheValue {+ /// Wraps an opaque custom-scalar JSON value.+ pub fn opaque(value: &serde_json::Value) -> Self {+ CacheValue::Opaque(canonical_json(value))+ }+}++/// A normalized record: field key → value.+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]+pub struct Record {+ pub fields: BTreeMap<FieldKey, CacheValue>,+}++impl Record {+ /// Merges `other` into `self` field-by-field (new values replace old;+ /// lists and embedded objects are replaced wholesale, graphcache+ /// semantics). Returns true when anything changed.+ pub fn merge(&mut self, other: Record) -> bool {+ let mut changed = false;+ for (k, v) in other.fields {+ match self.fields.get(&k) {+ Some(existing) if *existing == v => {}+ _ => {+ self.fields.insert(k, v);+ changed = true;+ }+ }+ }+ changed+ }++ pub fn typename(&self) -> Option<&str> {+ match self.fields.get("__typename") {+ Some(CacheValue::String(s)) => Some(s),+ _ => None,+ }+ }+}++/// Canonical JSON serialization: object keys sorted, no whitespace. Used for+/// argument field keys and operation hashing so logically-equal inputs+/// collide.+pub fn canonical_json(value: &serde_json::Value) -> String {+ let mut out = String::new();+ write_canonical(value, &mut out);+ out+}++fn write_canonical(value: &serde_json::Value, out: &mut String) {+ match value {+ serde_json::Value::Object(map) => {+ let mut entries: Vec<_> = map.iter().collect();+ entries.sort_by(|a, b| a.0.cmp(b.0));+ out.push('{');+ for (i, (k, v)) in entries.iter().enumerate() {+ if i > 0 {+ out.push(',');+ }+ out.push_str(&serde_json::to_string(k).expect("string serializes"));+ out.push(':');+ write_canonical(v, out);+ }+ out.push('}');+ }+ serde_json::Value::Array(items) => {+ out.push('[');+ for (i, v) in items.iter().enumerate() {+ if i > 0 {+ out.push(',');+ }+ write_canonical(v, out);+ }+ out.push(']');+ }+ other => out.push_str(&serde_json::to_string(other).expect("scalar serializes")),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn canonical_sorts_keys_recursively() {+ let v = json!({"b": {"z": 1, "a": [ {"y": 2, "x": 3} ]}, "a": null});+ assert_eq!(+ canonical_json(&v),+ r#"{"a":null,"b":{"a":[{"x":3,"y":2}],"z":1}}"#+ );+ }++ #[test]+ fn merge_reports_changes() {+ let mut r = Record::default();+ let mut other = Record::default();+ other+ .fields+ .insert("name".into(), CacheValue::String("A".into()));+ assert!(r.merge(other.clone()));+ assert!(!r.merge(other)); // idempotent+ let mut third = Record::default();+ third+ .fields+ .insert("name".into(), CacheValue::String("B".into()));+ assert!(r.merge(third));+ }++ #[test]+ fn entity_key_format() {+ assert_eq!(+ EntityKey::entity("GraphqlSoupDocument", &["doc-1"]).0,+ "GraphqlSoupDocument:doc-1"+ );+ assert_eq!(+ field_key("soup", Some(r#"{"input":{}}"#)),+ r#"soup({"input":{}})"#+ );+ assert_eq!(field_key("id", None), "id");+ }+}diff --git a/rust/cloud-storage/client/cache-core/tests/engine.rs b/rust/cloud-storage/client/cache-core/tests/engine.rsnew file mode 100644index 0000000000..7b38702157--- /dev/null+++ b/rust/cloud-storage/client/cache-core/tests/engine.rs@@ -0,0 +1,379 @@+//! Engine-level tests: read/write flow, hot-tier eviction falling back to+//! storage, dependency-driven re-execution, teardown, clear.++use cache_core::engine::{Engine, ReadResult};+use cache_core::store::InMemoryStorage;+use pollster::block_on;+use serde_json::{Value as Json, json};++const QUERY: &str = r#"+query Soup($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items {+ id+ entity {+ __typename+ ... on GraphqlSoupDocument { id documentName: name ownerId }+ }+ }+ nextCursor+ hasMore+ }+ }+}+"#;++fn vars(limit: u64) -> serde_json::Map<String, Json> {+ let Json::Object(map) = json!({ "input": { "limit": limit } }) else {+ unreachable!()+ };+ map+}++fn page(names: &[(&str, &str)]) -> Json {+ page_for_user("user-1", names)+}++fn page_for_user(user: &str, names: &[(&str, &str)]) -> Json {+ json!({+ "user": {+ "id": user,+ "soup": {+ "items": names.iter().map(|(id, name)| json!({+ "id": id,+ "entity": {+ "__typename": "GraphqlSoupDocument",+ "id": id,+ "documentName": name,+ "ownerId": user+ }+ })).collect::<Vec<_>>(),+ "nextCursor": null,+ "hasMore": false+ }+ }+ })+}++#[test]+fn miss_then_write_then_hit() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());++ let read = engine+ .read_query(Some(1), QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap();+ assert!(matches!(read, ReadResult::Miss));++ let data = page(&[("doc-1", "Design doc")]);+ let write = engine+ .write_query(Some(1), QUERY, Some("Soup"), &vars(10), &data, None)+ .await+ .unwrap();+ assert!(!write.changed.is_empty());+ // Only op 1 is active and it's the origin — no re-executions.+ assert!(write.affected_ops.is_empty());++ let read = engine+ .read_query(Some(1), QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap();+ let ReadResult::Hit { data: cached } = read else {+ panic!("expected hit");+ };+ assert_eq!(cached, data);+ });+}++#[test]+fn cross_operation_invalidation() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());++ // Op 1: limit 10; Op 2: limit 20 — different root fields, shared+ // entity doc-1.+ engine+ .write_query(+ Some(1),+ QUERY,+ Some("Soup"),+ &vars(10),+ &page(&[("doc-1", "A")]),+ None,+ )+ .await+ .unwrap();+ engine+ .read_query(Some(1), QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap();++ // Op 2's response renames doc-1 → op 1 must be re-executed.+ let write = engine+ .write_query(+ Some(2),+ QUERY,+ Some("Soup"),+ &vars(20),+ &page(&[("doc-1", "B")]),+ None,+ )+ .await+ .unwrap();+ assert!(write.affected_ops.contains(&1), "affected: {write:?}");++ // Re-executed op 1 sees the new name.+ let ReadResult::Hit { data } = engine+ .read_query(Some(1), QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap()+ else {+ panic!("expected hit");+ };+ assert_eq!(+ data["user"]["soup"]["items"][0]["entity"]["documentName"],+ json!("B")+ );++ // Identical rewrite changes nothing → nobody re-executes.+ let write = engine+ .write_query(+ Some(2),+ QUERY,+ Some("Soup"),+ &vars(20),+ &page(&[("doc-1", "B")]),+ None,+ )+ .await+ .unwrap();+ assert!(write.changed.is_empty());+ assert!(write.affected_ops.is_empty());++ // After teardown op 1 is no longer notified.+ engine.teardown_operation(1);+ let write = engine+ .write_query(+ Some(2),+ QUERY,+ Some("Soup"),+ &vars(20),+ &page(&[("doc-1", "C")]),+ None,+ )+ .await+ .unwrap();+ assert!(!write.changed.is_empty());+ assert!(write.affected_ops.is_empty());+ });+}++#[test]+fn hot_tier_eviction_falls_back_to_storage() {+ block_on(async {+ // Capacity 2: a page with 3+ records (root + item + entity) forces+ // eviction between write and read.+ let mut engine = Engine::with_capacity(InMemoryStorage::new(), 2);++ let data = page(&[("doc-1", "A"), ("doc-2", "B"), ("doc-3", "C")]);+ engine+ .write_query(None, QUERY, Some("Soup"), &vars(10), &data, None)+ .await+ .unwrap();++ let ReadResult::Hit { data: cached } = engine+ .read_query(None, QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap()+ else {+ panic!("expected hit via storage");+ };+ assert_eq!(cached, data);+ });+}++#[test]+fn clear_wipes_everything() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ engine+ .write_query(+ None,+ QUERY,+ Some("Soup"),+ &vars(10),+ &page(&[("doc-1", "A")]),+ None,+ )+ .await+ .unwrap();+ engine.clear().await.unwrap();+ let read = engine+ .read_query(None, QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap();+ assert!(matches!(read, ReadResult::Miss));+ });+}++#[test]+fn identity_witness_wipes_on_user_change() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());++ // User A populates the cache; op 1 is active.+ engine+ .write_query(+ None,+ QUERY,+ Some("Soup"),+ &vars(10),+ &page(&[("doc-1", "A")]),+ None,+ )+ .await+ .unwrap();+ engine+ .read_query(Some(1), QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap();++ // Same user again: no reset. Untagged writes never reset either.+ let write = engine+ .write_query(+ Some(2),+ QUERY,+ Some("Soup"),+ &vars(20),+ &page(&[("doc-2", "B")]),+ Some("user-1"),+ )+ .await+ .unwrap();+ assert!(!write.reset);+ let write = engine+ .write_query(+ Some(2),+ QUERY,+ Some("Soup"),+ &vars(20),+ &page(&[("doc-2", "B2")]),+ None,+ )+ .await+ .unwrap();+ assert!(!write.reset);++ // A response for a different user wipes everything (silent restart).+ let write = engine+ .write_query(+ Some(2),+ QUERY,+ Some("Soup"),+ &vars(20),+ &page_for_user("user-2", &[("doc-9", "Z")]),+ Some("user-2"),+ )+ .await+ .unwrap();+ assert!(write.reset);+ // Every active op except the origin re-executes.+ assert!(write.affected_ops.contains(&1));+ assert!(!write.affected_ops.contains(&2));++ // Old user's data is gone; new user's write landed.+ let read = engine+ .read_query(Some(1), QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap();+ assert!(matches!(read, ReadResult::Miss));+ let read = engine+ .read_query(Some(2), QUERY, Some("Soup"), &vars(20))+ .await+ .unwrap();+ let ReadResult::Hit { data } = read else {+ panic!("expected hit for new user");+ };+ assert_eq!(data["user"]["id"], serde_json::json!("user-2"));++ // external_reset drops local state and reports all local ops.+ let ops = engine.external_reset();+ assert!(ops.contains(&1) && ops.contains(&2));+ });+}++#[test]+fn capacity_constrained_rewrite_preserves_fields() {+ block_on(async {+ // Hot capacity far below the batch size: during a write, the batch+ // itself exceeds the LRU. A partial re-write over the same entities+ // must still merge against storage, not clobber it.+ let mut engine = Engine::with_capacity(InMemoryStorage::new(), 2);++ // Full write: documentName + ownerId (well over 2 records: root,+ // user, 3 items, 3 documents).+ let full = page(&[("doc-1", "A"), ("doc-2", "B"), ("doc-3", "C")]);+ engine+ .write_query(None, QUERY, Some("Soup"), &vars(10), &full, None)+ .await+ .unwrap();++ // Partial re-write of the same entities via a narrower query (no+ // ownerId), renaming them.+ const PARTIAL_QUERY: &str = r#"+ query Soup($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items {+ id+ entity {+ __typename+ ... on GraphqlSoupDocument { id documentName: name }+ }+ }+ nextCursor+ hasMore+ }+ }+ }+ "#;+ let partial = json!({+ "user": {+ "id": "user-1",+ "soup": {+ "items": [+ { "id": "doc-1", "entity": { "__typename": "GraphqlSoupDocument", "id": "doc-1", "documentName": "A2" } },+ { "id": "doc-2", "entity": { "__typename": "GraphqlSoupDocument", "id": "doc-2", "documentName": "B2" } },+ { "id": "doc-3", "entity": { "__typename": "GraphqlSoupDocument", "id": "doc-3", "documentName": "C2" } }+ ],+ "nextCursor": null,+ "hasMore": false+ }+ }+ });+ engine+ .write_query(None, PARTIAL_QUERY, Some("Soup"), &vars(10), &partial, None)+ .await+ .unwrap();++ // The full query must still be answerable: ownerId preserved from+ // the first write, names updated by the second.+ let ReadResult::Hit { data } = engine+ .read_query(None, QUERY, Some("Soup"), &vars(10))+ .await+ .unwrap()+ else {+ panic!("expected hit: partial re-write must not drop fields");+ };+ let items = data["user"]["soup"]["items"].as_array().unwrap();+ assert_eq!(items.len(), 3);+ for (item, name) in items.iter().zip(["A2", "B2", "C2"]) {+ assert_eq!(item["entity"]["documentName"], json!(name));+ assert_eq!(item["entity"]["ownerId"], json!("user-1"));+ }+ });+}diff --git a/rust/cloud-storage/client/cache-core/tests/roundtrip.rs b/rust/cloud-storage/client/cache-core/tests/roundtrip.rsnew file mode 100644index 0000000000..290f8e550e--- /dev/null+++ b/rust/cloud-storage/client/cache-core/tests/roundtrip.rs@@ -0,0 +1,347 @@+//! Normalize → denormalize round-trip tests against a realistic (trimmed)+//! Soup query, mirroring+//! `js/app/packages/service-clients/service-storage/graphql/soup.graphql`.++use cache_core::denormalize::{ReadOutcome, denormalize};+use cache_core::document::Document;+use cache_core::normalize::normalize;+use cache_core::value::{CacheValue, EntityKey, Record};+use serde_json::{Value as Json, json};+use std::collections::{BTreeMap, BTreeSet};++const SOUP_QUERY: &str = r#"+query Soup($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items {+ id+ entityType+ frecencyScore+ entity {+ __typename+ ... on GraphqlSoupDocument {+ id+ documentName: name+ ownerId+ updatedAt+ properties {+ ...SoupPropertyFields+ }+ }+ ... on GraphqlSoupChannel {+ id+ channelName: name+ channelType+ latestMessage {+ ...SoupChannelMessageFields+ }+ participants {+ channelId+ userId+ role+ }+ }+ }+ }+ nextCursor+ hasMore+ }+ }+}++fragment SoupPropertyFields on GraphqlSoupProperty {+ propertyDefinitionId+ displayName+ dataType+ isMultiSelect+ isSystem+ isMetadata+ value {+ kind+ boolValue+ selectOptionIds+ entityReferences {+ entityId+ entityType+ }+ links+ }+}++fragment SoupChannelMessageFields on GraphqlSoupChannelMessage {+ id+ threadId+ senderId+ content+ mentions+}+"#;++fn variables() -> serde_json::Map<String, Json> {+ let Json::Object(map) = json!({+ "input": { "limit": 2, "sortMethod": "UPDATED_AT", "cursor": null }+ }) else {+ unreachable!()+ };+ map+}++fn response_data() -> Json {+ json!({+ "user": {+ "id": "user-1",+ "soup": {+ "items": [+ {+ "id": "doc-1",+ "entityType": "DOCUMENT",+ "frecencyScore": 0.5,+ "entity": {+ "__typename": "GraphqlSoupDocument",+ "id": "doc-1",+ "documentName": "Design doc",+ "ownerId": "user-1",+ "updatedAt": "2026-07-01T00:00:00Z",+ "properties": [+ {+ "propertyDefinitionId": "prop-1",+ "displayName": "Status",+ "dataType": "select",+ "isMultiSelect": false,+ "isSystem": true,+ "isMetadata": false,+ "value": {+ "kind": "SelectOption",+ "boolValue": null,+ "selectOptionIds": ["opt-1"],+ "entityReferences": [+ { "entityId": "proj-9", "entityType": "PROJECT" }+ ],+ "links": []+ }+ }+ ]+ }+ },+ {+ "id": "ch-1",+ "entityType": "CHANNEL",+ "frecencyScore": 0.25,+ "entity": {+ "__typename": "GraphqlSoupChannel",+ "id": "ch-1",+ "channelName": "general",+ "channelType": "PUBLIC",+ "latestMessage": {+ "id": "msg-1",+ "threadId": null,+ "senderId": "user-2",+ "content": "hello",+ "mentions": ["user-1"]+ },+ "participants": [+ { "channelId": "ch-1", "userId": "user-1", "role": "member" }+ ]+ }+ }+ ],+ "nextCursor": "cursor-2",+ "hasMore": true+ }+ }+ })+}++fn write(records: &mut BTreeMap<EntityKey, Record>, doc: &Document, data: &Json) {+ let op = doc.operation(Some("Soup")).unwrap();+ let updates = normalize(op, &variables(), data).unwrap();+ for (key, record) in updates {+ records.entry(key).or_default().merge(record);+ }+}++#[test]+fn normalizes_expected_records() {+ let doc = Document::parse(SOUP_QUERY).unwrap();+ let mut records = BTreeMap::new();+ write(&mut records, &doc, &response_data());++ let keys: Vec<&str> = records.keys().map(|k| k.0.as_str()).collect();+ assert_eq!(+ keys,+ vec![+ "GraphqlSoupChannel:ch-1",+ "GraphqlSoupChannelMessage:msg-1",+ "GraphqlSoupDocument:doc-1",+ "GraphqlSoupItem:ch-1",+ "GraphqlSoupItem:doc-1",+ "GraphqlUser:user-1",+ "ROOT_QUERY",+ ]+ );++ // Aliased field stored under its schema name.+ let doc_record = &records[&EntityKey("GraphqlSoupDocument:doc-1".into())];+ assert!(matches!(+ doc_record.fields.get("name"),+ Some(CacheValue::String(s)) if s == "Design doc"+ ));+ assert!(!doc_record.fields.contains_key("documentName"));++ // Properties embedded (not their own records), message keyed by messageId.+ assert!(matches!(+ doc_record.fields.get("properties"),+ Some(CacheValue::List(items)) if matches!(&items[0], CacheValue::Object(_))+ ));+ let channel = &records[&EntityKey("GraphqlSoupChannel:ch-1".into())];+ assert!(matches!(+ channel.fields.get("latestMessage"),+ Some(CacheValue::Ref(k)) if k.0 == "GraphqlSoupChannelMessage:msg-1"+ ));++ // The root links to the viewer; the args-keyed soup page lives on it.+ let root = &records[&EntityKey::root()];+ assert!(matches!(+ root.fields.get("user"),+ Some(CacheValue::Ref(k)) if k.0 == "GraphqlUser:user-1"+ ));+ let user = &records[&EntityKey("GraphqlUser:user-1".into())];+ let soup_field = user.fields.keys().find(|k| k.starts_with("soup(")).unwrap();+ assert_eq!(+ soup_field,+ r#"soup({"input":{"cursor":null,"limit":2,"sortMethod":"UPDATED_AT"}})"#+ );+}++#[test]+fn round_trip_reproduces_response() {+ let doc = Document::parse(SOUP_QUERY).unwrap();+ let mut records = BTreeMap::new();+ write(&mut records, &doc, &response_data());++ let op = doc.operation(Some("Soup")).unwrap();+ let mut deps = BTreeSet::new();+ let outcome = denormalize(op, &variables(), &records, &mut deps).unwrap();+ let ReadOutcome::Complete(data) = outcome else {+ panic!("expected complete read, got {outcome:?}");+ };+ assert_eq!(data, response_data());++ // Dependencies include every entity visited.+ let dep_keys: Vec<&str> = deps.iter().map(|k| k.0.as_str()).collect();+ assert_eq!(+ dep_keys,+ vec![+ "GraphqlSoupChannel:ch-1",+ "GraphqlSoupChannelMessage:msg-1",+ "GraphqlSoupDocument:doc-1",+ "GraphqlSoupItem:ch-1",+ "GraphqlSoupItem:doc-1",+ "GraphqlUser:user-1",+ "ROOT_QUERY",+ ]+ );+}++#[test]+fn entity_update_visible_through_other_query() {+ let doc = Document::parse(SOUP_QUERY).unwrap();+ let mut records = BTreeMap::new();+ write(&mut records, &doc, &response_data());++ // A different document writes just the entity with a new name.+ let rename_doc = Document::parse(+ r#"query Doc($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items { id entity { __typename ... on GraphqlSoupDocument { id documentName: name } } }+ nextCursor+ hasMore+ }+ }+ }"#,+ )+ .unwrap();+ let rename_data = json!({+ "user": {+ "id": "user-1",+ "soup": {+ "items": [{+ "id": "doc-1",+ "entity": {+ "__typename": "GraphqlSoupDocument",+ "id": "doc-1",+ "documentName": "Renamed"+ }+ }],+ "nextCursor": null,+ "hasMore": false+ }+ }+ });+ let op = rename_doc.operation(Some("Doc")).unwrap();+ let updates = normalize(op, &variables(), &rename_data).unwrap();+ let mut changed = Vec::new();+ for (key, record) in updates {+ let entry = records.entry(key.clone()).or_default();+ if entry.merge(record) {+ changed.push(key.0);+ }+ }+ // The document record changed; the soup page (same args) also rewritten.+ assert!(changed.contains(&"GraphqlSoupDocument:doc-1".to_string()));++ // Original query now sees the new name everywhere.+ let op = doc.operation(Some("Soup")).unwrap();+ let mut deps = BTreeSet::new();+ let ReadOutcome::Complete(data) = denormalize(op, &variables(), &records, &mut deps).unwrap()+ else {+ panic!("expected complete read");+ };+ assert_eq!(+ data["user"]["soup"]["items"][0]["entity"]["documentName"],+ json!("Renamed")+ );+}++#[test]+fn different_args_are_a_miss() {+ let doc = Document::parse(SOUP_QUERY).unwrap();+ let mut records = BTreeMap::new();+ write(&mut records, &doc, &response_data());++ let op = doc.operation(Some("Soup")).unwrap();+ let Json::Object(other_vars) = json!({ "input": { "limit": 50 } }) else {+ unreachable!()+ };+ let mut deps = BTreeSet::new();+ let outcome = denormalize(op, &other_vars, &records, &mut deps).unwrap();+ assert!(+ matches!(&outcome, ReadOutcome::Miss { entity, field }+ if entity.0 == "GraphqlUser:user-1" && field == r#"soup({"input":{"limit":50}})"#),+ "got {outcome:?}"+ );+}++#[test]+fn missing_records_reported_for_batch_fetch() {+ let doc = Document::parse(SOUP_QUERY).unwrap();+ let mut records = BTreeMap::new();+ write(&mut records, &doc, &response_data());++ // Simulate the channel record being evicted from the available source.+ records.remove(&EntityKey("GraphqlSoupChannel:ch-1".into()));++ let op = doc.operation(Some("Soup")).unwrap();+ let mut deps = BTreeSet::new();+ let outcome = denormalize(op, &variables(), &records, &mut deps).unwrap();+ let ReadOutcome::NeedRecords(missing) = outcome else {+ panic!("expected NeedRecords, got {outcome:?}");+ };+ assert_eq!(+ missing.iter().map(|k| k.0.as_str()).collect::<Vec<_>>(),+ vec!["GraphqlSoupChannel:ch-1"]+ );+}diff --git a/rust/cloud-storage/client/cache-idb/Cargo.toml b/rust/cloud-storage/client/cache-idb/Cargo.tomlnew file mode 100644index 0000000000..fc7fb90ba6--- /dev/null+++ b/rust/cloud-storage/client/cache-idb/Cargo.toml@@ -0,0 +1,27 @@+[package]+edition = "2024"+name = "cache-idb"+publish = false+version = "0.1.0"++# wasm32-only implementation; the crate compiles to an empty shell on other+# targets so plain `cargo test` at the workspace root stays green.++[dependencies]+cache-core = { path = "../cache-core" }+thiserror = { workspace = true }++[target.'cfg(target_arch = "wasm32")'.dependencies]+idb = "0.6"+js-sys = "0.3"+wasm-bindgen = "0.2"+web-sys = { version = "0.3", features = [+ "Event",+ "EventTarget",+ "IdbDatabase",+ "console",+] }++[target.'cfg(target_arch = "wasm32")'.dev-dependencies]+serde_json = { workspace = true }+wasm-bindgen-test = "0.3"diff --git a/rust/cloud-storage/client/cache-idb/src/idb_storage.rs b/rust/cloud-storage/client/cache-idb/src/idb_storage.rsnew file mode 100644index 0000000000..1098cfcb2e--- /dev/null+++ b/rust/cloud-storage/client/cache-idb/src/idb_storage.rs@@ -0,0 +1,147 @@+use cache_core::codec::{CodecError, cache_namespace, decode_record, encode_record};+use cache_core::store::Storage;+use cache_core::value::{EntityKey, Record};+use idb::{Database, DatabaseEvent, Factory, ObjectStoreParams, TransactionMode};+use thiserror::Error;+use wasm_bindgen::{JsCast, JsValue};++const RECORDS_STORE: &str = "records";+const DB_VERSION: u32 = 1;++#[derive(Debug, Error)]+pub enum IdbStorageError {+ #[error("indexeddb: {0}")]+ Idb(#[from] idb::Error),+ #[error(transparent)]+ Codec(#[from] CodecError),+ #[error("stored value is not a Uint8Array")]+ NotBytes,+}++pub struct IdbStorage {+ db: Database,+}++impl IdbStorage {+ /// Opens the cache database for `scope`. A schema or format change+ /// yields a different database name, i.e. an implicitly fresh cache+ /// (stale namespaces are garbage-collected via [`Self::destroy`] by the+ /// host, or eventually by the browser under storage pressure).+ pub async fn open(scope: &str) -> Result<Self, IdbStorageError> {+ let name = cache_namespace(scope);+ let factory = Factory::new()?;+ let mut request = factory.open(&name, Some(DB_VERSION))?;+ request.on_upgrade_needed(|event| {+ let database = event.database().expect("upgrade event has database");+ // Out-of-line string keys (the entity key), Uint8Array values.+ // Surface setup failures immediately rather than as misleading+ // "store not found" errors on later transactions.+ database+ .create_object_store(RECORDS_STORE, ObjectStoreParams::new())+ .expect("create records object store");+ });+ let mut db = request.await?;+ // Close immediately when another context needs this database gone or+ // upgraded (delete/upgrade requests block while connections are+ // open); without this, `destroy` from another tab can hang forever.+ db.on_version_change(|event: web_sys::Event| {+ if let Some(target) = event.target() {+ if let Ok(db) = wasm_bindgen::JsCast::dyn_into::<web_sys::IdbDatabase>(target) {+ db.close();+ }+ }+ });+ Ok(IdbStorage { db })+ }++ /// Deletes the database for `scope` (logout / stale-namespace cleanup).+ ///+ /// Connections opened by [`Self::open`] auto-close on `versionchange`,+ /// so this does not block on our own live handles. A `blocked` event+ /// (foreign connection without that handler) is logged for diagnosis+ /// instead of hanging silently.+ pub async fn destroy(scope: &str) -> Result<(), IdbStorageError> {+ let factory = Factory::new()?;+ let mut request = factory.delete(&cache_namespace(scope))?;+ request.on_blocked(|_| {+ web_sys::console::warn_1(+ &"graphql-cache: database deletion blocked by an open connection".into(),+ );+ });+ request.await?;+ Ok(())+ }++ /// Closes the underlying connection. Subsequent operations on this+ /// storage will fail; call right before dropping/destroying.+ pub fn close(&self) {+ self.db.close();+ }+}++impl Storage for IdbStorage {+ type Error = IdbStorageError;++ async fn get_batch(&self, keys: &[EntityKey]) -> Result<Vec<Option<Record>>, Self::Error> {+ let tx = self+ .db+ .transaction(&[RECORDS_STORE], TransactionMode::ReadOnly)?;+ let store = tx.object_store(RECORDS_STORE)?;++ // Dispatch all gets first (they execute concurrently within the+ // transaction), then await in order.+ let mut requests = Vec::with_capacity(keys.len());+ for key in keys {+ requests.push(store.get(JsValue::from_str(&key.0))?);+ }+ let mut out = Vec::with_capacity(keys.len());+ for request in requests {+ let value = request.await?;+ out.push(match value {+ None => None,+ Some(js) => {+ let bytes: js_sys::Uint8Array =+ js.dyn_into().map_err(|_| IdbStorageError::NotBytes)?;+ Some(decode_record(&bytes.to_vec())?)+ }+ });+ }+ Ok(out)+ }++ async fn put_batch(&mut self, entries: Vec<(EntityKey, Record)>) -> Result<(), Self::Error> {+ let tx = self+ .db+ .transaction(&[RECORDS_STORE], TransactionMode::ReadWrite)?;+ let store = tx.object_store(RECORDS_STORE)?;+ for (key, record) in &entries {+ let bytes = encode_record(record);+ let value: JsValue = js_sys::Uint8Array::from(bytes.as_slice()).into();+ store.put(&value, Some(&JsValue::from_str(&key.0)))?;+ }+ // Committing the transaction is what makes the batch atomic.+ tx.commit()?.await?;+ Ok(())+ }++ async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {+ let tx = self+ .db+ .transaction(&[RECORDS_STORE], TransactionMode::ReadWrite)?;+ let store = tx.object_store(RECORDS_STORE)?;+ for key in keys {+ store.delete(JsValue::from_str(&key.0))?;+ }+ tx.commit()?.await?;+ Ok(())+ }++ async fn clear(&mut self) -> Result<(), Self::Error> {+ let tx = self+ .db+ .transaction(&[RECORDS_STORE], TransactionMode::ReadWrite)?;+ tx.object_store(RECORDS_STORE)?.clear()?;+ tx.commit()?.await?;+ Ok(())+ }+}diff --git a/rust/cloud-storage/client/cache-idb/src/lib.rs b/rust/cloud-storage/client/cache-idb/src/lib.rsnew file mode 100644index 0000000000..0097d55907--- /dev/null+++ b/rust/cloud-storage/client/cache-idb/src/lib.rs@@ -0,0 +1,17 @@+//! IndexedDB [`Storage`](cache_core::store::Storage) backend for the browser+//! host (wasm module in a SharedWorker / dedicated worker).+//!+//! One IndexedDB database per cache namespace — the database *name* embeds+//! scope + schema hash + format version+//! ([`cache_core::codec::cache_namespace`]), so a schema/format change simply+//! opens a fresh database. Records live in a single `records` object store+//! as postcard bytes (`Uint8Array`) under their entity-key string.+//!+//! wasm32-only; on other targets this crate is an empty shell so workspace+//! `cargo test` stays green.++#[cfg(target_arch = "wasm32")]+mod idb_storage;++#[cfg(target_arch = "wasm32")]+pub use idb_storage::{IdbStorage, IdbStorageError};diff --git a/rust/cloud-storage/client/cache-idb/tests/web.rs b/rust/cloud-storage/client/cache-idb/tests/web.rsnew file mode 100644index 0000000000..533cce74e0--- /dev/null+++ b/rust/cloud-storage/client/cache-idb/tests/web.rs@@ -0,0 +1,94 @@+//! Browser tests for the IndexedDB backend. Run with:+//! `wasm-pack test --headless --chrome cache-idb`+//! (or `--firefox`). Not part of native `cargo test`.++#![cfg(target_arch = "wasm32")]++use cache_core::engine::{Engine, ReadResult};+use cache_core::store::Storage;+use cache_core::value::{CacheValue, EntityKey, Record};+use cache_idb::IdbStorage;+use wasm_bindgen_test::*;++wasm_bindgen_test_configure!(run_in_browser);++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 {+ EntityKey(s.to_string())+}++#[wasm_bindgen_test]+async fn put_get_delete_roundtrip() {+ IdbStorage::destroy("test-rt").await.unwrap();+ let mut s = IdbStorage::open("test-rt").await.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"));++ 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!(s.get_batch(&[key("B:2")]).await.unwrap()[0].is_none());+}++#[wasm_bindgen_test]+async fn persists_across_reopen() {+ IdbStorage::destroy("test-persist").await.unwrap();+ let mut s = IdbStorage::open("test-persist").await.unwrap();+ s.put_batch(vec![(key("A:1"), record("a"))]).await.unwrap();+ s.close();++ let s = IdbStorage::open("test-persist").await.unwrap();+ let got = s.get_batch(&[key("A:1")]).await.unwrap();+ assert_eq!(got[0].as_ref().unwrap(), &record("a"));+}++#[wasm_bindgen_test]+async fn engine_over_idb() {+ IdbStorage::destroy("test-engine").await.unwrap();+ let storage = IdbStorage::open("test-engine").await.unwrap();+ let mut engine = Engine::new(storage);++ let query = r#"query Soup($input: SoupInput!) {+ user { id soup(input: $input) { nextCursor hasMore items { 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, "hasMore": false, "items": [{"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/rust/cloud-storage/client/cache-sqlite/Cargo.toml b/rust/cloud-storage/client/cache-sqlite/Cargo.tomlnew file mode 100644index 0000000000..eb622ac86f--- /dev/null+++ b/rust/cloud-storage/client/cache-sqlite/Cargo.toml@@ -0,0 +1,17 @@+[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 = "0.4"+serde_json = { workspace = true }+tempfile = "3"diff --git a/rust/cloud-storage/client/cache-sqlite/src/lib.rs b/rust/cloud-storage/client/cache-sqlite/src/lib.rsnew file mode 100644index 0000000000..a345c2568a--- /dev/null+++ b/rust/cloud-storage/client/cache-sqlite/src/lib.rs@@ -0,0 +1,244 @@+//! SQLite [`Storage`] backend for the Tauri native host.+//!+//! One database file per cache; the `meta` table pins the cache namespace+//! (scope + schema hash + 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. That's fine for the Tauri host, which runs the engine on a+//! dedicated thread (blocking IO is the point of the native host).++#![deny(missing_docs)]++use cache_core::codec::{cache_namespace, decode_record, encode_record};+use cache_core::store::Storage;+use cache_core::value::{EntityKey, Record};+use rusqlite::{Connection, OptionalExtension, params};+use std::path::Path;+use thiserror::Error;++/// 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 record failed to decode (corruption → discard & rebuild).+ #[error(transparent)]+ Codec(#[from] cache_core::codec::CodecError),+}++/// [`Storage`] backend over a SQLite database (Tauri native host).+pub struct SqliteStorage {+ conn: 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(conn: Connection, scope: &str) -> Result<Self, SqliteStorageError> {+ conn.pragma_update(None, "journal_mode", "WAL")?;+ conn.pragma_update(None, "synchronous", "NORMAL")?;+ 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);",+ )?;++ let expected = cache_namespace(scope);+ let stored: Option<String> = conn+ .query_row("SELECT v FROM meta WHERE k = 'namespace'", [], |row| {+ row.get(0)+ })+ .optional()?;+ if stored.as_deref() != Some(expected.as_str()) {+ // Different user, schema or format → disposable rebuild.+ conn.execute("DELETE FROM records", [])?;+ conn.execute(+ "INSERT INTO meta (k, v) VALUES ('namespace', ?1)+ ON CONFLICT(k) DO UPDATE SET v = excluded.v",+ params![expected],+ )?;+ }+ Ok(SqliteStorage { conn })+ }++ /// 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))?)+ }+}++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 mut out = Vec::with_capacity(keys.len());+ for key in keys {+ let bytes: Option<Vec<u8>> = stmt+ .query_row(params![key.0], |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, Record)>) -> Result<(), Self::Error> {+ let tx = self.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, encode_record(record)])?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ async fn delete_batch(&mut self, keys: &[EntityKey]) -> Result<(), Self::Error> {+ let tx = self.conn.transaction()?;+ {+ let mut stmt = tx.prepare_cached("DELETE FROM records WHERE key = ?1")?;+ for key in keys {+ stmt.execute(params![key.0])?;+ }+ }+ tx.commit()?;+ Ok(())+ }++ async fn clear(&mut self) -> Result<(), Self::Error> {+ self.conn.execute("DELETE FROM records", [])?;+ 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 {+ EntityKey(s.to_string())+ }++ #[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 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 namespace_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 hasMore items { 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, "hasMore": false, "items": [{"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/rust/cloud-storage/client/cache-wasm/Cargo.toml b/rust/cloud-storage/client/cache-wasm/Cargo.tomlnew file mode 100644index 0000000000..e132b7a112--- /dev/null+++ b/rust/cloud-storage/client/cache-wasm/Cargo.toml@@ -0,0 +1,28 @@+[package]+edition = "2024"+name = "cache-wasm"+publish = false+version = "0.1.0"++[lib]+crate-type = ["cdylib", "rlib"]++# Browser-only wasm-bindgen shell around the engine + IDB storage. Like+# cache-idb, it compiles to an empty shell off-wasm so workspace `cargo test`+# stays green.++[dependencies]+cache-core = { path = "../cache-core" }++[target.'cfg(target_arch = "wasm32")'.dependencies]+async-lock = { workspace = true }+cache-idb = { path = "../cache-idb" }+js-sys = { workspace = true }+serde = { workspace = true }+serde-wasm-bindgen = { workspace = true }+serde_json = { workspace = true }+wasm-bindgen = { workspace = true }+wasm-bindgen-futures = { workspace = true }++[target.'cfg(target_arch = "wasm32")'.dev-dependencies]+wasm-bindgen-test = "0.3"diff --git a/rust/cloud-storage/client/cache-wasm/src/lib.rs b/rust/cloud-storage/client/cache-wasm/src/lib.rsnew file mode 100644index 0000000000..05090a8611--- /dev/null+++ b/rust/cloud-storage/client/cache-wasm/src/lib.rs@@ -0,0 +1,17 @@+//! wasm-bindgen shell around the cache engine + IndexedDB storage.+//!+//! Exposes a `CacheEngine` class to the JS worker glue+//! (`js/app/packages/graphql-cache/`). All methods return Promises; the+//! engine is guarded by an async mutex so overlapping calls from the JS side+//! serialize safely instead of tripping reentrancy.+//!+//! Operation ids cross the boundary as strings (`"{clientId}:{urqlKey}"`)+//! so multiple tabs/webviews can register operations against one shared+//! engine without collisions; they're interned to the engine's `u64` ids+//! internally.++#[cfg(target_arch = "wasm32")]+mod shell;++#[cfg(target_arch = "wasm32")]+pub use shell::*;diff --git a/rust/cloud-storage/client/cache-wasm/src/shell.rs b/rust/cloud-storage/client/cache-wasm/src/shell.rsnew file mode 100644index 0000000000..9203f9dd42--- /dev/null+++ b/rust/cloud-storage/client/cache-wasm/src/shell.rs@@ -0,0 +1,254 @@+use async_lock::Mutex;+use cache_core::deps::OpId;+use cache_core::engine::{Engine, ReadResult};+use cache_core::value::EntityKey;+use cache_idb::IdbStorage;+use serde::Serialize;+use std::cell::RefCell;+use std::collections::HashMap;+use std::rc::Rc;+use wasm_bindgen::prelude::*;+use wasm_bindgen_futures::future_to_promise;++/// 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()+ }+}++#[derive(Serialize)]+#[serde(tag = "kind", rename_all = "camelCase")]+enum JsReadResult {+ Hit { data: serde_json::Value },+ Miss,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct JsWriteResult {+ changed: Vec<String>,+ affected_ops: Vec<String>,+ reset: bool,+}++#[wasm_bindgen]+pub struct CacheEngine {+ engine: Rc<Mutex<Engine<IdbStorage>>>,+ ops: Rc<RefCell<OpInterner>>,+}++/// Opens (or creates) the cache for `scope`. See+/// [`cache_core::codec::cache_namespace`] for how scope + schema hash ++/// format version determine the underlying database.+#[wasm_bindgen(js_name = openCache)]+pub async fn open_cache(scope: String, hot_capacity: Option<u32>) -> Result<CacheEngine, JsError> {+ let storage = IdbStorage::open(&scope)+ .await+ .map_err(|e| JsError::new(&e.to_string()))?;+ let engine = match hot_capacity {+ Some(cap) => Engine::with_capacity(storage, cap as usize),+ None => Engine::new(storage),+ };+ Ok(CacheEngine {+ engine: Rc::new(Mutex::new(engine)),+ ops: Rc::new(RefCell::new(OpInterner::default())),+ })+}++/// Deletes the cache database for `scope` (logout).+#[wasm_bindgen(js_name = destroyCache)]+pub async fn destroy_cache(scope: String) -> Result<(), JsError> {+ IdbStorage::destroy(&scope)+ .await+ .map_err(|e| JsError::new(&e.to_string()))+}++/// Schema hash baked into this build (namespace diagnostics).+#[wasm_bindgen(js_name = schemaHash)]+pub fn schema_hash() -> String {+ cache_core::meta::SCHEMA_HASH.to_string()+}++fn to_js<T: Serialize>(value: &T) -> Result<JsValue, JsValue> {+ value+ .serialize(&serde_wasm_bindgen::Serializer::json_compatible())+ .map_err(|e| JsValue::from_str(&e.to_string()))+}++/// All rejections surface as real `Error` objects (consistent+/// `instanceof Error` / `.message` behavior with the `JsError`-returning+/// functions like `openCache`).+fn err_js(e: impl std::fmt::Display) -> JsValue {+ js_sys::Error::new(&e.to_string()).into()+}++fn parse_variables(+ variables: JsValue,+) -> Result<serde_json::Map<String, serde_json::Value>, JsValue> {+ if variables.is_undefined() || variables.is_null() {+ return Ok(serde_json::Map::new());+ }+ serde_wasm_bindgen::from_value(variables).map_err(err_js)+}++#[wasm_bindgen]+impl CacheEngine {+ /// Attempts a cache read. Resolves to `{kind:"hit",data}` or+ /// `{kind:"miss"}`. When `opId` is given, the operation is registered+ /// as active for dependency-driven re-execution.+ #[wasm_bindgen(js_name = readQuery)]+ pub fn read_query(+ &self,+ op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: JsValue,+ ) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let vars = parse_variables(variables)?;+ let op = op_id.map(|name| ops.borrow_mut().intern(&name));+ let mut engine = engine.lock().await;+ let result = engine+ .read_query(op, &query, operation_name.as_deref(), &vars)+ .await+ .map_err(err_js)?;+ to_js(&match result {+ ReadResult::Hit { data } => JsReadResult::Hit { data },+ ReadResult::Miss => JsReadResult::Miss,+ })+ })+ }++ /// Normalizes and stores a network response. Resolves to+ /// `{changed: string[], affectedOps: string[], reset: boolean}` —+ /// `affectedOps` are the registered operation ids (excluding+ /// `originOpId`) whose data changed. `identity` is an opaque session tag+ /// (extracted by the exchange from the response); a tag mismatching the+ /// cache's bound identity wipes and rebinds atomically with this write.+ #[wasm_bindgen(js_name = writeQuery)]+ pub fn write_query(+ &self,+ origin_op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: JsValue,+ data: JsValue,+ identity: Option<String>,+ ) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let vars = parse_variables(variables)?;+ let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;+ let origin = origin_op_id.map(|name| ops.borrow_mut().intern(&name));+ let mut engine = engine.lock().await;+ let result = engine+ .write_query(+ origin,+ &query,+ operation_name.as_deref(),+ &vars,+ &data,+ identity.as_deref(),+ )+ .await+ .map_err(err_js)?;+ to_js(&JsWriteResult {+ changed: result.changed.into_iter().map(|k| k.0).collect(),+ affected_ops: ops.borrow().names(result.affected_ops),+ reset: result.reset,+ })+ })+ }++ /// Evicts externally-changed records from the hot tier (cross-tab+ /// broadcasts, push invalidation). Resolves to the affected local+ /// operation ids.+ #[wasm_bindgen(js_name = invalidateKeys)]+ pub fn invalidate_keys(&self, keys: Vec<String>) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let keys: Vec<EntityKey> = keys.into_iter().map(EntityKey).collect();+ let mut engine = engine.lock().await;+ let affected = engine.invalidate_keys(keys.iter());+ to_js(&ops.borrow().names(affected))+ })+ }++ /// Reacts to a cache reset performed by another engine instance sharing+ /// the same storage (cross-tab broadcast). Drops local in-memory state+ /// and resolves to every local operation id (all must re-execute).+ #[wasm_bindgen(js_name = externalReset)]+ pub fn external_reset(&self) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let affected = engine.lock().await.external_reset();+ to_js(&ops.borrow().names(affected))+ })+ }++ /// Unregisters an operation (urql teardown).+ #[wasm_bindgen(js_name = teardownOperation)]+ pub fn teardown_operation(&self, op_id: String) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let removed = ops.borrow_mut().remove(&op_id);+ if let Some(id) = removed {+ engine.lock().await.teardown_operation(id);+ }+ Ok(JsValue::UNDEFINED)+ })+ }++ /// Drops all cached state (logout, corruption rebuild).+ pub fn clear(&self) -> js_sys::Promise {+ let engine = self.engine.clone();+ future_to_promise(async move {+ engine.lock().await.clear().await.map_err(err_js)?;+ Ok(JsValue::UNDEFINED)+ })+ }++ /// Closes the underlying IndexedDB connection. Call before+ /// [`destroyCache`](destroy_cache) — database deletion blocks while+ /// connections are open. The engine is unusable afterwards.+ pub fn close(&self) -> js_sys::Promise {+ let engine = self.engine.clone();+ future_to_promise(async move {+ engine.lock().await.storage().close();+ Ok(JsValue::UNDEFINED)+ })+ }+}diff --git a/rust/cloud-storage/client/cache-wasm/tests/web.rs b/rust/cloud-storage/client/cache-wasm/tests/web.rsnew file mode 100644index 0000000000..8f72a68c4d--- /dev/null+++ b/rust/cloud-storage/client/cache-wasm/tests/web.rs@@ -0,0 +1,87 @@+//! Browser tests for the wasm shell (JsValue boundary + async mutex).+//! Run like cache-idb's tests (see workspace README).++#![cfg(target_arch = "wasm32")]++use cache_wasm::{destroy_cache, open_cache};+use wasm_bindgen::JsValue;+use wasm_bindgen_futures::JsFuture;+use wasm_bindgen_test::*;++wasm_bindgen_test_configure!(run_in_browser);++const QUERY: &str = r#"query Soup($input: SoupInput!) {+ user { id soup(input: $input) { nextCursor hasMore items { id } } }+}"#;++fn js(json: serde_json::Value) -> JsValue {+ use serde::Serialize;+ json.serialize(&serde_wasm_bindgen::Serializer::json_compatible())+ .unwrap()+}++#[wasm_bindgen_test]+async fn write_then_read_through_js_boundary() {+ destroy_cache("wasm-shell-test".into()).await.unwrap();+ let engine = open_cache("wasm-shell-test".into(), None).await.unwrap();++ let vars = serde_json::json!({"input": {"limit": 1}});+ let data = serde_json::json!({+ "user": { "id": "user-1", "soup": { "nextCursor": null, "hasMore": false, "items": [{"id": "doc-1"}] } }+ });++ // Miss first.+ let read = JsFuture::from(engine.read_query(+ Some("tab1:1".into()),+ QUERY.into(),+ Some("Soup".into()),+ js(vars.clone()),+ ))+ .await+ .unwrap();+ let read: serde_json::Value = serde_wasm_bindgen::from_value(read).unwrap();+ assert_eq!(read["kind"], "miss");++ // Write via op 2 (tagged with the viewer identity), expect op 1+ // affected (registered on the miss).+ let write = JsFuture::from(engine.write_query(+ Some("tab1:2".into()),+ QUERY.into(),+ Some("Soup".into()),+ js(vars.clone()),+ js(data.clone()),+ Some("user-1".into()),+ ))+ .await+ .unwrap();+ let write: serde_json::Value = serde_wasm_bindgen::from_value(write).unwrap();+ assert!(!write["changed"].as_array().unwrap().is_empty());+ assert_eq!(write["affectedOps"], serde_json::json!(["tab1:1"]));+ assert_eq!(write["reset"], serde_json::json!(false));++ // Hit now; data is a plain JS object round-tripped exactly.+ let read = JsFuture::from(engine.read_query(+ Some("tab1:1".into()),+ QUERY.into(),+ Some("Soup".into()),+ js(vars.clone()),+ ))+ .await+ .unwrap();+ let read: serde_json::Value = serde_wasm_bindgen::from_value(read).unwrap();+ assert_eq!(read["kind"], "hit");+ assert_eq!(read["data"], data);++ // Cross-instance invalidation path: evict + report local dependents.+ let affected =+ JsFuture::from(engine.invalidate_keys(vec!["GraphqlSoupItem:doc-1".to_string()]))+ .await+ .unwrap();+ let affected: Vec<String> = serde_wasm_bindgen::from_value(affected).unwrap();+ assert_eq!(affected, vec!["tab1:1".to_string()]);++ // Lifecycle: close the connection, then deletion completes (would hang+ // on a live connection without versionchange auto-close).+ JsFuture::from(engine.close()).await.unwrap();+ destroy_cache("wasm-shell-test".into()).await.unwrap();+}diff --git a/rust/cloud-storage/deny.toml b/rust/cloud-storage/deny.tomlindex 19936f9045..9860ee6ad8 100644--- a/rust/cloud-storage/deny.toml+++ b/rust/cloud-storage/deny.toml@@ -71,6 +71,7 @@ feature-depth = 1# output a note when they are encountered.ignore = [{ id = "RUSTSEC-2023-0071", reason = "At the time of writing there is no patch for this" },+ { id = "RUSTSEC-2023-0089", reason = "Dependency from heapless 0.7, showing up in Cargo.lock but not used on std platforms. " },{ id = "RUSTSEC-2024-0384", reason = "Cannot yet switch to web-time, due to a 3rd party openai dependency" },{ id = "RUSTSEC-2024-0436", reason = "Paste is a 'finished' crate which is heavily depended on" },{ id = "RUSTSEC-2025-0012", reason = "Cannot remove dep due to 3rd party openai dependency" },@@ -233,8 +234,8 @@ skip = [{ crate = "base16ct", reason = "Cryptographic dependencies version mismatch" },{ crate = "base64", reason = "AWS SDK and other dependencies require different versions" },{ crate = "bitflags", reason = "Different dependencies require different versions" },- { crate = "cpufeatures", reason = "Different dependencies require different versions" },{ crate = "core-foundation", reason = "Different dependencies require different versions" },+ { crate = "cpufeatures", reason = "Different dependencies require different versions" },{ crate = "crypto-bigint", reason = "AWS cryptographic dependencies version mismatch" },{ crate = "cssparser", reason = "HTML parsing dependencies version mismatch" },{ crate = "darling", reason = "Derive macro dependencies version mismatch" },@@ -257,14 +258,13 @@ skip = [{ crate = "http-body", reason = "Hyper and AWS SDK version mismatch" },{ crate = "hyper", reason = "AWS SDK uses older hyper version" },{ crate = "hyper-rustls", reason = "TLS dependencies version mismatch" },- { crate = "reqwest", reason = "livekit-api pins reqwest 0.12 via services-tokio feature; workspace uses 0.13" },{ crate = "infer", reason = "File type detection dependencies" },{ crate = "itertools", reason = "Various dependencies require different versions" },{ crate = "jni", reason = "Different dependencies require different versions" },{ crate = "jni-sys", reason = "Different dependencies require different versions" },{ crate = "jsonwebtoken", reason = "Git fork and crates.io version coexist" },- { crate = "match_token", reason = "HTML parsing dependencies" },{ crate = "markup5ever", reason = "HTML parsing dependencies" },+ { crate = "match_token", reason = "HTML parsing dependencies" },{ crate = "mio", reason = "Different dependencies require different versions" },{ crate = "nix", reason = "Different dependencies require different versions" },{ crate = "nom", reason = "Parser combinator dependencies" },@@ -280,12 +280,13 @@ skip = [{ crate = "rand", reason = "Different dependencies require different versions" },{ crate = "rand_chacha", reason = "Random number generation dependencies" },{ crate = "rand_core", reason = "Different dependencies require different versions" },+ { crate = "reqwest", reason = "livekit-api pins reqwest 0.12 via services-tokio feature; workspace uses 0.13" },{ crate = "rfc6979", reason = "Cryptographic dependencies version mismatch" },{ crate = "rustc-hash", reason = "Hash function dependencies" },{ crate = "rustls", reason = "TLS dependencies version mismatch" },{ crate = "rustls-webpki", reason = "TLS dependencies version mismatch" },- { crate = "security-framework", reason = "macOS security framework dependencies" },{ crate = "sec1", reason = "Cryptographic dependencies version mismatch" },+ { crate = "security-framework", reason = "macOS security framework dependencies" },{ crate = "selectors", reason = "CSS selector dependencies" },{ crate = "serde_qs", reason = "Query string serialization dependencies" },{ crate = "servo_arc", reason = "Arc implementation dependencies" },@@ -302,20 +303,20 @@ skip = [{ crate = "tower", reason = "Service framework dependencies" },{ crate = "unicode-width", reason = "Unicode dependencies" },{ crate = "wasi", reason = "WebAssembly system interface dependencies" },+ { crate = "windows-link", reason = "Windows dependencies" },+ { crate = "windows-registry", reason = "Windows dependencies version mismatch" },+ { crate = "windows-result", reason = "Windows dependencies version mismatch" },+ { crate = "windows-strings", reason = "Windows dependencies version mismatch" },{ crate = "windows-sys", reason = "Windows dependencies version mismatch" },{ crate = "windows-targets", reason = "Windows dependencies" },{ crate = "windows_aarch64_gnullvm", reason = "Windows dependencies" },{ crate = "windows_aarch64_msvc", reason = "Windows dependencies" },{ crate = "windows_i686_gnu", reason = "Windows dependencies" },+ { crate = "windows_i686_gnullvm", reason = "Windows dependencies" },{ crate = "windows_i686_msvc", reason = "Windows dependencies" },{ crate = "windows_x86_64_gnu", reason = "Windows dependencies" },{ crate = "windows_x86_64_gnullvm", reason = "Windows dependencies" },{ crate = "windows_x86_64_msvc", reason = "Windows dependencies" },- { crate = "windows-link", reason = "Windows dependencies" },- { crate = "windows-registry", reason = "Windows dependencies version mismatch" },- { crate = "windows-result", reason = "Windows dependencies version mismatch" },- { crate = "windows-strings", reason = "Windows dependencies version mismatch" },- { crate = "windows_i686_gnullvm", reason = "Windows dependencies" },{ crate = "zerocopy", reason = "Zero-copy serialization dependencies" },{ crate = "zip", reason = "Different dependencies require different versions" },{ crate = "zune-core", reason = "Duplicated dep" },@@ -344,9 +345,7 @@ unknown-git = "warn"# if not specified. If it is specified but empty, no registries are allowed.allow-registry = ["https://github.com/rust-lang/crates.io-index"]# List of URLs for allowed Git repositories-allow-git = [- "git+https://github.com/whutchinson98/jsonwebtoken",-]+allow-git = ["git+https://github.com/whutchinson98/jsonwebtoken"][sources.allow-org]# github.com organizations to allow git sources fordiff --git a/rust/cloud-storage/graphql_soup/AGENTS.md b/rust/cloud-storage/graphql_soup/AGENTS.mdnew file mode 100644index 0000000000..c54a2b31a1--- /dev/null+++ b/rust/cloud-storage/graphql_soup/AGENTS.md@@ -0,0 +1,67 @@+# graphql_soup — schema conventions++This crate defines the GraphQL schema consumed by the client's **normalized+cache** (`rust/cloud-storage/client`, design doc:+`js/app/docs/graphql-normalized-cache-plan.md`). Two field-naming+conventions in this schema are load-bearing for cache correctness. The+cache's build validates *shapes* but cannot validate *semantics* — that's+what schema review is for.++## 1. `id` is a reserved, semantic field name (presence-of-id convention)++Clients key cache records by `__typename:id`. Consequences:++- **An output object type with an `id: ID!` field is a normalized entity.**+ Two responses containing the same `__typename:id` pair are *merged into+ one record* — so `id` must identify the same logical value everywhere it+ can appear, across all queries, arguments, and parent objects.+- **Only name a field `id` when it is the object's global identity.** If a+ type carries a reference to something else's id, name it accordingly:+ - `GraphqlSoupProperty` exposes `propertyDefinitionId`, **not** `id` — a+ property instance's `value` is per-entity, while the definition id is+ shared. Naming it `id` would merge property values across entities.+ - `GraphqlSoupChannelMessage.id` (renamed from `messageId`) — it *is* the+ message's identity, so it uses the reserved name.+- **Types without an `id` field are embedded** inline in their parent+ record (`SoupPage`, participants, property values, `DocumentSubType`).+ This is correct for value objects and query-scoped wrappers. Do **not**+ add constant or synthetic ids to such types — a constant id (e.g.+ `"soup_page"`) would merge every instance into a single record globally.+- `id` fields must be exactly `ID!` (non-null, non-list); the cache build+ (`rust/cloud-storage/client/cache-core/build.rs`) fails otherwise, and fails if+ the query root exposes an `id`.++Review checklist when adding/changing a type:+1. Does it have a stable global identity? → expose it as `id: ID!`.+2. Is its content dependent on where it appears (parent entity, arguments)?+ → no `id` field; expose reference ids under descriptive names.+3. Renaming/removing an `id` field changes client caching semantics — it+ rotates cache keys and turns entities into embedded values (or vice+ versa). Deliberate, but call it out in review.++## 2. `QueryRoot → user` (viewer pattern) is the identity witness++All user-scoped data hangs off `user: GraphqlUser!`, and `GraphqlUser.id`+must be the **authenticated** user's id from the request context. The+client extracts it from every response and passes it to the cache as a+session tag: a response for a different user than the one bound to the+cache triggers a full wipe-and-rebind (cross-user leak protection on+account switches).++- Never resolve `GraphqlUser.id` from anything other than the+ authenticated request context.+- New user-scoped root data should be added under `GraphqlUser`, not as+ new root fields.++## Regenerating the SDL++After schema changes:++```sh+cargo run -p graphql_soup --bin graphql_soup_schema -- schema.graphql # from rust/cloud-storage+```++The exported `schema.graphql` feeds both the client codegen+(`js/app && bun gen-graphql`) and the cache metadata codegen (hashing it —+any change rotates all persisted client caches, which rebuild from the+network automatically).diff --git a/rust/cloud-storage/graphql_soup/src/objects.rs b/rust/cloud-storage/graphql_soup/src/objects.rsindex a78c356c11..22781bc35a 100644--- a/rust/cloud-storage/graphql_soup/src/objects.rs+++ b/rust/cloud-storage/graphql_soup/src/objects.rs@@ -97,8 +97,8 @@ impl From<EntityType> for GraphqlSoupEntityType {#[Object]impl GraphqlSoupItem {- async fn id(&self) -> &str {- &self.id+ async fn id(&self) -> ID {+ ID(self.id.clone())}async fn entity_type(&self) -> GraphqlSoupEntityType {@@ -352,7 +352,11 @@ pub struct GraphqlSoupProperty(SoupProperty);#[Object]impl GraphqlSoupProperty {- async fn id(&self) -> ID {+ /// Id of the shared property *definition* — deliberately not named `id`:+ /// a property instance has no global identity (its `value` is+ /// per-entity), so it must never be treated as a cacheable entity.+ /// Normalized caches key objects by the presence of an `id` field.+ async fn property_definition_id(&self) -> ID {ID(self.0.definition.id.to_string())}@@ -976,9 +980,12 @@ impl GraphqlSoupChannelParticipant {/// GraphQL channel message summary.pub struct GraphqlSoupChannelMessage(ChannelMessage);+// NOTE: `id` (not `messageId`) — objects exposing `id: ID!` are treated as+// normalized entities by clients' caches (presence-of-id convention).+#[Object]impl GraphqlSoupChannelMessage {- async fn message_id(&self) -> ID {+ async fn id(&self) -> ID {ID(self.0.message_id.to_string())}diff --git a/rust/cloud-storage/graphql_soup/src/schema.rs b/rust/cloud-storage/graphql_soup/src/schema.rsindex 3e2db04852..943cda9884 100644--- a/rust/cloud-storage/graphql_soup/src/schema.rs+++ b/rust/cloud-storage/graphql_soup/src/schema.rs@@ -49,9 +49,14 @@ impl SoupService for SchemaOnlySoupService {}/// Object-safe-ish wrapper for sharing a concrete Soup service with GraphQL.-#[derive(Clone)]pub struct SharedSoupService<S>(Arc<S>);+impl<S> Clone for SharedSoupService<S> {+ fn clone(&self) -> Self {+ Self(Arc::clone(&self.0))+ }+}+impl<S> SharedSoupService<S> {/// Create a shared Soup service wrapper.pub fn new(service: Arc<S>) -> Self {@@ -95,6 +100,13 @@ impl<S> SoupQueryRoot<S> {}}+/// The authenticated user (viewer). All user-scoped data hangs off this+/// object so clients (and their normalized caches) observe data ownership+/// structurally rather than implicitly through the session.+pub struct GraphqlUser<S> {+ service: S,+}+/// Build a GraphQL schema for Soup suitable for SDL export or introspection.pub fn build_schema() -> SchemaOnlySoupSchema {build_schema_with_service(SchemaOnlySoupService)@@ -103,7 +115,7 @@ pub fn build_schema() -> SchemaOnlySoupSchema {/// Build a GraphQL schema for Soup backed by the provided service.pub fn build_schema_with_service<S>(service: S) -> SoupSchema<S>where- S: SoupService,+ S: SoupService + Clone,{Schema::build(SoupQueryRoot::new(service),@@ -123,9 +135,28 @@ where#[Object]impl<S> SoupQueryRoot<S>+where+ S: SoupService + Clone,+{+ /// The authenticated user.+ async fn user(&self) -> GraphqlUser<S> {+ GraphqlUser {+ service: self.service.clone(),+ }+ }+}++#[Object(name = "GraphqlUser")]+impl<S> GraphqlUser<S>whereS: SoupService,{+ /// Stable id of the authenticated user.+ async fn id(&self, ctx: &Context<'_>) -> async_graphql::Result<async_graphql::ID> {+ let request_context = ctx.data::<GraphqlSoupRequestContext>()?;+ Ok(async_graphql::ID(request_context.macro_user_id.to_string()))+ }+/// Fetch a page of Soup items using the existing Soup filter AST format.async fn soup(&self, ctx: &Context<'_>, input: SoupInput) -> async_graphql::Result<SoupPage> {let request_context = ctx.data::<GraphqlSoupRequestContext>()?;diff --git a/rust/cloud-storage/schema.graphql b/rust/cloud-storage/schema.graphqlindex 568ec48f63..2c9a321adb 100644--- a/rust/cloud-storage/schema.graphql+++ b/rust/cloud-storage/schema.graphql@@ -387,7 +387,7 @@ type GraphqlSoupChannel {}type GraphqlSoupChannelMessage {- messageId: ID!+ id: ID!threadId: IDsenderId: String!content: String!@@ -587,7 +587,7 @@ type GraphqlSoupForeignEntity {}type GraphqlSoupItem {- id: String!+ id: ID!entityType: GraphqlSoupEntityType!frecencyScore: Float!entity: GraphqlSoupEntity!@@ -622,7 +622,13 @@ type GraphqlSoupProject {}type GraphqlSoupProperty {- id: ID!+ """+ Id of the shared property *definition* — deliberately not named `id`:+ a property instance has no global identity (its `value` is+ per-entity), so it must never be treated as a cacheable entity.+ Normalized caches key objects by the presence of an `id` field.+ """+ propertyDefinitionId: ID!displayName: String!dataType: String!isMultiSelect: Boolean!@@ -655,6 +661,17 @@ type GraphqlSoupPropertyValue {links: [String!]!}+type GraphqlUser {+ """+ Stable id of the authenticated user.+ """+ id: ID!+ """+ Fetch a page of Soup items using the existing Soup filter AST format.+ """+ soup(input: SoupInput!): SoupPage!+}+"""A scalar that can represent any JSON value."""@@ -711,9 +728,9 @@ type SoupPage {type SoupQueryRoot {"""- Fetch a page of Soup items using the existing Soup filter AST format.+ The authenticated user."""- soup(input: SoupInput!): SoupPage!+ user: GraphqlUser!}"""diff --git a/rust/cloud-storage/tools/xtask/Cargo.toml b/rust/cloud-storage/tools/xtask/Cargo.tomlindex 1dac555b17..7e5abce912 100644--- a/rust/cloud-storage/tools/xtask/Cargo.toml+++ b/rust/cloud-storage/tools/xtask/Cargo.toml@@ -1,6 +1,6 @@[package]description = "Repo automation: regenerates workspace-hack and the deploy dep-closure map"-edition = "2021"+edition = "2024"name = "xtask"publish = falseversion = "0.1.0"diff --git a/rust/cloud-storage/tools/xtask/src/cache_wasm.rs b/rust/cloud-storage/tools/xtask/src/cache_wasm.rsnew file mode 100644index 0000000000..01d71f518d--- /dev/null+++ b/rust/cloud-storage/tools/xtask/src/cache_wasm.rs@@ -0,0 +1,109 @@+//! `cargo run -p xtask -- cache-wasm [--force]`+//!+//! Ensures the browser cache wasm package (`client/cache-wasm`, built by+//! wasm-pack into the gitignored `js/app/packages/graphql-cache/wasm/`) is+//! present and version-matched before the vite dev server starts. Without+//! it the cache worker's dynamic import 404s at runtime and the normalized+//! cache silently degrades to network-only.+//!+//! Staleness is judged by semver only: the version in the crate's+//! Cargo.toml vs the version wasm-pack wrote into the generated+//! package.json. **Bump `client/cache-wasm`'s version whenever engine or+//! schema changes should reach dev machines.** CI app builds do not rely on+//! this check — they always rebuild (`just build-cache-wasm` → `--force`),+//! so deploys never depend on version-bump discipline.++use std::{+ path::{Path, PathBuf},+ process::Command,+};++use anyhow::{Context, Result, bail};++const CRATE_REL: &str = "client/cache-wasm";+const PKG_REL: &str = "js/app/packages/graphql-cache/wasm";++pub(crate) fn run(force: bool) -> Result<()> {+ let workspace_dir: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR"))+ .ancestors()+ .nth(2)+ .context("xtask manifest dir has no workspace root two levels up")?+ .to_path_buf();+ let repo_root = workspace_dir+ .ancestors()+ .nth(2)+ .context("workspace root has no repo root two levels up")?+ .to_path_buf();++ let crate_version = crate_version(&workspace_dir.join(CRATE_REL).join("Cargo.toml"))?;+ let pkg_dir = repo_root.join(PKG_REL);+ let built_version = built_version(&pkg_dir.join("package.json"))?;++ if !force && built_version.as_deref() == Some(crate_version.as_str()) {+ println!("cache-wasm: up to date (v{crate_version})");+ return Ok(());+ }++ match &built_version {+ None => println!("cache-wasm: not built yet, building v{crate_version}"),+ Some(built) if force => {+ println!("cache-wasm: forced rebuild (built v{built}, crate v{crate_version})")+ }+ Some(built) => {+ println!("cache-wasm: built v{built} != crate v{crate_version}, rebuilding")+ }+ }++ let status = Command::new("wasm-pack")+ .current_dir(&workspace_dir)+ .arg("build")+ .arg(CRATE_REL)+ .arg("--target")+ .arg("web")+ .arg("--release")+ .arg("--out-dir")+ .arg(&pkg_dir)+ .status()+ .context(+ "running wasm-pack (missing? it ships in the nix dev shell — \+ enter it or install wasm-pack)",+ )?;+ if !status.success() {+ bail!("wasm-pack build failed with status {status}");+ }+ Ok(())+}++/// Reads `version = "…"` from the crate's `[package]` section. A focused+/// line scan (the first `version =` in the manifest precedes any other+/// section) keeps xtask free of a toml dependency.+fn crate_version(manifest: &Path) -> Result<String> {+ let text = std::fs::read_to_string(manifest)+ .with_context(|| format!("reading {}", manifest.display()))?;+ text.lines()+ .map(str::trim)+ .find_map(|line| {+ line.strip_prefix("version = \"")+ .and_then(|rest| rest.strip_suffix('"'))+ })+ .map(str::to_string)+ .with_context(|| format!("no `version = \"…\"` line in {}", manifest.display()))+}++/// Version wasm-pack wrote into the generated package.json, or `None` when+/// the package has not been built (or is unreadable — treated as unbuilt so+/// a corrupt output dir heals via rebuild).+fn built_version(package_json: &Path) -> Result<Option<String>> {+ let text = match std::fs::read_to_string(package_json) {+ Ok(text) => text,+ Err(_) => return Ok(None),+ };+ let parsed: serde_json::Value = match serde_json::from_str(&text) {+ Ok(parsed) => parsed,+ Err(_) => return Ok(None),+ };+ Ok(parsed+ .get("version")+ .and_then(|v| v.as_str())+ .map(str::to_string))+}diff --git a/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rs b/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rsindex 75e1cfe4bf..7fc11adce6 100644--- a/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rs+++ b/rust/cloud-storage/tools/xtask/src/graphql_soup_schema.rs@@ -1,6 +1,6 @@use std::{path::Path, process::Command};-use anyhow::{bail, Context, Result};+use anyhow::{Context, Result, bail};pub(crate) fn run(output_path: &Path) -> Result<()> {let workspace_dir = Path::new(env!("CARGO_MANIFEST_DIR"))diff --git a/rust/cloud-storage/tools/xtask/src/hakari_ops.rs b/rust/cloud-storage/tools/xtask/src/hakari_ops.rsindex bfde9eff89..37b36719d4 100644--- a/rust/cloud-storage/tools/xtask/src/hakari_ops.rs+++ b/rust/cloud-storage/tools/xtask/src/hakari_ops.rs@@ -1,10 +1,10 @@//! workspace-hack maintenance through the hakari library — the same engine//! the `cargo hakari` CLI wraps, minus the CLI (and its version skew).-use anyhow::{anyhow, Context, Result};+use anyhow::{Context, Result, anyhow};use guppy::graph::PackageGraph;-use hakari::summaries::{HakariConfig, DEFAULT_CONFIG_PATH};use hakari::HakariBuilder;+use hakari::summaries::{DEFAULT_CONFIG_PATH, HakariConfig};/// Regenerates (or, in check mode, diffs) the workspace-hack crate:/// the generated section of its Cargo.toml, plus the `workspace-hack`diff --git a/rust/cloud-storage/tools/xtask/src/kafka_topics.rs b/rust/cloud-storage/tools/xtask/src/kafka_topics.rsindex db7c6c2b0b..0d50cd23c1 100644--- a/rust/cloud-storage/tools/xtask/src/kafka_topics.rs+++ b/rust/cloud-storage/tools/xtask/src/kafka_topics.rs@@ -7,7 +7,7 @@use std::collections::BTreeSet;use std::path::Path;-use anyhow::{bail, Context, Result};+use anyhow::{Context, Result, bail};const OUTPUT_REL: &str = ".github/kafka-cluster-topics.json";diff --git a/rust/cloud-storage/tools/xtask/src/local/arch.rs b/rust/cloud-storage/tools/xtask/src/local/arch.rsindex ba569451ca..8feb285902 100644--- a/rust/cloud-storage/tools/xtask/src/local/arch.rs+++ b/rust/cloud-storage/tools/xtask/src/local/arch.rs@@ -6,7 +6,7 @@//! pins glibc rather than cross-compiling between architectures — a materially//! lower-risk use of zigbuild than full cross builds.-use anyhow::{bail, Result};+use anyhow::{Result, bail};/// The glibc version the binaries are linked against, expressed as a/// `cargo zigbuild` target suffix (the same mechanism the Lambda builds use indiff --git a/rust/cloud-storage/tools/xtask/src/local/build/binaries_dir.rs b/rust/cloud-storage/tools/xtask/src/local/build/binaries_dir.rsindex c9d0a6f2f9..3cabc1f91d 100644--- a/rust/cloud-storage/tools/xtask/src/local/build/binaries_dir.rs+++ b/rust/cloud-storage/tools/xtask/src/local/build/binaries_dir.rs@@ -4,7 +4,7 @@use std::path::{Path, PathBuf};-use anyhow::{bail, Context, Result};+use anyhow::{Context, Result, bail};/// Where the service binaries live on the host.#[derive(Clone, Debug)]diff --git a/rust/cloud-storage/tools/xtask/src/local/build/mod.rs b/rust/cloud-storage/tools/xtask/src/local/build/mod.rsindex 4bfdee8a36..6c52a5e078 100644--- a/rust/cloud-storage/tools/xtask/src/local/build/mod.rs+++ b/rust/cloud-storage/tools/xtask/src/local/build/mod.rs@@ -10,7 +10,7 @@ mod runtime_image;mod zigbuild;pub use binaries_dir::BinariesDir;-pub use runtime_image::{ensure_runtime_image, RUNTIME_IMAGE_TAG};+pub use runtime_image::{RUNTIME_IMAGE_TAG, ensure_runtime_image};use anyhow::Result;diff --git a/rust/cloud-storage/tools/xtask/src/local/build/zigbuild.rs b/rust/cloud-storage/tools/xtask/src/local/build/zigbuild.rsindex 27e8cdf1a1..988919f9ca 100644--- a/rust/cloud-storage/tools/xtask/src/local/build/zigbuild.rs+++ b/rust/cloud-storage/tools/xtask/src/local/build/zigbuild.rs@@ -8,7 +8,7 @@use std::path::Path;use std::process::Command;-use anyhow::{bail, Context, Result};+use anyhow::{Context, Result, bail};use super::super::arch::Target;use super::super::inventory::RUST_SERVICES;diff --git a/rust/cloud-storage/tools/xtask/src/local/docker.rs b/rust/cloud-storage/tools/xtask/src/local/docker.rsindex f0e2675c40..0e27d69c66 100644--- a/rust/cloud-storage/tools/xtask/src/local/docker.rs+++ b/rust/cloud-storage/tools/xtask/src/local/docker.rs@@ -5,8 +5,8 @@//! has no compose support.)use anyhow::{Context, Result};-use bollard::models::{NetworkCreateRequest, VolumeCreateRequest};use bollard::Docker;+use bollard::models::{NetworkCreateRequest, VolumeCreateRequest};use macro_env_var::maybe_env_var;/// Run a future to completion on a throwaway current-thread runtime (xtask'sdiff --git a/rust/cloud-storage/tools/xtask/src/local/doctor.rs b/rust/cloud-storage/tools/xtask/src/local/doctor.rsindex cfa812d813..1e78d4b71a 100644--- a/rust/cloud-storage/tools/xtask/src/local/doctor.rs+++ b/rust/cloud-storage/tools/xtask/src/local/doctor.rs@@ -2,7 +2,7 @@use std::process::Command;-use anyhow::{bail, Result};+use anyhow::{Result, bail};use super::{arch, cli::InstanceArgs, instance::Instance, stage::Stage};@@ -113,7 +113,7 @@ fn check_rust_target() -> Status {return Status::Fail {msg: e.to_string(),hint: None,- }+ };}};let sysroot = match Command::new("rustc").args(["--print", "sysroot"]).output() {@@ -122,7 +122,7 @@ fn check_rust_target() -> Status {return Status::Fail {msg: "rustc not found".into(),hint: None,- }+ };}};let std_dir = std::path::Path::new(&sysroot)diff --git a/rust/cloud-storage/tools/xtask/src/local/env_layer.rs b/rust/cloud-storage/tools/xtask/src/local/env_layer.rsindex ca1da6db7c..6f14daf36d 100644--- a/rust/cloud-storage/tools/xtask/src/local/env_layer.rs+++ b/rust/cloud-storage/tools/xtask/src/local/env_layer.rs@@ -20,7 +20,7 @@ use std::process::Command;use anyhow::{Context, Result};use super::instance::Instance;-use super::{local_env, Mode};+use super::{Mode, local_env};/// The fully resolved environment for a run.pub struct ResolvedEnv {diff --git a/rust/cloud-storage/tools/xtask/src/local/frontend.rs b/rust/cloud-storage/tools/xtask/src/local/frontend.rsindex 886168db7b..9370eeda02 100644--- a/rust/cloud-storage/tools/xtask/src/local/frontend.rs+++ b/rust/cloud-storage/tools/xtask/src/local/frontend.rs@@ -11,7 +11,7 @@ use std::thread::JoinHandle;use anyhow::{Context, Result};use super::instance::{Instance, Port};-use super::{proxy, repo_root, stage::Stage, Mode};+use super::{Mode, proxy, repo_root, stage::Stage};/// The app dir where `bun run dev` runs.fn app_dir() -> std::path::PathBuf {diff --git a/rust/cloud-storage/tools/xtask/src/local/gen_compose.rs b/rust/cloud-storage/tools/xtask/src/local/gen_compose.rsindex 93aa7cf3fc..8dce42077a 100644--- a/rust/cloud-storage/tools/xtask/src/local/gen_compose.rs+++ b/rust/cloud-storage/tools/xtask/src/local/gen_compose.rs@@ -18,13 +18,13 @@ use std::process::Command;use anyhow::{Context, Result};use docker_compose_types as dct;use indexmap::IndexMap;-use serde_yaml::value::{Tag, TaggedValue};use serde_yaml::Value;+use serde_yaml::value::{Tag, TaggedValue};use super::build::{BinariesDir, RUNTIME_IMAGE_TAG};use super::instance::{Instance, Port};use super::inventory::services_for_mode;-use super::{repo_root, Mode};+use super::{Mode, repo_root};pub const LOCALSTACK_IMAGE: &str = "localstack/localstack:4";pub const MAILPIT_IMAGE: &str = "axllent/mailpit:v1.20";@@ -68,10 +68,11 @@ pub fn generate(mode: Mode, instance: &Instance, binaries: &BinariesDir) -> Resu// Named instances need their own host ports (replacing the base ports —// emitted as `!override` in apply_tags). Only the self-contained local// stacks remap; dev inherits the base-compose ports.- if mode.spec().runs_local_infra && !instance.is_default() {- if let Some(port) = svc.host_port {- s.ports = dct::Ports::Short(vec![format!("{}:8080", instance.port(port))]);- }+ if mode.spec().runs_local_infra+ && !instance.is_default()+ && let Some(port) = svc.host_port+ {+ s.ports = dct::Ports::Short(vec![format!("{}:8080", instance.port(port))]);}services.insert(svc.compose_name.to_string(), Some(s));}diff --git a/rust/cloud-storage/tools/xtask/src/local/instance.rs b/rust/cloud-storage/tools/xtask/src/local/instance.rsindex 258258fd14..ef5508877d 100644--- a/rust/cloud-storage/tools/xtask/src/local/instance.rs+++ b/rust/cloud-storage/tools/xtask/src/local/instance.rs@@ -8,7 +8,7 @@use std::net::TcpListener;-use anyhow::{bail, Context, Result};+use anyhow::{Context, Result, bail};use strum::{EnumIter, IntoEnumIterator};use super::repo_root;diff --git a/rust/cloud-storage/tools/xtask/src/local/inventory.rs b/rust/cloud-storage/tools/xtask/src/local/inventory.rsindex 63d6e9f7da..1e27133e99 100644--- a/rust/cloud-storage/tools/xtask/src/local/inventory.rs+++ b/rust/cloud-storage/tools/xtask/src/local/inventory.rs@@ -8,8 +8,8 @@//! `email_service` crate) and makes "a port on a portless worker"//! unrepresentable (`host_port: None` == portless worker).-use super::instance::Port;use super::Mode;+use super::instance::Port;/// A Rust service whose binary the orchestrator builds on the host and mounts/// into the runtime image at `/app/out/<cargo_bin>`. Several fields documentdiff --git a/rust/cloud-storage/tools/xtask/src/local/kafka.rs b/rust/cloud-storage/tools/xtask/src/local/kafka.rsindex afcaa68858..c1ca75b12e 100644--- a/rust/cloud-storage/tools/xtask/src/local/kafka.rs+++ b/rust/cloud-storage/tools/xtask/src/local/kafka.rs@@ -17,13 +17,13 @@ use std::time::Duration;use anyhow::Context;use anyhow::Result;#[cfg(feature = "local-stack")]+use rdkafka::ClientConfig;+#[cfg(feature = "local-stack")]use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};#[cfg(feature = "local-stack")]use rdkafka::client::DefaultClientContext;#[cfg(feature = "local-stack")]use rdkafka::types::RDKafkaErrorCode;-#[cfg(feature = "local-stack")]-use rdkafka::ClientConfig;use super::instance::Instance;#[cfg(feature = "local-stack")]diff --git a/rust/cloud-storage/tools/xtask/src/local/kickstart.rs b/rust/cloud-storage/tools/xtask/src/local/kickstart.rsindex 097ae63ee9..e255a9c237 100644--- a/rust/cloud-storage/tools/xtask/src/local/kickstart.rs+++ b/rust/cloud-storage/tools/xtask/src/local/kickstart.rs@@ -9,7 +9,7 @@//! (after the app it registers against exists); passwordless login auto-creates//! all other users on demand.-use serde_json::{json, Value};+use serde_json::{Value, json};use super::identity;diff --git a/rust/cloud-storage/tools/xtask/src/local/local_env.rs b/rust/cloud-storage/tools/xtask/src/local/local_env.rsindex 79d2381778..0fada947de 100644--- a/rust/cloud-storage/tools/xtask/src/local/local_env.rs+++ b/rust/cloud-storage/tools/xtask/src/local/local_env.rs@@ -15,7 +15,7 @@use std::collections::BTreeMap;use super::instance::{Instance, Port};-use super::{identity, resources, Mode};+use super::{Mode, identity, resources};/// The full local environment for one instance.pub struct LocalEnv {diff --git a/rust/cloud-storage/tools/xtask/src/local/local_env/test.rs b/rust/cloud-storage/tools/xtask/src/local/local_env/test.rsindex 26daadc189..16482f4bab 100644--- a/rust/cloud-storage/tools/xtask/src/local/local_env/test.rs+++ b/rust/cloud-storage/tools/xtask/src/local/local_env/test.rs@@ -1,6 +1,6 @@use super::*;-use crate::local::instance::Instance;use crate::local::Mode;+use crate::local::instance::Instance;fn local_env() -> BTreeMap<String, String> {let instance = Instance::derive(None, None).expect("default instance derives");diff --git a/rust/cloud-storage/tools/xtask/src/local/proxy.rs b/rust/cloud-storage/tools/xtask/src/local/proxy.rsindex 8f6c2f6ef8..6d28de5473 100644--- a/rust/cloud-storage/tools/xtask/src/local/proxy.rs+++ b/rust/cloud-storage/tools/xtask/src/local/proxy.rs@@ -12,7 +12,7 @@ use anyhow::{Context, Result};use super::gen_compose::caddyfile_path;use super::instance::{Instance, Port};-use super::{inventory, Mode};+use super::{Mode, inventory};/// The host-facing proxy origin.pub fn url(instance: &Instance) -> String {diff --git a/rust/cloud-storage/tools/xtask/src/local/stage.rs b/rust/cloud-storage/tools/xtask/src/local/stage.rsindex 4d6770426f..4b84b0f74f 100644--- a/rust/cloud-storage/tools/xtask/src/local/stage.rs+++ b/rust/cloud-storage/tools/xtask/src/local/stage.rs@@ -15,7 +15,7 @@ use std::io::Read;use std::process::{Command, Stdio};use std::time::{Duration, Instant};-use anyhow::{bail, Result};+use anyhow::{Result, bail};use console::Style;use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};diff --git a/rust/cloud-storage/tools/xtask/src/local/summary.rs b/rust/cloud-storage/tools/xtask/src/local/summary.rsindex 4e8aa6921e..9c3af622cc 100644--- a/rust/cloud-storage/tools/xtask/src/local/summary.rs+++ b/rust/cloud-storage/tools/xtask/src/local/summary.rs@@ -4,7 +4,7 @@ use console::Style;use super::env_layer::ResolvedEnv;use super::instance::{Instance, Port};-use super::{frontend, mailpit, proxy, Mode};+use super::{Mode, frontend, mailpit, proxy};/// Print the mode/instance/endpoints block after a successful startup.pub fn print(mode: Mode, instance: &Instance, env: &ResolvedEnv) {diff --git a/rust/cloud-storage/tools/xtask/src/local/validate.rs b/rust/cloud-storage/tools/xtask/src/local/validate.rsindex a69a9f37dc..e954ff7348 100644--- a/rust/cloud-storage/tools/xtask/src/local/validate.rs+++ b/rust/cloud-storage/tools/xtask/src/local/validate.rs@@ -4,12 +4,12 @@//! service builds in Docker for the local path, and local mode never requires//! Pulumi / real AWS / real SES.-use anyhow::{bail, Context, Result};+use anyhow::{Context, Result, bail};use serde_json::Value;use super::build::{BinariesDir, RUNTIME_IMAGE_TAG};use super::inventory::services_for_mode;-use super::{arch, env_layer, gen_compose, instance::Instance, workspace_root, Mode};+use super::{Mode, arch, env_layer, gen_compose, instance::Instance, workspace_root};/// Required non-Rust services that must be present in the rendered local/// compose.@@ -153,12 +153,13 @@ pub fn local_env(("DATABASE_URL", "postgres"),("REDIS_URI", "redis"),] {- if let Some(v) = env.get(key) {- if !v.contains(host) && !v.contains("localhost") {- failures.push(format!(- "{key}={v} is not a local endpoint (expected host '{host}')"- ));- }+ if let Some(v) = env.get(key)+ && !v.contains(host)+ && !v.contains("localhost")+ {+ failures.push(format!(+ "{key}={v} is not a local endpoint (expected host '{host}')"+ ));}}}@@ -180,7 +181,9 @@ pub fn local_env(match env.get("DATABASE_URL") {None => failures.push("run-dev requires a dev DATABASE_URL (none found)".into()),Some(v) if v.contains("@postgres:") || v.contains("localhost") => {- failures.push(format!("run-dev DATABASE_URL={v} points at local infra; expected a shared-dev host"));+ failures.push(format!(+ "run-dev DATABASE_URL={v} points at local infra; expected a shared-dev host"+ ));}Some(_) => {}}diff --git a/rust/cloud-storage/tools/xtask/src/main.rs b/rust/cloud-storage/tools/xtask/src/main.rsindex 834313d381..e895c2035a 100644--- a/rust/cloud-storage/tools/xtask/src/main.rs+++ b/rust/cloud-storage/tools/xtask/src/main.rs@@ -15,6 +15,7 @@//! runs and CI cannot disagree about generator versions. `just hakari` wraps//! the regenerate mode; CI runs `--check` and fails on drift.+mod cache_wasm;mod closures;mod doppler_bins;mod graphql_soup_schema;@@ -26,9 +27,9 @@ mod workflows;use std::path::Path;-use anyhow::{bail, Context, Result};-use guppy::graph::PackageGraph;+use anyhow::{Context, Result, bail};use guppy::MetadataCommand;+use guppy::graph::PackageGraph;fn main() -> Result<()> {let args: Vec<String> = std::env::args().skip(1).collect();@@ -44,6 +45,8 @@ fn main() -> Result<()> {doppler_bins::run(&graph, Path::new(changed_files_path))}["graphql-soup-schema", output_path] => graphql_soup_schema::run(Path::new(output_path)),+ ["cache-wasm"] => cache_wasm::run(false),+ ["cache-wasm", "--force"] => cache_wasm::run(true),["kafka-topics"] => kafka_topics::run(false),["kafka-topics", "--check"] => kafka_topics::run(true),["workflows"] => workflows::generate(),@@ -59,7 +62,7 @@ fn main() -> Result<()> {/// Usage for the repo-automation verbs handled by the slice match above. The/// local orchestration parser appends its own usage and prints both on an/// unrecognized command.-const LEGACY_USAGE: &str = "repo automation (from rust/cloud-storage):\n cargo x deps [--check]\n cargo x nextest-filter <changed-files-path>\n cargo x doppler-bins <changed-files-path>\n cargo x graphql-soup-schema <output-path>\n cargo x kafka-topics [--check]\n cargo x workflows [--check]";+const LEGACY_USAGE: &str = "repo automation (from rust/cloud-storage):\n cargo x deps [--check]\n cargo x nextest-filter <changed-files-path>\n cargo x doppler-bins <changed-files-path>\n cargo x graphql-soup-schema <output-path>\n cargo x cache-wasm [--force]\n cargo x kafka-topics [--check]\n cargo x workflows [--check]";fn run_deps(check: bool) -> Result<()> {let graph = build_graph(check)?;diff --git a/rust/cloud-storage/tools/xtask/src/workflows/mod.rs b/rust/cloud-storage/tools/xtask/src/workflows/mod.rsindex 1d1b6230e7..ad5adf2261 100644--- a/rust/cloud-storage/tools/xtask/src/workflows/mod.rs+++ b/rust/cloud-storage/tools/xtask/src/workflows/mod.rs@@ -35,7 +35,7 @@ mod web_app_check_main;use std::fs;use std::path::{Path, PathBuf};-use anyhow::{bail, Context, Result};+use anyhow::{Context, Result, bail};use gh_workflow::Workflow;/// A generated workflow. `slug` is the snake_case source module (`<slug>.rs`)diff --git a/rust/cloud-storage/tools/xtask/src/workflows/steps.rs b/rust/cloud-storage/tools/xtask/src/workflows/steps.rsindex 58fa3772a6..54efa40f3b 100644--- a/rust/cloud-storage/tools/xtask/src/workflows/steps.rs+++ b/rust/cloud-storage/tools/xtask/src/workflows/steps.rs@@ -18,11 +18,7 @@ pub trait FluentBuilder: Sized {}/// Apply `f` only when `cond` holds.fn when(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {- if cond {- f(self)- } else {- self- }+ if cond { f(self) } else { self }}}diff --git a/rust/cloud-storage/workspace-hack/Cargo.toml b/rust/cloud-storage/workspace-hack/Cargo.tomlindex 3947421dc0..aae4b4a9a0 100644--- a/rust/cloud-storage/workspace-hack/Cargo.toml+++ b/rust/cloud-storage/workspace-hack/Cargo.toml@@ -3,10 +3,10 @@# cargo hakari generate[package]+description = "workspace-hack package, managed by hakari"+edition = "2024"name = "workspace-hack"version = "0.1.0"-edition = "2021"-description = "workspace-hack package, managed by hakari"# You can choose to publish this crate: see https://docs.rs/cargo-hakari/latest/cargo_hakari/publishing.publish = falsediff --git a/rust/sync-service/bebop-schema/Cargo.toml b/rust/sync-service/bebop-schema/Cargo.tomlindex 07b995836a..e86607229b 100644--- a/rust/sync-service/bebop-schema/Cargo.toml+++ b/rust/sync-service/bebop-schema/Cargo.toml@@ -1,7 +1,7 @@[package]+edition = "2024"name = "sync_service_bebop_schema"version = "0.1.0"-edition = "2021"[features]bebop-owned-all = []