@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
@@ -9,13 +9,44 @@ import {
9
9
  DEFAULT_LIST_REF_POLL_INTERVAL_MS,
10
10
  buildListRefSelect,
11
11
  buildSubqueryListRefSelect,
12
+ buildListRefBatchSelect,
13
+ buildQueryRowCountBatchSelect,
14
+ planListRefPollChunks,
12
15
  nextPollDelayMs,
13
16
  listRefPollDelayMs,
14
17
  LIST_REF_POLL_MAX_INTERVAL_MS,
15
18
  recordVersionArraysEqual,
16
- } from './utils';
17
- import type { RecordVersionArray, RecordVersionDiff } from '../../types';
18
- import { encodeRecordId } from '../../utils/index';
19
+ } from './policy';
20
+ import type { RecordVersionArray, RecordVersionDiff } from '../types';
21
+ import { encodeRecordId } from '../utils/index';
22
+
23
+ describe('ArraySyncer.update', () => {
24
+ it('planListRefPollChunks keeps duplicate hashes with equal ages stable', () => {
25
+ const now = 1000;
26
+ const chunks = planListRefPollChunks(
27
+ [
28
+ { hash: 'x', rows: 1, lastPolledAt: 0 },
29
+ { hash: 'x', rows: 1, lastPolledAt: 0 },
30
+ { hash: 'a', rows: 1, lastPolledAt: 0 },
31
+ ],
32
+ { now }
33
+ );
34
+ expect(chunks).toEqual([['a', 'x', 'x']]);
35
+ });
36
+ it('nextPollDelayMs treats a future live event as no event', () => {
37
+ expect(nextPollDelayMs({ now: 100, lastLiveEventAt: 200, baseIntervalMs: 500 })).toBe(500);
38
+ });
39
+ it('bumps only the matching record and re-sorts on the next diff', () => {
40
+ const syncer = new ArraySyncer([['t:b', 1], ['t:a', 1]], [['t:a', 2], ['t:b', 1]]);
41
+ syncer.update('t:a', 2);
42
+ expect(syncer.nextSet()).toEqual({ added: [], updated: [], removed: [] });
43
+ syncer.insert('t:c', 1);
44
+ syncer.delete('t:b');
45
+ const diff = syncer.nextSet();
46
+ expect(diff!.added.map((a) => encodeRecordId(a.id))).toEqual(['t:b']);
47
+ expect(diff!.removed.map((r) => encodeRecordId(r))).toEqual(['t:c']);
48
+ });
49
+ });
19
50
 
