@spooky-sync/core 0.0.1-canary.24 → 0.0.1-canary.240

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 (303) hide show
  1. package/AGENTS.md +58 -0
  2. package/coverage/lcov-report/base.css +224 -0
  3. package/coverage/lcov-report/block-navigation.js +87 -0
  4. package/coverage/lcov-report/favicon.png +0 -0
  5. package/coverage/lcov-report/index.html +476 -0
  6. package/coverage/lcov-report/prettify.css +1 -0
  7. package/coverage/lcov-report/prettify.js +2 -0
  8. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  9. package/coverage/lcov-report/sorter.js +210 -0
  10. package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +271 -0
  11. package/coverage/lcov-report/src/boot/boot.saga.ts.html +469 -0
  12. package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +430 -0
  13. package/coverage/lcov-report/src/boot/index.html +161 -0
  14. package/coverage/lcov-report/src/boot/preload.saga.ts.html +178 -0
  15. package/coverage/lcov-report/src/client/bucket-handle.ts.html +766 -0
  16. package/coverage/lcov-report/src/client/index.html +161 -0
  17. package/coverage/lcov-report/src/client/router.ts.html +367 -0
  18. package/coverage/lcov-report/src/client/runtime.ts.html +940 -0
  19. package/coverage/lcov-report/src/client/sp00ky-client.ts.html +1531 -0
  20. package/coverage/lcov-report/src/events/index.html +116 -0
  21. package/coverage/lcov-report/src/events/index.ts.html +877 -0
  22. package/coverage/lcov-report/src/index.html +146 -0
  23. package/coverage/lcov-report/src/index.ts.html +202 -0
  24. package/coverage/lcov-report/src/kernel/constants.ts.html +247 -0
  25. package/coverage/lcov-report/src/kernel/effects.ts.html +562 -0
  26. package/coverage/lcov-report/src/kernel/events.ts.html +250 -0
  27. package/coverage/lcov-report/src/kernel/index.html +176 -0
  28. package/coverage/lcov-report/src/kernel/interpreter.ts.html +514 -0
  29. package/coverage/lcov-report/src/kernel/saga.ts.html +304 -0
  30. package/coverage/lcov-report/src/modules/app-release/index.html +116 -0
  31. package/coverage/lcov-report/src/modules/app-release/index.ts.html +712 -0
  32. package/coverage/lcov-report/src/modules/auth/events/index.html +116 -0
  33. package/coverage/lcov-report/src/modules/auth/events/index.ts.html +142 -0
  34. package/coverage/lcov-report/src/modules/auth/index.html +116 -0
  35. package/coverage/lcov-report/src/modules/auth/index.ts.html +1225 -0
  36. package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +967 -0
  37. package/coverage/lcov-report/src/modules/crdt/index.html +146 -0
  38. package/coverage/lcov-report/src/modules/crdt/index.ts.html +1474 -0
  39. package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +160 -0
  40. package/coverage/lcov-report/src/modules/devtools/flags.ts.html +1132 -0
  41. package/coverage/lcov-report/src/modules/devtools/index.html +161 -0
  42. package/coverage/lcov-report/src/modules/devtools/index.ts.html +2413 -0
  43. package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +589 -0
  44. package/coverage/lcov-report/src/modules/devtools/versions.ts.html +415 -0
  45. package/coverage/lcov-report/src/modules/feature-flag/index.html +116 -0
  46. package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +1033 -0
  47. package/coverage/lcov-report/src/modules/index.html +116 -0
  48. package/coverage/lcov-report/src/modules/ref-tables.ts.html +349 -0
  49. package/coverage/lcov-report/src/mutation/index.html +191 -0
  50. package/coverage/lcov-report/src/mutation/jobs.ts.html +208 -0
  51. package/coverage/lcov-report/src/mutation/mutation-id.ts.html +190 -0
  52. package/coverage/lcov-report/src/mutation/push.saga.ts.html +730 -0
  53. package/coverage/lcov-report/src/mutation/rows.ts.html +1216 -0
  54. package/coverage/lcov-report/src/mutation/tray.saga.ts.html +229 -0
  55. package/coverage/lcov-report/src/mutation/write.saga.ts.html +583 -0
  56. package/coverage/lcov-report/src/otel/index.html +116 -0
  57. package/coverage/lcov-report/src/otel/index.ts.html +466 -0
  58. package/coverage/lcov-report/src/query/env.ts.html +253 -0
  59. package/coverage/lcov-report/src/query/fetch.saga.ts.html +412 -0
  60. package/coverage/lcov-report/src/query/hash.ts.html +139 -0
  61. package/coverage/lcov-report/src/query/index.html +281 -0
  62. package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +388 -0
  63. package/coverage/lcov-report/src/query/materialize.saga.ts.html +310 -0
  64. package/coverage/lcov-report/src/query/materialize.ts.html +217 -0
  65. package/coverage/lcov-report/src/query/membership.saga.ts.html +709 -0
  66. package/coverage/lcov-report/src/query/membership.ts.html +559 -0
  67. package/coverage/lcov-report/src/query/register.saga.ts.html +655 -0
  68. package/coverage/lcov-report/src/query/render-set.ts.html +265 -0
  69. package/coverage/lcov-report/src/query/sql.ts.html +322 -0
  70. package/coverage/lcov-report/src/query/window-query.ts.html +670 -0
  71. package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +1894 -0
  72. package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +766 -0
  73. package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +1162 -0
  74. package/coverage/lcov-report/src/services/blobs/index.html +161 -0
  75. package/coverage/lcov-report/src/services/blobs/index.ts.html +295 -0
  76. package/coverage/lcov-report/src/services/database/cache-engine.ts.html +664 -0
  77. package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +1330 -0
  78. package/coverage/lcov-report/src/services/database/database.ts.html +658 -0
  79. package/coverage/lcov-report/src/services/database/engine-factory.ts.html +184 -0
  80. package/coverage/lcov-report/src/services/database/errors.ts.html +187 -0
  81. package/coverage/lcov-report/src/services/database/events/index.html +116 -0
  82. package/coverage/lcov-report/src/services/database/events/index.ts.html +184 -0
  83. package/coverage/lcov-report/src/services/database/index.html +386 -0
  84. package/coverage/lcov-report/src/services/database/index.ts.html +121 -0
  85. package/coverage/lcov-report/src/services/database/local-migrator.ts.html +703 -0
  86. package/coverage/lcov-report/src/services/database/local.ts.html +1633 -0
  87. package/coverage/lcov-report/src/services/database/plan-render.ts.html +409 -0
  88. package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +682 -0
  89. package/coverage/lcov-report/src/services/database/remote.ts.html +1036 -0
  90. package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +4132 -0
  91. package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +220 -0
  92. package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +577 -0
  93. package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +499 -0
  94. package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +478 -0
  95. package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +757 -0
  96. package/coverage/lcov-report/src/services/database/surql-translate.ts.html +1333 -0
  97. package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +568 -0
  98. package/coverage/lcov-report/src/services/logger/index.html +116 -0
  99. package/coverage/lcov-report/src/services/logger/index.ts.html +154 -0
  100. package/coverage/lcov-report/src/services/persistence/index.html +146 -0
  101. package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +163 -0
  102. package/coverage/lcov-report/src/services/persistence/resilient.ts.html +208 -0
  103. package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +271 -0
  104. package/coverage/lcov-report/src/services/stream-processor/index.html +146 -0
  105. package/coverage/lcov-report/src/services/stream-processor/index.ts.html +3313 -0
  106. package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +244 -0
  107. package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +346 -0
  108. package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +934 -0
  109. package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +1984 -0
  110. package/coverage/lcov-report/src/services/tabs/index.html +191 -0
  111. package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +310 -0
  112. package/coverage/lcov-report/src/services/tabs/protocol.ts.html +871 -0
  113. package/coverage/lcov-report/src/services/tabs/support.ts.html +193 -0
  114. package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +2005 -0
  115. package/coverage/lcov-report/src/sp00ky.ts.html +100 -0
  116. package/coverage/lcov-report/src/state/client-state.ts.html +637 -0
  117. package/coverage/lcov-report/src/state/index.html +161 -0
  118. package/coverage/lcov-report/src/state/lifecycle.ts.html +343 -0
  119. package/coverage/lcov-report/src/state/reducers.ts.html +1471 -0
  120. package/coverage/lcov-report/src/state/selectors.ts.html +637 -0
  121. package/coverage/lcov-report/src/sync/connection.saga.ts.html +343 -0
  122. package/coverage/lcov-report/src/sync/index.html +176 -0
  123. package/coverage/lcov-report/src/sync/live.saga.ts.html +232 -0
  124. package/coverage/lcov-report/src/sync/policy.ts.html +1606 -0
  125. package/coverage/lcov-report/src/sync/poll.saga.ts.html +193 -0
  126. package/coverage/lcov-report/src/sync/tabs.saga.ts.html +361 -0
  127. package/coverage/lcov-report/src/types.ts.html +2419 -0
  128. package/coverage/lcov-report/src/utils/blurhash.ts.html +355 -0
  129. package/coverage/lcov-report/src/utils/error-classification.ts.html +244 -0
  130. package/coverage/lcov-report/src/utils/index.html +191 -0
  131. package/coverage/lcov-report/src/utils/index.ts.html +820 -0
  132. package/coverage/lcov-report/src/utils/parser.ts.html +313 -0
  133. package/coverage/lcov-report/src/utils/semver.ts.html +175 -0
  134. package/coverage/lcov-report/src/utils/surql.ts.html +667 -0
  135. package/coverage/lcov.info +19079 -0
  136. package/dist/index.d.ts +2946 -140
  137. package/dist/index.js +13424 -2356
  138. package/dist/otel/index.d.ts +2 -2
  139. package/dist/otel/index.js +6 -6
  140. package/dist/sqlite-open.js +322 -0
  141. package/dist/sqlite-worker.d.ts +1 -0
  142. package/dist/sqlite-worker.js +439 -0
  143. package/dist/tabs-broker-worker.d.ts +8 -0
  144. package/dist/tabs-broker-worker.js +472 -0
  145. package/dist/types.d.ts +769 -11
  146. package/package.json +11 -7
  147. package/scripts/check-broker-bundle.mjs +33 -0
  148. package/skills/{spooky-core → sp00ky-core}/SKILL.md +12 -12
  149. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  150. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  151. package/src/bucket-blurhash.test.ts +148 -0
  152. package/src/build-globals.d.ts +12 -0
  153. package/src/events/events.test.ts +2 -1
  154. package/src/events/index.ts +3 -0
  155. package/src/index.ts +36 -2
  156. package/src/modules/app-release/index.test.ts +125 -0
  157. package/src/modules/app-release/index.ts +201 -0
  158. package/src/modules/auth/auth.local-first.test.ts +141 -0
  159. package/src/modules/auth/events/index.ts +2 -1
  160. package/src/modules/auth/index.ts +138 -25
  161. package/src/modules/cache/cache.relay.test.ts +95 -0
  162. package/src/modules/cache/index.ts +163 -43
  163. package/src/modules/cache/types.ts +2 -2
  164. package/src/modules/crdt/crdt-field.ts +294 -0
  165. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  166. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  167. package/src/modules/crdt/index.ts +463 -0
  168. package/src/modules/crdt/loro-loader.ts +25 -0
  169. package/src/modules/data/data.activity.test.ts +109 -0
  170. package/src/modules/data/data.authority.test.ts +122 -0
  171. package/src/modules/data/data.heartbeat-wake.test.ts +115 -0
  172. package/src/modules/data/data.hydration.test.ts +142 -0
  173. package/src/modules/data/data.membership.test.ts +623 -0
  174. package/src/modules/data/data.notify-table.test.ts +41 -0
  175. package/src/modules/data/data.pending-ids.test.ts +199 -0
  176. package/src/modules/data/data.rebind.test.ts +170 -0
  177. package/src/modules/data/data.rematerialize.test.ts +114 -0
  178. package/src/modules/data/data.run.test.ts +113 -0
  179. package/src/modules/data/data.settled-writes.test.ts +235 -0
  180. package/src/modules/data/data.status.test.ts +249 -0
  181. package/src/modules/data/id-set-plan.test.ts +122 -0
  182. package/src/modules/data/index.ts +2031 -150
  183. package/src/modules/data/mutation-id.test.ts +25 -0
  184. package/src/modules/data/mutation-id.ts +35 -0
  185. package/src/modules/data/window-query.test.ts +52 -0
  186. package/src/modules/data/window-query.ts +194 -0
  187. package/src/modules/devtools/flags.ts +349 -0
  188. package/src/modules/devtools/index.ts +451 -46
  189. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  190. package/src/modules/devtools/state-shape.test.ts +146 -0
  191. package/src/modules/devtools/storage-info.test.ts +79 -0
  192. package/src/modules/devtools/storage-info.ts +168 -0
  193. package/src/modules/devtools/versions.test.ts +74 -0
  194. package/src/modules/devtools/versions.ts +110 -0
  195. package/src/modules/feature-flag/index.test.ts +251 -0
  196. package/src/modules/feature-flag/index.ts +308 -0
  197. package/src/modules/ref-tables.test.ts +91 -0
  198. package/src/modules/ref-tables.ts +88 -0
  199. package/src/modules/sync/engine.ts +170 -86
  200. package/src/modules/sync/events/index.ts +9 -2
  201. package/src/modules/sync/queue/queue-down.test.ts +228 -0
  202. package/src/modules/sync/queue/queue-down.ts +108 -13
  203. package/src/modules/sync/queue/queue-up.forwarded.test.ts +164 -0
  204. package/src/modules/sync/queue/queue-up.ts +241 -57
  205. package/src/modules/sync/scheduler.pause.test.ts +109 -0
  206. package/src/modules/sync/scheduler.retry.test.ts +237 -0
  207. package/src/modules/sync/scheduler.ts +215 -13
  208. package/src/modules/sync/sync.cleanup.test.ts +116 -0
  209. package/src/modules/sync/sync.health.test.ts +167 -0
  210. package/src/modules/sync/sync.heartbeat.test.ts +80 -0
  211. package/src/modules/sync/sync.list-ref-meta.test.ts +193 -0
  212. package/src/modules/sync/sync.live-removal.test.ts +289 -0
  213. package/src/modules/sync/sync.reconnect.test.ts +145 -0
  214. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +93 -0
  215. package/src/modules/sync/sync.settled-poll.test.ts +58 -0
  216. package/src/modules/sync/sync.subquery.test.ts +82 -0
  217. package/src/modules/sync/sync.tabs.test.ts +249 -0
  218. package/src/modules/sync/sync.ts +2350 -133
  219. package/src/modules/sync/utils.test.ts +322 -2
  220. package/src/modules/sync/utils.ts +286 -16
  221. package/src/otel/index.ts +13 -10
  222. package/src/services/blobs/blob-cache.test.ts +359 -0
  223. package/src/services/blobs/blob-cache.ts +603 -0
  224. package/src/services/blobs/blob-manifest.ts +227 -0
  225. package/src/services/blobs/blob-store.test.ts +77 -0
  226. package/src/services/blobs/blob-store.ts +359 -0
  227. package/src/services/blobs/blob.fixture.ts +90 -0
  228. package/src/services/blobs/index.ts +70 -0
  229. package/src/services/database/cache-engine.ts +193 -0
  230. package/src/services/database/connection-supervisor.test.ts +289 -0
  231. package/src/services/database/connection-supervisor.ts +415 -0
  232. package/src/services/database/database.query-timeout.test.ts +140 -0
  233. package/src/services/database/database.ts +130 -62
  234. package/src/services/database/engine-factory.ts +33 -0
  235. package/src/services/database/errors.ts +34 -0
  236. package/src/services/database/events/index.ts +2 -1
  237. package/src/services/database/index.ts +7 -0
  238. package/src/services/database/local-migrator.ts +30 -27
  239. package/src/services/database/local.test.ts +64 -0
  240. package/src/services/database/local.ts +484 -67
  241. package/src/services/database/plan-render.test.ts +159 -0
  242. package/src/services/database/plan-render.ts +108 -0
  243. package/src/services/database/relation-resolver.test.ts +467 -0
  244. package/src/services/database/relation-resolver.ts +0 -0
  245. package/src/services/database/remote.ts +222 -15
  246. package/src/services/database/sqlite-cache-engine.test.ts +616 -0
  247. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  248. package/src/services/database/sqlite-cache-engine.ts +1358 -0
  249. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  250. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  251. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  252. package/src/services/database/sqlite-lock-verify.ts +45 -0
  253. package/src/services/database/sqlite-open.test.ts +150 -0
  254. package/src/services/database/sqlite-open.ts +164 -0
  255. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  256. package/src/services/database/sqlite-plan-sql.ts +138 -0
  257. package/src/services/database/sqlite-projection.test.ts +99 -0
  258. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  259. package/src/services/database/sqlite-select.test.ts +246 -0
  260. package/src/services/database/sqlite-select.ts +131 -0
  261. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  262. package/src/services/database/sqlite-transport.ts +224 -0
  263. package/src/services/database/sqlite-worker.ts +437 -0
  264. package/src/services/database/surql-translate.ts +416 -0
  265. package/src/services/database/surreal-cache-engine.ts +161 -0
  266. package/src/services/logger/index.ts +3 -2
  267. package/src/services/persistence/localstorage.ts +2 -2
  268. package/src/services/persistence/resilient.ts +11 -4
  269. package/src/services/persistence/surrealdb.ts +10 -10
  270. package/src/services/stream-processor/index.ts +796 -84
  271. package/src/services/stream-processor/permissions.test.ts +47 -0
  272. package/src/services/stream-processor/permissions.ts +53 -0
  273. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  274. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  275. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  276. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  277. package/src/services/stream-processor/wasm-types.ts +59 -3
  278. package/src/services/tabs/broker-client.ts +283 -0
  279. package/src/services/tabs/broker.test.ts +327 -0
  280. package/src/services/tabs/coordinator.test.ts +365 -0
  281. package/src/services/tabs/coordinator.ts +633 -0
  282. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  283. package/src/services/tabs/leader-locks.ts +75 -0
  284. package/src/services/tabs/protocol.ts +258 -0
  285. package/src/services/tabs/support.ts +36 -0
  286. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  287. package/src/sp00ky.auth-order.test.ts +112 -0
  288. package/src/sp00ky.init-query.test.ts +183 -0
  289. package/src/sp00ky.local-first.test.ts +60 -0
  290. package/src/sp00ky.ts +1854 -0
  291. package/src/types.ts +548 -13
  292. package/src/utils/blurhash.ts +90 -0
  293. package/src/utils/error-classification.test.ts +54 -0
  294. package/src/utils/error-classification.ts +25 -0
  295. package/src/utils/index.ts +79 -13
  296. package/src/utils/parser.test.ts +49 -120
  297. package/src/utils/parser.ts +32 -2
  298. package/src/utils/semver.test.ts +32 -0
  299. package/src/utils/semver.ts +30 -0
  300. package/src/utils/surql.ts +30 -18
  301. package/src/utils/withRetry.test.ts +1 -1
  302. package/tsdown.config.ts +86 -1
  303. package/src/spooky.ts +0 -395
