@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,1244 +0,0 @@
1
- import type { LocalDatabaseService, RemoteDatabaseService } from '../../services/database/index';
2
- import type { RecordVersionArray, RecordVersionDiff, SyncHealth, SyncHealthStatus } from '../../types';
3
- import { createSyncEventSystem, SyncEventTypes, SyncQueueEventTypes } from './events/index';
4
- import type { Logger } from '../../services/logger/index';
5
- import type { DownEvent, UpEvent} from './queue/index';
6
- import { DownQueue, UpQueue } from './queue/index';
7
- import type { RecordId, Uuid } from 'surrealdb';
8
- import {
9
- ArraySyncer,
10
- buildListRefSelect,
11
- buildSubqueryListRefSelect,
12
- createDiffFromDbOp,
13
- diffRecordVersionArray,
14
- listRefPollDelayMs,
15
- recordVersionArraysEqual,
16
- resolveListRefPollInterval,
17
- } from './utils';
18
- import { SyncEngine } from './engine';
19
- import { SyncScheduler } from './scheduler';
20
- import type { SchemaStructure } from '@spooky-sync/query-builder';
21
- import type { CacheModule } from '../cache/index';
22
- import type { DataModule } from '../data/index';
23
- import { classifySyncError, encodeRecordId, extractIdPart, extractTablePart, surql } from '../../utils/index';
24
- import { ANON_USER_ID, DEFAULT_REF_MODE, listRefTableFor, RefMode } from '../ref-tables';
25
-
26
- /**
27
- * Tunables for `Sp00kySync` construction.
28
- */
29
- export interface Sp00kySyncOptions {
30
- /**
31
- * Cadence (ms) for the `_00_list_ref` poll fallback that catches
32
- * cross-session UPDATEs the LIVE-permission gap drops. Non-positive
33
- * values fall back to the default; see
34
- * {@link resolveListRefPollInterval}.
35
- */
36
- refSyncIntervalMs?: number;
37
- /**
38
- * Enable realtime sync for unauthenticated clients against the shared
39
- * `_00_list_ref_anon` table. See {@link Sp00kyConfig.enableAnonymousLiveQueries}.
40
- * Defaults to `false`.
41
- */
42
- anonymousLiveQueries?: boolean;
43
- /**
44
- * Consecutive failed sync rounds before sync health flips to `degraded`.
45
- * `0` disables degraded reporting. See {@link Sp00kyConfig.syncHealth}.
46
- * Defaults to `3`.
47
- */
48
- degradeAfterConsecutiveFailures?: number;
49
- }
50
-
51
- /**
52
- * The main synchronization engine for Sp00ky.
53
- * Handles the bidirectional synchronization between the local database and the remote backend.
54
- * Uses a queue-based architecture with 'up' (local to remote) and 'down' (remote to local) queues.
55
- * @template S The schema structure type.
56
- */
57
- export class Sp00kySync<S extends SchemaStructure> {
58
- private upQueue: UpQueue;
59
- private downQueue: DownQueue;
60
- private isInit: boolean = false;
61
- private logger: Logger;
62
- private syncEngine: SyncEngine;
63
- /** Engine-level events (e.g. `SYNC_REMOTE_DATA_INGESTED`). Distinct
64
- * from `this.events`, which carries Sp00kySync-level events like
65
- * `SYNC_QUERY_UPDATED` and `SYNC_MUTATION_ROLLED_BACK`. */
66
- public get engineEvents() {
67
- return this.syncEngine.events;
68
- }
69
- private scheduler: SyncScheduler;
70
- private wasDisconnected: boolean = false;
71
- public events = createSyncEventSystem();
72
-
73
- // Auth identity that drives per-user `_00_list_ref_user_<id>` routing
74
- // in `RefMode.Dedicated`. Updated by `setCurrentUserId` from the auth
75
- // subscription in `Sp00kyClient`; null when unauthenticated.
76
- private currentUserId: string | null = null;
77
-
78
- private refMode: RefMode = DEFAULT_REF_MODE;
79
-
80
- // When true, an unauthenticated client still runs the `_00_list_ref` poll
81
- // and LIVE subscription, routed to the shared `_00_list_ref_anon` table, so
82
- // a logged-out page gets realtime `useQuery` updates. Off by default.
83
- private readonly anonLiveEnabled: boolean;
84
-
85
- // Bookkeeping for the LIVE subscription on `_00_list_ref[_user_*]`.
86
- // SurrealDB binds the permission context at LIVE-registration time and
87
- // the table name in dedicated mode depends on the authenticated user,
88
- // so we have to re-register whenever auth state flips.
89
- private currentLiveQueryUuid: Uuid | null = null;
90
- private liveQueryUnsubscribe: (() => void) | null = null;
91
-
92
- // Periodic re-poll of `_00_list_ref` as a safety net for missed LIVE
93
- // notifications. SurrealDB v3 occasionally drops LIVE deliveries
94
- // across sessions even when the row matches the permission rule;
95
- // this catches those without requiring users to reload. The
96
- // interval is configurable via the constructor; see
97
- // `resolveListRefPollInterval` for fallback semantics.
98
- //
99
- // Self-rescheduling rather than setInterval so each tick can pick
100
- // its own delay via `nextPollDelayMs` — slows the poll down when
101
- // LIVE is delivering events and speeds it back up when LIVE quiets.
102
- private listRefPollTimer: ReturnType<typeof setTimeout> | null = null;
103
- private listRefPollRunning: boolean = false;
104
- public readonly refSyncIntervalMs: number;
105
-
106
- // Consecutive poll cycles that observed NO list_ref change. Drives the
107
- // adaptive backoff in `startListRefPoll` via `listRefPollDelayMs`: an idle
108
- // page coasts from the fast base cadence toward the 5s cap, and any activity
109
- // (a poll-detected change or a LIVE event) resets it to 0 so the poll snaps
110
- // back to responsive. Replaces the old LIVE-liveness backoff, which kept the
111
- // poll pinned at 500ms forever whenever LIVE wasn't firing (the common case
112
- // on a quiet page, thanks to the cross-session LIVE-permission gap).
113
- private listRefIdleStreak: number = 0;
114
-
115
- // `${queryHash}:${recordId}` -> consecutive rounds the id has been "still
116
- // remote" (left the query's list_ref but still exists upstream). Used to
117
- // distinguish a PERSISTENT view-membership disagreement (the `job:` churn,
118
- // converged once it crosses the threshold) from a record that's merely
119
- // mid-deletion (still-remote for ~one round, then gone) — which must NOT be
120
- // converged, or it gets stranded in this window before its delete is observed.
121
- private stillRemoteStreaks: Map<string, number> = new Map();
122
-
123
- // Wall-clock timestamp (ms) of the most recent LIVE event delivered
124
- // through `handleRemoteListRefChange`. Kept as a diagnostic / liveness
125
- // signal; the poll cadence is now driven by `listRefIdleStreak`.
126
- private lastLiveEventAt: number | null = null;
127
-
128
- // Number of times the initial `_00_list_ref[_user_*]` LIVE subscription
129
- // had to retry on `setCurrentUserId`. Stays at 0 when the SSP has
130
- // pre-emptively created the user's dedicated tables; otherwise
131
- // increments on each retry attempt until LIVE succeeds or attempts
132
- // are exhausted. Surfaced as a diagnostic so the e2e suite can prove
133
- // the pre-emptive table-creation path is keeping the first sign-in
134
- // off the lazy-creation race.
135
- private _liveRetryCount: number = 0;
136
- public get liveRetryCount(): number {
137
- return this._liveRetryCount;
138
- }
139
-
140
- get isSyncing() {
141
- return this.scheduler.isSyncing;
142
- }
143
-
144
- get pendingMutationCount(): number {
145
- return this.upQueue.size;
146
- }
147
-
148
- subscribeToPendingMutations(cb: (count: number) => void): () => void {
149
- const id1 = this.upQueue.events.subscribe(
150
- SyncQueueEventTypes.MutationEnqueued,
151
- (event) => cb(event.payload.queueSize)
152
- );
153
- const id2 = this.upQueue.events.subscribe(
154
- SyncQueueEventTypes.MutationDequeued,
155
- (event) => cb(event.payload.queueSize)
156
- );
157
- return () => {
158
- this.upQueue.events.unsubscribe(id1);
159
- this.upQueue.events.unsubscribe(id2);
160
- };
161
- }
162
-
163
- // ---- Sync health -------------------------------------------------------
164
- // `0` disables degraded reporting (config `syncHealth: false`). Resolved
165
- // from config in Sp00kyClient and passed through the constructor options.
166
- private readonly degradeAfterFailures: number;
167
- private consecutiveSyncFailures = 0;
168
- private syncHealthStatus: SyncHealthStatus = 'healthy';
169
- private lastSyncErrorKind: 'network' | 'application' | undefined;
170
- private lastSyncErrorMessage: string | undefined;
171
-
172
- // Self-heal: while degraded, re-drive sync on an exponential backoff so the
173
- // app recovers on its own — even when the socket never actually dropped (in
174
- // that case no `connected` event fires, so this re-registration is the ONLY
175
- // thing that re-probes the server). Started on the degrade transition,
176
- // cleared on recovery. Capped cadence so a long outage doesn't busy-loop.
177
- private selfHealTimer: ReturnType<typeof setTimeout> | null = null;
178
- private selfHealAttempts = 0;
179
- private static readonly SELF_HEAL_BASE_MS = 2_000;
180
- private static readonly SELF_HEAL_MAX_MS = 30_000;
181
-
182
- /** Current sync-health snapshot. */
183
- get syncHealth(): SyncHealth {
184
- return {
185
- status: this.syncHealthStatus,
186
- consecutiveFailures: this.consecutiveSyncFailures,
187
- kind: this.syncHealthStatus === 'degraded' ? this.lastSyncErrorKind : undefined,
188
- error: this.syncHealthStatus === 'degraded' ? this.lastSyncErrorMessage : undefined,
189
- };
190
- }
191
-
192
- /**
193
- * Observe sync health. The callback fires immediately with the current
194
- * status and again on every healthy↔degraded transition. Returns an
195
- * unsubscribe. Mirrors {@link subscribeToPendingMutations}.
196
- */
197
- subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void {
198
- cb(this.syncHealth);
199
- const id = this.events.subscribe(SyncEventTypes.SyncHealthChanged, (event) =>
200
- cb(event.payload)
201
- );
202
- return () => this.events.unsubscribe(id);
203
- }
204
-
205
- private emitSyncHealth(): void {
206
- this.events.emit(SyncEventTypes.SyncHealthChanged, this.syncHealth);
207
- }
208
-
209
- /**
210
- * Fed by the scheduler once per drained sync round. Individual failures are
211
- * absorbed by the queue's retry; only a run of `degradeAfterFailures`
212
- * consecutive failures flips the status to `degraded`, and the next clean
213
- * round flips it back. No-op when reporting is disabled (`degradeAfterFailures`
214
- * is 0).
215
- */
216
- private recordSyncOutcome(ok: boolean, error?: unknown): void {
217
- if (this.degradeAfterFailures <= 0) return;
218
- if (ok) {
219
- if (this.consecutiveSyncFailures === 0) return;
220
- this.consecutiveSyncFailures = 0;
221
- if (this.syncHealthStatus !== 'healthy') {
222
- this.syncHealthStatus = 'healthy';
223
- this.lastSyncErrorKind = undefined;
224
- this.lastSyncErrorMessage = undefined;
225
- this.stopSelfHeal();
226
- this.logger.info(
227
- { Category: 'sp00ky-client::Sp00kySync::syncHealth' },
228
- 'Sync recovered; health back to healthy'
229
- );
230
- this.emitSyncHealth();
231
- }
232
- return;
233
- }
234
- this.consecutiveSyncFailures++;
235
- this.lastSyncErrorKind = classifySyncError(error);
236
- this.lastSyncErrorMessage = error instanceof Error ? error.message : String(error);
237
- if (
238
- this.syncHealthStatus !== 'degraded' &&
239
- this.consecutiveSyncFailures >= this.degradeAfterFailures
240
- ) {
241
- this.syncHealthStatus = 'degraded';
242
- this.logger.warn(
243
- {
244
- consecutiveFailures: this.consecutiveSyncFailures,
245
- kind: this.lastSyncErrorKind,
246
- error,
247
- Category: 'sp00ky-client::Sp00kySync::syncHealth',
248
- },
249
- 'Sync degraded after sustained failures'
250
- );
251
- this.emitSyncHealth();
252
- this.startSelfHeal();
253
- }
254
- }
255
-
256
- /**
257
- * Begin self-heal retries (no-op if already running). Started on the
258
- * healthy→degraded transition; {@link recordSyncOutcome} stops it on recovery.
259
- */
260
- private startSelfHeal(): void {
261
- if (this.selfHealTimer !== null) return;
262
- this.selfHealAttempts = 0;
263
- this.scheduleSelfHeal();
264
- }
265
-
266
- private scheduleSelfHeal(): void {
267
- const delay = Math.min(
268
- Sp00kySync.SELF_HEAL_MAX_MS,
269
- Sp00kySync.SELF_HEAL_BASE_MS * 2 ** this.selfHealAttempts
270
- );
271
- this.selfHealTimer = setTimeout(async () => {
272
- this.selfHealTimer = null;
273
- if (this.syncHealthStatus !== 'degraded') return;
274
- this.selfHealAttempts++;
275
- this.logger.debug(
276
- { attempt: this.selfHealAttempts, delayMs: delay, Category: 'sp00ky-client::Sp00kySync::selfHeal' },
277
- 'Self-heal: re-driving sync while degraded'
278
- );
279
- try {
280
- // Retry whatever is still queued first; the failing op (register or
281
- // mutation) was re-queued by the queue, so this re-probes the server
282
- // and reports the outcome through the scheduler → recordSyncOutcome.
283
- if (this.upQueue.size > 0) {
284
- await this.scheduler.syncUp();
285
- } else if (this.downQueue.size > 0) {
286
- await this.scheduler.syncDown();
287
- } else {
288
- // Nothing queued (e.g. the failing op was rolled back + dropped):
289
- // re-register active queries — mirroring the reconnect handler — so
290
- // there's a concrete op whose success flips health. If there are no
291
- // active queries either, probe connectivity directly.
292
- const hashes = this.dataModule.getActiveQueryHashes();
293
- if (hashes.length > 0) {
294
- for (const hash of hashes) {
295
- this.scheduler.enqueueDownEvent({ type: 'register', payload: { hash } });
296
- }
297
- await this.scheduler.syncDown();
298
- } else {
299
- await this.remote.query('RETURN true');
300
- this.recordSyncOutcome(true);
301
- }
302
- }
303
- } catch (err) {
304
- // Only the direct connectivity probe can throw here (syncUp/syncDown
305
- // swallow + self-report); treat a probe failure as another failed round.
306
- this.recordSyncOutcome(false, err);
307
- }
308
- // Keep retrying until recovery. recordSyncOutcome(true) calls stopSelfHeal
309
- // (clearing any pending timer), so only continue while still degraded.
310
- if (this.syncHealthStatus === 'degraded') this.scheduleSelfHeal();
311
- }, delay);
312
- }
313
-
314
- private stopSelfHeal(): void {
315
- if (this.selfHealTimer !== null) {
316
- clearTimeout(this.selfHealTimer);
317
- this.selfHealTimer = null;
318
- }
319
- this.selfHealAttempts = 0;
320
- }
321
-
322
- constructor(
323
- private local: LocalDatabaseService,
324
- private remote: RemoteDatabaseService,
325
- private cache: CacheModule,
326
- private dataModule: DataModule<S>,
327
- private schema: S,
328
- logger: Logger,
329
- options?: Sp00kySyncOptions
330
- ) {
331
- this.logger = logger.child({ service: 'Sp00kySync' });
332
- this.upQueue = new UpQueue(this.local, this.logger);
333
- this.downQueue = new DownQueue(this.local, this.logger);
334
- this.syncEngine = new SyncEngine(this.remote, this.cache, this.schema, this.logger);
335
- this.scheduler = new SyncScheduler(
336
- this.upQueue,
337
- this.downQueue,
338
- this.processUpEvent.bind(this),
339
- this.processDownEvent.bind(this),
340
- this.logger,
341
- this.handleRollback.bind(this),
342
- this.recordSyncOutcome.bind(this)
343
- );
344
- this.refSyncIntervalMs = resolveListRefPollInterval(options?.refSyncIntervalMs);
345
- this.anonLiveEnabled = options?.anonymousLiveQueries ?? false;
346
- this.degradeAfterFailures = Math.max(0, options?.degradeAfterConsecutiveFailures ?? 3);
347
- }
348
-
349
- /**
350
- * Initializes the synchronization system.
351
- * Starts the scheduler and initiates the initial sync cycles.
352
- * @throws Error if already initialized.
353
- */
354
- public async init() {
355
- if (this.isInit) throw new Error('Sp00kySync is already initialized');
356
- this.isInit = true;
357
- await this.scheduler.init();
358
- this.subscribeToReconnect();
359
- void this.scheduler.syncUp();
360
- void this.scheduler.syncDown();
361
- // No initial LIVE subscription — wait for `setCurrentUserId` to fire
362
- // from the auth subscription. In dedicated mode the table name
363
- // depends on the authenticated user, and an unauthenticated
364
- // subscription wouldn't match any of the per-user tables anyway.
365
- //
366
- // Exception: when anonymous live queries are enabled, start realtime now
367
- // against the shared `_00_list_ref_anon` table so a logged-out client
368
- // syncs immediately. `setCurrentUserId` re-points LIVE to the per-user
369
- // table on sign-in. Guard on `currentUserId` because the auth callback can
370
- // fire (and authenticate) before `init()` runs — don't clobber that back
371
- // to the anon table. `setCurrentUserId(null)` is a no-op on first load
372
- // (it's already null), so this is the only place anon realtime starts.
373
- if (this.anonLiveEnabled && !this.currentUserId) {
374
- this.startListRefPoll();
375
- this.restartRefLiveQuery().catch((err) => {
376
- this.logger.debug(
377
- { err, Category: 'sp00ky-client::Sp00kySync::init' },
378
- 'Anonymous ref LIVE start failed; relying on periodic poll fallback'
379
- );
380
- });
381
- }
382
- }
383
-
384
- /**
385
- * Push the authenticated user's record id from the parent client's
386
- * auth subscription. Tears down the existing `_00_list_ref` LIVE (if
387
- * any) and re-registers it under the new user's dedicated table so
388
- * SurrealDB binds the permission rule under the post-flip auth
389
- * context. Pass `null` on sign-out.
390
- *
391
- * The dedicated `_00_list_ref_user_<id>` table is created lazily by
392
- * the SSP when the first query registration arrives, which may be
393
- * concurrent with this call. We retry the LIVE registration with a
394
- * short backoff so a "table not found" race resolves without
395
- * surfacing as a permanent auth-loading hang.
396
- */
397
- public async setCurrentUserId(userId: string | null): Promise<void> {
398
- if (this.currentUserId === userId) return;
399
- this.currentUserId = userId;
400
- if (!userId) {
401
- if (this.anonLiveEnabled) {
402
- // Signed out but anonymous realtime is on: keep the poll running and
403
- // re-point LIVE from the (now stale) per-user table to the shared
404
- // `_00_list_ref_anon`. `startListRefPoll` is idempotent; the poll
405
- // re-resolves `listRefTable()` each tick so it follows automatically.
406
- this.startListRefPoll();
407
- await this.restartRefLiveQuery().catch((err) => {
408
- this.logger.debug(
409
- { err, Category: 'sp00ky-client::Sp00kySync::setCurrentUserId' },
410
- 'Anonymous ref LIVE restart failed; relying on periodic poll fallback'
411
- );
412
- });
413
- return;
414
- }
415
- await this.killRefLiveQuery();
416
- this.stopListRefPoll();
417
- return;
418
- }
419
- // Start periodic polling FIRST so we have a deterministic fallback
420
- // even when LIVE registration fails or SurrealDB drops a delivery.
421
- this.startListRefPoll();
422
- // Try to start LIVE with backoff for low-latency delivery on the
423
- // happy path; the poll handles the rest.
424
- const attemptDelays = [0, 250, 500, 1000, 2000];
425
- for (let i = 0; i < attemptDelays.length; i++) {
426
- if (attemptDelays[i] > 0) {
427
- this._liveRetryCount++;
428
- await new Promise((r) => setTimeout(r, attemptDelays[i]));
429
- }
430
- try {
431
- await this.restartRefLiveQuery();
432
- return;
433
- } catch (err) {
434
- this.logger.debug(
435
- { err, attempt: i + 1, Category: 'sp00ky-client::Sp00kySync::setCurrentUserId' },
436
- 'Ref LIVE start failed; relying on periodic poll fallback'
437
- );
438
- }
439
- }
440
- }
441
-
442
- private startListRefPoll(): void {
443
- if (this.listRefPollRunning) return;
444
- this.listRefPollRunning = true;
445
- this.logger.debug(
446
- {
447
- intervalMs: this.refSyncIntervalMs,
448
- Category: 'sp00ky-client::Sp00kySync::startListRefPoll',
449
- },
450
- 'list_ref poll loop started'
451
- );
452
- const schedule = (delayMs: number) => {
453
- this.listRefPollTimer = setTimeout(async () => {
454
- if (!this.listRefPollRunning) return;
455
- let changed = false;
456
- try {
457
- changed = await this.pollListRefForActiveQueries();
458
- } finally {
459
- if (!this.listRefPollRunning) return;
460
- // Reset the idle streak on any observed change so the poll snaps
461
- // back to the fast base cadence; otherwise grow it so a quiet page
462
- // backs off toward the cap. (`handleRemoteListRefChange` also resets
463
- // it when a LIVE event lands.)
464
- this.listRefIdleStreak = changed ? 0 : this.listRefIdleStreak + 1;
465
- const next = listRefPollDelayMs({
466
- idleStreak: this.listRefIdleStreak,
467
- baseIntervalMs: this.refSyncIntervalMs,
468
- });
469
- schedule(next);
470
- }
471
- }, delayMs);
472
- };
473
- schedule(this.refSyncIntervalMs);
474
- }
475
-
476
- private stopListRefPoll(): void {
477
- this.listRefPollRunning = false;
478
- if (this.listRefPollTimer !== null) {
479
- clearTimeout(this.listRefPollTimer);
480
- this.listRefPollTimer = null;
481
- }
482
- }
483
-
484
- /**
485
- * One poll cycle: refetch `_00_list_ref` for every active query. Returns
486
- * whether ANY query's remoteArray actually changed — the scheduler uses this
487
- * to drive the adaptive idle backoff.
488
- */
489
- private async pollListRefForActiveQueries(): Promise<boolean> {
490
- const hashes = this.dataModule.getActiveQueryHashes();
491
- if (hashes.length === 0) return false;
492
- let anyChanged = false;
493
- for (const hash of hashes) {
494
- try {
495
- if (await this.refetchListRefForQuery(hash)) anyChanged = true;
496
- } catch (err) {
497
- this.logger.debug(
498
- { err: (err as Error)?.message ?? err, hash, Category: 'sp00ky-client::Sp00kySync::pollListRefForActiveQueries' },
499
- 'Per-query list_ref poll failed'
500
- );
501
- }
502
- }
503
- return anyChanged;
504
- }
505
-
506
- /**
507
- * Pull the upstream list_ref entries for `queryHash`, diff them
508
- * against the local `remoteArray` cache, sync any added/updated rows
509
- * through the SyncEngine, then persist the new remoteArray. This is
510
- * the same shape `createRemoteQuery` does for its initial fetch and
511
- * what `handleRemoteListRefChange` does per-LIVE-event — we reuse
512
- * it on a timer as a fallback for missed LIVE notifications.
513
- */
514
- private async refetchListRefForQuery(queryHash: string): Promise<boolean> {
515
- const queryState = this.dataModule.getQueryByHash(queryHash);
516
- if (!queryState) return false;
517
- const listRefTbl = this.listRefTable();
518
- const [items] = await this.remote.query<[{ out: RecordId<string>; version: number }[]]>(
519
- buildListRefSelect(listRefTbl),
520
- { in: queryState.config.id }
521
- );
522
- if (!Array.isArray(items)) return false;
523
- const fresh: RecordVersionArray = items.map((item) => [
524
- encodeRecordId(item.out),
525
- item.version,
526
- ]);
527
- // Capture which ids LEFT the query's window (present in the cached
528
- // remoteArray, absent from `fresh`) BEFORE we overwrite remoteArray — these
529
- // are cross-window deletes (or rows that scrolled out). They drive the
530
- // forced re-render below.
531
- const prevRemote = queryState.config.remoteArray ?? [];
532
- const freshIds = new Set(fresh.map(([id]) => id));
533
- const removedIds = prevRemote.filter(([id]) => !freshIds.has(id)).map(([id]) => id);
534
- // Idempotent poll: only persist the remoteArray when it actually changed.
535
- // The poll runs continuously as a LIVE fallback, so on a quiet page `fresh`
536
- // equals the cached array every tick — re-writing it (an `UPDATE _00_query`
537
- // each cycle, per active query) was pure churn and the bulk of the idle
538
- // traffic. `recordVersionArraysEqual` is order-insensitive because the
539
- // list_ref SELECT has no `ORDER BY`.
540
- const changed = !recordVersionArraysEqual(fresh, queryState.config.remoteArray);
541
- if (changed) {
542
- // Update the cached remoteArray so the next diff/sync sees the new state.
543
- // `syncQuery` (below) then writes through `cache.saveBatch`, which UPSERTs
544
- // the local DB row and ingests it into the in-browser SSP — the SSP's
545
- // stream updates run `processStreamUpdate`, which re-queries the local DB
546
- // and notifies subscribers. We skip an explicit `notifyQuerySynced`
547
- // because that path races the stream-update path (can notify with stale
548
- // records).
549
- await this.dataModule.updateQueryRemoteArray(queryHash, fresh);
550
- }
551
- // Run `syncQuery` every tick regardless: it's a no-op when localArray has
552
- // caught up to remoteArray (`if (!diff) return`, issues no query), but it
553
- // covers the rare case where remoteArray is stable yet localArray is behind
554
- // (a prior record fetch failed) — so a missed row still gets retried.
555
- // For REMOVALS it runs the ids through `handleRemovedRecords`, which deletes
556
- // confirmed-gone records from the local DB.
557
- try {
558
- await this.syncQuery(queryHash);
559
- } catch (err) {
560
- this.logger.info(
561
- { err: (err as Error)?.message ?? err, queryHash, Category: 'sp00ky-client::Sp00kySync::refetchListRefForQuery' },
562
- 'syncQuery failed during poll'
563
- );
564
- }
565
- // Cross-session fallback for `.related()` child rows: the LIVE-permission
566
- // gap can drop child-edge notifications, so converge their bodies on the
567
- // poll too (idempotent — no-op when nothing changed).
568
- await this.syncSubqueryChildren(queryHash).catch((err) => {
569
- this.logger.info(
570
- { err: (err as Error)?.message ?? err, queryHash, Category: 'sp00ky-client::Sp00kySync::refetchListRefForQuery' },
571
- 'Subquery child sync failed during poll'
572
- );
573
- });
574
- // A REMOVAL needs no record fetch, so unlike the added-row path it doesn't
575
- // get a re-render from the SSP stream on this code path reliably (and the
576
- // non-windowed window-0 query re-queries the local DB rather than the id-set).
577
- // Force a re-materialize + notify so the deleted row drops from the list in
578
- // this (second) window — the reliable, LIVE-independent cross-window path.
579
- if (removedIds.length > 0) {
580
- try {
581
- await this.dataModule.notifyQuerySynced(queryHash);
582
- } catch (err) {
583
- this.logger.info(
584
- { err: (err as Error)?.message ?? err, queryHash, Category: 'sp00ky-client::Sp00kySync::refetchListRefForQuery' },
585
- 'notifyQuerySynced failed during poll-removal re-render'
586
- );
587
- }
588
- }
589
- return changed;
590
- }
591
-
592
- /**
593
- * Resolve the current `_00_list_ref` table name for the active auth
594
- * context. Public so the `createRemoteQuery` initial-fetch path can
595
- * read from the right per-user table.
596
- *
597
- * Reads the user id from `DataModule` rather than the local mirror,
598
- * because `DataModule.setCurrentUserId` runs synchronously from the
599
- * auth callback (before any `await`), whereas `sync.setCurrentUserId`
600
- * is async — the userQuery's initial fetch can fire between those
601
- * two points and we need the correct table name immediately.
602
- */
603
- public listRefTable(): string {
604
- const userId = this.dataModule.getCurrentUserId();
605
- // Unauthenticated with the flag on → the shared `_00_list_ref_anon` table.
606
- if (userId == null && this.anonLiveEnabled) {
607
- return listRefTableFor(this.refMode, ANON_USER_ID);
608
- }
609
- return listRefTableFor(this.refMode, userId);
610
- }
611
-
612
- private async killRefLiveQuery(): Promise<void> {
613
- if (this.liveQueryUnsubscribe) {
614
- try { this.liveQueryUnsubscribe(); } catch { /* ignore */ }
615
- this.liveQueryUnsubscribe = null;
616
- }
617
- if (this.currentLiveQueryUuid !== null) {
618
- try {
619
- await this.remote.query('KILL $u', { u: this.currentLiveQueryUuid });
620
- } catch (err) {
621
- this.logger.debug(
622
- { err, Category: 'sp00ky-client::Sp00kySync::killRefLiveQuery' },
623
- 'Prior LIVE KILL failed; continuing'
624
- );
625
- }
626
- this.currentLiveQueryUuid = null;
627
- }
628
- }
629
-
630
- private async restartRefLiveQuery(): Promise<void> {
631
- await this.killRefLiveQuery();
632
- await this.startRefLiveQueries();
633
- }
634
-
635
- // Only the connect that follows a prior disconnect counts as a
636
- // reconnect; the initial connect after init() must not trigger a
637
- // refetch storm.
638
- private subscribeToReconnect() {
639
- const client = this.remote.getClient();
640
- client.subscribe('disconnected', () => {
641
- this.wasDisconnected = true;
642
- this.logger.info(
643
- { Category: 'sp00ky-client::Sp00kySync::onDisconnect' },
644
- 'Remote disconnected'
645
- );
646
- });
647
- client.subscribe('connected', () => {
648
- if (!this.wasDisconnected) return;
649
- this.wasDisconnected = false;
650
- this.logger.info(
651
- { Category: 'sp00ky-client::Sp00kySync::onReconnect' },
652
- 'Remote reconnected, refetching active queries'
653
- );
654
- for (const hash of this.dataModule.getActiveQueryHashes()) {
655
- this.scheduler.enqueueDownEvent({ type: 'register', payload: { hash } });
656
- }
657
- // The WS reconnect leaves the server-side LIVE subscription dead — the
658
- // re-enqueued `register` events only re-fetch initial state, they don't
659
- // re-subscribe. Without this, LIVE never recovers after a reconnect and
660
- // the poll silently becomes the sole sync path (and never backs off).
661
- // Authenticated → per-user table; signed-out with anon live enabled →
662
- // the shared `_00_list_ref_anon`. Otherwise there's no table to re-bind.
663
- if (this.currentUserId || this.anonLiveEnabled) {
664
- this.restartRefLiveQuery().catch((err) => {
665
- this.logger.debug(
666
- { err, Category: 'sp00ky-client::Sp00kySync::onReconnect' },
667
- 'LIVE restart after reconnect failed; relying on poll fallback'
668
- );
669
- });
670
- }
671
- });
672
- }
673
-
674
- private async startRefLiveQueries() {
675
- const tableName = this.listRefTable();
676
- this.logger.debug(
677
- { tableName, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
678
- 'Starting ref live queries'
679
- );
680
-
681
- const [queryUuid] = await this.remote.query<[Uuid]>(
682
- `LIVE SELECT * FROM ${tableName}`
683
- );
684
- this.currentLiveQueryUuid = queryUuid;
685
-
686
- const live = await this.remote.getClient().liveOf(queryUuid);
687
- this.liveQueryUnsubscribe = live.subscribe((message) => {
688
- this.logger.debug(
689
- { message, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
690
- 'Live update received'
691
- );
692
- if (message.action === 'KILLED') return;
693
- // Subquery child edges (rows with `parent` set) are NOT primary window
694
- // rows — the client's `RecordVersionArray` only tracks primary rows, so
695
- // routing them through `handleRemoteListRefChange` would surface them as
696
- // spurious "added" diffs and pollute the window. Instead route them to
697
- // the dedicated child-body sync so `.related()` data stays realtime
698
- // cross-session (the LIVE-permission gap otherwise leaves it to the poll).
699
- if ((message.value as { parent?: unknown }).parent != null) {
700
- this.handleRemoteSubqueryChange(
701
- message.action,
702
- message.value.in as RecordId<string>,
703
- message.value.out as RecordId<string>,
704
- message.value.version as number
705
- ).catch((err) => {
706
- this.logger.error(
707
- { err, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
708
- 'Error handling remote subquery change'
709
- );
710
- });
711
- return;
712
- }
713
- this.handleRemoteListRefChange(
714
- message.action,
715
- message.value.in as RecordId<string>,
716
- message.value.out as RecordId<string>,
717
- message.value.version as number
718
- ).catch((err) => {
719
- this.logger.error(
720
- { err, Category: 'sp00ky-client::Sp00kySync::startRefLiveQueries' },
721
- 'Error handling remote list ref change'
722
- );
723
- });
724
- });
725
- }
726
-
727
- private async handleRemoteListRefChange(
728
- action: 'CREATE' | 'UPDATE' | 'DELETE',
729
- queryId: RecordId,
730
- recordId: RecordId,
731
- version: number
732
- ) {
733
- // Any LIVE delivery is evidence of activity — a CREATE/UPDATE/DELETE on a
734
- // query's window, or a notification for an unknown local query. Reset the
735
- // poll's idle streak so it snaps back to the fast base cadence (the page
736
- // is clearly not idle), and record the timestamp as a liveness diagnostic.
737
- this.lastLiveEventAt = Date.now();
738
- this.listRefIdleStreak = 0;
739
-
740
- // NOTE: DELETE is handled like CREATE/UPDATE below. When another window (or
741
- // this one) deletes a record, the server's SSP removes it from `_00_list_ref`
742
- // and the LIVE subscription delivers a DELETE here — `createDiffFromDbOp`
743
- // turns it into a `removed: [recordId]` diff so the row drops from the window
744
- // in realtime. (It was previously ignored, so other windows only caught up on
745
- // reload / the slow poll.)
746
- const existing = this.dataModule.getQueryById(queryId);
747
-
748
- if (!existing) {
749
- this.logger.warn(
750
- {
751
- queryId: queryId.toString(),
752
- Category: 'sp00ky-client::Sp00kySync::handleRemoteListRefChange',
753
- },
754
- 'Received remote update for unknown local query'
755
- );
756
- return;
757
- }
758
-
759
- const { localArray } = existing.config;
760
-
761
- this.logger.debug(
762
- {
763
- action,
764
- queryId,
765
- recordId,
766
- version,
767
- localArray,
768
- Category: 'sp00ky-client::Sp00kySync::handleRemoteListRefChange',
769
- },
770
- 'Live update is being processed'
771
- );
772
- const diff = createDiffFromDbOp(action, recordId, version, localArray);
773
- // `config.id` is `_00_query:<hash>`, so its id-part IS the query hash
774
- // (a SHA-256 over query content + sessionId) — the key DataModule uses.
775
- const hash = extractIdPart(existing.config.id);
776
- await this.runSyncForQuery(hash, diff);
777
- }
778
-
779
- /**
780
- * Handle a LIVE change to a SUBQUERY child edge (a `_00_list_ref` row with
781
- * `parent` set) for a `.related()` query. Unlike primary rows, child rows
782
- * must NOT touch the query's `localArray`/`remoteArray`/`rowCount`; we only
783
- * keep the child BODY fresh in the local cache so the in-browser SSP's
784
- * subquery-table dependency re-materializes the parent view.
785
- *
786
- * CREATE/UPDATE fetch+upsert the child body. DELETE is intentionally a
787
- * no-op: a child leaving this query's set must not delete a body another
788
- * query may still show (see `syncSubqueryChildren` deletion-safety note);
789
- * a genuine record delete propagates via the normal delete path.
790
- */
791
- private async handleRemoteSubqueryChange(
792
- action: 'CREATE' | 'UPDATE' | 'DELETE',
793
- queryId: RecordId,
794
- childId: RecordId,
795
- version: number
796
- ) {
797
- this.lastLiveEventAt = Date.now();
798
- this.listRefIdleStreak = 0;
799
-
800
- if (action === 'DELETE') return;
801
-
802
- const existing = this.dataModule.getQueryById(queryId);
803
- if (!existing) return;
804
-
805
- const item = { id: childId, version };
806
- await this.syncEngine.syncRecords(
807
- action === 'CREATE'
808
- ? { added: [item], updated: [], removed: [] }
809
- : { added: [], updated: [item], removed: [] }
810
- );
811
-
812
- // Keep the in-memory child array in step so the poll's idempotent diff
813
- // doesn't re-fetch this body on the next tick.
814
- const key = encodeRecordId(childId);
815
- const prev = existing.config.subqueryRemoteArray ?? [];
816
- existing.config.subqueryRemoteArray = [...prev.filter(([id]) => id !== key), [key, version]];
817
- }
818
-
819
- /**
820
- * Enqueues a 'down' event (from remote to local) for processing.
821
- * @param event The DownEvent to enqueue.
822
- */
823
- public enqueueDownEvent(event: DownEvent) {
824
- this.scheduler.enqueueDownEvent(event);
825
- }
826
-
827
- private async processUpEvent(event: UpEvent) {
828
- this.logger.debug(
829
- { event, Category: 'sp00ky-client::Sp00kySync::processUpEvent' },
830
- 'Processing up event'
831
- );
832
- switch (event.type) {
833
- case 'create': {
834
- const dataKeys = Object.keys(event.data).map((key) => ({ key, variable: `data_${key}` }));
835
- const prefixedParams = Object.fromEntries(
836
- dataKeys.map(({ key, variable }) => [variable, event.data[key]])
837
- );
838
- const query = surql.seal(surql.createSet('id', dataKeys));
839
- await this.remote.query(query, {
840
- id: event.record_id,
841
- ...prefixedParams,
842
- });
843
- break;
844
- }
845
- case 'update':
846
- await this.remote.query(`UPDATE $id MERGE $data`, {
847
- id: event.record_id,
848
- data: event.data,
849
- });
850
- break;
851
- case 'delete':
852
- await this.remote.query(`DELETE $id`, {
853
- id: event.record_id,
854
- });
855
- break;
856
- default:
857
- this.logger.error(
858
- { event, Category: 'sp00ky-client::Sp00kySync::processUpEvent' },
859
- 'processUpEvent unknown event type'
860
- );
861
- return;
862
- }
863
- }
864
-
865
- private async handleRollback(event: UpEvent, error: Error): Promise<void> {
866
- const recordId = encodeRecordId(event.record_id);
867
- const tableName =
868
- event.type === 'create' && event.tableName
869
- ? event.tableName
870
- : extractTablePart(recordId);
871
-
872
- this.logger.warn(
873
- {
874
- type: event.type,
875
- recordId,
876
- tableName,
877
- error: error.message,
878
- Category: 'sp00ky-client::Sp00kySync::handleRollback',
879
- },
880
- 'Rolling back failed mutation'
881
- );
882
-
883
- switch (event.type) {
884
- case 'create':
885
- await this.dataModule.rollbackCreate(event.record_id, tableName);
886
- break;
887
- case 'update':
888
- if (event.beforeRecord) {
889
- await this.dataModule.rollbackUpdate(event.record_id, tableName, event.beforeRecord);
890
- } else {
891
- this.logger.warn(
892
- {
893
- recordId,
894
- Category: 'sp00ky-client::Sp00kySync::handleRollback',
895
- },
896
- 'Cannot rollback update: no beforeRecord available. Down-sync will reconcile.'
897
- );
898
- }
899
- break;
900
- case 'delete':
901
- this.logger.warn(
902
- {
903
- recordId,
904
- Category: 'sp00ky-client::Sp00kySync::handleRollback',
905
- },
906
- 'Delete rollback not implemented. Down-sync will reconcile.'
907
- );
908
- break;
909
- }
910
-
911
- this.events.emit(SyncEventTypes.MutationRolledBack, {
912
- eventType: event.type,
913
- recordId,
914
- error: error.message,
915
- });
916
- }
917
-
918
- private async processDownEvent(event: DownEvent) {
919
- this.logger.debug(
920
- { event, Category: 'sp00ky-client::Sp00kySync::processDownEvent' },
921
- 'Processing down event'
922
- );
923
- switch (event.type) {
924
- case 'register':
925
- return this.registerQuery(event.payload.hash);
926
- case 'sync':
927
- return this.syncQuery(event.payload.hash);
928
- case 'heartbeat':
929
- return this.heartbeatQuery(event.payload.hash);
930
- case 'cleanup':
931
- return this.cleanupQuery(event.payload.hash);
932
- }
933
- }
934
-
935
- /**
936
- * Synchronizes a specific query by hash.
937
- * Compares local and remote version arrays and fetches differences.
938
- * @param hash The hash of the query to sync.
939
- */
940
- public async syncQuery(hash: string) {
941
- const queryState = this.dataModule.getQueryByHash(hash);
942
- if (!queryState) {
943
- this.logger.warn(
944
- { hash, Category: 'sp00ky-client::Sp00kySync::syncQuery' },
945
- 'Query not found'
946
- );
947
- return;
948
- }
949
-
950
- const diff = new ArraySyncer(
951
- queryState.config.localArray,
952
- queryState.config.remoteArray
953
- ).nextSet();
954
-
955
- if (!diff) {
956
- return;
957
- }
958
- return this.runSyncForQuery(hash, diff);
959
- }
960
-
961
- /**
962
- * Run a sync for a single query while reflecting its fetch status. Marks the
963
- * query `fetching` for the duration when the diff actually pulls records
964
- * (added/updated), then resets to `idle` in a `finally` so a failed sync
965
- * never leaves a query stuck `fetching`. Part A's notification coalescing
966
- * means the single resulting UI update lands after this completes.
967
- */
968
- private async runSyncForQuery(hash: string, diff: RecordVersionDiff): Promise<void> {
969
- // Don't let sync re-add a record the user just deleted locally. The remote
970
- // delete is queued in the outbox, so until it's processed the server's
971
- // `_00_list_ref` still lists the record — the diff then classifies it as
972
- // `added` (present remotely, absent locally) and `syncRecords` re-fetches +
973
- // re-inserts it, so a deleted database reappears a few seconds later. Drop
974
- // any id with a pending local DELETE from the re-add paths. Once the remote
975
- // delete lands, the pending row clears and the server drops it from
976
- // `_00_list_ref`, so this guard naturally stops applying.
977
- if (diff.added.length > 0 || diff.updated.length > 0) {
978
- const pendingDeletes = await this.getPendingDeleteIds();
979
- if (pendingDeletes.size > 0) {
980
- diff = {
981
- added: diff.added.filter((r) => !pendingDeletes.has(encodeRecordId(r.id))),
982
- updated: diff.updated.filter((r) => !pendingDeletes.has(encodeRecordId(r.id))),
983
- removed: diff.removed,
984
- };
985
- }
986
- }
987
-
988
- const fetching = diff.added.length + diff.updated.length > 0;
989
- if (fetching) {
990
- this.dataModule.setQueryStatus(hash, 'fetching');
991
- }
992
- try {
993
- const { remoteFetchMs, stillRemoteIds } = await this.syncEngine.syncRecords(diff);
994
- if (fetching) {
995
- this.dataModule.recordRemoteFetch(hash, remoteFetchMs);
996
- }
997
- // Converge localArray to the authoritative remoteArray for ids that left
998
- // the server's list_ref but still exist — a view-membership change, not a
999
- // delete — so the poll's diff stops re-flagging them every tick (the `job:`
1000
- // churn). CRUCIAL: only converge after the id has been still-remote for
1001
- // several CONSECUTIVE rounds. A record that's merely mid-deletion is
1002
- // still-remote for ~one round (its delete hasn't committed when our
1003
- // existence check races it) and is gone the next round → it never reaches
1004
- // the threshold, so it's deleted normally instead of being stranded here.
1005
- if (stillRemoteIds.length > 0) {
1006
- const CONVERGE_AFTER = 3;
1007
- const toConverge: string[] = [];
1008
- for (const id of stillRemoteIds) {
1009
- const key = `${hash}:${id}`;
1010
- const n = (this.stillRemoteStreaks.get(key) ?? 0) + 1;
1011
- if (n >= CONVERGE_AFTER) {
1012
- this.stillRemoteStreaks.delete(key);
1013
- toConverge.push(id);
1014
- } else {
1015
- this.stillRemoteStreaks.set(key, n);
1016
- }
1017
- }
1018
- if (toConverge.length > 0) {
1019
- const qs = this.dataModule.getQueryByHash(hash);
1020
- const local = qs?.config.localArray;
1021
- if (local && local.length > 0) {
1022
- const drop = new Set(toConverge);
1023
- const next = local.filter(([id]) => !drop.has(id));
1024
- if (next.length !== local.length) {
1025
- await this.dataModule.updateQueryLocalArray(hash, next);
1026
- }
1027
- }
1028
- }
1029
- }
1030
- } finally {
1031
- if (fetching) {
1032
- this.dataModule.setQueryStatus(hash, 'idle');
1033
- }
1034
- }
1035
- }
1036
-
1037
- /**
1038
- * Record ids with a pending local DELETE in the outbox (`_00_pending_mutations`).
1039
- * Sync must not re-fetch/re-insert these — the remote delete is async, so the
1040
- * server's `_00_list_ref` still lists them until it's processed, and the diff
1041
- * would otherwise resurrect a just-deleted record.
1042
- */
1043
- private async getPendingDeleteIds(): Promise<Set<string>> {
1044
- try {
1045
- const [rows] = await this.local.query<[{ recordId: RecordId<string> }[]]>(
1046
- "SELECT recordId FROM _00_pending_mutations WHERE mutationType = 'delete'"
1047
- );
1048
- return new Set((rows ?? []).map((r) => encodeRecordId(r.recordId)));
1049
- } catch (err) {
1050
- this.logger.warn(
1051
- { err, Category: 'sp00ky-client::Sp00kySync::getPendingDeleteIds' },
1052
- 'Failed to read pending deletes; sync may briefly resurrect a just-deleted record'
1053
- );
1054
- return new Set();
1055
- }
1056
- }
1057
-
1058
- /**
1059
- * Enqueues a list of mutations (up events) to be sent to the remote.
1060
- * @param mutations Array of UpEvents (create/update/delete) to enqueue.
1061
- */
1062
- public async enqueueMutation(mutations: UpEvent[]) {
1063
- this.scheduler.enqueueMutation(mutations);
1064
- }
1065
-
1066
- private async registerQuery(queryHash: string) {
1067
- try {
1068
- this.logger.debug(
1069
- { queryHash, Category: 'sp00ky-client::Sp00kySync::registerQuery' },
1070
- 'Register Query state'
1071
- );
1072
- await this.createRemoteQuery(queryHash);
1073
- await this.syncQuery(queryHash);
1074
- // Always notify after sync completes — handles empty result sets
1075
- // where no stream updates fire but the UI needs to stop loading
1076
- await this.dataModule.notifyQuerySynced(queryHash);
1077
- } catch (e) {
1078
- this.logger.error(
1079
- { err: e, Category: 'sp00ky-client::Sp00kySync::registerQuery' },
1080
- 'registerQuery error'
1081
- );
1082
- throw e;
1083
- }
1084
- }
1085
-
1086
- private async createRemoteQuery(queryHash: string) {
1087
- const queryState = this.dataModule.getQueryByHash(queryHash);
1088
-
1089
- if (!queryState) {
1090
- this.logger.warn(
1091
- { queryHash, Category: 'sp00ky-client::Sp00kySync::createRemoteQuery' },
1092
- 'Query to register not found'
1093
- );
1094
- throw new Error('Query to register not found');
1095
- }
1096
- // Delegate to remote function which handles DBSP registration & persistence.
1097
- // clientId is set server-side from session::id() — see fn::query::register.
1098
- await this.remote.query('fn::query::register($config)', {
1099
- config: {
1100
- id: queryState.config.id,
1101
- surql: queryState.config.surql,
1102
- params: queryState.config.params,
1103
- ttl: queryState.config.ttl,
1104
- },
1105
- });
1106
-
1107
- // Initial materialized-view fetch — pull from the same per-user
1108
- // `_00_list_ref_user_<id>` (or global `_00_list_ref` in single
1109
- // mode) that the LIVE subscription listens on, so the two stay in
1110
- // sync. `parent IS NONE` excludes subquery entries; the
1111
- // `localArray` cache only tracks primary records.
1112
- const listRefTbl = this.listRefTable();
1113
- const [items] = await this.remote.query<[{ out: RecordId<string>; version: number }[]]>(
1114
- buildListRefSelect(listRefTbl),
1115
- {
1116
- in: queryState.config.id,
1117
- }
1118
- );
1119
-
1120
- this.logger.trace(
1121
- {
1122
- queryId: encodeRecordId(queryState.config.id),
1123
- items,
1124
- Category: 'sp00ky-client::Sp00kySync::createRemoteQuery',
1125
- },
1126
- 'Got query record version array from remote'
1127
- );
1128
-
1129
- const array: RecordVersionArray = items.map((item) => [encodeRecordId(item.out), item.version]);
1130
-
1131
- this.logger.debug(
1132
- {
1133
- queryId: encodeRecordId(queryState.config.id),
1134
- array,
1135
- Category: 'sp00ky-client::Sp00kySync::createRemoteQuery',
1136
- },
1137
- 'createdRemoteQuery'
1138
- );
1139
-
1140
- if (array) {
1141
- /// Incantation existed already
1142
- await this.dataModule.updateQueryRemoteArray(queryHash, array);
1143
- }
1144
-
1145
- // Pull the bodies of any `.related()` subquery children into the local
1146
- // cache. The primary fetch above (`parent IS NONE`) tracks only window
1147
- // rows, so without this a cold-reload re-materialization of the
1148
- // correlated surql finds no child rows and related fields come back
1149
- // empty. Best-effort: never fail registration over it.
1150
- await this.syncSubqueryChildren(queryHash).catch((err) => {
1151
- this.logger.info(
1152
- { err: (err as Error)?.message ?? err, queryHash, Category: 'sp00ky-client::Sp00kySync::createRemoteQuery' },
1153
- 'Subquery child sync failed during registration; poll will retry'
1154
- );
1155
- });
1156
- }
1157
-
1158
- /**
1159
- * Sync the BODIES of a `.related()` query's subquery child rows into the
1160
- * local cache, separately from the primary window array. The SSP writes
1161
- * each matched child as a `_00_list_ref` edge tagged `parent`/`parent_rel`;
1162
- * `buildSubqueryListRefSelect` pulls those `out`+`version` pairs (any
1163
- * nesting depth). We diff against the in-memory `subqueryRemoteArray` and
1164
- * fetch added/updated bodies through the SyncEngine — which `saveBatch`s
1165
- * them into the local DB AND the in-browser SSP, whose subquery-table
1166
- * dependency then re-materializes the parent view (no explicit notify).
1167
- *
1168
- * Deletion safety: we pass `removed: []` deliberately. A child body can be
1169
- * shared by other queries; letting `handleRemovedRecords` delete one that
1170
- * merely left THIS query's child set would clobber data another query still
1171
- * shows. Genuine record deletes flow through the normal delete path; a
1172
- * lingering orphan body is invisible (the correlated WHERE stops matching).
1173
- *
1174
- * Kept off `runSyncForQuery` on purpose so child fetches never flip the
1175
- * query to `fetching` or skew its DevTools timings.
1176
- */
1177
- private async syncSubqueryChildren(queryHash: string): Promise<void> {
1178
- const queryState = this.dataModule.getQueryByHash(queryHash);
1179
- if (!queryState) return;
1180
-
1181
- const listRefTbl = this.listRefTable();
1182
- const [items] = await this.remote.query<[{ out: RecordId<string>; version: number }[]]>(
1183
- buildSubqueryListRefSelect(listRefTbl),
1184
- { in: queryState.config.id }
1185
- );
1186
- if (!Array.isArray(items)) return;
1187
-
1188
- const fresh: RecordVersionArray = items.map((item) => [encodeRecordId(item.out), item.version]);
1189
- const prev = queryState.config.subqueryRemoteArray ?? [];
1190
- if (recordVersionArraysEqual(fresh, prev)) return; // idempotent: nothing new
1191
-
1192
- const diff = diffRecordVersionArray(prev, fresh);
1193
- if (diff.added.length > 0 || diff.updated.length > 0) {
1194
- await this.syncEngine.syncRecords({
1195
- added: diff.added,
1196
- updated: diff.updated,
1197
- removed: [], // never delete child bodies here — see method doc
1198
- });
1199
- }
1200
- // In-memory only — child rows must never enter the persisted primary array.
1201
- queryState.config.subqueryRemoteArray = fresh;
1202
- }
1203
-
1204
- public async heartbeatQuery(queryHash: string) {
1205
- const queryState = this.dataModule.getQueryByHash(queryHash);
1206
- if (!queryState) {
1207
- this.logger.warn(
1208
- { queryHash, Category: 'sp00ky-client::Sp00kySync::heartbeatQuery' },
1209
- 'Query to register not found'
1210
- );
1211
- throw new Error('Query to register not found');
1212
- }
1213
- await this.remote.query('fn::query::heartbeat($id)', {
1214
- id: queryState.config.id,
1215
- });
1216
- }
1217
-
1218
- // Eager teardown of a deregistered query's remote `_00_query` view (opt-in,
1219
- // e.g. a viewport-windowed list cancelling an off-screen window). Query ids
1220
- // are a deterministic hash of (surql+params), so a DELETE racing a scroll-back
1221
- // re-register (same id) could nuke a freshly-recreated view — hence two
1222
- // guards: abort if a subscriber reappeared BEFORE the delete; re-register if
1223
- // one reappears DURING the delete's network await. Tolerant of a
1224
- // missing/already-gone query (no throw).
1225
- private async cleanupQuery(queryHash: string) {
1226
- const queryState = this.dataModule.getQueryByHash(queryHash);
1227
- if (!queryState) return; // already torn down / never registered
1228
-
1229
- // Re-subscribed before the queued cleanup ran → keep everything as-is.
1230
- if (this.dataModule.hasSubscribers(queryHash)) return;
1231
-
1232
- await this.remote.query(`DELETE $id`, { id: queryState.config.id });
1233
-
1234
- // Re-subscribed while we awaited the DELETE → the remote view is now gone
1235
- // but a subscriber needs it; recreate it instead of leaving a zombie.
1236
- if (this.dataModule.hasSubscribers(queryHash)) {
1237
- this.enqueueDownEvent({ type: 'register', payload: { hash: queryHash } });
1238
- return;
1239
- }
1240
-
1241
- // No subscribers throughout → safe to free the local view + state.
1242
- this.dataModule.finalizeDeregister(queryHash);
1243
- }
1244
- }