@spooky-sync/core 0.0.1-canary.26 → 0.0.1-canary.261

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 (231) hide show
  1. package/AGENTS.md +78 -0
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +2355 -81
  4. package/dist/index.js +13247 -2595
  5. package/dist/otel/index.d.ts +2 -2
  6. package/dist/otel/index.js +6 -6
  7. package/dist/sqlite-open.js +331 -0
  8. package/dist/sqlite-worker.d.ts +1 -0
  9. package/dist/sqlite-worker.js +439 -0
  10. package/dist/tabs-broker-worker.d.ts +8 -0
  11. package/dist/tabs-broker-worker.js +472 -0
  12. package/dist/types.d.ts +793 -46
  13. package/package.json +16 -8
  14. package/scripts/check-broker-bundle.mjs +33 -0
  15. package/skills/{spooky-core → sp00ky-core}/SKILL.md +30 -12
  16. package/skills/{spooky-core → sp00ky-core}/references/auth.md +1 -1
  17. package/skills/{spooky-core → sp00ky-core}/references/config.md +2 -2
  18. package/src/boot/auth-flip.saga.test.ts +82 -0
  19. package/src/boot/auth-flip.saga.ts +62 -0
  20. package/src/boot/boot.saga.test.ts +151 -0
  21. package/src/boot/boot.saga.ts +128 -0
  22. package/src/boot/bucket-switch.saga.test.ts +187 -0
  23. package/src/boot/bucket-switch.saga.ts +131 -0
  24. package/src/boot/preload.saga.test.ts +51 -0
  25. package/src/boot/preload.saga.ts +31 -0
  26. package/src/bucket-blurhash.test.ts +148 -0
  27. package/src/build-globals.d.ts +12 -0
  28. package/src/client/bucket-handle.test.ts +117 -0
  29. package/src/client/bucket-handle.ts +227 -0
  30. package/src/client/router.test.ts +56 -0
  31. package/src/client/router.ts +96 -0
  32. package/src/client/runtime.test.ts +192 -0
  33. package/src/client/runtime.ts +296 -0
  34. package/src/client/services.ts +386 -0
  35. package/src/client/sp00ky-client.test.ts +264 -0
  36. package/src/client/sp00ky-client.ts +507 -0
  37. package/src/events/events.test.ts +2 -1
  38. package/src/events/index.ts +3 -0
  39. package/src/index.ts +37 -2
  40. package/src/kernel/constants.test.ts +19 -0
  41. package/src/kernel/constants.ts +61 -0
  42. package/src/kernel/effects.test.ts +40 -0
  43. package/src/kernel/effects.ts +161 -0
  44. package/src/kernel/events.ts +56 -0
  45. package/src/kernel/interpreter.test.ts +116 -0
  46. package/src/kernel/interpreter.ts +148 -0
  47. package/src/kernel/saga.test.ts +89 -0
  48. package/src/kernel/saga.ts +73 -0
  49. package/src/modules/app-release/index.test.ts +125 -0
  50. package/src/modules/app-release/index.ts +209 -0
  51. package/src/modules/auth/auth.local-first.test.ts +141 -0
  52. package/src/modules/auth/events/index.ts +9 -2
  53. package/src/modules/auth/impersonation-banner.ts +112 -0
  54. package/src/modules/auth/impersonation.test.ts +282 -0
  55. package/src/modules/auth/impersonation.ts +179 -0
  56. package/src/modules/auth/index.ts +344 -27
  57. package/src/modules/crdt/crdt-field.ts +294 -0
  58. package/src/modules/crdt/crdt-hydration.test.ts +210 -0
  59. package/src/modules/crdt/crdt-reconnect.test.ts +195 -0
  60. package/src/modules/crdt/index.ts +463 -0
  61. package/src/modules/crdt/loro-loader.ts +25 -0
  62. package/src/modules/devtools/flags.ts +349 -0
  63. package/src/modules/devtools/index.ts +529 -47
  64. package/src/modules/devtools/notify-throttle.test.ts +154 -0
  65. package/src/modules/devtools/state-shape.test.ts +149 -0
  66. package/src/modules/devtools/storage-info.test.ts +79 -0
  67. package/src/modules/devtools/storage-info.ts +168 -0
  68. package/src/modules/devtools/versions.test.ts +74 -0
  69. package/src/modules/devtools/versions.ts +110 -0
  70. package/src/modules/feature-flag/index.test.ts +251 -0
  71. package/src/modules/feature-flag/index.ts +316 -0
  72. package/src/modules/ref-tables.test.ts +91 -0
  73. package/src/modules/ref-tables.ts +88 -0
  74. package/src/mutation/jobs.test.ts +25 -0
  75. package/src/mutation/jobs.ts +41 -0
  76. package/src/mutation/mutation-id.test.ts +37 -0
  77. package/src/mutation/mutation-id.ts +35 -0
  78. package/src/mutation/push.saga.test.ts +285 -0
  79. package/src/mutation/push.saga.ts +215 -0
  80. package/src/mutation/rows.test.ts +201 -0
  81. package/src/mutation/rows.ts +377 -0
  82. package/src/mutation/tray.saga.test.ts +63 -0
  83. package/src/mutation/tray.saga.ts +48 -0
  84. package/src/mutation/write.saga.test.ts +163 -0
  85. package/src/mutation/write.saga.ts +166 -0
  86. package/src/otel/index.ts +13 -10
  87. package/src/query/env.test.ts +23 -0
  88. package/src/query/env.ts +56 -0
  89. package/src/query/fetch.saga.test.ts +156 -0
  90. package/src/query/fetch.saga.ts +115 -0
  91. package/src/query/hash.test.ts +14 -0
  92. package/src/query/hash.ts +18 -0
  93. package/src/query/id-set-plan.test.ts +132 -0
  94. package/src/query/lifecycle.saga.test.ts +122 -0
  95. package/src/query/lifecycle.saga.ts +101 -0
  96. package/src/query/materialize.saga.test.ts +82 -0
  97. package/src/query/materialize.saga.ts +75 -0
  98. package/src/query/materialize.test.ts +50 -0
  99. package/src/query/materialize.ts +44 -0
  100. package/src/query/membership.saga.test.ts +317 -0
  101. package/src/query/membership.saga.ts +262 -0
  102. package/src/query/membership.test.ts +118 -0
  103. package/src/query/membership.ts +171 -0
  104. package/src/query/register.saga.test.ts +293 -0
  105. package/src/query/register.saga.ts +226 -0
  106. package/src/query/render-set.test.ts +36 -0
  107. package/src/query/render-set.ts +60 -0
  108. package/src/query/sql.test.ts +62 -0
  109. package/src/query/sql.ts +79 -0
  110. package/src/query/window-query.test.ts +70 -0
  111. package/src/query/window-query.ts +195 -0
  112. package/src/services/blobs/blob-cache.test.ts +359 -0
  113. package/src/services/blobs/blob-cache.ts +603 -0
  114. package/src/services/blobs/blob-manifest.ts +227 -0
  115. package/src/services/blobs/blob-store.test.ts +77 -0
  116. package/src/services/blobs/blob-store.ts +359 -0
  117. package/src/services/blobs/blob.fixture.ts +90 -0
  118. package/src/services/blobs/index.ts +70 -0
  119. package/src/services/database/cache-engine.ts +199 -0
  120. package/src/services/database/connection-supervisor.test.ts +318 -0
  121. package/src/services/database/connection-supervisor.ts +422 -0
  122. package/src/services/database/database.query-timeout.test.ts +140 -0
  123. package/src/services/database/database.responses.test.ts +43 -0
  124. package/src/services/database/database.ts +145 -62
  125. package/src/services/database/engine-factory.ts +33 -0
  126. package/src/services/database/errors.ts +34 -0
  127. package/src/services/database/events/index.ts +2 -1
  128. package/src/services/database/index.ts +7 -0
  129. package/src/services/database/local-migrator.ts +30 -27
  130. package/src/services/database/local.test.ts +64 -0
  131. package/src/services/database/local.ts +491 -67
  132. package/src/services/database/plan-render.test.ts +159 -0
  133. package/src/services/database/plan-render.ts +108 -0
  134. package/src/services/database/relation-resolver.test.ts +467 -0
  135. package/src/services/database/relation-resolver.ts +0 -0
  136. package/src/services/database/remote.ts +222 -15
  137. package/src/services/database/sqlite-cache-engine.test.ts +617 -0
  138. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  139. package/src/services/database/sqlite-cache-engine.ts +1366 -0
  140. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  141. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  142. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  143. package/src/services/database/sqlite-lock-verify.ts +45 -0
  144. package/src/services/database/sqlite-open.test.ts +150 -0
  145. package/src/services/database/sqlite-open.ts +164 -0
  146. package/src/services/database/sqlite-plan-sql.test.ts +104 -0
  147. package/src/services/database/sqlite-plan-sql.ts +153 -0
  148. package/src/services/database/sqlite-projection.test.ts +121 -0
  149. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  150. package/src/services/database/sqlite-select.test.ts +246 -0
  151. package/src/services/database/sqlite-select.ts +131 -0
  152. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  153. package/src/services/database/sqlite-transport.ts +224 -0
  154. package/src/services/database/sqlite-worker.ts +437 -0
  155. package/src/services/database/surql-translate.ts +416 -0
  156. package/src/services/database/surreal-cache-engine.ts +161 -0
  157. package/src/services/logger/index.ts +3 -2
  158. package/src/services/persistence/localstorage.ts +2 -2
  159. package/src/services/persistence/resilient.ts +11 -4
  160. package/src/services/persistence/surrealdb.ts +10 -10
  161. package/src/services/stream-processor/index.ts +796 -84
  162. package/src/services/stream-processor/permissions.test.ts +47 -0
  163. package/src/services/stream-processor/permissions.ts +53 -0
  164. package/src/services/stream-processor/stream-processor.batch.test.ts +186 -0
  165. package/src/services/stream-processor/stream-processor.prime.test.ts +198 -0
  166. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  167. package/src/services/stream-processor/stream-processor.test.ts +1 -1
  168. package/src/services/stream-processor/wasm-types.ts +59 -3
  169. package/src/services/tabs/broker-client.ts +283 -0
  170. package/src/services/tabs/broker.test.ts +327 -0
  171. package/src/services/tabs/coordinator.test.ts +365 -0
  172. package/src/services/tabs/coordinator.ts +633 -0
  173. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  174. package/src/services/tabs/leader-locks.ts +75 -0
  175. package/src/services/tabs/protocol.ts +262 -0
  176. package/src/services/tabs/support.ts +36 -0
  177. package/src/services/tabs/tabs-broker-worker.ts +640 -0
  178. package/src/sp00ky.ts +5 -0
  179. package/src/state/client-state.ts +191 -0
  180. package/src/state/lifecycle.test.ts +118 -0
  181. package/src/state/lifecycle.ts +86 -0
  182. package/src/state/reducers.test.ts +280 -0
  183. package/src/state/reducers.ts +488 -0
  184. package/src/state/selectors.test.ts +149 -0
  185. package/src/state/selectors.ts +184 -0
  186. package/src/sync/connection.saga.test.ts +86 -0
  187. package/src/sync/connection.saga.ts +85 -0
  188. package/src/sync/live.saga.test.ts +178 -0
  189. package/src/sync/live.saga.ts +107 -0
  190. package/src/sync/policy.health.test.ts +56 -0
  191. package/src/sync/policy.test.ts +659 -0
  192. package/src/sync/policy.ts +502 -0
  193. package/src/sync/poll.saga.test.ts +51 -0
  194. package/src/sync/poll.saga.ts +36 -0
  195. package/src/sync/tabs.saga.test.ts +74 -0
  196. package/src/sync/tabs.saga.ts +93 -0
  197. package/src/testing/adapters.ts +133 -0
  198. package/src/testing/build.ts +63 -0
  199. package/src/testing/fake-services.ts +34 -0
  200. package/src/testing/run-pure.test.ts +92 -0
  201. package/src/testing/run-pure.ts +128 -0
  202. package/src/testing/services.ts +17 -0
  203. package/src/types.ts +591 -14
  204. package/src/utils/blurhash.ts +90 -0
  205. package/src/utils/error-classification.test.ts +54 -0
  206. package/src/utils/error-classification.ts +25 -0
  207. package/src/utils/index.ts +79 -13
  208. package/src/utils/parser.test.ts +49 -120
  209. package/src/utils/parser.ts +32 -2
  210. package/src/utils/semver.test.ts +32 -0
  211. package/src/utils/semver.ts +30 -0
  212. package/src/utils/surql.ts +30 -18
  213. package/src/utils/utils.test.ts +2 -1
  214. package/src/utils/withRetry.test.ts +1 -1
  215. package/tsdown.config.ts +86 -1
  216. package/vitest.config.ts +48 -0
  217. package/src/modules/cache/index.ts +0 -241
  218. package/src/modules/cache/types.ts +0 -19
  219. package/src/modules/data/data.test.ts +0 -58
  220. package/src/modules/data/index.ts +0 -879
  221. package/src/modules/sync/engine.ts +0 -173
  222. package/src/modules/sync/events/index.ts +0 -77
  223. package/src/modules/sync/index.ts +0 -3
  224. package/src/modules/sync/queue/index.ts +0 -2
  225. package/src/modules/sync/queue/queue-down.ts +0 -89
  226. package/src/modules/sync/queue/queue-up.ts +0 -223
  227. package/src/modules/sync/scheduler.ts +0 -84
  228. package/src/modules/sync/sync.ts +0 -421
  229. package/src/modules/sync/utils.test.ts +0 -311
  230. package/src/modules/sync/utils.ts +0 -167
  231. 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