@@ -0,0 +1,91 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
3
+ import { ANON_USER_ID, bucketIdForUser, listRefTableFor, sanitizeUserId } from './ref-tables';
4
+
5
+ describe('listRefTableFor', () => {
6
+ it('returns global table in single mode regardless of user', () => {
7
+ expect(listRefTableFor('single', 'user:abc')).toBe('_00_list_ref');
8
+ expect(listRefTableFor('single', null)).toBe('_00_list_ref');
9
+ expect(listRefTableFor('single', undefined)).toBe('_00_list_ref');
10
+ });
11
+
12
+ it('returns per-user table in dedicated mode with valid user id', () => {
13
+ expect(listRefTableFor('dedicated', 'user:abc')).toBe(
14
+ '_00_list_ref_user_abc'
15
+ );
16
+ });
17
+
18
+ it('accepts a RecordId object in dedicated mode', () => {
19
+ const rid = new RecordId('user', 'def');
20
+ expect(listRefTableFor('dedicated', rid)).toBe('_00_list_ref_user_def');
21
+ });
22
+
23
+ it('falls back to global in dedicated mode when user id is missing', () => {
24
+ expect(listRefTableFor('dedicated', null)).toBe('_00_list_ref');
25
+ expect(listRefTableFor('dedicated', undefined)).toBe('_00_list_ref');
26
+ });
27
+
28
+ it('falls back to global in dedicated mode when user id has invalid chars', () => {
29
+ // SurrealDB table identifiers only accept alphanumerics + underscore.
30
+ expect(listRefTableFor('dedicated', 'user:abc-with-dash')).toBe(
31
+ '_00_list_ref'
32
+ );
33
+ expect(listRefTableFor('dedicated', 'user:abc.dot')).toBe('_00_list_ref');
34
+ });
35
+
36
+ it('routes the anon sentinel to the shared anon table in both modes', () => {
37
+ expect(listRefTableFor('dedicated', ANON_USER_ID)).toBe('_00_list_ref_anon');
38
+ expect(listRefTableFor('single', ANON_USER_ID)).toBe('_00_list_ref_anon');
39
+ // A real user whose id sanitizes to "anon" still carries the user: prefix,
40
+ // so it never collides with the bare sentinel.
41
+ expect(listRefTableFor('dedicated', 'user:anon')).toBe(
42
+ '_00_list_ref_user_anon'
43
+ );
44
+ });
45
+ });
46
+
47
+ describe('sanitizeUserId', () => {
48
+ it('strips the user: prefix', () => {
49
+ expect(sanitizeUserId('user:abc123')).toBe('abc123');
50
+ });
51
+
52
+ it('accepts plain ids without the user: prefix', () => {
53
+ expect(sanitizeUserId('abc123')).toBe('abc123');
54
+ });
55
+
56
+ it('accepts RecordId objects', () => {
57
+ expect(sanitizeUserId(new RecordId('user', 'xyz'))).toBe('xyz');
58
+ });
59
+
60
+ it('returns null for invalid id shapes', () => {
61
+ expect(sanitizeUserId(null)).toBeNull();
62
+ expect(sanitizeUserId(undefined)).toBeNull();
63
+ expect(sanitizeUserId('user:')).toBeNull();
64
+ expect(sanitizeUserId('user:has-dash')).toBeNull();
65
+ });
66
+ });
67
+
68
+ describe('bucketIdForUser', () => {
69
+ it('routes signed-out sessions to the anon bucket', () => {
70
+ expect(bucketIdForUser(null)).toBe(ANON_USER_ID);
71
+ expect(bucketIdForUser(undefined)).toBe(ANON_USER_ID);
72
+ expect(bucketIdForUser(ANON_USER_ID)).toBe(ANON_USER_ID);
73
+ });
74
+
75
+ it('uses the sanitized id for valid users', () => {
76
+ expect(bucketIdForUser('user:abc123')).toBe('abc123');
77
+ expect(bucketIdForUser(new RecordId('user', 'xyz'))).toBe('xyz');
78
+ });
79
+
80
+ it('gives unsanitizable ids a deterministic per-user bucket, never anon', () => {
81
+ const a = bucketIdForUser('user:has-dash');
82
+ const b = bucketIdForUser('user:has-dash');
83
+ const c = bucketIdForUser('user:other-dash');
84
+ // Falling back to the shared anon bucket here would recreate the
85
+ // cross-user local-cache leak this helper exists to prevent.
86
+ expect(a).not.toBe(ANON_USER_ID);
87
+ expect(a).toBe(b);
88
+ expect(a).not.toBe(c);
89
+ expect(a).toMatch(/^u[0-9a-f]+$/);
90
+ });
91
+ });
@@ -0,0 +1,88 @@
1
+ // Client-side mirror of `packages/ssp-protocol/src/lib.rs`'s
2
+ // `query_table_for` / `list_ref_table_for`. Same naming convention so
3
+ // the LIVE subscription, the initial-fetch read, and the SSP's writes
4
+ // all land on the same table.
5
+ //
6
+ // The mode is currently hardcoded to `dedicated` because that's the
7
+ // only mode the e2e suite exercises and threading the value through
8
+ // codegen wasn't necessary to land the cross-session fix. If single
9
+ // mode ever needs to be exposed from the TS client too, the SSP server
10
+ // already reads it from `SPKY_SSP_REF_MODE`; add a matching codegen
11
+ // export then.
12
+
13
+ import { cyrb53 } from '@spooky-sync/query-builder';
14
+
15
+ export type RefMode = 'single' | 'dedicated';
16
+
17
+ /**
18
+ * Sentinel user id for unauthenticated clients when anonymous live queries are
19
+ * enabled. Mirrors `ssp_protocol::ANON_AUTH_ID`. It carries no `user:` prefix
20
+ * so it can never collide with a real user id (those arrive as `user:<id>`);
21
+ * both sides resolve it to the shared `_00_list_ref_anon` table.
22
+ */
23
+ export const ANON_USER_ID = 'anon';
24
+
25
+ /**
26
+ * Default ref-storage mode for this client build. Mirrors the SSP's
27
+ * default (`RefMode::Dedicated`) so cross-session sync works out of the
28
+ * box.
29
+ */
30
+ export const DEFAULT_REF_MODE: RefMode = 'dedicated';
31
+
32
+ /**
33
+ * Sanitize a user record id (e.g. `"user:abc"`) into the segment that
34
+ * goes into a dedicated table name (e.g. `"abc"`). Returns `null` if
35
+ * the id is missing the `user:` prefix or contains characters that
36
+ * aren't valid in a SurrealDB table identifier — the server-side
37
+ * `ssp_protocol::sanitize_user_id` uses the same predicate.
38
+ *
39
+ * Accepts both string ids (`"user:abc"`) and SurrealDB `RecordId`
40
+ * objects (which only stringify cleanly via `.toString()`), since
41
+ * `AuthService` passes the record-id object as-is to its subscribers.
42
+ */
43
+ export function sanitizeUserId(userId: unknown): string | null {
44
+ if (userId === null || userId === undefined) return null;
45
+ const asString =
46
+ typeof userId === 'string'
47
+ ? userId
48
+ : typeof (userId as { toString?: unknown }).toString === 'function'
49
+ ? (userId as { toString: () => string }).toString()
50
+ : null;
51
+ if (!asString) return null;
52
+ const raw = asString.startsWith('user:') ? asString.slice('user:'.length) : asString;
53
+ if (raw.length === 0) return null;
54
+ if (!/^[A-Za-z0-9_]+$/.test(raw)) return null;
55
+ return raw;
56
+ }
57
+
58
+ /**
59
+ * Resolve the LOCAL storage bucket id for a user. Every user gets their own
60
+ * IndexedDB-backed local store (`indxdb://sp00ky-<bucketId>`) so cached rows,
61
+ * query state, and the mutation outbox never leak across accounts on a shared
62
+ * device. Signed-out sessions share the `anon` bucket.
63
+ *
64
+ * An id that fails sanitization still gets a DETERMINISTIC per-user bucket
65
+ * (cyrb53 hex of the raw id) — falling back to `anon` here would put an
66
+ * authenticated user in the shared bucket and recreate the cross-user leak.
67
+ */
68
+ export function bucketIdForUser(userId: unknown): string {
69
+ if (userId === null || userId === undefined || userId === ANON_USER_ID) return ANON_USER_ID;
70
+ const uid = sanitizeUserId(userId);
71
+ if (uid) return uid;
72
+ return `u${cyrb53(String(userId)).toString(16)}`;
73
+ }
74
+
75
+ /**
76
+ * Returns the `_00_list_ref` table name for `(mode, userId)`. Falls
77
+ * back to the global `_00_list_ref` when sanitization fails or in
78
+ * single mode.
79
+ */
80
+ export function listRefTableFor(mode: RefMode, userId: unknown): string {
81
+ // Anonymous clients (flag-enabled) share one dedicated table in both modes —
82
+ // checked before the mode split so it never lands on the per-user or the
83
+ // auth-gated global table. Matches `ssp_protocol::list_ref_table_for`.
84
+ if (userId === ANON_USER_ID) return '_00_list_ref_anon';
85
+ if (mode === 'single') return '_00_list_ref';
86
+ const uid = sanitizeUserId(userId);
87
+ return uid ? `_00_list_ref_user_${uid}` : '_00_list_ref';
88
+ }
@@ -1,18 +1,21 @@
1
- import { RecordId } from 'surrealdb';
2
- import { SchemaStructure } from '@spooky-sync/query-builder';
3
- import { RemoteDatabaseService } from '../../services/database/index';
4
- import { CacheModule, CacheRecord, RecordWithId } from '../cache/index';
5
- import { RecordVersionDiff } from '../../types';
6
- import { Logger } from '../../services/logger/index';
1
+ import type { RecordId } from 'surrealdb';
2
+ import type { SchemaStructure } from '@spooky-sync/query-builder';
3
+ import type { RemoteDatabaseService } from '../../services/database/index';
4
+ import type { CacheModule, CacheRecord, RecordWithId } from '../cache/index';
5
+ import type { RecordVersionDiff } from '../../types';
6
+ import type { Logger } from '../../services/logger/index';
7
7
  import { SyncEventTypes, createSyncEventSystem } from './events/index';
