@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -1,1491 +0,0 @@
1
- import { RecordId, Duration } from 'surrealdb';
2
- import type {
3
- SchemaStructure,
4
- TableNames,
5
- BackendNames,
6
- BackendRoutes,
7
- RoutePayload,
8
- } from '@spooky-sync/query-builder';
9
- import type { LocalDatabaseService } from '../../services/database/index';
10
- import type { CacheModule, RecordWithId, CacheRecord } from '../cache/index';
11
- import type { Logger } from '../../services/logger/index';
12
- import type { StreamUpdate } from '../../services/stream-processor/index';
13
- import type {
14
- QueryConfig,
15
- QueryHash,
16
- QueryState,
17
- QueryStatus,
18
- QueryStatusCallback,
19
- QueryTimeToLive,
20
- QueryUpdateCallback,
21
- MutationCallback,
22
- RecordVersionArray,
23
- QueryConfigRecord,
24
- UpdateOptions,
25
- QueryTimings,
26
- PhaseStat,
27
- RegistrationTimings,
28
- RunOptions} from '../../types';
29
- import { MATERIALIZATION_SAMPLE_WINDOW } from '../../types';
30
- import {
31
- parseRecordIdString,
32
- extractIdPart,
33
- encodeRecordId,
34
- parseDuration,
35
- withRetry,
36
- surql,
37
- parseParams,
38
- cleanRecord,
39
- extractTablePart,
40
- generateId,
41
- } from '../../utils/index';
42
- import type { CreateEvent, DeleteEvent, UpdateEvent } from '../sync/index';
43
- import type { PushEventOptions } from '../../events/index';
44
- import { buildWindowMaterialization } from './window-query';
45
-
46
- /** Push a timing sample (ms) into a rolling window, capped at the sample window. */
47
- function pushSample(samples: number[], ms: number): void {
48
- samples.push(ms);
49
- if (samples.length > MATERIALIZATION_SAMPLE_WINDOW) samples.shift();
50
- }
51
-
52
- /** Build a {lastMs,p50,p90,p99,count} summary from a rolling sample window. */
53
- function phaseStatOf(samples: number[], lastMs: number | null): PhaseStat {
54
- if (samples.length === 0) {
55
- return { lastMs, p50: null, p90: null, p99: null, count: 0 };
56
- }
57
- const sorted = [...samples].sort((a, b) => a - b);
58
- const pick = (q: number) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]!;
59
- return { lastMs, p50: pick(0.5), p90: pick(0.9), p99: pick(0.99), count: samples.length };
60
- }
61
-
62
- /**
63
- * DataModule - Unified query and mutation management
64
- *
65
- * Merges the functionality of QueryManager and MutationManager.
66
- * Uses CacheModule for all storage operations.
67
- */
68
- export class DataModule<S extends SchemaStructure> {
69
- private activeQueries: Map<QueryHash, QueryState> = new Map();
70
- private pendingQueries: Map<QueryHash, Promise<QueryHash>> = new Map();
71
- private subscriptions: Map<QueryHash, Set<QueryUpdateCallback>> = new Map();
72
- private statusSubscriptions: Map<QueryHash, Set<QueryStatusCallback>> = new Map();
73
- private mutationCallbacks: Set<MutationCallback> = new Set();
74
- private debounceTimers: Map<QueryHash, NodeJS.Timeout> = new Map();
75
- private logger: Logger;
76
- /**
77
- * Optional observer notified whenever a query's fetch status changes.
78
- * Wired by Sp00kyClient to push status changes into DevTools. Kept as a
79
- * settable field (rather than a constructor arg) because DevTools is
80
- * constructed after DataModule.
81
- */
82
- public onQueryStatusChange?: (hash: QueryHash, status: QueryStatus) => void;
83
- /**
84
- * Optional observer invoked when a still-subscribed query's TTL heartbeat
85
- * fires (~90% of the TTL). Wired by Sp00kyClient to
86
- * `Sp00kySync.heartbeatQuery`, which refreshes the remote `_00_query`
87
- * row's `lastActiveAt` so an actively-watched query never expires. Settable
88
- * field (not a constructor arg) because the sync engine is wired after
89
- * DataModule is constructed — mirrors `onQueryStatusChange`.
90
- */
91
- public onHeartbeat?: (hash: QueryHash) => void;
92
- /**
93
- * Optional hook fired by {@link deregisterQuery} when an opt-in query (e.g. a
94
- * viewport-windowed list cancelling an off-screen window) loses its last
95
- * subscriber. Wired by Sp00kyClient to enqueue a `cleanup` down-event, which
96
- * tears the remote `_00_query` view down (releasing its `_00_list_ref` edges)
97
- * instead of leaving it for the TTL sweep. The local view + state are freed in
98
- * {@link finalizeDeregister} only after that remote delete, so a fast
99
- * re-subscribe (scroll back) can abort/heal the teardown — see `cleanupQuery`.
100
- */
101
- public onDeregister?: (hash: QueryHash) => void;
102
- // Salt for query-id hashing. Set from SurrealDB's session::id() so two
103
- // browser sessions registering the same logical query (same surql + params)
104
- // don't collide on the same `_00_query` row — each session gets its own.
105
- // Empty string until init(sessionId) is called.
106
- private sessionId: string = '';
107
- // Authenticated user record id (e.g. `"user:abc"`). Updated by
108
- // `setCurrentUserId` from the auth subscription. null when
109
- // unauthenticated. Consulted by `Sp00kySync.listRefTable()` so the
110
- // poll and LIVE subscription target the same per-user
111
- // `_00_list_ref_user_<id>` table the sync engine writes to.
112
- private currentUserId: string | null = null;
113
-
114
- constructor(
115
- private cache: CacheModule,
116
- private local: LocalDatabaseService,
117
- private schema: S,
118
- logger: Logger,
119
- // Client-side SSP aggregation throttle: coalesces the in-browser
120
- // StreamProcessor's per-record stream updates per query before notifying
121
- // readers, so a burst of synced records repaints the UI once per window
122
- // rather than row-by-row. 50ms keeps it responsive while still batching the
123
- // initial-sync stream. Override via `SyncedDbConfig.streamDebounceTime`.
124
- private streamDebounceTime: number = 50
125
- ) {
126
- this.logger = logger.child({ service: 'DataModule' });
127
- }
128
-
129
- async init(sessionId: string): Promise<void> {
130
- this.sessionId = sessionId;
131
- this.logger.info(
132
- { sessionId, Category: 'sp00ky-client::DataModule::init' },
133
- 'DataModule initialized'
134
- );
135
- }
136
-
137
- /**
138
- * Update the session salt used in query-id hashing. Call this when the
139
- * SurrealDB session changes (sign-in, sign-out, reconnect). Subsequently
140
- * registered queries will get fresh, session-scoped IDs.
141
- */
142
- setSessionId(sessionId: string): void {
143
- this.sessionId = sessionId;
144
- }
145
-
146
- /**
147
- * Update the authenticated user record id. Pass `null` on sign-out.
148
- * Read by `Sp00kySync.listRefTable()` so the LIVE subscription and
149
- * the poll route to the same per-user `_00_list_ref_user_<id>` the
150
- * SSP writes to.
151
- */
152
- setCurrentUserId(userId: string | null): void {
153
- this.currentUserId = userId;
154
- }
155
-
156
- /** Read-only view of the authenticated user id used for per-user
157
- * `_00_list_ref` routing. Other modules consult this so they pick the
158
- * same table name DataModule does. */
159
- getCurrentUserId(): string | null {
160
- return this.currentUserId;
161
- }
162
-
163
- // ==================== QUERY MANAGEMENT ====================
164
-
165
- /**
166
- * Register a query and return its hash for subscriptions
167
- */
168
- async query<T extends TableNames<S>>(
169
- tableName: T,
170
- surqlString: string,
171
- params: Record<string, any>,
172
- ttl: QueryTimeToLive
173
- ): Promise<QueryHash> {
174
- const hash = await this.calculateHash({ surql: surqlString, params });
175
- this.logger.debug(
176
- { hash, Category: 'sp00ky-client::DataModule::query' },
177
- 'Query Initialization: started'
178
- );
179
-
180
- // `_00_query` stays the single shared registration table in both
181
- // ref-modes; the per-user split happens only on `_00_list_ref`.
182
- const recordId = new RecordId('_00_query', hash);
183
-
184
- if (this.activeQueries.has(hash)) {
185
- this.logger.debug(
186
- { hash, Category: 'sp00ky-client::DataModule::query' },
187
- 'Query Initialization: exists, returning'
188
- );
189
- return hash;
190
- }
191
-
192
- // Another call is already creating this query — wait for it
193
- if (this.pendingQueries.has(hash)) {
194
- this.logger.debug(
195
- { hash, Category: 'sp00ky-client::DataModule::query' },
196
- 'Query Initialization: pending, waiting for existing creation'
197
- );
198
- await this.pendingQueries.get(hash);
199
- return hash;
200
- }
201
-
202
- this.logger.debug(
203
- { hash, Category: 'sp00ky-client::DataModule::query' },
204
- 'Query Initialization: not found, creating new query'
205
- );
206
-
207
- // Create the query and track the pending promise
208
- const promise = this.createAndRegisterQuery<T>(hash, recordId, surqlString, params, ttl, tableName);
209
- this.pendingQueries.set(hash, promise);
210
- try {
211
- await promise;
212
- } finally {
213
- this.pendingQueries.delete(hash);
214
- }
215
-
216
- return hash;
217
- }
218
-
219
- /**
220
- * Subscribe to query updates
221
- */
222
- subscribe(
223
- queryHash: string,
224
- callback: QueryUpdateCallback,
225
- options: { immediate?: boolean } = {}
226
- ): () => void {
227
- if (!this.subscriptions.has(queryHash)) {
228
- this.subscriptions.set(queryHash, new Set());
229
- }
230
-
231
- this.subscriptions.get(queryHash)?.add(callback);
232
-
233
- if (options.immediate) {
234
- const query = this.activeQueries.get(queryHash);
235
- if (query) {
236
- callback(query.records);
237
- }
238
- }
239
-
240
- // Return unsubscribe function
241
- return () => {
242
- const subs = this.subscriptions.get(queryHash);
243
- if (subs) {
244
- subs.delete(callback);
245
- if (subs.size === 0) {
246
- this.subscriptions.delete(queryHash);
247
- // NOTE: intentionally do NOT tear down the query / free its in-browser
248
- // SSP view here. The subscriber-gated heartbeat (startTTLHeartbeat)
249
- // already self-stops once subscribers hit 0, so an abandoned query
250
- // stops being kept alive and the server's TTL sweep removes it. Freeing
251
- // the local view on every last-unsubscribe caused re-registration churn
252
- // on navigation (open A → leave → open A again re-registers), which is
253
- // a flakiness risk for no real benefit — keep the local view resident.
254
- }
255
- }
256
- };
257
- }
258
-
259
- /**
260
- * Subscribe to a query's fetch-status changes (idle/fetching).
261
- * With `{ immediate: true }` the callback fires synchronously with the
262
- * current status (defaults to `idle` if the query isn't registered yet).
263
- */
264
- subscribeStatus(
265
- queryHash: string,
266
- callback: QueryStatusCallback,
267
- options: { immediate?: boolean } = {}
268
- ): () => void {
269
- if (!this.statusSubscriptions.has(queryHash)) {
270
- this.statusSubscriptions.set(queryHash, new Set());
271
- }
272
- this.statusSubscriptions.get(queryHash)?.add(callback);
273
-
274
- if (options.immediate) {
275
- callback(this.activeQueries.get(queryHash)?.status ?? 'idle');
276
- }
277
-
278
- return () => {
279
- const subs = this.statusSubscriptions.get(queryHash);
280
- if (subs) {
281
- subs.delete(callback);
282
- if (subs.size === 0) {
283
- this.statusSubscriptions.delete(queryHash);
284
- }
285
- }
286
- };
287
- }
288
-
289
- /**
290
- * Set a query's fetch status and notify status observers (DevTools +
291
- * `subscribeStatus` listeners). No-op when the status is unchanged or the
292
- * query is unknown.
293
- */
294
- setQueryStatus(queryHash: string, status: QueryStatus): void {
295
- const queryState = this.activeQueries.get(queryHash);
296
- if (!queryState || queryState.status === status) {
297
- return;
298
- }
299
- queryState.status = status;
300
-
301
- this.onQueryStatusChange?.(queryHash, status);
302
-
303
- const subs = this.statusSubscriptions.get(queryHash);
304
- if (subs) {
305
- for (const callback of subs) {
306
- callback(status);
307
- }
308
- }
309
- }
310
-
311
- /**
312
- * Subscribe to mutations (for sync)
313
- */
314
- onMutation(callback: MutationCallback): () => void {
315
- this.mutationCallbacks.add(callback);
316
- return () => {
317
- this.mutationCallbacks.delete(callback);
318
- };
319
- }
320
-
321
- /**
322
- * Handle stream updates from DBSP (via CacheModule)
323
- */
324
- async onStreamUpdate(update: StreamUpdate): Promise<void> {
325
- const { queryHash, op } = update;
326
-
327
- // DELETE propagates immediately — a removed row should disappear without
328
- // waiting on a debounce.
329
- //
330
- // CREATE and UPDATE are coalesced per query on a trailing timer. A list's
331
- // rows stream in from sync as many small `_00_list_ref` diffs, each its own
332
- // `cache.saveBatch` → one stream update per chunk. `ingestMany` only
333
- // coalesces records ingested synchronously together, so chunks spread over
334
- // time each re-materialize and re-notify — a 50-row window can fire 30+
335
- // updates as it fills. Each StreamUpdate carries the full materialized
336
- // `localArray`, so the latest one already reflects every prior chunk: keep
337
- // only it and fire once on the trailing edge, settling the query in a couple
338
- // of notifications instead of one per chunk.
339
- if (op === 'DELETE') {
340
- const existing = this.debounceTimers.get(queryHash);
341
- if (existing) {
342
- clearTimeout(existing);
343
- this.debounceTimers.delete(queryHash);
344
- }
345
- await this.processStreamUpdate(update);
346
- return;
347
- }
348
-
349
- // Clear existing timer if any
350
- if (this.debounceTimers.has(queryHash)) {
351
- // oxlint-disable-next-line no-non-null-assertion -- guarded by .has() check above
352
- clearTimeout(this.debounceTimers.get(queryHash)!);
353
- }
354
-
355
- // Set new timer
356
- const timer = setTimeout(async () => {
357
- this.debounceTimers.delete(queryHash);
358
- await this.processStreamUpdate(update);
359
- }, this.streamDebounceTime);
360
-
361
- this.debounceTimers.set(queryHash, timer);
362
- }
363
-
364
- // Materialize a query's result rows from the local DB. For a windowed query
365
- // (`LIMIT n START m`, m>0) the original surql is NOT re-run — re-applying
366
- // `START m` against the shared local store would skip the window's own rows
367
- // (sparse windowing) and return nothing. Instead we select the window's
368
- // record id-set directly, preferring the server's `list_ref` (`remoteArray`,
369
- // authoritative) over the in-browser SSP's view (`sspArray`), and re-apply
370
- // the original ORDER BY for stable order.
371
- private async materializeRecords(
372
- queryState: QueryState,
373
- sspArray?: Array<[string, number]>
374
- ): Promise<Record<string, any>[]> {
375
- const t0 = performance.now();
376
- const windowMat = buildWindowMaterialization(queryState.config.surql);
377
- let records: Record<string, any>[];
378
- if (windowMat) {
379
- const win =
380
- (queryState.config.remoteArray?.length && queryState.config.remoteArray) ||
381
- (sspArray?.length && sspArray) ||
382
- queryState.config.localArray ||
383
- [];
384
- const winIds = win.map(([id]) => parseRecordIdString(id));
385
- const [rows] = await this.local.query<[Record<string, any>[]]>(windowMat.query, {
386
- ...queryState.config.params,
387
- __win: winIds,
388
- });
389
- records = rows || [];
390
- } else {
391
- const [rows] = await this.local.query<[Record<string, any>[]]>(
392
- queryState.config.surql,
393
- queryState.config.params
394
- );
395
- records = rows || [];
396
- }
397
- // Local SurrealDB record-fetch time → DevTools "localFetch" phase.
398
- this.recordPhase(queryState, 'localFetch', performance.now() - t0);
399
- return records;
400
- }
401
-
402
- private async processStreamUpdate(update: StreamUpdate): Promise<void> {
403
- const { queryHash, localArray, materializationTimeMs } = update;
404
- const queryState = this.activeQueries.get(queryHash);
405
- if (!queryState) {
406
- this.logger.warn(
407
- { queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
408
- 'Received update for unknown query. Skipping...'
409
- );
410
- return;
411
- }
412
-
413
- // Update the rolling materialization-sample window before the work that
414
- // could throw, so the percentiles still move when the downstream local
415
- // query fails (the materialization step itself ran).
416
- if (typeof materializationTimeMs === 'number') {
417
- queryState.materializationSamples.push(materializationTimeMs);
418
- if (queryState.materializationSamples.length > MATERIALIZATION_SAMPLE_WINDOW) {
419
- queryState.materializationSamples.shift();
420
- }
421
- queryState.lastIngestLatencyMs = materializationTimeMs;
422
- }
423
- // Record the SSP internal sub-phase timings (from the WASM binding) so
424
- // DevTools can attribute ingest cost to store-apply vs circuit-step vs transform.
425
- if (typeof update.storeApplyMs === 'number')
426
- this.recordPhase(queryState, 'sspStoreApply', update.storeApplyMs);
427
- if (typeof update.circuitStepMs === 'number')
428
- this.recordPhase(queryState, 'sspCircuitStep', update.circuitStepMs);
429
- if (typeof update.transformMs === 'number')
430
- this.recordPhase(queryState, 'sspTransform', update.transformMs);
431
- const percentiles = this.computeMaterializationPercentiles(queryState.materializationSamples);
432
-
433
- try {
434
- // Materialize the query's rows. For a windowed (offset) query, re-running
435
- // the original surql would re-apply `START n` against the shared local DB
436
- // and skip the window's rows entirely; instead select the SSP's
437
- // materialized window id-set (`localArray`) directly, re-applying the
438
- // original ORDER BY for stable display order. Non-offset queries keep the
439
- // normal re-query path.
440
- const newRecords = await this.materializeRecords(queryState, localArray);
441
- queryState.config.localArray = localArray;
442
-
443
- const prevJson = JSON.stringify(queryState.records);
444
- const newJson = JSON.stringify(newRecords);
445
- queryState.records = newRecords;
446
- const recordsChanged = prevJson !== newJson;
447
-
448
- // updateCount counts user-visible updates (matches the prior semantic),
449
- // while the materialization sample/percentiles already moved above for
450
- // every observed engine step.
451
- if (recordsChanged) {
452
- queryState.updateCount++;
453
- }
454
-
455
- await this.local.query(
456
- surql.seal(
457
- surql.updateSet('id', [
458
- 'localArray',
459
- 'rowCount',
460
- 'updateCount',
461
- 'lastIngestLatency',
462
- 'materializationP55',
463
- 'materializationP90',
464
- 'materializationP99',
465
- ])
466
- ),
467
- {
468
- id: queryState.config.id,
469
- localArray,
470
- rowCount: localArray.length,
471
- updateCount: queryState.updateCount,
472
- lastIngestLatency: queryState.lastIngestLatencyMs,
473
- materializationP55: percentiles.p55,
474
- materializationP90: percentiles.p90,
475
- materializationP99: percentiles.p99,
476
- }
477
- );
478
-
479
- if (!recordsChanged) {
480
- this.logger.debug(
481
- { queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
482
- 'Query records unchanged, skipping notification'
483
- );
484
- return;
485
- }
486
-
487
- // Notify subscribers
488
- const subscribers = this.subscriptions.get(queryHash);
489
- if (subscribers) {
490
- for (const callback of subscribers) {
491
- callback(queryState.records);
492
- }
493
- }
494
-
495
- this.logger.debug(
496
- {
497
- queryHash,
498
- recordCount: newRecords?.length,
499
- Category: 'sp00ky-client::DataModule::onStreamUpdate',
500
- },
501
- 'Query updated from stream'
502
- );
503
- } catch (err) {
504
- queryState.errorCount++;
505
- this.logger.error(
506
- { err, queryHash, Category: 'sp00ky-client::DataModule::onStreamUpdate' },
507
- 'Failed to fetch records for stream update'
508
- );
509
- // Best-effort persist of the bumped errorCount; swallow secondary
510
- // failures to avoid masking the original error in logs.
511
- try {
512
- await this.local.query(surql.seal(surql.updateSet('id', ['errorCount'])), {
513
- id: queryState.config.id,
514
- errorCount: queryState.errorCount,
515
- });
516
- } catch (persistErr) {
517
- this.logger.warn(
518
- {
519
- err: persistErr,
520
- queryHash,
521
- Category: 'sp00ky-client::DataModule::onStreamUpdate',
522
- },
523
- 'Failed to persist incremented errorCount'
524
- );
525
- }
526
- }
527
- }
528
-
529
- /**
530
- * Compute p55/p90/p99 from a rolling window of materialization samples.
531
- * Returns nulls for any percentile that has no samples yet so SurrealDB
532
- * `option<float>` columns stay NONE rather than 0 before the first ingest.
533
- */
534
- private computeMaterializationPercentiles(samples: number[]): {
535
- p55: number | null;
536
- p90: number | null;
537
- p99: number | null;
538
- } {
539
- if (samples.length === 0) {
540
- return { p55: null, p90: null, p99: null };
541
- }
542
- const sorted = [...samples].sort((a, b) => a - b);
543
- const pick = (q: number) => {
544
- const idx = Math.min(sorted.length - 1, Math.floor(q * sorted.length));
545
- return sorted[idx]!;
546
- };
547
- return { p55: pick(0.55), p90: pick(0.90), p99: pick(0.99) };
548
- }
549
-
550
- /** Record a per-phase timing sample (ms) on a query's rolling window. */
551
- private recordPhase(qs: QueryState, phase: string, ms: number): void {
552
- if (!Number.isFinite(ms)) return;
553
- const arr = qs.phaseSamples[phase] ?? (qs.phaseSamples[phase] = []);
554
- pushSample(arr, ms);
555
- qs.phaseLast[phase] = ms;
556
- }
557
-
558
- /** Record the remote record-fetch time (ms) for a query. Called by the sync engine. */
559
- recordRemoteFetch(hash: string, ms: number): void {
560
- const qs = this.activeQueries.get(hash);
561
- if (qs) this.recordPhase(qs, 'remoteFetch', ms);
562
- }
563
-
564
- /**
565
- * Record the frontend reconcile time (ms) for a query. Called from `useQuery`
566
- * via `Sp00kyClient.reportFrontendTiming` after it applies an update to its store.
567
- */
568
- recordFrontendTiming(hash: string, ms: number): void {
569
- const qs = this.activeQueries.get(hash);
570
- if (qs) this.recordPhase(qs, 'frontend', ms);
571
- }
572
-
573
- /**
574
- * Build the per-query processing-time breakdown surfaced to the DevTools panel
575
- * and the MCP. `ssp` is the WASM-ingest wall time (from `materializationSamples`);
576
- * the rest come from the per-phase rolling windows + one-shot registration timings.
577
- */
578
- phaseTimings(q: QueryState): QueryTimings {
579
- const stat = (phase: string) =>
580
- phaseStatOf(q.phaseSamples[phase] ?? [], q.phaseLast[phase] ?? null);
581
- return {
582
- ssp: phaseStatOf(q.materializationSamples, q.lastIngestLatencyMs),
583
- sspStoreApply: stat('sspStoreApply'),
584
- sspCircuitStep: stat('sspCircuitStep'),
585
- sspTransform: stat('sspTransform'),
586
- localFetch: stat('localFetch'),
587
- remoteFetch: stat('remoteFetch'),
588
- frontend: stat('frontend'),
589
- registration: q.registrationTimings,
590
- updateCount: q.updateCount,
591
- errorCount: q.errorCount,
592
- };
593
- }
594
-
595
- /**
596
- * Get query state (for sync and devtools)
597
- */
598
- getQueryByHash(hash: string): QueryState | undefined {
599
- return this.activeQueries.get(hash);
600
- }
601
-
602
- /**
603
- * Cold-query guard for instant-hydrate: true when the query exists, hasn't been
604
- * hydrated, and has NOT yet fetched its server result (`remoteArray` empty).
605
- * We gate on `remoteArray`, not local `records`: a windowed query is often
606
- * partially pre-seeded from the circuit (e.g. the dashboard's 5-row preview),
607
- * but it still hasn't loaded its own full window from the server — so it should
608
- * still hydrate. A warm re-subscribe (remoteArray already populated) is skipped.
609
- */
610
- isCold(hash: string): boolean {
611
- const qs = this.activeQueries.get(hash);
612
- return !!qs && !qs.hydrated && (qs.config.remoteArray?.length ?? 0) === 0;
613
- }
614
-
615
- /**
616
- * Walk a hydrated record's fields and append any EMBEDDED child records to
617
- * `batch` (recursing for nested related fields). An embedded child is a
618
- * value that is itself a record — a non-null object whose `id` is a
619
- * `RecordId` — or an array of such records (one-to-many vs one-to-one). A
620
- * bare `RecordId` (a foreign-key reference) or any other value is skipped,
621
- * so this never mistakes a FK column for an embedded body. Children are
622
- * keyed by their own `record.id.table`, versioned by `_00_rv`, and cleaned
623
- * to their table's real columns (which strips the alias/related fields).
624
- * `seen` dedupes within the batch.
625
- */
626
- private collectEmbeddedChildren(
627
- record: Record<string, any>,
628
- batch: CacheRecord[],
629
- seen: Set<string>
630
- ): void {
631
- const isEmbeddedRecord = (v: unknown): v is RecordWithId =>
632
- !!v &&
633
- typeof v === 'object' &&
634
- !(v instanceof RecordId) &&
635
- (v as { id?: unknown }).id instanceof RecordId;
636
-
637
- for (const value of Object.values(record)) {
638
- const children = Array.isArray(value)
639
- ? value.filter(isEmbeddedRecord)
640
- : isEmbeddedRecord(value)
641
- ? [value]
642
- : [];
643
- for (const child of children) {
644
- const key = encodeRecordId(child.id);
645
- if (seen.has(key)) continue;
646
- seen.add(key);
647
- // Recurse FIRST so nested grandchildren are captured before `cleanRecord`
648
- // strips this child's alias fields.
649
- this.collectEmbeddedChildren(child, batch, seen);
650
- const table = child.id.table.toString();
651
- const tableSchema = this.schema.tables.find((t) => t.name === table);
652
- batch.push({
653
- table,
654
- op: 'CREATE',
655
- record: (tableSchema
656
- ? cleanRecord(tableSchema.columns, child)
657
- : child) as RecordWithId,
658
- version: (child._00_rv as number) || 1,
659
- });
660
- }
661
- }
662
- }
663
-
664
- /**
665
- * Instant-hydrate: ingest rows fetched one-shot from the remote (the query's own
666
- * surql run directly) so the query DISPLAYS immediately, while the full realtime
667
- * registration proceeds in the background. Ingests with versions (`_00_rv`) so the
668
- * later `syncRecords` dedup skips re-pulling unchanged bodies, and seeds
669
- * `remoteArray` so windowed queries materialize the correct window (no sparse
670
- * local-circuit issue). Runs at most once per query (the `hydrated` flag).
671
- */
672
- async applyHydration(hash: string, rows: RecordWithId[]): Promise<void> {
673
- const queryState = this.activeQueries.get(hash);
674
- if (!queryState) return;
675
- queryState.hydrated = true; // run-once, even when the remote returns nothing
676
- if (rows.length === 0) return;
677
-
678
- const tableName = queryState.config.tableName;
679
- const batch: CacheRecord[] = rows.map((record) => ({
680
- table: tableName,
681
- op: 'CREATE' as const,
682
- record,
683
- version: (record._00_rv as number) || 1,
684
- }));
685
-
686
- // Flicker-free related data on cold first paint: a `.related()` query's
687
- // rows arrive with their child rows EMBEDDED (the correlated subquery,
688
- // e.g. `(SELECT * FROM comment WHERE game=$parent.id) AS comments`). The
689
- // primary batch above persists only the parent table, so the immediate
690
- // `materializeRecords` below would re-run the correlated surql against a
691
- // local DB with no child rows and overwrite the embedded result with
692
- // empties. Extract those embedded children (any nesting depth) and
693
- // persist them as their own records so the re-materialization finds them.
694
- const seen = new Set<string>(rows.map((r) => encodeRecordId(r.id)));
695
- for (const record of rows) {
696
- this.collectEmbeddedChildren(record, batch, seen);
697
- }
698
-
699
- await this.cache.saveBatch(batch);
700
-
701
- // Prime remoteArray from the hydrated id+version pairs: `materializeRecords`
702
- // prefers it for windowed queries (correct window) and it feeds the version
703
- // dedup. Registration later overwrites it with the authoritative `_00_list_ref`.
704
- queryState.config.remoteArray = rows.map(
705
- (r) => [encodeRecordId(r.id), (r._00_rv as number) || 1] as [string, number]
706
- );
707
-
708
- queryState.records = await this.materializeRecords(queryState);
709
- const subscribers = this.subscriptions.get(hash);
710
- if (subscribers) {
711
- for (const cb of subscribers) cb(queryState.records);
712
- }
713
- }
714
-
715
- /** True while ≥1 live subscriber is watching this query (refcount guard). */
716
- hasSubscribers(hash: string): boolean {
717
- return (this.subscriptions.get(hash)?.size ?? 0) > 0;
718
- }
719
-
720
- /**
721
- * Opt-in eager teardown for a query whose LAST subscriber just left — used by
722
- * viewport-windowed lists to cancel off-screen windows instead of leaving
723
- * their remote views to expire on the TTL sweep. No-op while any subscriber
724
- * remains (refcount). Only enqueues the remote cleanup here; the local WASM
725
- * view + in-memory state are freed in {@link finalizeDeregister} after the
726
- * remote delete completes, so a re-subscribe in between aborts/heals it.
727
- *
728
- * NOTE: most queries should NOT use this — the default keep-alive on
729
- * unsubscribe avoids re-registration churn on navigation.
730
- */
731
- deregisterQuery(hash: string): void {
732
- if (this.hasSubscribers(hash)) return;
733
- if (!this.activeQueries.has(hash)) return;
734
- this.onDeregister?.(hash);
735
- }
736
-
737
- /**
738
- * Final local teardown after the remote `_00_query` row was deleted: free the
739
- * WASM view, heartbeat timer, debounce timer, and in-memory state. Caller
740
- * (`cleanupQuery`) guarantees no subscriber remains.
741
- */
742
- finalizeDeregister(hash: string): void {
743
- const qs = this.activeQueries.get(hash);
744
- if (qs?.ttlTimer) {
745
- clearTimeout(qs.ttlTimer);
746
- qs.ttlTimer = null;
747
- }
748
- const debounce = this.debounceTimers.get(hash);
749
- if (debounce) {
750
- clearTimeout(debounce);
751
- this.debounceTimers.delete(hash);
752
- }
753
- this.cache.unregisterQuery(hash);
754
- this.activeQueries.delete(hash);
755
- this.subscriptions.delete(hash);
756
- }
757
-
758
- /**
759
- * Get query state by id (for sync and devtools)
760
- */
761
- getQueryById(id: RecordId<string>): QueryState | undefined {
762
- return this.activeQueries.get(extractIdPart(id));
763
- }
764
-
765
- /**
766
- * Get all active queries (for devtools)
767
- */
768
- getActiveQueries(): QueryState[] {
769
- return Array.from(this.activeQueries.values());
770
- }
771
-
772
- getActiveQueryHashes(): QueryHash[] {
773
- return Array.from(this.activeQueries.keys());
774
- }
775
-
776
- async updateQueryLocalArray(id: string, localArray: RecordVersionArray): Promise<void> {
777
- const queryState = this.activeQueries.get(id);
778
- if (!queryState) {
779
- this.logger.warn(
780
- { id, Category: 'sp00ky-client::DataModule::updateQueryLocalArray' },
781
- 'Query to update local array not found'
782
- );
783
- return;
784
- }
785
- queryState.config.localArray = localArray;
786
- await this.local.query(surql.seal(surql.updateSet('id', ['localArray'])), {
787
- id: queryState.config.id,
788
- localArray,
789
- });
790
- }
791
-
792
- async updateQueryRemoteArray(hash: string, remoteArray: RecordVersionArray): Promise<void> {
793
- const queryState = this.getQueryByHash(hash);
794
- if (!queryState) {
795
- this.logger.warn(
796
- { hash, Category: 'sp00ky-client::DataModule::updateQueryRemoteArray' },
797
- 'Query to update remote array not found'
798
- );
799
- return;
800
- }
801
- queryState.config.remoteArray = remoteArray;
802
- await this.local.query(surql.seal(surql.updateSet('id', ['remoteArray'])), {
803
- id: queryState.config.id,
804
- remoteArray,
805
- });
806
- }
807
-
808
- /**
809
- * Called after a query's initial sync completes.
810
- * Ensures subscribers are notified even if no stream updates fired (e.g. empty result set).
811
- */
812
- async notifyQuerySynced(queryHash: string): Promise<void> {
813
- const queryState = this.activeQueries.get(queryHash);
814
- if (!queryState) return;
815
-
816
- // Re-query local DB for latest data (windowed queries materialize from the
817
- // list_ref window so they resolve even if the in-browser SSP never emits —
818
- // it can't compute a high offset whose preceding rows aren't resident).
819
- const newRecords = await this.materializeRecords(queryState);
820
- const changed = JSON.stringify(queryState.records) !== JSON.stringify(newRecords);
821
- queryState.records = newRecords;
822
-
823
- // Notify if data changed OR if this is the first sync (updateCount === 0)
824
- // The latter handles "query truly has no results" so UI can stop loading
825
- if (changed || queryState.updateCount === 0) {
826
- queryState.updateCount++;
827
- const subscribers = this.subscriptions.get(queryHash);
828
- if (subscribers) {
829
- for (const callback of subscribers) {
830
- callback(queryState.records);
831
- }
832
- }
833
- }
834
- }
835
-
836
- // ==================== RUN JOBS ====================
837
-
838
- async run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(
839
- backend: B,
840
- path: R,
841
- data: RoutePayload<S, B, R>,
842
- options?: RunOptions
843
- ): Promise<void> {
844
- const route = this.schema.backends?.[backend]?.routes?.[path];
845
- if (!route) {
846
- throw new Error(`Route ${backend}.${path} not found`);
847
- }
848
-
849
- const tableName = this.schema.backends?.[backend]?.outboxTable;
850
- if (!tableName) {
851
- throw new Error(`Outbox table for backend ${backend} not found`);
852
- }
853
-
854
- const payload: Record<string, unknown> = {};
855
- for (const argName of Object.keys(route.args)) {
856
- const arg = route.args[argName];
857
- if ((data as Record<string, unknown>)[argName] === undefined && arg.optional === false) {
858
- throw new Error(`Missing required argument ${argName}`);
859
- }
860
- payload[argName] = (data as Record<string, unknown>)[argName];
861
- }
862
-
863
- const record: Record<string, unknown> = {
864
- path,
865
- payload: JSON.stringify(payload),
866
- max_retries: options?.max_retries ?? 3,
867
- retry_strategy: options?.retry_strategy ?? 'linear',
868
- };
869
-
870
- if (options?.timeout != null) {
871
- record.timeout = options.timeout;
872
- }
873
-
874
- if (options?.delay != null) {
875
- record.delay = options.delay;
876
- }
877
-
878
- if (options?.assignedTo) {
879
- record.assigned_to = options.assignedTo;
880
- }
881
-
882
- const recordId = `${tableName}:${generateId()}`;
883
- await this.create(recordId, record);
884
- }
885
-
886
- // ==================== MUTATION MANAGEMENT ====================
887
-
888
- /**
889
- * Create a new record
890
- */
891
- async create<T extends Record<string, unknown>>(id: string, data: T): Promise<T> {
892
- const tableName = extractTablePart(id);
893
- const tableSchema = this.schema.tables.find((t) => t.name === tableName);
894
- if (!tableSchema) {
895
- throw new Error(`Table ${tableName} not found`);
896
- }
897
-
898
- const rid = parseRecordIdString(id);
899
- const params = parseParams(tableSchema.columns, data);
900
- const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
901
-
902
- const dataKeys = Object.keys(params).map((key) => ({ key, variable: `data_${key}` }));
903
- const prefixedParams = Object.fromEntries(
904
- dataKeys.map(({ key, variable }) => [variable, params[key]])
905
- );
906
- const query = surql.seal<T>(
907
- surql.tx([
908
- surql.createSet('id', dataKeys),
909
- surql.createMutation('create', 'mid', 'id', 'data'),
910
- ]),
911
- { resultIndex: 0 }
912
- );
913
-
914
- const target = await withRetry(this.logger, () =>
915
- this.local.execute(query, {
916
- id: rid,
917
- mid: mutationId,
918
- ...prefixedParams,
919
- })
920
- );
921
-
922
- const parsedRecord = parseParams(tableSchema.columns, target) as RecordWithId;
923
-
924
- // Save to cache (which handles DBSP ingestion)
925
- await this.cache.save(
926
- {
927
- table: tableName,
928
- op: 'CREATE',
929
- record: parsedRecord,
930
- version: 1,
931
- },
932
- true
933
- );
934
-
935
- // Emit mutation event for sync
936
- const mutationEvent: CreateEvent = {
937
- type: 'create',
938
- mutation_id: mutationId,
939
- record_id: rid,
940
- data: params,
941
- record: target,
942
- tableName,
943
- };
944
-
945
- for (const callback of this.mutationCallbacks) {
946
- callback([mutationEvent]);
947
- }
948
-
949
- this.logger.debug({ id, Category: 'sp00ky-client::DataModule::create' }, 'Record created');
950
-
951
- return target;
952
- }
953
-
954
- /**
955
- * Update an existing record
956
- */
957
- async update<T extends Record<string, unknown>>(
958
- table: string,
959
- id: string,
960
- data: Partial<T>,
961
- options?: UpdateOptions
962
- ): Promise<T> {
963
- const tableName = extractTablePart(id);
964
- const tableSchema = this.schema.tables.find((t) => t.name === tableName);
965
- if (!tableSchema) {
966
- throw new Error(`Table ${tableName} not found`);
967
- }
968
-
969
- const rid = parseRecordIdString(id);
970
- const params = parseParams(tableSchema.columns, data);
971
- const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
972
-
973
- // Note: CRDT state is pushed directly to the _00_crdt table by CrdtField.pushToRemote(),
974
- // NOT through the record update pipeline. This keeps the record data clean.
975
-
976
- // Capture current record state before mutation for rollback support
977
- const [beforeRecord] = await withRetry(this.logger, () =>
978
- this.local.query<[Record<string, any>]>('SELECT * FROM ONLY $id', { id: rid })
979
- );
980
-
981
- const query = surql.seal<{ target: T }>(
982
- surql.tx([
983
- surql.updateSet('id', [{ statement: '_00_rv += 1' }]),
984
- surql.let('updated', surql.updateMerge('id', 'data')),
985
- surql.createMutation('update', 'mid', 'id', 'data'),
986
- surql.returnObject([{ key: 'target', variable: 'updated' }]),
987
- ])
988
- );
989
-
990
- const { target } = await withRetry(this.logger, () =>
991
- this.local.execute(query, {
992
- id: rid,
993
- mid: mutationId,
994
- data: params,
995
- })
996
- );
997
-
998
- // Build a partial record with only the fields the user actually changed
999
- // This avoids overwriting rich relation objects (e.g. author: {id, name, ...})
1000
- // with flat RecordIds from the UPDATE...MERGE result
1001
- const updatedFields: Record<string, any> = { id: target.id };
1002
- for (const key of Object.keys(data)) {
1003
- if (key in target) {
1004
- updatedFields[key] = (target as Record<string, any>)[key];
1005
- }
1006
- }
1007
- if ('_00_rv' in (target as Record<string, any>)) {
1008
- updatedFields._00_rv = (target as Record<string, any>)._00_rv;
1009
- }
1010
- this.replaceRecordInQueries(updatedFields);
1011
-
1012
- const parsedRecord = parseParams(tableSchema.columns, target) as RecordWithId;
1013
-
1014
- // Save to cache
1015
- await this.cache.save(
1016
- {
1017
- table: table,
1018
- op: 'UPDATE',
1019
- record: parsedRecord,
1020
- version: target._00_rv as number,
1021
- },
1022
- true
1023
- );
1024
-
1025
- const pushEventOptions = parseUpdateOptions(id, data, options);
1026
-
1027
- // Emit mutation event
1028
- const mutationEvent: UpdateEvent = {
1029
- type: 'update',
1030
- mutation_id: mutationId,
1031
- record_id: rid,
1032
- data: params,
1033
- record: target,
1034
- beforeRecord: beforeRecord || undefined,
1035
- options: pushEventOptions,
1036
- };
1037
-
1038
- for (const callback of this.mutationCallbacks) {
1039
- callback([mutationEvent]);
1040
- }
1041
-
1042
- this.logger.debug({ id, Category: 'sp00ky-client::DataModule::update' }, 'Record updated');
1043
-
1044
- return target;
1045
- }
1046
-
1047
- /**
1048
- * Delete a record
1049
- */
1050
- async delete(table: string, id: string): Promise<void> {
1051
- const tableName = extractTablePart(id);
1052
- const tableSchema = this.schema.tables.find((t) => t.name === tableName);
1053
- if (!tableSchema) {
1054
- throw new Error(`Table ${tableName} not found`);
1055
- }
1056
-
1057
- const rid = parseRecordIdString(id);
1058
- const mutationId = parseRecordIdString(`_00_pending_mutations:${Date.now()}`);
1059
-
1060
- // Fetch the record before deleting so DBSP can match it against query predicates
1061
- const [beforeRecords] = await this.local.query<[Record<string, any>[]]>(
1062
- 'SELECT * FROM ONLY $id',
1063
- { id: rid }
1064
- );
1065
- const beforeRecord = beforeRecords ?? {};
1066
-
1067
- const query = surql.seal<void>(
1068
- surql.tx([surql.delete('id'), surql.createMutation('delete', 'mid', 'id')])
1069
- );
1070
-
1071
- await withRetry(this.logger, () => this.local.execute(query, { id: rid, mid: mutationId }));
1072
-
1073
- // The local DELETE has now committed. Everything below must reflect that in
1074
- // active live queries — so the deleted row disappears optimistically without
1075
- // a reload — even if the optimistic SSP-view ingest below fails. Previously a
1076
- // throw from `cache.delete` (the WASM ingest) aborted `delete()` after the
1077
- // commit, so the manual notify loop never ran and the row lingered on screen
1078
- // until reload. Ingesting the delete into the in-browser SSP view is
1079
- // best-effort: the manual re-materialize reads the local DB (which already
1080
- // excludes the row), so the result is correct regardless.
1081
- try {
1082
- await this.cache.delete(table, id, true, beforeRecord);
1083
- } catch (err) {
1084
- this.logger.error(
1085
- { err, id, Category: 'sp00ky-client::DataModule::delete' },
1086
- 'SSP delete-ingest failed; relying on query re-materialize to reflect the delete'
1087
- );
1088
- }
1089
-
1090
- // DBSP may not emit view updates for DELETE ops — manually notify all queries
1091
- // that reference this table. Each is isolated so one failing re-materialize
1092
- // can't stop the others (or the sync emit below) from running.
1093
- for (const [queryHash, queryState] of this.activeQueries) {
1094
- if (queryState.config.tableName === tableName) {
1095
- try {
1096
- await this.notifyQuerySynced(queryHash);
1097
- } catch (err) {
1098
- this.logger.error(
1099
- { err, queryHash, Category: 'sp00ky-client::DataModule::delete' },
1100
- 'notifyQuerySynced failed after delete'
1101
- );
1102
- }
1103
- }
1104
- }
1105
-
1106
- // Emit mutation event
1107
- const mutationEvent: DeleteEvent = {
1108
- type: 'delete',
1109
- mutation_id: mutationId,
1110
- record_id: rid,
1111
- };
1112
-
1113
- for (const callback of this.mutationCallbacks) {
1114
- callback([mutationEvent]);
1115
- }
1116
-
1117
- this.logger.debug({ id, Category: 'sp00ky-client::DataModule::delete' }, 'Record deleted');
1118
- }
1119
-
1120
- // ==================== ROLLBACK METHODS ====================
1121
-
1122
- /**
1123
- * Rollback a failed optimistic create by deleting the record locally
1124
- */
1125
- async rollbackCreate(recordId: RecordId, tableName: string): Promise<void> {
1126
- const id = encodeRecordId(recordId);
1127
-
1128
- try {
1129
- await withRetry(this.logger, () =>
1130
- this.local.query('DELETE $id', { id: recordId })
1131
- );
1132
- await this.cache.delete(tableName, id, true);
1133
- this.removeRecordFromQueries(recordId);
1134
-
1135
- this.logger.info(
1136
- { id, tableName, Category: 'sp00ky-client::DataModule::rollbackCreate' },
1137
- 'Rolled back optimistic create'
1138
- );
1139
- } catch (err) {
1140
- this.logger.error(
1141
- { err, id, tableName, Category: 'sp00ky-client::DataModule::rollbackCreate' },
1142
- 'Failed to rollback create'
1143
- );
1144
- }
1145
- }
1146
-
1147
- /**
1148
- * Rollback a failed optimistic update by restoring the previous record state
1149
- */
1150
- async rollbackUpdate(
1151
- recordId: RecordId,
1152
- tableName: string,
1153
- beforeRecord: Record<string, unknown>
1154
- ): Promise<void> {
1155
- const id = encodeRecordId(recordId);
1156
-
1157
- try {
1158
- const { id: _recordId, ...content } = beforeRecord;
1159
- await withRetry(this.logger, () =>
1160
- this.local.query(surql.seal(surql.upsert('id', 'content')), {
1161
- id: recordId,
1162
- content,
1163
- })
1164
- );
1165
-
1166
- const tableSchema = this.schema.tables.find((t) => t.name === tableName);
1167
- const parsedRecord = tableSchema
1168
- ? (parseParams(tableSchema.columns, beforeRecord) as RecordWithId)
1169
- : (beforeRecord as RecordWithId);
1170
-
1171
- await this.cache.save(
1172
- {
1173
- table: tableName,
1174
- op: 'UPDATE',
1175
- record: parsedRecord,
1176
- version: (beforeRecord._00_rv as number) || 1,
1177
- },
1178
- true
1179
- );
1180
-
1181
- // Replace in active queries for immediate UI update
1182
- await this.replaceRecordInQueries(beforeRecord);
1183
-
1184
- this.logger.info(
1185
- { id, tableName, Category: 'sp00ky-client::DataModule::rollbackUpdate' },
1186
- 'Rolled back optimistic update'
1187
- );
1188
- } catch (err) {
1189
- this.logger.error(
1190
- { err, id, tableName, Category: 'sp00ky-client::DataModule::rollbackUpdate' },
1191
- 'Failed to rollback update'
1192
- );
1193
- }
1194
- }
1195
-
1196
- /**
1197
- * Remove a record from all active query states and notify subscribers
1198
- */
1199
- private removeRecordFromQueries(recordId: RecordId): void {
1200
- const encodedId = encodeRecordId(recordId);
1201
-
1202
- for (const [queryHash, queryState] of this.activeQueries.entries()) {
1203
- const index = queryState.records.findIndex((r) => {
1204
- const rId = r.id instanceof RecordId ? encodeRecordId(r.id) : String(r.id);
1205
- return rId === encodedId;
1206
- });
1207
-
1208
- if (index !== -1) {
1209
- queryState.records.splice(index, 1);
1210
- const subscribers = this.subscriptions.get(queryHash);
1211
- if (subscribers) {
1212
- for (const callback of subscribers) {
1213
- callback(queryState.records);
1214
- }
1215
- }
1216
- }
1217
- }
1218
- }
1219
-
1220
- // ==================== PRIVATE HELPERS ====================
1221
-
1222
- private async createAndRegisterQuery<T extends TableNames<S>>(
1223
- hash: QueryHash,
1224
- recordId: RecordId,
1225
- surqlString: string,
1226
- params: Record<string, any>,
1227
- ttl: QueryTimeToLive,
1228
- tableName: T
1229
- ): Promise<QueryHash> {
1230
- const queryState = await this.createNewQuery<T>({
1231
- recordId,
1232
- surql: surqlString,
1233
- params,
1234
- ttl,
1235
- tableName,
1236
- });
1237
-
1238
- const t0 = performance.now();
1239
- const { localArray, registrationTimings } = this.cache.registerQuery({
1240
- queryHash: hash,
1241
- surql: surqlString,
1242
- params,
1243
- ttl: new Duration(ttl),
1244
- lastActiveAt: new Date(),
1245
- });
1246
- const registrationTime = performance.now() - t0;
1247
-
1248
- // Record the one-shot SSP registration timings (parse/plan/snapshot from the
1249
- // WASM binding) + the register_view wall time for DevTools.
1250
- queryState.registrationTimings = {
1251
- parseMs: registrationTimings?.parseMs ?? null,
1252
- planMs: registrationTimings?.planMs ?? null,
1253
- snapshotMs: registrationTimings?.snapshotMs ?? null,
1254
- wallMs: registrationTime,
1255
- };
1256
-
1257
- await withRetry(this.logger, () =>
1258
- this.local.query(
1259
- surql.seal(surql.updateSet('id', ['localArray', 'registrationTime', 'rowCount'])),
1260
- {
1261
- id: recordId,
1262
- localArray,
1263
- registrationTime,
1264
- rowCount: localArray.length,
1265
- }
1266
- )
1267
- );
1268
-
1269
- // Windowed (`START n`) queries skipped the raw initial load in
1270
- // createNewQuery (O(offset) + wrong rows for sparse windows). Seed the
1271
- // initial rows now from the SSP's window id-set (`localArray`) via the same
1272
- // window-materialization path the stream updates use — O(window), and the
1273
- // ids are already the correct window — so the first paint isn't empty while
1274
- // the remote `_00_list_ref` syncs in.
1275
- const windowMat = buildWindowMaterialization(surqlString);
1276
- if (windowMat && localArray.length > 0) {
1277
- try {
1278
- const winIds = localArray.map(([id]) => parseRecordIdString(id));
1279
- const [seeded] = await this.local.query<[Record<string, any>[]]>(windowMat.query, {
1280
- ...params,
1281
- __win: winIds,
1282
- });
1283
- queryState.records = seeded || [];
1284
- } catch (err) {
1285
- this.logger.warn(
1286
- { err, hash, Category: 'sp00ky-client::DataModule::createAndRegisterQuery' },
1287
- 'Failed to seed windowed initial records from localArray'
1288
- );
1289
- }
1290
- }
1291
-
1292
- this.activeQueries.set(hash, queryState);
1293
- this.startTTLHeartbeat(queryState, hash);
1294
- this.logger.debug(
1295
- {
1296
- hash,
1297
- tableName,
1298
- recordCount: queryState.records.length,
1299
- Category: 'sp00ky-client::DataModule::query',
1300
- },
1301
- 'Query registered'
1302
- );
1303
-
1304
- return hash;
1305
- }
1306
-
1307
- private async createNewQuery<T extends TableNames<S>>({
1308
- recordId,
1309
- surql: surqlString,
1310
- params,
1311
- ttl,
1312
- tableName,
1313
- }: {
1314
- recordId: RecordId;
1315
- surql: string;
1316
- params: Record<string, any>;
1317
- ttl: QueryTimeToLive;
1318
- tableName: T;
1319
- }): Promise<QueryState> {
1320
- const tableSchema = this.schema.tables.find((t) => t.name === tableName);
1321
- if (!tableSchema) {
1322
- throw new Error(`Table ${tableName} not found`);
1323
- }
1324
-
1325
- let [configRecord] = await withRetry(this.logger, () =>
1326
- this.local.query<[QueryConfigRecord]>('SELECT * FROM ONLY $id', {
1327
- id: recordId,
1328
- })
1329
- );
1330
-
1331
- if (!configRecord) {
1332
- const [createdRecord] = await withRetry(this.logger, () =>
1333
- this.local.query<[QueryConfigRecord]>(surql.seal(surql.create('id', 'data')), {
1334
- id: recordId,
1335
- data: {
1336
- surql: surqlString,
1337
- params: params,
1338
- localArray: [],
1339
- remoteArray: [],
1340
- lastActiveAt: new Date(),
1341
- createdAt: new Date(),
1342
- ttl,
1343
- tableName,
1344
- updateCount: 0,
1345
- rowCount: 0,
1346
- errorCount: 0,
1347
- },
1348
- })
1349
- );
1350
- configRecord = createdRecord;
1351
- }
1352
-
1353
- const config: QueryConfig = {
1354
- ...configRecord,
1355
- id: recordId,
1356
- params: parseParams(tableSchema.columns, configRecord.params),
1357
- };
1358
-
1359
- let records: Record<string, any>[] = [];
1360
- // Windowed (`START n`) queries: do NOT seed from the raw surql here. Running
1361
- // `… LIMIT n START m` against the shared local store is O(m) — it sorts and
1362
- // skips m rows on every window open — AND returns the wrong rows for sparse
1363
- // windows (the reason `buildWindowMaterialization` exists). Those windows are
1364
- // seeded from the SSP `localArray` in `createAndRegisterQuery` instead.
1365
- if (buildWindowMaterialization(surqlString) === null) {
1366
- try {
1367
- const [result] = await this.local.query<[Record<string, any>[]]>(surqlString, params);
1368
- records = result || [];
1369
- } catch (err) {
1370
- this.logger.warn(
1371
- { err, Category: 'sp00ky-client::DataModule::createNewQuery' },
1372
- 'Failed to load initial cached records'
1373
- );
1374
- }
1375
- }
1376
-
1377
- // Persisted counters survive a restart even though the rolling
1378
- // sample window is rebuilt from scratch in memory.
1379
- const persistedUpdateCount =
1380
- typeof (configRecord as any)?.updateCount === 'number'
1381
- ? (configRecord as any).updateCount
1382
- : 0;
1383
- const persistedErrorCount =
1384
- typeof (configRecord as any)?.errorCount === 'number'
1385
- ? (configRecord as any).errorCount
1386
- : 0;
1387
-
1388
- return {
1389
- config,
1390
- records,
1391
- ttlTimer: null,
1392
- ttlDurationMs: parseDuration(ttl),
1393
- updateCount: persistedUpdateCount,
1394
- materializationSamples: [],
1395
- lastIngestLatencyMs: null,
1396
- errorCount: persistedErrorCount,
1397
- status: 'idle',
1398
- phaseSamples: {},
1399
- phaseLast: {},
1400
- registrationTimings: { parseMs: null, planMs: null, snapshotMs: null, wallMs: null },
1401
- };
1402
- }
1403
-
1404
- private async calculateHash(data: any): Promise<string> {
1405
- // sessionId is part of the hash so the same logical query from two
1406
- // sessions (e.g. two browser tabs of the same user) lands on different
1407
- // `_00_query` rows and doesn't fight over a shared one.
1408
- const content = JSON.stringify({ ...data, sessionId: this.sessionId });
1409
- const msgBuffer = new TextEncoder().encode(content);
1410
- const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
1411
- const hashArray = Array.from(new Uint8Array(hashBuffer));
1412
- return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
1413
- }
1414
-
1415
- private startTTLHeartbeat(queryState: QueryState, hash: QueryHash): void {
1416
- if (queryState.ttlTimer) return;
1417
-
1418
- const heartbeatTime = Math.floor(queryState.ttlDurationMs * 0.9);
1419
-
1420
- queryState.ttlTimer = setTimeout(() => {
1421
- queryState.ttlTimer = null;
1422
- // Only keep the remote query alive while something is actually watching
1423
- // it. With the server now sweeping ALL expired views (not just in-circuit
1424
- // ones), an un-refreshed query WOULD be swept after its TTL — so a live
1425
- // subscriber must heartbeat. An abandoned query (no subscribers) is left
1426
- // to expire and get swept; its local view was already torn down at the
1427
- // last unsubscribe, so we just stop the timer here.
1428
- const subscriberCount = this.subscriptions.get(hash)?.size ?? 0;
1429
- if (subscriberCount === 0) {
1430
- this.logger.debug(
1431
- { hash, Category: 'sp00ky-client::DataModule::startTTLHeartbeat' },
1432
- 'TTL heartbeat: no subscribers, stopping'
1433
- );
1434
- return;
1435
- }
1436
- this.onHeartbeat?.(hash);
1437
- this.logger.debug(
1438
- {
1439
- hash,
1440
- id: encodeRecordId(queryState.config.id),
1441
- Category: 'sp00ky-client::DataModule::startTTLHeartbeat',
1442
- },
1443
- 'TTL heartbeat sent'
1444
- );
1445
- this.startTTLHeartbeat(queryState, hash);
1446
- }, heartbeatTime);
1447
- }
1448
-
1449
- private async replaceRecordInQueries(record: Record<string, any>): Promise<void> {
1450
- for (const [queryHash, queryState] of this.activeQueries.entries()) {
1451
- const index = queryState.records.findIndex((r) => r.id === record.id);
1452
- if (index !== -1) {
1453
- queryState.records[index] = { ...queryState.records[index], ...record };
1454
- // Notify subscribers so UI updates immediately
1455
- const subscribers = this.subscriptions.get(queryHash);
1456
- if (subscribers) {
1457
- for (const callback of subscribers) {
1458
- callback(queryState.records);
1459
- }
1460
- }
1461
- }
1462
- }
1463
- }
1464
- }
1465
-
1466
- // ==================== HELPER FUNCTIONS ====================
1467
-
1468
- /**
1469
- * Parse update options to generate push event options
1470
- */
1471
- export function parseUpdateOptions(
1472
- id: string,
1473
- data: any,
1474
- options?: UpdateOptions
1475
- ): PushEventOptions {
1476
- let pushEventOptions: PushEventOptions = {};
1477
- if (options?.debounced) {
1478
- const delay = options.debounced !== true ? (options.debounced?.delay ?? 200) : 200;
1479
- const keyType = options.debounced !== true ? (options.debounced?.key ?? id) : id;
1480
- const key =
1481
- keyType === 'recordId_x_fields' ? `${id}::${Object.keys(data).toSorted().join('#')}` : id;
1482
-
1483
- pushEventOptions = {
1484
- debounced: {
1485
- delay,
1486
- key,
1487
- },
1488
- };
1489
- }
1490
- return pushEventOptions;
1491
- }