20
51
  function rid(table: string, id: string): RecordId<string> {
21
52
  return new RecordId(table, id);
@@ -353,14 +384,18 @@ describe('resolveListRefPollInterval', () => {
353
384
 
354
385
  describe('buildListRefSelect', () => {
355
386
  it('substitutes the table name', () => {
356
- expect(buildListRefSelect('_00_list_ref')).toContain('FROM _00_list_ref ');
387
+ expect(buildListRefSelect('_00_list_ref')).toContain('->_00_list_ref ');
357
388
  expect(buildListRefSelect('_00_list_ref_user_abc')).toContain(
358
- 'FROM _00_list_ref_user_abc '
389
+ '->_00_list_ref_user_abc '
359
390
  );
360
391
  });
361
392
 
362
- it('filters by the bound query id', () => {
363
- expect(buildListRefSelect('_00_list_ref')).toContain('WHERE in = $in');
393
+ it('traverses from the bound query id instead of scanning the table', () => {
394
+ // `_00_list_ref*` has no index on `in`: `FROM table WHERE in = $in` is a
395
+ // full scan, which on the shared anon table is every visitor's edges.
396
+ const sql = buildListRefSelect('_00_list_ref');
397
+ expect(sql).toContain('FROM $in->_00_list_ref ');
398
+ expect(sql).not.toContain('in = $in');
364
399
  });
365
400
 
366
401
  it('excludes subquery rows via parent IS NONE', () => {
@@ -380,14 +415,14 @@ describe('buildListRefSelect', () => {
380
415
 
381
416
  describe('buildSubqueryListRefSelect', () => {
382
417
  it('substitutes the table name', () => {
383
- expect(buildSubqueryListRefSelect('_00_list_ref')).toContain('FROM _00_list_ref ');
418
+ expect(buildSubqueryListRefSelect('_00_list_ref')).toContain('->_00_list_ref ');
384
419
  expect(buildSubqueryListRefSelect('_00_list_ref_user_abc')).toContain(
385
- 'FROM _00_list_ref_user_abc '
420
+ '->_00_list_ref_user_abc '
386
421
  );
387
422
  });
388
423
 
389
- it('filters by the bound query id', () => {
390
- expect(buildSubqueryListRefSelect('_00_list_ref')).toContain('WHERE in = $in');
424
+ it('traverses from the bound query id', () => {
425
+ expect(buildSubqueryListRefSelect('_00_list_ref')).toContain('FROM $in->_00_list_ref ');
391
426
  });
392
427
 
393
428
  it('selects ONLY subquery child rows via parent IS NOT NONE', () => {
@@ -576,3 +611,53 @@ describe('recordVersionArraysEqual', () => {
576
611
  expect(recordVersionArraysEqual([], [])).toBe(true);
577
612
  });
578
613
  });
614
+
615
+ describe('list_ref poll batching', () => {
616
+ it('reads many queries in one statement and their rowCounts keyed by id', () => {
617
+ expect(buildListRefBatchSelect('_00_list_ref_user_abc')).toBe(
618
+ 'SELECT in, out, version, parent FROM $ins->_00_list_ref_user_abc'
619
+ );
620
+ expect(buildQueryRowCountBatchSelect()).toBe(
621
+ 'SELECT VALUE { id: id, rowCount: rowCount, state: state } FROM $ins'
622
+ );
623
+ });
624
+
625
+ it('packs due queries oldest-first under the row budget', () => {
626
+ const chunks = planListRefPollChunks(
627
+ [
628
+ { hash: 'a', rows: 600, lastPolledAt: 300 },
629
+ { hash: 'b', rows: 600, lastPolledAt: 100 },
630
+ { hash: 'c', rows: 0, lastPolledAt: 0 },
631
+ { hash: 'd', rows: 900, lastPolledAt: 200 },
632
+ ],
633
+ { now: 1_000, rowBudget: 1_400 }
634
+ );
635
+ // c (never polled) first, then b, d, a by age; d does not fit next to b.
636
+ expect(chunks).toEqual([['c', 'b'], ['d'], ['a']]);
637
+ });
638
+
639
+ it('never splits below one query and always refreshes a lone huge view', () => {
640
+ expect(
641
+ planListRefPollChunks([{ hash: 'big', rows: 10_000, lastPolledAt: 0 }], {
642
+ now: 100_000,
643
+ rowBudget: 100,
644
+ })
645
+ ).toEqual([['big']]);
646
+ });
647
+
648
+ it('defers large views until their minimum age has passed', () => {
649
+ const large = { hash: 'large', rows: 5_000, lastPolledAt: 990_000 };
650
+ const small = { hash: 'small', rows: 10, lastPolledAt: 990_000 };
651
+ expect(
652
+ planListRefPollChunks([large, small], { now: 1_000_000, largeViewRows: 1_000, largeViewMinAgeMs: 15_000 })
653
+ ).toEqual([['small']]);
654
+ expect(
655
+ planListRefPollChunks([large, small], { now: 1_006_000, largeViewRows: 1_000, largeViewMinAgeMs: 15_000 })
656
+ // Same age: hash order breaks the tie, and the large view fills its own chunk.
657
+ ).toEqual([['large'], ['small']]);
658
+ });
659
+
660
+ it('returns no chunks when nothing is due', () => {
661
+ expect(planListRefPollChunks([], { now: 1 })).toEqual([]);
662
+ });
663
+ });
@@ -1,6 +1,9 @@
1
1
  import type { RecordId } from 'surrealdb';
2
- import type { RecordVersionArray, RecordVersionDiff } from '../../types';
3
- import { parseRecordIdString, encodeRecordId } from '../../utils/index';
2
+ import type { RecordVersionArray, RecordVersionDiff } from '../types';
3
+ import { parseRecordIdString, encodeRecordId } from '../utils/index';
4
+ import type { SyncHealth } from '../types';
5
+ import { classifySyncError } from '../utils/error-classification';
6
+ import { SELF_HEAL_BASE_MS, SELF_HEAL_MAX_MS } from '../kernel/constants';
4
7
 
5
8
  export class ArraySyncer {
6
9
  private localArray: RecordVersionArray;
@@ -8,8 +11,8 @@ export class ArraySyncer {
8
11
  private needsSort = false;
9
12
 
10
13
  constructor(localArray: RecordVersionArray, remoteArray: RecordVersionArray) {
11
- this.remoteArray = remoteArray.toSorted((a, b) => a[0].localeCompare(b[0]));
12
- this.localArray = localArray.toSorted((a, b) => a[0].localeCompare(b[0]));
14
+ this.remoteArray = remoteArray.toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
15
+ this.localArray = localArray.toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
13
16
  }
14
17
 
15
18
  /**
@@ -128,7 +131,7 @@ export function applyRecordVersionDiff(
128
131
  currentMap.set(encodeRecordId(item.id), item.version);
129
132
  }
130
133
 
131
- return Array.from(currentMap).toSorted((a, b) => a[0].localeCompare(b[0]));
134
+ return Array.from(currentMap).toSorted((a: [string, number], b: [string, number]) => a[0].localeCompare(b[0]));
132
135
  }
133
136
 
134
137
  export function createDiffFromDbOp(
@@ -183,9 +186,45 @@ export const DEFAULT_LIST_REF_POLL_INTERVAL_MS = 500;
183
186
  * because the client's `RecordVersionArray` only tracks primary rows;
184
187
  * including subquery rows would surface them as spurious "added"
185
188
  * diffs every tick.
189
+ *
190
+ * Read through the graph (`$in->table`), not `FROM table WHERE in = $in`:
191
+ * the edge tables have no index on `in`, so the WHERE form is a full table
192
+ * scan. On a per-user table that is one user's edges; on the shared
193
+ * `_00_list_ref_anon` it is every signed-out visitor's, on every poll of
194
+ * every anonymous client. The traversal walks only this view's edge keys
195
+ * (`GraphEdgeScan` on SurrealDB v3) and the edge table's select permission
196
+ * still applies to each row it returns. Edges are written with `RELATE`, so
197
+ * the graph keys always exist.
186
198
  */
187
199
  export function buildListRefSelect(table: string): string {
188
- return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NONE`;
200
+ return `SELECT out, version FROM $in->${table} WHERE parent IS NONE`;
201
+ }
202
+
203
+ /**
204
+ * Build the select that says whether an EMPTY id-set means "this query has no
205
+ * rows" or "the server has not published them yet".
206
+ *
207
+ * The SSP writes `rowCount` onto the `_00_query` row in the same statement that
208
+ * registers the view — synchronously, and BEFORE it hands the view's initial
209
+ * edges to the coalescing edge flusher. So the two are not interchangeable:
210
+ * `rowCount > 0` with no edges is the flush window, and only `rowCount === 0`
211
+ * is a genuinely empty query. Polling the edges alone cannot tell those apart
212
+ * no matter how long it waits, which is why this is read alongside them rather
213
+ * than a retry counter.
214
+ *
215
+ * `state` rides along: the SSP writes `materializing` when it hands a full
216
+ * publish to its edge flusher and flips it to `ready` INSIDE the transaction
217
+ * that writes the edges. So `ready` + no edges + `rowCount 0` is a real empty
218
+ * result, `materializing` + no edges is "still publishing", and a missing row
219
+ * (the whole object is `NONE`) is "the server no longer has this view". A
220
+ * server that predates the marker returns `state: NONE` and callers fall back
221
+ * to `rowCount` alone.
222
+ *
223
+ * Returns `NONE` (→ null) when the row is not readable or does not exist yet;
224
+ * callers must treat that as "unknown", not as zero.
225
+ */
226
+ export function buildQueryRowCountSelect(): string {
227
+ return 'SELECT VALUE { rowCount: rowCount, state: state } FROM ONLY $in';
189
228
  }
190
229
 
191
230
  /**
@@ -201,7 +240,88 @@ export function buildListRefSelect(table: string): string {
201
240
  * store SEPARATELY from the primary window array.
202
241
  */
203
242
  export function buildSubqueryListRefSelect(table: string): string {
204
- return `SELECT out, version FROM ${table} WHERE in = $in AND parent IS NOT NONE`;
243
+ return `SELECT out, version FROM $in->${table} WHERE parent IS NOT NONE`;
244
+ }
245
+
246
+ /**
247
+ * One round trip for the edges of MANY queries: primary and subquery rows
248
+ * together, split client-side on `parent`. Replaces two selects per query per
249
+ * poll tick, which on a page with 20+ live queries was ~50 serialized round
250
+ * trips per cycle and kept the remote busy full-time.
251
+ *
252
+ * Traverses from every id in `$ins` (see {@link buildListRefSelect}); the
253
+ * result is one flat list of edge rows, and `in` names the query each belongs
254
+ * to.
255
+ */
256
+ export function buildListRefBatchSelect(table: string): string {
257
+ return `SELECT in, out, version, parent FROM $ins->${table}`;
258
+ }
259
+
260
+ /**
261
+ * `rowCount` for many `_00_query` rows at once, keyed by id so the caller does
262
+ * not depend on the array order. Same semantics as
263
+ * {@link buildQueryRowCountSelect}: a row the session cannot read comes back
264
+ * without an id and must be treated as "unknown".
265
+ */
266
+ export function buildQueryRowCountBatchSelect(): string {
267
+ return 'SELECT VALUE { id: id, rowCount: rowCount, state: state } FROM $ins';
268
+ }
269
+
270
+ /** Known edges one poll round trip may carry before the cycle is split. */
271
+ export const LIST_REF_POLL_ROW_BUDGET = 1_500;
272
+ /** A view at or past this many edges is "large": it rides on LIVE and is only
273
+ * re-polled every {@link LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS}. */
274
+ export const LIST_REF_POLL_LARGE_VIEW_ROWS = 1_000;
275
+ export const LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS = 15_000;
276
+
277
+ export interface ListRefPollCandidate {
278
+ hash: string;
279
+ /** Edges the client currently holds for the query (`remoteArray.length`). */
280
+ rows: number;
281
+ /** When the query was last refreshed by the poll; `0` = never. */
282
+ lastPolledAt: number;
283
+ }
284
+
285
+ /**
286
+ * Split the active queries into the round trips of one poll cycle.
287
+ *
288
+ * Every query that is due is refreshed once per cycle, oldest refresh first,
289
+ * packed greedily into chunks of at most `rowBudget` known edges so one
290
+ * response never carries a whole page's worth of ids at once. A view with
291
+ * `largeViewRows` or more edges is only due once `largeViewMinAgeMs` has
292
+ * passed since its last refresh (LIVE remains its primary path); a chunk
293
+ * always holds at least one query, so a single huge view still refreshes.
294
+ */
295
+ export function planListRefPollChunks(
296
+ candidates: ListRefPollCandidate[],
297
+ opts: { now: number; rowBudget?: number; largeViewRows?: number; largeViewMinAgeMs?: number }
298
+ ): string[][] {
299
+ const {
300
+ now,
301
+ rowBudget = LIST_REF_POLL_ROW_BUDGET,
302
+ largeViewRows = LIST_REF_POLL_LARGE_VIEW_ROWS,
303
+ largeViewMinAgeMs = LIST_REF_POLL_LARGE_VIEW_MIN_AGE_MS,
304
+ } = opts;
305
+ const due = candidates
306
+ .filter((c) => c.rows < largeViewRows || now - c.lastPolledAt >= largeViewMinAgeMs)
307
+ .sort(
308
+ (a, b) => a.lastPolledAt - b.lastPolledAt || (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0)
309
+ );
310
+ const chunks: string[][] = [];
311
+ let current: string[] = [];
312
+ let currentRows = 0;
313
+ for (const c of due) {
314
+ const cost = Math.max(1, c.rows);
315
+ if (current.length > 0 && currentRows + cost > rowBudget) {
316
+ chunks.push(current);
317
+ current = [];
318
+ currentRows = 0;
319
+ }
320
+ current.push(c.hash);
321
+ currentRows += cost;
322
+ }
323
+ if (current.length > 0) chunks.push(current);
324
+ return chunks;
205
325
  }
206
326
 
207
327
  /**
@@ -334,3 +454,62 @@ export function recordVersionArraysEqual(
334
454
  }
335
455
  return true;
336
456
  }
457
+
458
+ // ---- health ------------------------------------------------------------------
459
+
460
+
461
+ export interface HealthInput {
462
+ health: SyncHealth;
463
+ consecutiveFailures: number;
464
+ hasSyncedOnce: boolean;
465
+ }
466
+
467
+ export interface HealthOutput extends HealthInput {
468
+ /** Crossed into degraded on this outcome: start self-heal. */
469
+ degradedNow: boolean;
470
+ /** Left degraded on this outcome: stop self-heal. */
471
+ recoveredNow: boolean;
472
+ }
473
+
474
+ /**
475
+ * Fold one sync round's outcome into health. A single failure is absorbed;
476
+ * `degradeAfter` consecutive ones flip to degraded, the next success flips
477
+ * back. `degradeAfter <= 0` disables reporting.
478
+ */
479
+ export function nextHealth(input: HealthInput, ok: boolean, error: unknown, degradeAfter: number): HealthOutput {
480
+ const base = { ...input, degradedNow: false, recoveredNow: false };
481
+ if (degradeAfter <= 0) return base;
482
+ if (ok) {
483
+ const everConnected = true;
484
+ if (input.consecutiveFailures === 0) {
485
+ return { ...base, hasSyncedOnce: true, health: { ...input.health, everConnected } };
486
+ }
487
+ const recovered = input.health.status === 'degraded';
488
+ return {
489
+ ...base,
490
+ hasSyncedOnce: true,
491
+ consecutiveFailures: 0,
492
+ health: { ...input.health, status: 'healthy', kind: undefined, error: undefined, everConnected },
493
+ recoveredNow: recovered,
494
+ };
495
+ }
496
+ const consecutiveFailures = input.consecutiveFailures + 1;
497
+ const kind = classifySyncError(error);
498
+ const message = error instanceof Error ? error.message : String(error);
499
+ if (input.health.status !== 'degraded' && consecutiveFailures >= degradeAfter) {
500
+ return {
501
+ ...base,
502
+ consecutiveFailures,
503
+ health: { ...input.health, status: 'degraded', consecutiveFailures, kind, error: message },
504
+ degradedNow: true,
505
+ };
506
+ }
507
+ return {
508
+ ...base,
509
+ consecutiveFailures,
510
+ health: { ...input.health, consecutiveFailures, kind, error: message },
511
+ };
512
+ }
513
+
514
+ export const selfHealDelayMs = (attempt: number): number =>
515
+ Math.min(SELF_HEAL_MAX_MS, SELF_HEAL_BASE_MS * 2 ** Math.min(attempt, 30));
@@ -0,0 +1,51 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
3
+ import { runPure } from '../testing/run-pure';
4
+ import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
5
+ import * as R from '../state/reducers';
6
+ import { defaultEnv } from '../query/env';
7
+ import { pollTick } from './poll.saga';
8
+
9
+ const env = defaultEnv({ tables: [] } as any);
10
+ const ok = (result: unknown) => ({ status: 'OK', result });
11
+
12
+ describe('pollTick', () => {
13
+ it('with no queries: probes connectivity, backs off while idle', async () => {
14
+ const out = await runPure(pollTick(env), { state: R.patchSync({ pollIdleStreak: 2 })(buildState()), handlers: { 'remote.query': () => [ok(true)] } });
15
+ expect(out.dispatched).toEqual([{ type: 'SyncOutcome', ok: true }]);
16
+ expect(out.state.sync.pollIdleStreak).toBe(3);
17
+ expect(out.timers.get('poll')).toEqual({ ms: 4000, event: { type: 'PollTick' } });
18
+ const failed = await runPure(pollTick(env), {
19
+ state: buildState(),
20
+ handlers: {
21
+ 'remote.query': () => {
22
+ throw new Error('offline');
23
+ },
24
+ },
25
+ });
26
+ expect(failed.dispatched).toEqual([{ type: 'SyncOutcome', ok: false, error: new Error('offline') }]);
27
+ });
28
+ it('with queries: reads membership; a change or an acked write resets the streak', async () => {
29
+ const entry = buildEntry({ def: { hash: 'a', id: new RecordId('_00_query', 'a') }, lifecycle: { phase: 'live' }, serverState: 'ready' });
30
+ const changed = await runPure(pollTick(env), {
31
+ state: R.patchSync({ pollIdleStreak: 5 })(buildState([entry])),
32
+ handlers: {
33
+ 'remote.query': () => [ok([{ out: new RecordId('thing', '1'), version: 1 }]), ok({ rowCount: 1, state: 'ready' }), ok([])],
34
+ 'local.upsert': () => undefined,
35
+ },
36
+ });
37
+ expect(changed.state.sync.pollIdleStreak).toBe(0);
38
+ expect(changed.timers.get('poll')!.ms).toBe(500);
39
+ const quiet = await runPure(pollTick(env), {
40
+ state: R.patchSync({ pollIdleStreak: 1 })(buildState([entry])),
41
+ handlers: { 'remote.query': () => [ok([]), ok({ rowCount: 0, state: 'ready' }), ok([])], 'local.upsert': () => undefined },
42
+ });
43
+ expect(quiet.state.sync.pollIdleStreak).toBe(2);
44
+ expect(quiet.timers.get('poll')!.ms).toBe(2000);
45
+ const acked = await runPure(pollTick(env), {
46
+ state: buildState([entry], R.patchSync({ pollIdleStreak: 4 }), R.outboxReplace([buildOutboxItem({ status: 'acked', ackedAt: 1 })])),
47
+ handlers: { 'remote.query': () => [ok([]), ok({ rowCount: 0, state: 'ready' }), ok([])], 'local.upsert': () => undefined },
48
+ });
49
+ expect(acked.state.sync.pollIdleStreak).toBe(0);
50
+ });
51
+ });
@@ -0,0 +1,36 @@
1
+ import type { Saga } from '../kernel/saga';
2
+ import { fx } from '../kernel/effects';
3
+ import * as R from '../state/reducers';
4
+ import { activeHashes, hasAckedWrites } from '../state/selectors';
5
+ import type { SagaEnv } from '../query/env';
6
+ import { readMembership } from '../query/membership.saga';
7
+ import { listRefPollDelayMs } from './policy';
8
+
9
+ /**
10
+ * The `_00_list_ref` poll: the safety net under LIVE. Reads every active
11
+ * query's membership on a backoff that snaps to the base cadence whenever
12
+ * something changed (or an acked write still waits for membership) and
13
+ * coasts up to the cap while quiet. With no queries it probes connectivity.
14
+ */
15
+ export function* pollTick(env: SagaEnv): Saga<void> {
16
+ const [hashes, streak, acked] = (yield fx.state.read((s) => [activeHashes(s), s.sync.pollIdleStreak, hasAckedWrites(s)])) as [
17
+ string[],
18
+ number,
19
+ boolean,
20
+ ];
21
+ let changed = false;
22
+ if (hashes.length === 0) {
23
+ try {
24
+ yield fx.remote.query('RETURN true', undefined, env.remoteTimeoutMs);
25
+ yield fx.dispatch({ type: 'SyncOutcome', ok: true });
26
+ } catch (error) {
27
+ yield fx.dispatch({ type: 'SyncOutcome', ok: false, error });
28
+ }
29
+ } else {
30
+ const result = yield* readMembership(env, hashes);
31
+ changed = result.changed;
32
+ }
33
+ const idleStreak = changed || acked ? 0 : streak + 1;
34
+ yield fx.state.update(R.patchSync({ pollIdleStreak: idleStreak }));
35
+ yield fx.timer.set('poll', listRefPollDelayMs({ idleStreak, baseIntervalMs: env.pollBaseMs }), { type: 'PollTick' });
36
+ }
@@ -0,0 +1,78 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { runPure } from '../testing/run-pure';
3
+ import { buildEntry, buildOutboxItem, buildState } from '../testing/build';
4
+ import * as R from '../state/reducers';
5
+ import { defaultEnv } from '../query/env';
6
+ import { setRole, tabMessage } from './tabs.saga';
7
+
8
+ const env = defaultEnv({ tables: [] } as any);
9
+
10
+ describe('setRole', () => {
11
+ it('leader: loads the outbox and starts live/poll/registrations; follower: stops its timers; same role is a no-op', async () => {
12
+ const leader = await runPure(setRole(env, 'leader'), { state: buildState(), handlers: { 'local.query': () => [] } });
13
+ expect(leader.state.tabRole).toBe('leader');
14
+ expect(leader.dispatched).toEqual([{ type: 'AdoptPendingWrites' }, { type: 'LiveStart' }, { type: 'PollTick' }, { type: 'EnsureRegistered' }]);
15
+ const follower = await runPure(setRole(env, 'follower'), { state: R.patchSync({ liveUuid: 'u' })(buildState()) });
16
+ expect(follower.state.tabRole).toBe('follower');
17
+ expect(follower.state.sync.liveUuid).toBeNull();
18
+ expect(follower.log.filter((e) => e.kind === 'timer.clear').map((e) => (e as any).key)).toEqual(['poll', 'outbox']);
19
+ const same = await runPure(setRole(env, 'solo'), { state: buildState() });
20
+ expect(same.log).toHaveLength(1);
21
+ });
22
+ });
23
+
24
+ describe('tabMessage', () => {
25
+ const s = () => buildState([buildEntry({ def: { hash: 'a', tableName: 'thing' } })], R.outboxReplace([buildOutboxItem({ id: 'm1', recordId: 'thing:1' })]));
26
+ it('ignores junk', async () => {
27
+ for (const junk of [null, 'x', {}, { type: 'weird' }, { type: 'ingest', records: [] }, { type: 'membership-dirty' }, { type: 'failed-mutations-changed' }]) {
28
+ const out = await runPure(tabMessage(env, junk), { state: s() });
29
+ expect(out.emitted).toEqual([]);
30
+ }
31
+ });
32
+ it('ingest: feeds the circuit, tracks versions, dirties tables; a failing ingest is logged', async () => {
33
+ const msg = {
34
+ type: 'ingest',
35
+ records: [
36
+ { table: 'thing', op: 'CREATE', id: 'thing:2', record: { _00_rv: 3 } },
37
+ { table: 'thing', op: 'DELETE', id: 'thing:1', record: {} },
38
+ { table: 'other', op: 'UPDATE', id: 'other:1', record: {} },
39
+ ],
40
+ };
41
+ const out = await runPure(tabMessage(env, msg), { state: R.setVersions([['thing:1', 1]])(s()), handlers: { 'ssp.ingest': () => undefined } });
42
+ expect(out.state.versions.get('thing:2')).toBe(3);
43
+ expect(out.state.versions.get('other:1')).toBe(0);
44
+ expect(out.state.versions.has('thing:1')).toBe(false);
45
+ expect(out.state.dirty.has('a')).toBe(true);
46
+ // A relayed delete (another tab's GC) may drop a body this tab names: the fetch plan decides.
47
+ expect(out.dispatched).toEqual([{ type: 'FetchRows' }]);
48
+ const writesOnly = await runPure(tabMessage(env, { ...msg, records: msg.records.filter((r) => r.op !== 'DELETE') }), { state: s(), handlers: { 'ssp.ingest': () => undefined } });
49
+ expect(writesOnly.dispatched).toEqual([]);
50
+ const failing = await runPure(tabMessage(env, msg), {
51
+ state: s(),
52
+ handlers: {
53
+ 'ssp.ingest': () => {
54
+ throw new Error('wasm');
55
+ },
56
+ },
57
+ });
58
+ expect(failing.emitted).toEqual([expect.objectContaining({ level: 'warn' })]);
59
+ });
60
+ it('membership-dirty, outbox-changed (leader only), settled, rolled-back, tray count', async () => {
61
+ const dirty = await runPure(tabMessage(env, { type: 'membership-dirty', hashes: ['a'] }), { state: { ...s(), tabRole: 'follower' } });
62
+ expect(dirty.state.membershipDirty.has('a')).toBe(true);
63
+ const ob = await runPure(tabMessage(env, { type: 'outbox-changed', mutationId: 'm' }), { state: { ...s(), tabRole: 'leader' }, handlers: { 'local.query': () => [] } });
64
+ expect(ob.log.some((e) => e.kind === 'local.query')).toBe(true);
65
+ const obFollower = await runPure(tabMessage(env, { type: 'outbox-changed', mutationId: 'm' }), { state: { ...s(), tabRole: 'follower' } });
66
+ expect(obFollower.log.some((e) => e.kind === 'local.query')).toBe(false);
67
+ const settled = await runPure(tabMessage(env, { type: 'mutation-settled', mutationId: 'm1', recordId: 'thing:1', eventType: 'create' }), { state: s(), now: 9 });
68
+ expect(settled.state.outbox[0]).toMatchObject({ status: 'acked', ackedAt: 9 });
69
+ expect(settled.emitted).toEqual([{ type: 'mutation:settled', mutationId: 'm1', recordId: 'thing:1', eventType: 'create' }]);
70
+ const rolled = await runPure(tabMessage(env, { type: 'mutation-rolled-back', mutationId: 'm1', recordId: 'thing:1', eventType: 'create', error: 'denied' }), { state: s() });
71
+ expect(rolled.state.outbox).toEqual([]);
72
+ expect(rolled.state.dirty.has('a')).toBe(true);
73
+ expect(rolled.emitted[0]).toMatchObject({ type: 'mutation:rolled-back', error: 'denied' });
74
+ const tray = await runPure(tabMessage(env, { type: 'failed-mutations-changed', count: 4 }), { state: s() });
75
+ expect(tray.state.failedCount).toBe(4);
76
+ expect(tray.emitted).toEqual([{ type: 'tray:changed', count: 4 }]);
77
+ });
78
+ });
@@ -0,0 +1,96 @@
1
+ import type { Saga } from '../kernel/saga';
2
+ import { fx } from '../kernel/effects';
3
+ import type { IngestRecord } from '../services/stream-processor/index';
4
+ import type { ClientState, TabRole } from '../state/client-state';
5
+ import * as R from '../state/reducers';
6
+ import type { SagaEnv } from '../query/env';
7
+ import { loadOutbox } from '../mutation/push.saga';
8
+ import { liveChange } from './live.saga';
9
+
10
+ /**
11
+ * Shared-tabs role changes. The leader owns the outbox drain, the poll and
12
+ * LIVE; a follower keeps its own circuit and materialization but gets
13
+ * membership dirt, acks and rollbacks relayed.
14
+ */
15
+ export function* setRole(env: SagaEnv, role: TabRole): Saga<void> {
16
+ const prev = (yield fx.state.read((s) => s.tabRole)) as TabRole;
17
+ if (prev === role) return;
18
+ yield fx.state.update(R.setTabRole(role));
19
+ if (role === 'follower') {
20
+ yield fx.timer.clear('poll');
21
+ yield fx.timer.clear('outbox');
22
+ yield fx.state.update(R.patchSync({ liveUuid: null, liveTable: null }));
23
+ return;
24
+ }
25
+ yield* loadOutbox(env);
26
+ yield fx.dispatch({ type: 'LiveStart' });
27
+ yield fx.dispatch({ type: 'PollTick' });
28
+ yield fx.dispatch({ type: 'EnsureRegistered' });
29
+ }
30
+
31
+ type TabMessage =
32
+ | { type: 'ingest'; records: IngestRecord[] }
33
+ | { type: 'membership-dirty'; hashes: string[] }
34
+ | { type: 'outbox-changed'; mutationId: string }
35
+ | { type: 'mutation-settled'; mutationId: string; recordId: string; eventType: string }
36
+ | { type: 'mutation-rolled-back'; mutationId: string; recordId: string; eventType: string; error: string }
37
+ | { type: 'failed-mutations-changed'; count: number };
38
+
39
+ /** A message from another tab of the same origin. */
40
+ export function* tabMessage(env: SagaEnv, raw: unknown): Saga<void> {
41
+ const msg = raw as TabMessage | null;
42
+ if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') return;
43
+ const role = (yield fx.state.read((s) => s.tabRole)) as ClientState['tabRole'];
44
+ switch (msg.type) {
45
+ case 'ingest': {
46
+ if (!Array.isArray(msg.records) || msg.records.length === 0) return;
47
+ try {
48
+ yield fx.ssp.ingest(msg.records);
49
+ } catch (error) {
50
+ yield fx.emit({ type: 'log', level: 'warn', message: 'relayed ingest failed', data: { error } });
51
+ }
52
+ yield fx.state.update(
53
+ R.compose(
54
+ R.setVersions(
55
+ msg.records
56
+ .filter((r) => r.op !== 'DELETE')
57
+ .map((r) => [r.id, typeof r.record?._00_rv === 'number' ? (r.record._00_rv as number) : 0] as const)
58
+ ),
59
+ R.deleteVersions(msg.records.filter((r) => r.op === 'DELETE').map((r) => r.id)),
60
+ ...[...new Set(msg.records.map((r) => r.table))].map((t) => R.markTableDirty(t))
61
+ )
62
+ );
63
+ // A body another tab deleted (its orphan GC) may still be one this tab
64
+ // names: with the version gone, the fetch plan pulls it back.
65
+ if (msg.records.some((r) => r.op === 'DELETE')) yield fx.dispatch({ type: 'FetchRows' });
66
+ return;
67
+ }
68
+ case 'membership-dirty':
69
+ // No inline rows here: the leader relays its own bodies as an `ingest`.
70
+ if (Array.isArray(msg.hashes)) yield* liveChange(env, msg.hashes);
71
+ return;
72
+ case 'outbox-changed':
73
+ if (role !== 'leader') return;
74
+ yield* loadOutbox(env);
75
+ return;
76
+ case 'mutation-settled': {
77
+ const now = (yield fx.now()) as number;
78
+ yield fx.state.update(R.outboxAck(msg.mutationId, now));
79
+ yield fx.emit({ type: 'mutation:settled', mutationId: msg.mutationId, recordId: msg.recordId, eventType: msg.eventType });
80
+ return;
81
+ }
82
+ case 'mutation-rolled-back': {
83
+ const table = msg.recordId.slice(0, msg.recordId.indexOf(':'));
84
+ yield fx.state.update(R.compose(R.outboxRemove(msg.mutationId), R.markTableDirty(table)));
85
+ yield fx.emit({ type: 'mutation:rolled-back', mutationId: msg.mutationId, recordId: msg.recordId, eventType: msg.eventType, error: msg.error });
86
+ return;
87
+ }
88
+ case 'failed-mutations-changed':
89
+ if (typeof msg.count !== 'number') return;
90
+ yield fx.state.update(R.setFailedCount(msg.count));
91
+ yield fx.emit({ type: 'tray:changed', count: msg.count });
92
+ return;
93
+ default:
94
+ return;
95
+ }
96
+ }