8
8
  import { encodeRecordId } from '../../utils/index';
9
9
  import { cleanRecord } from '../../utils/parser';
10
10
 
11
+ /** Ids per remote `SELECT * FROM $ids` round trip. */
12
+ const FETCH_CHUNK = 500;
13
+
11
14
  /**
12
15
  * SyncEngine handles the core sync operations: fetching remote records,
13
16
  * caching them locally, and ingesting into DBSP.
14
17
  *
15
- * This is extracted from SpookySync to separate "how to sync" from "when to sync".
18
+ * This is extracted from Sp00kySync to separate "how to sync" from "when to sync".
16
19
  */
17
20
  export class SyncEngine {
18
21
  private logger: Logger;
@@ -24,7 +27,7 @@ export class SyncEngine {
24
27
  private schema: SchemaStructure,
25
28
  logger: Logger
26
29
  ) {
27
- this.logger = logger.child({ service: 'SpookySync:SyncEngine' });
30
+ this.logger = logger.child({ service: 'Sp00kySync:SyncEngine' });
28
31
  }
29
32
 
30
33
  /**
@@ -32,7 +35,9 @@ export class SyncEngine {
32
35
  * Main entry point for sync operations.
33
36
  * Uses batch processing to minimize events emitted.
34
37
  */
35
- async syncRecords(diff: RecordVersionDiff): Promise<void> {
38
+ async syncRecords(
39
+ diff: RecordVersionDiff
40
+ ): Promise<{ remoteFetchMs: number; stillRemoteIds: string[]; confirmedRemovedIds: string[] }> {
36
41
  const { added, updated, removed } = diff;
37
42
 
38
43
  this.logger.debug(
@@ -40,127 +45,206 @@ export class SyncEngine {
40
45
  added,
41
46
  updated,
42
47
  removed,
43
- Category: 'spooky-client::SyncEngine::syncRecords',
48
+ Category: 'sp00ky-client::SyncEngine::syncRecords',
44
49
  },
45
50
  'SyncEngine.syncRecords diff'
46
51
  );
47
52
 
48
- // Handle removed records: verify they don't exist remotely before deleting locally
53
+ // Handle removed records: verify they don't exist remotely before deleting
54
+ // locally. Returns ids that LEFT the view's list_ref but still exist upstream
55
+ // (so they weren't deleted) — the caller converges localArray to drop them.
56
+ let stillRemoteIds: string[] = [];
57
+ let confirmedRemovedIds: string[] = [];
49
58
  if (removed.length > 0) {
50
- await this.handleRemovedRecords(removed);
59
+ ({ stillRemoteIds, confirmedRemovedIds } = await this.handleRemovedRecords(removed));
51
60
  }
52
61
 
53
- // Fetch added/updated records from remote
54
- const toFetch = [...added, ...updated];
55
- const idsToFetch = toFetch.map((x) => x.id);
56
- if (idsToFetch.length === 0) {
57
- return;
62
+ // Fetch added/updated records from remote. Skip ids whose body the local
63
+ // store already holds at this version (the circuit prime seeded the memo
64
+ // from `_00_rv`): after a reload every id in the server's list_ref used to
65
+ // classify as `added` against an empty circuit, and this fetched the
66
+ // whole working set again.
67
+ const toFetch = [...added, ...updated].filter((item) => {
68
+ const localVersion = this.cache.lookup(encodeRecordId(item.id));
69
+ return !(localVersion && item.version <= localVersion);
70
+ });
71
+ if (toFetch.length === 0) {
72
+ return { remoteFetchMs: 0, stillRemoteIds, confirmedRemovedIds };
58
73
  }
59
74
 
60
- const [remoteResults] = await this.remote.query<
61
- [(RecordWithId & { spooky_rv: number })[]]
62
- >(
63
- "SELECT *, (SELECT version FROM ONLY _spooky_version WHERE record_id = $parent.id)['version'] as spooky_rv FROM $idsToFetch",
64
- { idsToFetch }
65
- );
66
-
67
- // Prepare batch for cache (which handles both DB and DBSP)
68
- const cacheBatch: CacheRecord[] = [];
69
-
70
- for (const result of remoteResults) {
71
- if (!result?.id) {
72
- this.logger.warn(
73
- {
74
- result,
75
- idsToFetch,
76
- Category: 'spooky-client::SyncEngine::syncRecords',
77
- },
78
- 'Remote record has no id (possibly deleted). Skipping record'
79
- );
80
- continue;
81
- }
82
- const { spooky_rv, ...record } = result;
83
- const fullId = encodeRecordId(record.id);
84
- const table = record.id.table.toString();
85
- const isAdded = added.some((item) => encodeRecordId(item.id) === fullId);
86
-
87
- const localVersion = this.cache.lookup(fullId);
88
- if (localVersion && spooky_rv <= localVersion) {
89
- this.logger.info(
90
- {
91
- recordId: fullId,
92
- version: spooky_rv,
93
- localVersion,
94
- Category: 'spooky-client::SyncEngine::syncRecords',
95
- },
96
- 'Local version is higher than remote version. Skipping record'
97
- );
98
- continue;
99
- }
100
- const tableSchema = this.schema.tables.find((t) => t.name === table);
101
- const cleanedRecord = tableSchema
102
- ? cleanRecord(tableSchema.columns, record)
103
- : record;
104
-
105
- cacheBatch.push({
106
- table,
107
- op: isAdded ? 'CREATE' : 'UPDATE',
108
- record: cleanedRecord as RecordWithId,
109
- version: spooky_rv,
110
- });
75
+ // Build a version map from the diff (versions come from _00_list_ref)
76
+ const versionMap = new Map<string, number>();
77
+ for (const item of toFetch) {
78
+ versionMap.set(encodeRecordId(item.id), item.version);
111
79
  }
80
+ const addedIds = new Set(added.map((item) => encodeRecordId(item.id)));
81
+
82
+ // Fetch records from remote — avoid SELECT *, <subquery> FROM $param
83
+ // pattern which drops the * fields in SurrealDB v3 (known bug).
84
+ // Versions are already known from the diff's list_ref data.
85
+ //
86
+ // Chunked so a genuinely cold load lands progressively: one response
87
+ // holding thousands of bodies, then one transaction MERGEing all of them,
88
+ // was a single main-thread stall and a memory spike on top of it.
89
+ let remoteFetchMs = 0;
90
+ const remoteResults: RecordWithId[] = [];
91
+ for (let i = 0; i < toFetch.length; i += FETCH_CHUNK) {
92
+ const idsToFetch = toFetch.slice(i, i + FETCH_CHUNK).map((x) => x.id);
93
+ const remoteFetchStart = performance.now();
94
+ const [chunkResults] = await this.remote.query<[RecordWithId[]]>(
95
+ 'SELECT * FROM $idsToFetch',
96
+ { idsToFetch }
97
+ );
98
+ remoteFetchMs += performance.now() - remoteFetchStart;
99
+
100
+ // Prepare batch for cache (which handles both DB and DBSP)
101
+ const cacheBatch: CacheRecord[] = [];
102
+ for (const record of chunkResults ?? []) {
103
+ if (!record?.id) {
104
+ this.logger.warn(
105
+ {
106
+ record,
107
+ idsToFetch,
108
+ Category: 'sp00ky-client::SyncEngine::syncRecords',
109
+ },
110
+ 'Remote record has no id (possibly deleted). Skipping record'
111
+ );
112
+ continue;
113
+ }
114
+ remoteResults.push(record);
115
+ const fullId = encodeRecordId(record.id);
116
+ const table = record.id.table.toString();
117
+ const version = versionMap.get(fullId) ?? 0;
118
+
119
+ const localVersion = this.cache.lookup(fullId);
120
+ if (localVersion && version <= localVersion) {
121
+ this.logger.info(
122
+ {
123
+ recordId: fullId,
124
+ version,
125
+ localVersion,
126
+ Category: 'sp00ky-client::SyncEngine::syncRecords',
127
+ },
128
+ 'Local version is higher than remote version. Skipping record'
129
+ );
130
+ continue;
131
+ }
132
+ const tableSchema = this.schema.tables.find((t) => t.name === table);
133
+ const cleanedRecord = tableSchema
134
+ ? cleanRecord(tableSchema.columns, record)
135
+ : record;
136
+
137
+ cacheBatch.push({
138
+ table,
139
+ op: addedIds.has(fullId) ? 'CREATE' : 'UPDATE',
140
+ record: cleanedRecord as RecordWithId,
141
+ version,
142
+ });
143
+ }
112
144
 
113
- // Use CacheModule to handle both local DB and DBSP ingestion
114
- if (cacheBatch.length > 0) {
115
- await this.cache.saveBatch(cacheBatch);
145
+ // Use CacheModule to handle both local DB and DBSP ingestion
146
+ if (cacheBatch.length > 0) {
147
+ await this.cache.saveBatch(cacheBatch);
148
+ }
116
149
  }
117
150
 
118
151
  this.events.emit(SyncEventTypes.RemoteDataIngested, {
119
152
  records: remoteResults,
120
153
  });
154
+
155
+ return { remoteFetchMs, stillRemoteIds, confirmedRemovedIds };
121
156
  }
122
157
 
123
158
  /**
124
159
  * Handle records that exist locally but not in remote array.
160
+ *
161
+ * "Removed" here is a derived signal: the SSP's `_00_list_ref` array no
162
+ * longer references a record that exists locally. That can mean the row
163
+ * was genuinely deleted upstream — but it can also be a benign race
164
+ * (e.g. a record we just created hasn't propagated into the SSP's
165
+ * incantation list yet). Before deleting locally we verify against
166
+ * upstream SurrealDB: if the row still exists there, skip the delete.
167
+ *
168
+ * On verification failure we skip deletion too. Losing a stale local
169
+ * row to a later sync round is recoverable; deleting a fresh row that
170
+ * upstream still has is not.
125
171
  */
126
- private async handleRemovedRecords(removed: RecordId[]): Promise<void> {
172
+ private async handleRemovedRecords(
173
+ removed: RecordId[]
174
+ ): Promise<{ stillRemoteIds: string[]; confirmedRemovedIds: string[] }> {
127
175
  this.logger.debug(
128
176
  {
129
177
  removed: removed.map((r) => r.toString()),
130
- Category: 'spooky-client::SyncEngine::handleRemovedRecords',
178
+ Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
131
179
  },
132
180
  'Checking removed records'
133
181
  );
134
182
 
135
- let existingRemoteIds = new Set<string>();
183
+ // Confirm which of the "removed" ids still exist remotely by selecting the
184
+ // records directly from the id array (the records ARE the FROM target).
185
+ //
186
+ // The exact query form matters on SurrealDB v3.x:
187
+ // - `WHERE id IN $ids` is broken: record-id `IN` matches nothing, so every
188
+ // removed id looked gone and live local records got deleted (a fresh
189
+ // collection vanished mid-session). Do NOT use `IN`.
190
+ // - `SELECT id FROM $ids` — a FIELD projection over a record-id ARRAY —
191
+ // errors "Specify a database to use" on the deployed engine. The catch
192
+ // below then swallowed it and skipped EVERY deletion, so nothing could be
193
+ // deleted anywhere (games, comments, …). Do NOT project a field over the
194
+ // array. (`SELECT * FROM $ids` works but pulls full records — wasteful.)
195
+ // - `SELECT VALUE id FROM $ids` works: a flat array of ids with a NONE entry
196
+ // for each id that no longer exists. We filter the NONE entries out; the
197
+ // survivors are the ids still present upstream.
198
+ let existingRemoteIds: Set<string>;
136
199
  try {
137
- const [existingRemote] = await this.remote.query<[{ id: RecordId }[]]>('SELECT id FROM $ids', {
138
- ids: removed,
139
- });
140
- existingRemoteIds = new Set(existingRemote.map((r) => encodeRecordId(r.id)));
141
- } catch {
142
- // If remote check fails (e.g., SurrealDB parameter serialization issue),
143
- // proceed with deletion — the caller has already determined these should be removed
144
- this.logger.debug(
145
- { Category: 'spooky-client::SyncEngine::handleRemovedRecords' },
146
- 'Remote existence check failed, proceeding with deletion'
200
+ const [existing] = await this.remote.query<[(RecordId | null | undefined)[]]>(
201
+ 'SELECT VALUE id FROM $ids',
202
+ { ids: removed }
203
+ );
204
+ existingRemoteIds = new Set(
205
+ (existing ?? [])
206
+ .filter((id): id is RecordId => id != null)
207
+ .map((id) => encodeRecordId(id))
147
208
  );
209
+ } catch (err) {
210
+ // Verification failed. Skip deletion entirely — the next sync
211
+ // round re-derives the diff and we get another shot. The
212
+ // alternative (delete on uncertainty) destroys freshly-created
213
+ // rows when the SSP hasn't yet refreshed `_00_list_ref`.
214
+ this.logger.warn(
215
+ {
216
+ err,
217
+ removed: removed.map((r) => r.toString()),
218
+ Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
219
+ },
220
+ 'Remote existence check failed, skipping deletion to avoid clobbering fresh data'
221
+ );
222
+ return { stillRemoteIds: [], confirmedRemovedIds: [] };
148
223
  }
149
224
 
225
+ // Ids that left the view's list_ref but STILL exist upstream — not deletions,
226
+ // just a view-membership change (e.g. a record whose field changed so it no
227
+ // longer matches the query). The caller drops these from `localArray` so the
228
+ // poll's diff stops re-flagging them every tick (the `job:` churn).
229
+ const stillRemoteIds: string[] = [];
230
+ const confirmedRemovedIds: string[] = [];
150
231
  for (const recordId of removed) {
151
232
  const recordIdStr = encodeRecordId(recordId);
152
233
  if (!existingRemoteIds.has(recordIdStr)) {
153
234
  this.logger.debug(
154
235
  {
155
236
  recordId: recordIdStr,
156
- Category: 'spooky-client::SyncEngine::handleRemovedRecords',
237
+ Category: 'sp00ky-client::SyncEngine::handleRemovedRecords',
157
238
  },
158
239
  'Deleting confirmed removed record'
159
240
  );
160
-
161
241
  // Use CacheModule to handle both local DB and DBSP deletion
162
242
  await this.cache.delete(recordId.table.name, recordIdStr);
243
+ confirmedRemovedIds.push(recordIdStr);
244
+ } else {
245
+ stillRemoteIds.push(recordIdStr);
163
246
  }
164
247
  }
248
+ return { stillRemoteIds, confirmedRemovedIds };
165
249
  }
166
250
  }
@@ -1,5 +1,6 @@
1
- import { createEventSystem, EventDefinition, EventSystem } from '../../../events/index';
2
- import { RecordVersionArray } from '../../../types';
1
+ import type { EventDefinition, EventSystem } from '../../../events/index';
2
+ import { createEventSystem } from '../../../events/index';
3
+ import type { RecordVersionArray, SyncHealth } from '../../../types';
3
4
 
4
5
  export const SyncQueueEventTypes = {
5
6
  MutationEnqueued: 'MUTATION_ENQUEUED',
@@ -36,6 +37,7 @@ export const SyncEventTypes = {
36
37
  QueryUpdated: 'SYNC_QUERY_UPDATED',
37
38
  RemoteDataIngested: 'SYNC_REMOTE_DATA_INGESTED',
38
39
  MutationRolledBack: 'SYNC_MUTATION_ROLLED_BACK',
40
+ SyncHealthChanged: 'SYNC_HEALTH_CHANGED',
39
41
  } as const;
40
42
 
41
43
  export type SyncEventTypeMap = {
@@ -64,6 +66,10 @@ export type SyncEventTypeMap = {
64
66
  error: string;
65
67
  }
66
68
  >;
69
+ [SyncEventTypes.SyncHealthChanged]: EventDefinition<
70
+ typeof SyncEventTypes.SyncHealthChanged,
71
+ SyncHealth
72
+ >;
67
73
  };
68
74
 
69
75
  export type SyncEventSystem = EventSystem<SyncEventTypeMap>;
@@ -73,5 +79,6 @@ export function createSyncEventSystem(): SyncEventSystem {
73
79
  SyncEventTypes.QueryUpdated,
74
80
  SyncEventTypes.RemoteDataIngested,
75
81
  SyncEventTypes.MutationRolledBack,
82
+ SyncEventTypes.SyncHealthChanged,
76
83
  ]);
77
84
  }