+ }
@@ -0,0 +1,25 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { buildJobRecord } from './jobs';
3
+
4
+ const schema = {
5
+ tables: [],
6
+ backends: {
7
+ api: { outboxTable: '_00_job_api', routes: { hello: { args: { name: { optional: false }, tone: { optional: true } } } } },
8
+ bare: { routes: { x: { args: {} } } },
9
+ },
10
+ } as any;
11
+
12
+ describe('buildJobRecord', () => {
13
+ it('builds a pending job row with the route payload and option overrides', () => {
14
+ const { tableName, record } = buildJobRecord(schema, 'api', 'hello', { name: 'a', extra: 1 }, { max_retries: 5, retry_strategy: 'exponential', timeout: 9, delay: 100, assignedTo: 'w1' });
15
+ expect(tableName).toBe('_00_job_api');
16
+ expect(record).toEqual({ path: 'hello', payload: JSON.stringify({ name: 'a', tone: undefined }), status: 'pending', max_retries: 5, retry_strategy: 'exponential', timeout: 9, delay: 100, assigned_to: 'w1' });
17
+ expect(buildJobRecord(schema, 'api', 'hello', { name: 'a' }).record).toMatchObject({ max_retries: 3, retry_strategy: 'linear' });
18
+ });
19
+ it('rejects unknown routes, missing outbox tables and missing required args', () => {
20
+ expect(() => buildJobRecord(schema, 'api', 'nope', {})).toThrow('Route api.nope not found');
21
+ expect(() => buildJobRecord(schema, 'bare', 'x', {})).toThrow('Outbox table for backend bare not found');
22
+ expect(() => buildJobRecord(schema, 'api', 'hello', {})).toThrow('Missing required argument name');
23
+ expect(() => buildJobRecord({ tables: [] } as any, 'api', 'hello', {})).toThrow('Route api.hello not found');
24
+ });
25
+ });
@@ -0,0 +1,41 @@
1
+ import type { SchemaStructure } from '@spooky-sync/query-builder';
2
+ import type { RunOptions } from '../types';
3
+
4
+ /**
5
+ * Build the outbox job record for a backend route and resolve its table.
6
+ * Every job is a single execution; recurring work is declared server-side.
7
+ */
8
+ export function buildJobRecord(
9
+ schema: SchemaStructure,
10
+ backend: string,
11
+ path: string,
12
+ data: Record<string, unknown>,
13
+ options?: RunOptions
14
+ ): { tableName: string; record: Record<string, unknown> } {
15
+ const backends = (schema as { backends?: Record<string, { outboxTable?: string; routes?: Record<string, { args: Record<string, { optional: boolean }> }> }> }).backends;
16
+ const route = backends?.[backend]?.routes?.[path];
17
+ if (!route) throw new Error(`Route ${backend}.${path} not found`);
18
+ const tableName = backends?.[backend]?.outboxTable;
19
+ if (!tableName) throw new Error(`Outbox table for backend ${backend} not found`);
20
+
21
+ const payload: Record<string, unknown> = {};
22
+ for (const argName of Object.keys(route.args)) {
23
+ const arg = route.args[argName];
24
+ if (data[argName] === undefined && arg.optional === false) throw new Error(`Missing required argument ${argName}`);
25
+ payload[argName] = data[argName];
26
+ }
27
+
28
+ const record: Record<string, unknown> = {
29
+ path,
30
+ payload: JSON.stringify(payload),
31
+ // Explicit: the schema's server-side DEFAULT does not apply to an
32
+ // optimistic local create, and in-flight indicators key on `pending`.
33
+ status: 'pending',
34
+ max_retries: options?.max_retries ?? 3,
35
+ retry_strategy: options?.retry_strategy ?? 'linear',
36
+ };
37
+ if (options?.timeout != null) record.timeout = options.timeout;
38
+ if (options?.delay != null) record.delay = options.delay;
39
+ if (options?.assignedTo) record.assigned_to = options.assignedTo;
40
+ return { tableName, record };
41
+ }
@@ -0,0 +1,37 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { mintMutationId, mutationOwnerTabId } from './mutation-id';
3
+
4
+ describe('mutationOwnerTabId (raw ids)', () => {
5
+ it('mints with the fallback tab id when none is given', () => {
6
+ const id = mintMutationId();
7
+ expect(id.startsWith('_00_pending_mutations:')).toBe(true);
8
+ expect(mutationOwnerTabId(id)).toMatch(/^[a-z0-9]+$/);
9
+ });
10
+ it('accepts an id without the table prefix', () => {
11
+ expect(mutationOwnerTabId('1700000000000_0001_tab9')).toBe('tab9');
12
+ expect(mutationOwnerTabId('1700000000000')).toBeNull();
13
+ });
14
+ });
15
+
16
+ // The old `_00_pending_mutations:${Date.now()}` collided within a millisecond
17
+ // (guaranteed once multiple tabs share a store) and never actually ordered the
18
+ // drain. These pin the new id's three properties: unique, sortable, routable.
19
+ describe('mutation ids', () => {
20
+ it('never collides within a burst', () => {
21
+ const ids = new Set(Array.from({ length: 1000 }, () => mintMutationId('tabx')));
22
+ expect(ids.size).toBe(1000);
23
+ });
24
+
25
+ it('sorts lexicographically in mint order (ORDER BY id is chronological)', () => {
26
+ const ids = Array.from({ length: 200 }, () => mintMutationId('tabx'));
27
+ expect([...ids].sort()).toEqual(ids);
28
+ });
29
+
30
+ it('routes back to the owning tab', () => {
31
+ expect(mutationOwnerTabId(mintMutationId('tab-abc'))).toBe('tab-abc');
32
+ });
33
+
34
+ it('returns null for a legacy numeric id instead of misrouting', () => {
35
+ expect(mutationOwnerTabId('_00_pending_mutations:1753875000000')).toBeNull();
36
+ });
37
+ });
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Outbox mutation ids. Previously `_00_pending_mutations:${Date.now()}`, which
3
+ * (a) collides when two mutations land in the same millisecond, a real case
4
+ * once multiple tabs share one store, and (b) never actually ordered the
5
+ * drain, because `loadFromDatabase` sorted by a `created_at` field that does
6
+ * not exist on the table. The new shape is sortable AND collision-free:
7
+ *
8
+ * <13-digit zero-padded ms timestamp>_<4-digit base36 seq>_<tabId>
9
+ *
10
+ * Lexicographic order == chronological order (per tab; cross-tab within-ms
11
+ * ordering is arbitrary, which matches reality), so `ORDER BY id` in the
12
+ * drain is now meaningful. The tabId suffix also routes rollbacks back to the
13
+ * tab that owns the mutation in shared-tabs mode.
14
+ */
15
+
16
+ let seq = 0;
17
+
18
+ /** Tab identity for mutation ids in SOLO mode, minted once per session. In
19
+ * shared-tabs mode the coordinator's tabId is passed in instead. */
20
+ const FALLBACK_TAB_ID = Math.random().toString(36).slice(2, 8);
21
+
22
+ export function mintMutationId(tabId?: string): string {
23
+ const ts = Date.now().toString().padStart(13, '0');
24
+ const n = (seq = (seq + 1) % 36 ** 4).toString(36).padStart(4, '0');
25
+ return `_00_pending_mutations:${ts}_${n}_${tabId ?? FALLBACK_TAB_ID}`;
26
+ }
27
+
28
+ /** The tab that created the mutation, or null for a legacy numeric id. */
29
+ export function mutationOwnerTabId(mutationId: string): string | null {
30
+ const raw = mutationId.startsWith('_00_pending_mutations:')
31
+ ? mutationId.slice('_00_pending_mutations:'.length)
32
+ : mutationId;
33
+ const parts = raw.split('_');
34
+ return parts.length >= 3 ? parts[parts.length - 1] : null;
35
+ }
@@ -0,0 +1,285 @@
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 { drain, loadOutbox, refreshFailedCount, rollback } from './push.saga';
8
+ import type { StatementResult } from '../kernel/effects';
9
+ import type { PendingMutationRow } from './rows';
10
+
11
+ const env = defaultEnv({ tables: [{ name: 'thing', columns: {} }] } as any, { outboxBatchSize: 2 });
12
+ const ok = (result: unknown = null): StatementResult => ({ status: 'OK', result });
13
+ const err = (error: string): StatementResult => ({ status: 'ERR', error });
14
+ const pendingRow = (n: number, type: PendingMutationRow['mutationType'] = 'create', extra: Partial<PendingMutationRow> = {}) => ({
15
+ id: `_00_pending_mutations:m${n}`,
16
+ mutationType: type,
17
+ recordId: `thing:${n}`,
18
+ tableName: 'thing',
19
+ data: type === 'delete' ? undefined : { a: n },
20
+ beforeRecord: type === 'create' ? undefined : { id: `thing:${n}`, a: 0, _00_rv: 7 },
21
+ createdAt: 1,
22
+ v: 2,
23
+ ...extra,
24
+ });
25
+ const items = (...ns: number[]) => ns.map((n) => buildOutboxItem({ id: `_00_pending_mutations:m${n}`, recordId: `thing:${n}`, type: 'create' }));
26
+ const stateWith = (rows: number[], ...extra: Parameters<typeof buildState>[1][]) =>
27
+ buildState([buildEntry({ def: { hash: 'q', tableName: 'thing' } })], R.outboxReplace(items(...rows)), ...extra);
28
+
29
+ describe('drain', () => {
30
+ it('re-types stored payloads from the schema before pushing (a stored record field is a string)', async () => {
31
+ const typedEnv = defaultEnv({ tables: [{ name: 'thing', columns: { owner: { recordId: true } } }] } as any, { outboxBatchSize: 2 });
32
+ let vars: any = null;
33
+ await runPure(drain(typedEnv), {
34
+ state: stateWith([1]),
35
+ handlers: {
36
+ 'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [[pendingRow(1, 'create', { data: { owner: 'user:u1' } })]] : []),
37
+ 'remote.query': (e: any) => ((vars = e.vars), [ok()]),
38
+ },
39
+ });
40
+ expect(vars.d0_owner).toEqual(new RecordId('user', 'u1'));
41
+ });
42
+
43
+ it('pushes batches in FIFO order, acks each accepted row, deletes its pending row, then loops', async () => {
44
+ const pushed: string[] = [];
45
+ const out = await runPure(drain(env), {
46
+ state: stateWith([1, 2, 3]),
47
+ now: 500,
48
+ handlers: {
49
+ 'local.query': (e: any) => {
50
+ if (e.sql === 'SELECT * FROM $ids') return [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))];
51
+ return [];
52
+ },
53
+ 'remote.query': (e: any) => {
54
+ pushed.push(e.sql);
55
+ return e.sql.split(';\n').map(() => ok());
56
+ },
57
+ },
58
+ });
59
+ expect(pushed).toEqual(['CREATE ONLY $id0 SET a = $d0_a;\nCREATE ONLY $id1 SET a = $d1_a', 'CREATE ONLY $id0 SET a = $d0_a']);
60
+ expect(out.state.outbox.every((i) => i.status === 'acked' && i.ackedAt === 500)).toBe(true);
61
+ expect(out.log.filter((e) => e.kind === 'local.query' && (e as any).sql === 'DELETE $mid')).toHaveLength(3);
62
+ expect(out.emitted.filter((e) => e.type === 'mutation:settled')).toHaveLength(3);
63
+ expect(out.timers.get('ack-prune')).toEqual({ ms: 30_000, event: { type: 'AckPrune' } });
64
+ expect(out.dispatched.filter((d) => d.type === 'SyncOutcome')).toEqual([{ type: 'SyncOutcome', ok: true, error: undefined }, { type: 'SyncOutcome', ok: true, error: undefined }]);
65
+ });
66
+
67
+ it('a rejected statement rolls back only that row; the rest of the batch is acked', async () => {
68
+ const out = await runPure(drain(env), {
69
+ state: stateWith([1, 2]),
70
+ handlers: {
71
+ 'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [[pendingRow(1), pendingRow(2)]] : []),
72
+ 'remote.query': () => [err('permission denied'), ok()],
73
+ 'local.execute': () => undefined,
74
+ 'ssp.ingest': () => undefined,
75
+ },
76
+ });
77
+ expect(out.state.outbox.map((i) => [i.id, i.status])).toEqual([['_00_pending_mutations:m2', 'acked']]);
78
+ expect(out.state.failedCount).toBe(1);
79
+ expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '_00_pending_mutations:m1', error: 'permission denied' }));
80
+ expect(out.dispatched.at(-1)).toEqual({ type: 'SyncOutcome', ok: true, error: undefined });
81
+ });
82
+
83
+ it('transport failures keep the tail queued behind a backoff timer (thrown, or a network ERR mid-batch, or a short result list)', async () => {
84
+ const thrown = await runPure(drain(env), {
85
+ state: stateWith([1, 2]),
86
+ handlers: {
87
+ 'local.query': () => [[pendingRow(1), pendingRow(2)]],
88
+ 'remote.query': () => {
89
+ throw new Error('socket closed');
90
+ },
91
+ },
92
+ });
93
+ expect(thrown.state.outbox.map((i) => i.status)).toEqual(['pending', 'pending']);
94
+ expect(thrown.state.outbox[0].attempts).toBe(1);
95
+ expect(thrown.timers.get('outbox')).toEqual({ ms: 500, event: { type: 'Drain' } });
96
+ expect(thrown.dispatched).toEqual([{ type: 'SyncOutcome', ok: false, error: new Error('socket closed') }]);
97
+ const mid = await runPure(drain(env), {
98
+ state: stateWith([1, 2]),
99
+ handlers: { 'local.query': () => [[pendingRow(1), pendingRow(2)]], 'remote.query': () => [ok(), err('connection reset')] },
100
+ });
101
+ expect(mid.state.outbox.map((i) => [i.status, i.attempts])).toEqual([['acked', 0], ['pending', 1]]);
102
+ expect(mid.timers.get('outbox')!.ms).toBe(500);
103
+ const short = await runPure(drain(env), {
104
+ state: stateWith([1, 2]),
105
+ handlers: { 'local.query': () => [[pendingRow(1), pendingRow(2)]], 'remote.query': () => [ok()] },
106
+ });
107
+ expect(short.state.outbox.map((i) => i.status)).toEqual(['acked', 'pending']);
108
+ const undefinedRows = await runPure(drain(env), { state: stateWith([1]), handlers: { 'local.query': () => undefined } });
109
+ expect(undefinedRows.state.outbox).toEqual([]);
110
+ const notArray = await runPure(drain(env), {
111
+ state: stateWith([1]),
112
+ handlers: { 'local.query': () => [[pendingRow(1)]], 'remote.query': () => 'nope' },
113
+ });
114
+ expect(notArray.timers.has('outbox')).toBe(true);
115
+ });
116
+
117
+ it('a request rejected as a whole with an application error rolls back the head and continues', async () => {
118
+ let calls = 0;
119
+ const out = await runPure(drain(env), {
120
+ state: stateWith([1, 2]),
121
+ handlers: {
122
+ 'local.query': (e: any) => (e.sql === 'SELECT * FROM $ids' ? [e.vars.ids.map((id: RecordId) => pendingRow(Number(String(id.id).slice(1))))] : []),
123
+ 'remote.query': () => {
124
+ calls++;
125
+ if (calls === 1) throw 'Parse error at line 1';
126
+ return [ok()];
127
+ },
128
+ 'local.execute': () => undefined,
129
+ 'ssp.ingest': () => undefined,
130
+ },
131
+ });
132
+ expect(calls).toBe(2);
133
+ expect(out.state.failedCount).toBe(1);
134
+ expect(out.state.outbox.map((i) => [i.id, i.status])).toEqual([['_00_pending_mutations:m2', 'acked']]);
135
+ const asError = await runPure(drain(env), {
136
+ state: stateWith([1]),
137
+ handlers: {
138
+ 'local.query': () => [[pendingRow(1)]],
139
+ 'remote.query': () => {
140
+ throw new Error('Parse error at line 1');
141
+ },
142
+ 'local.execute': (e: any) => {
143
+ if (e.vars.failed) expect(e.vars.failed.error.message).toBe('Parse error at line 1');
144
+ },
145
+ 'ssp.ingest': () => undefined,
146
+ },
147
+ });
148
+ expect(asError.state.failedCount).toBe(1);
149
+ });
150
+
151
+ it('skips pending rows the store no longer has, does nothing as a follower or when empty, tolerates a failed row delete', async () => {
152
+ const gone = await runPure(drain(env), { state: stateWith([1]), handlers: { 'local.query': () => [[]] } });
153
+ expect(gone.state.outbox).toEqual([]);
154
+ expect(gone.log.filter((e) => e.kind === 'remote.query')).toHaveLength(0);
155
+ const follower = await runPure(drain(env), { state: { ...stateWith([1]), tabRole: 'follower' } });
156
+ expect(follower.log.filter((e) => e.kind === 'local.query')).toHaveLength(0);
157
+ const empty = await runPure(drain(env), { state: buildState() });
158
+ expect(empty.log.filter((e) => e.kind === 'local.query')).toHaveLength(0);
159
+ const delFail = await runPure(drain(env), {
160
+ state: stateWith([1]),
161
+ handlers: {
162
+ 'local.query': (e: any) => {
163
+ if (e.sql === 'DELETE $mid') throw new Error('locked');
164
+ return [[pendingRow(1)]];
165
+ },
166
+ 'remote.query': () => [ok()],
167
+ },
168
+ });
169
+ expect(delFail.state.outbox[0].status).toBe('acked');
170
+ expect(delFail.emitted).toContainEqual(expect.objectContaining({ level: 'error' }));
171
+ });
172
+ });
173
+
174
+ describe('rollback', () => {
175
+ it('create: tray move first, local delete, circuit DELETE, version dropped, owner relay when leading', async () => {
176
+ const order: string[] = [];
177
+ const state = { ...stateWith([1]), tabRole: 'leader' as const, tabId: 'tab-a' };
178
+ const row = pendingRow(1, 'create', { id: '_00_pending_mutations:1700000000000_0001_tabz' });
179
+ const out = await runPure(rollback(env, row, { message: 'denied', kind: 'application' }), {
180
+ state: R.setVersions([['thing:1', 1]])(state),
181
+ handlers: {
182
+ 'local.execute': (e: any) => void order.push(e.query.sql.includes('_00_failed') || e.query.sql.includes('CREATE ONLY $fid') ? 'tray' : 'revert'),
183
+ 'ssp.ingest': (e: any) => void order.push(`circuit:${e.records[0].op}`),
184
+ },
185
+ });
186
+ expect(order).toEqual(['tray', 'revert', 'circuit:DELETE']);
187
+ expect(out.state.versions.has('thing:1')).toBe(false);
188
+ expect(out.state.failedCount).toBe(1);
189
+ expect(out.state.dirty.has('q')).toBe(true);
190
+ expect(out.emitted).toContainEqual({ type: 'tabs:sendTo', tabId: 'tabz', message: expect.objectContaining({ type: 'mutation-rolled-back' }) });
191
+ expect(out.emitted).toContainEqual({ type: 'tabs:broadcast', message: { type: 'ingest', records: [expect.objectContaining({ op: 'DELETE' })] } });
192
+ expect(out.emitted).toContainEqual({ type: 'tray:changed', count: 1 });
193
+ expect(out.emitted).toContainEqual({ type: 'tabs:broadcast', message: { type: 'failed-mutations-changed', count: 1 } });
194
+ });
195
+ it('update / delete restore beforeRecord and its version; legacy rows read the server row (or end partial)', async () => {
196
+ const upd = await runPure(rollback(env, pendingRow(1, 'update'), { message: 'x', kind: 'application' }), {
197
+ state: stateWith([1]),
198
+ handlers: { 'local.execute': () => undefined, 'ssp.ingest': (e: any) => expect(e.records[0].op).toBe('UPDATE') },
199
+ });
200
+ expect(upd.state.versions.get('thing:1')).toBe(7);
201
+ const del = await runPure(rollback(env, pendingRow(1, 'delete'), { message: 'x', kind: 'application' }), {
202
+ state: stateWith([1]),
203
+ handlers: { 'local.execute': () => undefined, 'ssp.ingest': (e: any) => expect(e.records[0].op).toBe('CREATE') },
204
+ });
205
+ expect(del.state.versions.get('thing:1')).toBe(7);
206
+ const legacy = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
207
+ state: stateWith([1]),
208
+ handlers: {
209
+ 'remote.query': () => [ok({ id: new RecordId('thing', '1'), a: 9, _00_rv: 2 })],
210
+ 'local.execute': (e: any) => {
211
+ if (e.query.sql.includes('CREATE ONLY $fid')) expect(e.vars.failed.revert).toBe('full');
212
+ },
213
+ 'ssp.ingest': () => undefined,
214
+ },
215
+ });
216
+ expect(legacy.state.versions.get('thing:1')).toBe(2);
217
+ const partial = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
218
+ state: stateWith([1]),
219
+ handlers: {
220
+ 'remote.query': () => {
221
+ throw new Error('offline');
222
+ },
223
+ 'local.execute': (e: any) => expect(e.vars.failed.revert).toBe('partial'),
224
+ 'ssp.ingest': () => undefined,
225
+ },
226
+ });
227
+ expect(partial.log.filter((e) => e.kind === 'local.execute')).toHaveLength(1);
228
+ const errRow = await runPure(rollback(env, pendingRow(1, 'update', { beforeRecord: undefined }), { message: 'x', kind: 'application' }), {
229
+ state: stateWith([1]),
230
+ handlers: { 'remote.query': () => [err('nope')], 'local.execute': () => undefined, 'ssp.ingest': () => undefined },
231
+ });
232
+ expect(errRow.state.failedCount).toBe(1);
233
+ });
234
+ it('every local step is best-effort: tray move, revert and circuit failures are logged', async () => {
235
+ const out = await runPure(rollback(env, pendingRow(1, 'update'), { message: 'x', kind: 'unreplayable' }), {
236
+ state: stateWith([1]),
237
+ handlers: {
238
+ 'local.execute': () => {
239
+ throw new Error('disk');
240
+ },
241
+ 'ssp.ingest': () => {
242
+ throw new Error('wasm');
243
+ },
244
+ },
245
+ });
246
+ expect(out.emitted.filter((e) => e.type === 'log')).toHaveLength(3);
247
+ expect(out.state.outbox).toEqual([]);
248
+ });
249
+ });
250
+
251
+ describe('loadOutbox / refreshFailedCount', () => {
252
+ it('mirrors pending rows, sends unreplayable ones to the tray, refreshes the count, starts a drain', async () => {
253
+ const out = await runPure(loadOutbox(env), {
254
+ state: buildState(),
255
+ handlers: {
256
+ 'local.query': (e: any) => {
257
+ if (e.sql.startsWith('SELECT * FROM _00_pending_mutations'))
258
+ return [[pendingRow(1), { id: '_00_pending_mutations:bad', mutationType: 'create', recordId: 'thing:9' }, { tableName: 'thing' }, { mutationType: 'delete' }, 'junk']];
259
+ if (e.sql.startsWith('SELECT count()')) return [[{ count: 4 }]];
260
+ return [];
261
+ },
262
+ 'local.execute': () => undefined,
263
+ 'ssp.ingest': () => undefined,
264
+ },
265
+ });
266
+ expect(out.state.outbox.map((i) => i.id)).toEqual(['_00_pending_mutations:m1']);
267
+ expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '_00_pending_mutations:bad' }));
268
+ expect(out.emitted).toContainEqual(expect.objectContaining({ type: 'mutation:rolled-back', mutationId: '' }));
269
+ expect(out.state.failedCount).toBe(4);
270
+ expect(out.dispatched).toEqual([{ type: 'Drain' }]);
271
+ const empty = await runPure(loadOutbox(env), { state: buildState(), handlers: { 'local.query': () => [] } });
272
+ expect(empty.dispatched).toEqual([]);
273
+ const missingTable = await runPure(refreshFailedCount(), {
274
+ state: R.setFailedCount(2)(buildState()),
275
+ handlers: {
276
+ 'local.query': () => {
277
+ throw new Error('no table');
278
+ },
279
+ },
280
+ });
281
+ expect(missingTable.state.failedCount).toBe(2);
282
+ const noRows = await runPure(refreshFailedCount(), { state: R.setFailedCount(2)(buildState()), handlers: { 'local.query': () => [[]] } });
283
+ expect(noRows.state.failedCount).toBe(0);
284
+ });
285
+ });