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

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 (289) hide show
  1. package/AGENTS.md +34 -15
  2. package/README.md +56 -16
  3. package/dist/index.d.ts +1136 -1846
  4. package/dist/index.js +10168 -11267
  5. package/dist/types.d.ts +22 -79
  6. package/package.json +8 -4
  7. package/skills/sp00ky-core/SKILL.md +18 -0
  8. package/src/boot/auth-flip.saga.test.ts +82 -0
  9. package/src/boot/auth-flip.saga.ts +62 -0
  10. package/src/boot/boot.saga.test.ts +151 -0
  11. package/src/boot/boot.saga.ts +128 -0
  12. package/src/boot/bucket-switch.saga.test.ts +158 -0
  13. package/src/boot/bucket-switch.saga.ts +115 -0
  14. package/src/boot/preload.saga.test.ts +51 -0
  15. package/src/boot/preload.saga.ts +31 -0
  16. package/src/client/bucket-handle.test.ts +117 -0
  17. package/src/client/bucket-handle.ts +227 -0
  18. package/src/client/router.test.ts +56 -0
  19. package/src/client/router.ts +94 -0
  20. package/src/client/runtime.test.ts +192 -0
  21. package/src/client/runtime.ts +296 -0
  22. package/src/client/services.ts +349 -0
  23. package/src/client/sp00ky-client.test.ts +241 -0
  24. package/src/client/sp00ky-client.ts +482 -0
  25. package/src/index.ts +1 -0
  26. package/src/kernel/constants.test.ts +19 -0
  27. package/src/kernel/constants.ts +54 -0
  28. package/src/kernel/effects.test.ts +40 -0
  29. package/src/kernel/effects.ts +159 -0
  30. package/src/kernel/events.ts +55 -0
  31. package/src/kernel/interpreter.test.ts +116 -0
  32. package/src/kernel/interpreter.ts +143 -0
  33. package/src/kernel/saga.test.ts +89 -0
  34. package/src/kernel/saga.ts +73 -0
  35. package/src/modules/app-release/index.ts +13 -5
  36. package/src/modules/devtools/index.ts +10 -3
  37. package/src/modules/devtools/state-shape.test.ts +4 -1
  38. package/src/modules/feature-flag/index.ts +13 -5
  39. package/src/mutation/jobs.test.ts +25 -0
  40. package/src/mutation/jobs.ts +41 -0
  41. package/src/{modules/data → mutation}/mutation-id.test.ts +12 -0
  42. package/src/mutation/push.saga.test.ts +285 -0
  43. package/src/mutation/push.saga.ts +215 -0
  44. package/src/mutation/rows.test.ts +201 -0
  45. package/src/mutation/rows.ts +377 -0
  46. package/src/mutation/tray.saga.test.ts +63 -0
  47. package/src/mutation/tray.saga.ts +48 -0
  48. package/src/mutation/write.saga.test.ts +163 -0
  49. package/src/mutation/write.saga.ts +166 -0
  50. package/src/query/env.test.ts +23 -0
  51. package/src/query/env.ts +56 -0
  52. package/src/query/fetch.saga.test.ts +156 -0
  53. package/src/query/fetch.saga.ts +109 -0
  54. package/src/query/hash.test.ts +14 -0
  55. package/src/query/hash.ts +18 -0
  56. package/src/{modules/data → query}/id-set-plan.test.ts +12 -2
  57. package/src/query/lifecycle.saga.test.ts +122 -0
  58. package/src/query/lifecycle.saga.ts +101 -0
  59. package/src/query/materialize.saga.test.ts +82 -0
  60. package/src/query/materialize.saga.ts +75 -0
  61. package/src/query/materialize.test.ts +50 -0
  62. package/src/query/materialize.ts +44 -0
  63. package/src/query/membership.saga.test.ts +246 -0
  64. package/src/query/membership.saga.ts +208 -0
  65. package/src/query/membership.test.ts +118 -0
  66. package/src/query/membership.ts +158 -0
  67. package/src/query/register.saga.test.ts +251 -0
  68. package/src/query/register.saga.ts +190 -0
  69. package/src/query/render-set.test.ts +36 -0
  70. package/src/query/render-set.ts +60 -0
  71. package/src/query/sql.test.ts +62 -0
  72. package/src/query/sql.ts +79 -0
  73. package/src/{modules/data → query}/window-query.test.ts +18 -0
  74. package/src/{modules/data → query}/window-query.ts +2 -1
  75. package/src/services/database/connection-supervisor.test.ts +29 -0
  76. package/src/services/database/connection-supervisor.ts +7 -0
  77. package/src/services/database/database.responses.test.ts +43 -0
  78. package/src/services/database/database.ts +25 -10
  79. package/src/services/database/local-migrator.ts +2 -2
  80. package/src/services/database/plan-render.test.ts +1 -1
  81. package/src/services/database/sqlite-cache-engine.test.ts +4 -3
  82. package/src/services/database/sqlite-cache-engine.ts +2 -11
  83. package/src/services/database/sqlite-devtools-queries.integration.test.ts +1 -1
  84. package/src/services/tabs/protocol.ts +7 -3
  85. package/src/sp00ky.ts +5 -1854
  86. package/src/state/client-state.ts +184 -0
  87. package/src/state/lifecycle.test.ts +118 -0
  88. package/src/state/lifecycle.ts +86 -0
  89. package/src/state/reducers.test.ts +280 -0
  90. package/src/state/reducers.ts +476 -0
  91. package/src/state/selectors.test.ts +149 -0
  92. package/src/state/selectors.ts +184 -0
  93. package/src/sync/connection.saga.test.ts +86 -0
  94. package/src/sync/connection.saga.ts +85 -0
  95. package/src/sync/live.saga.test.ts +69 -0
  96. package/src/sync/live.saga.ts +49 -0
  97. package/src/sync/policy.health.test.ts +56 -0
  98. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +31 -3
  99. package/src/{modules/sync/utils.ts → sync/policy.ts} +67 -5
  100. package/src/sync/poll.saga.test.ts +51 -0
  101. package/src/sync/poll.saga.ts +36 -0
  102. package/src/sync/tabs.saga.test.ts +74 -0
  103. package/src/sync/tabs.saga.ts +92 -0
  104. package/src/testing/adapters.ts +133 -0
  105. package/src/testing/build.ts +61 -0
  106. package/src/testing/fake-services.ts +34 -0
  107. package/src/testing/run-pure.test.ts +92 -0
  108. package/src/testing/run-pure.ts +128 -0
  109. package/src/testing/services.ts +17 -0
  110. package/src/types.ts +8 -7
  111. package/src/utils/utils.test.ts +2 -1
  112. package/vitest.config.ts +48 -0
  113. package/coverage/lcov-report/base.css +0 -224
  114. package/coverage/lcov-report/block-navigation.js +0 -87
  115. package/coverage/lcov-report/favicon.png +0 -0
  116. package/coverage/lcov-report/index.html +0 -476
  117. package/coverage/lcov-report/prettify.css +0 -1
  118. package/coverage/lcov-report/prettify.js +0 -2
  119. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  120. package/coverage/lcov-report/sorter.js +0 -210
  121. package/coverage/lcov-report/src/boot/auth-flip.saga.ts.html +0 -271
  122. package/coverage/lcov-report/src/boot/boot.saga.ts.html +0 -469
  123. package/coverage/lcov-report/src/boot/bucket-switch.saga.ts.html +0 -430
  124. package/coverage/lcov-report/src/boot/index.html +0 -161
  125. package/coverage/lcov-report/src/boot/preload.saga.ts.html +0 -178
  126. package/coverage/lcov-report/src/client/bucket-handle.ts.html +0 -766
  127. package/coverage/lcov-report/src/client/index.html +0 -161
  128. package/coverage/lcov-report/src/client/router.ts.html +0 -367
  129. package/coverage/lcov-report/src/client/runtime.ts.html +0 -940
  130. package/coverage/lcov-report/src/client/sp00ky-client.ts.html +0 -1531
  131. package/coverage/lcov-report/src/events/index.html +0 -116
  132. package/coverage/lcov-report/src/events/index.ts.html +0 -877
  133. package/coverage/lcov-report/src/index.html +0 -146
  134. package/coverage/lcov-report/src/index.ts.html +0 -202
  135. package/coverage/lcov-report/src/kernel/constants.ts.html +0 -247
  136. package/coverage/lcov-report/src/kernel/effects.ts.html +0 -562
  137. package/coverage/lcov-report/src/kernel/events.ts.html +0 -250
  138. package/coverage/lcov-report/src/kernel/index.html +0 -176
  139. package/coverage/lcov-report/src/kernel/interpreter.ts.html +0 -514
  140. package/coverage/lcov-report/src/kernel/saga.ts.html +0 -304
  141. package/coverage/lcov-report/src/modules/app-release/index.html +0 -116
  142. package/coverage/lcov-report/src/modules/app-release/index.ts.html +0 -712
  143. package/coverage/lcov-report/src/modules/auth/events/index.html +0 -116
  144. package/coverage/lcov-report/src/modules/auth/events/index.ts.html +0 -142
  145. package/coverage/lcov-report/src/modules/auth/index.html +0 -116
  146. package/coverage/lcov-report/src/modules/auth/index.ts.html +0 -1225
  147. package/coverage/lcov-report/src/modules/crdt/crdt-field.ts.html +0 -967
  148. package/coverage/lcov-report/src/modules/crdt/index.html +0 -146
  149. package/coverage/lcov-report/src/modules/crdt/index.ts.html +0 -1474
  150. package/coverage/lcov-report/src/modules/crdt/loro-loader.ts.html +0 -160
  151. package/coverage/lcov-report/src/modules/devtools/flags.ts.html +0 -1132
  152. package/coverage/lcov-report/src/modules/devtools/index.html +0 -161
  153. package/coverage/lcov-report/src/modules/devtools/index.ts.html +0 -2413
  154. package/coverage/lcov-report/src/modules/devtools/storage-info.ts.html +0 -589
  155. package/coverage/lcov-report/src/modules/devtools/versions.ts.html +0 -415
  156. package/coverage/lcov-report/src/modules/feature-flag/index.html +0 -116
  157. package/coverage/lcov-report/src/modules/feature-flag/index.ts.html +0 -1033
  158. package/coverage/lcov-report/src/modules/index.html +0 -116
  159. package/coverage/lcov-report/src/modules/ref-tables.ts.html +0 -349
  160. package/coverage/lcov-report/src/mutation/index.html +0 -191
  161. package/coverage/lcov-report/src/mutation/jobs.ts.html +0 -208
  162. package/coverage/lcov-report/src/mutation/mutation-id.ts.html +0 -190
  163. package/coverage/lcov-report/src/mutation/push.saga.ts.html +0 -730
  164. package/coverage/lcov-report/src/mutation/rows.ts.html +0 -1216
  165. package/coverage/lcov-report/src/mutation/tray.saga.ts.html +0 -229
  166. package/coverage/lcov-report/src/mutation/write.saga.ts.html +0 -583
  167. package/coverage/lcov-report/src/otel/index.html +0 -116
  168. package/coverage/lcov-report/src/otel/index.ts.html +0 -466
  169. package/coverage/lcov-report/src/query/env.ts.html +0 -253
  170. package/coverage/lcov-report/src/query/fetch.saga.ts.html +0 -412
  171. package/coverage/lcov-report/src/query/hash.ts.html +0 -139
  172. package/coverage/lcov-report/src/query/index.html +0 -281
  173. package/coverage/lcov-report/src/query/lifecycle.saga.ts.html +0 -388
  174. package/coverage/lcov-report/src/query/materialize.saga.ts.html +0 -310
  175. package/coverage/lcov-report/src/query/materialize.ts.html +0 -217
  176. package/coverage/lcov-report/src/query/membership.saga.ts.html +0 -709
  177. package/coverage/lcov-report/src/query/membership.ts.html +0 -559
  178. package/coverage/lcov-report/src/query/register.saga.ts.html +0 -655
  179. package/coverage/lcov-report/src/query/render-set.ts.html +0 -265
  180. package/coverage/lcov-report/src/query/sql.ts.html +0 -322
  181. package/coverage/lcov-report/src/query/window-query.ts.html +0 -670
  182. package/coverage/lcov-report/src/services/blobs/blob-cache.ts.html +0 -1894
  183. package/coverage/lcov-report/src/services/blobs/blob-manifest.ts.html +0 -766
  184. package/coverage/lcov-report/src/services/blobs/blob-store.ts.html +0 -1162
  185. package/coverage/lcov-report/src/services/blobs/index.html +0 -161
  186. package/coverage/lcov-report/src/services/blobs/index.ts.html +0 -295
  187. package/coverage/lcov-report/src/services/database/cache-engine.ts.html +0 -664
  188. package/coverage/lcov-report/src/services/database/connection-supervisor.ts.html +0 -1330
  189. package/coverage/lcov-report/src/services/database/database.ts.html +0 -658
  190. package/coverage/lcov-report/src/services/database/engine-factory.ts.html +0 -184
  191. package/coverage/lcov-report/src/services/database/errors.ts.html +0 -187
  192. package/coverage/lcov-report/src/services/database/events/index.html +0 -116
  193. package/coverage/lcov-report/src/services/database/events/index.ts.html +0 -184
  194. package/coverage/lcov-report/src/services/database/index.html +0 -386
  195. package/coverage/lcov-report/src/services/database/index.ts.html +0 -121
  196. package/coverage/lcov-report/src/services/database/local-migrator.ts.html +0 -703
  197. package/coverage/lcov-report/src/services/database/local.ts.html +0 -1633
  198. package/coverage/lcov-report/src/services/database/plan-render.ts.html +0 -409
  199. package/coverage/lcov-report/src/services/database/relation-resolver.ts.html +0 -682
  200. package/coverage/lcov-report/src/services/database/remote.ts.html +0 -1036
  201. package/coverage/lcov-report/src/services/database/sqlite-cache-engine.ts.html +0 -4132
  202. package/coverage/lcov-report/src/services/database/sqlite-lock-verify.ts.html +0 -220
  203. package/coverage/lcov-report/src/services/database/sqlite-open.ts.html +0 -577
  204. package/coverage/lcov-report/src/services/database/sqlite-plan-sql.ts.html +0 -499
  205. package/coverage/lcov-report/src/services/database/sqlite-select.ts.html +0 -478
  206. package/coverage/lcov-report/src/services/database/sqlite-transport.ts.html +0 -757
  207. package/coverage/lcov-report/src/services/database/surql-translate.ts.html +0 -1333
  208. package/coverage/lcov-report/src/services/database/surreal-cache-engine.ts.html +0 -568
  209. package/coverage/lcov-report/src/services/logger/index.html +0 -116
  210. package/coverage/lcov-report/src/services/logger/index.ts.html +0 -154
  211. package/coverage/lcov-report/src/services/persistence/index.html +0 -146
  212. package/coverage/lcov-report/src/services/persistence/localstorage.ts.html +0 -163
  213. package/coverage/lcov-report/src/services/persistence/resilient.ts.html +0 -208
  214. package/coverage/lcov-report/src/services/persistence/surrealdb.ts.html +0 -271
  215. package/coverage/lcov-report/src/services/stream-processor/index.html +0 -146
  216. package/coverage/lcov-report/src/services/stream-processor/index.ts.html +0 -3313
  217. package/coverage/lcov-report/src/services/stream-processor/permissions.ts.html +0 -244
  218. package/coverage/lcov-report/src/services/stream-processor/wasm-types.ts.html +0 -346
  219. package/coverage/lcov-report/src/services/tabs/broker-client.ts.html +0 -934
  220. package/coverage/lcov-report/src/services/tabs/coordinator.ts.html +0 -1984
  221. package/coverage/lcov-report/src/services/tabs/index.html +0 -191
  222. package/coverage/lcov-report/src/services/tabs/leader-locks.ts.html +0 -310
  223. package/coverage/lcov-report/src/services/tabs/protocol.ts.html +0 -871
  224. package/coverage/lcov-report/src/services/tabs/support.ts.html +0 -193
  225. package/coverage/lcov-report/src/services/tabs/tabs-broker-worker.ts.html +0 -2005
  226. package/coverage/lcov-report/src/sp00ky.ts.html +0 -100
  227. package/coverage/lcov-report/src/state/client-state.ts.html +0 -637
  228. package/coverage/lcov-report/src/state/index.html +0 -161
  229. package/coverage/lcov-report/src/state/lifecycle.ts.html +0 -343
  230. package/coverage/lcov-report/src/state/reducers.ts.html +0 -1471
  231. package/coverage/lcov-report/src/state/selectors.ts.html +0 -637
  232. package/coverage/lcov-report/src/sync/connection.saga.ts.html +0 -343
  233. package/coverage/lcov-report/src/sync/index.html +0 -176
  234. package/coverage/lcov-report/src/sync/live.saga.ts.html +0 -232
  235. package/coverage/lcov-report/src/sync/policy.ts.html +0 -1606
  236. package/coverage/lcov-report/src/sync/poll.saga.ts.html +0 -193
  237. package/coverage/lcov-report/src/sync/tabs.saga.ts.html +0 -361
  238. package/coverage/lcov-report/src/types.ts.html +0 -2419
  239. package/coverage/lcov-report/src/utils/blurhash.ts.html +0 -355
  240. package/coverage/lcov-report/src/utils/error-classification.ts.html +0 -244
  241. package/coverage/lcov-report/src/utils/index.html +0 -191
  242. package/coverage/lcov-report/src/utils/index.ts.html +0 -820
  243. package/coverage/lcov-report/src/utils/parser.ts.html +0 -313
  244. package/coverage/lcov-report/src/utils/semver.ts.html +0 -175
  245. package/coverage/lcov-report/src/utils/surql.ts.html +0 -667
  246. package/coverage/lcov.info +0 -19079
  247. package/src/modules/cache/cache.relay.test.ts +0 -95
  248. package/src/modules/cache/index.ts +0 -361
  249. package/src/modules/cache/types.ts +0 -19
  250. package/src/modules/data/data.activity.test.ts +0 -109
  251. package/src/modules/data/data.authority.test.ts +0 -122
  252. package/src/modules/data/data.heartbeat-wake.test.ts +0 -115
  253. package/src/modules/data/data.hydration.test.ts +0 -142
  254. package/src/modules/data/data.membership.test.ts +0 -623
  255. package/src/modules/data/data.notify-table.test.ts +0 -41
  256. package/src/modules/data/data.pending-ids.test.ts +0 -199
  257. package/src/modules/data/data.rebind.test.ts +0 -170
  258. package/src/modules/data/data.rematerialize.test.ts +0 -114
  259. package/src/modules/data/data.run.test.ts +0 -113
  260. package/src/modules/data/data.settled-writes.test.ts +0 -235
  261. package/src/modules/data/data.status.test.ts +0 -249
  262. package/src/modules/data/data.test.ts +0 -58
  263. package/src/modules/data/index.ts +0 -2745
  264. package/src/modules/sync/engine.ts +0 -250
  265. package/src/modules/sync/events/index.ts +0 -84
  266. package/src/modules/sync/index.ts +0 -3
  267. package/src/modules/sync/queue/index.ts +0 -2
  268. package/src/modules/sync/queue/queue-down.test.ts +0 -228
  269. package/src/modules/sync/queue/queue-down.ts +0 -184
  270. package/src/modules/sync/queue/queue-up.forwarded.test.ts +0 -164
  271. package/src/modules/sync/queue/queue-up.ts +0 -407
  272. package/src/modules/sync/scheduler.pause.test.ts +0 -109
  273. package/src/modules/sync/scheduler.retry.test.ts +0 -237
  274. package/src/modules/sync/scheduler.ts +0 -286
  275. package/src/modules/sync/sync.cleanup.test.ts +0 -116
  276. package/src/modules/sync/sync.health.test.ts +0 -167
  277. package/src/modules/sync/sync.heartbeat.test.ts +0 -80
  278. package/src/modules/sync/sync.list-ref-meta.test.ts +0 -193
  279. package/src/modules/sync/sync.live-removal.test.ts +0 -289
  280. package/src/modules/sync/sync.reconnect.test.ts +0 -145
  281. package/src/modules/sync/sync.rematerialize-after-fetch.test.ts +0 -93
  282. package/src/modules/sync/sync.settled-poll.test.ts +0 -58
  283. package/src/modules/sync/sync.subquery.test.ts +0 -82
  284. package/src/modules/sync/sync.tabs.test.ts +0 -249
  285. package/src/modules/sync/sync.ts +0 -2626
  286. package/src/sp00ky.auth-order.test.ts +0 -112
  287. package/src/sp00ky.init-query.test.ts +0 -183
  288. package/src/sp00ky.local-first.test.ts +0 -60
  289. /package/src/{modules/data → mutation}/mutation-id.ts +0 -0
@@ -0,0 +1,159 @@
1
+ import type { QueryPlan } from '@spooky-sync/query-builder';
2
+ import type { SealedQuery } from '../utils/surql';
3
+ import type { ClientState } from '../state/client-state';
4
+ import type { IngestRecord } from '../services/stream-processor/index';
5
+ import type { RecordVersionArray, RegistrationTimings } from '../types';
6
+ import type { OutEvent, RuntimeEvent } from './events';
7
+
8
+ export type Vars = Record<string, unknown>;
9
+
10
+ /** What the in-browser SSP needs to build a local view. */
11
+ export interface RegisterPlan {
12
+ queryHash: string;
13
+ surql: string;
14
+ params: Vars;
15
+ ttl: string;
16
+ tableName: string;
17
+ involvedTables?: string[];
18
+ }
19
+ export interface RegisterResult {
20
+ localArray: RecordVersionArray;
21
+ timings: RegistrationTimings;
22
+ }
23
+
24
+ /** One statement's outcome of a multi-statement remote request. */
25
+ export type StatementResult =
26
+ | { status: 'OK'; result: unknown }
27
+ | { status: 'ERR'; error: string };
28
+
29
+ /** One entry of an `all` fan-out result (allSettled semantics). */
30
+ export type Settled<T = unknown> = { ok: true; value: T } | { ok: false; error: unknown };
31
+
32
+ /**
33
+ * Effects are data. A saga yields one and gets its result back on the next
34
+ * `next()`; the interpreter (client/runtime) is the only place they execute.
35
+ */
36
+ export type Effect =
37
+ | { kind: 'local.query'; sql: string; vars?: Vars; epoch?: number }
38
+ | { kind: 'local.select'; plan: QueryPlan; params?: Vars }
39
+ | { kind: 'local.execute'; query: SealedQuery<unknown>; vars?: Vars; epoch?: number }
40
+ | { kind: 'local.getById'; table: string; id: unknown }
41
+ | { kind: 'local.upsert'; table: string; id: unknown; data: Record<string, unknown>; mode: 'replace' | 'merge' }
42
+ | { kind: 'local.delete'; table: string; id: unknown }
43
+ | { kind: 'local.epoch' }
44
+ | { kind: 'remote.query'; sql: string; vars?: Vars; timeoutMs?: number }
45
+ | { kind: 'remote.live'; table: string }
46
+ | { kind: 'remote.kill'; uuid: string }
47
+ | { kind: 'ssp.register'; plan: RegisterPlan }
48
+ | { kind: 'ssp.unregister'; hash: string }
49
+ | { kind: 'ssp.ingest'; records: IngestRecord[] }
50
+ | { kind: 'timer.set'; key: string; ms: number; event: RuntimeEvent }
51
+ | { kind: 'timer.clear'; key: string }
52
+ | { kind: 'state.read'; select: (s: ClientState) => unknown }
53
+ | { kind: 'state.update'; fn: (s: ClientState) => ClientState }
54
+ | { kind: 'state.wait'; until: (s: ClientState) => boolean }
55
+ | { kind: 'now' }
56
+ | { kind: 'id'; scope: 'mutation' | 'salt' }
57
+ | { kind: 'hash'; input: string }
58
+ | { kind: 'emit'; event: OutEvent }
59
+ | { kind: 'dispatch'; event: RuntimeEvent }
60
+ | { kind: 'all'; effects: Effect[] }
61
+ | { kind: 'service'; name: ServiceName; args: unknown[] };
62
+
63
+ export type EffectKind = Effect['kind'];
64
+
65
+ /**
66
+ * Calls into the legacy services that are adapters, not state: auth, tabs,
67
+ * blobs, migrator, crdt, persistence, the SSP lifecycle, the remote socket.
68
+ * A saga names the call; the runtime binds it to the real service.
69
+ */
70
+ export interface ServiceCalls {
71
+ 'hint.read': () => string | null;
72
+ 'hint.write': (bucketId: string) => void;
73
+ 'local.connect': (bucketId: string) => Promise<void>;
74
+ 'local.switchStore': (bucketId: string) => Promise<void>;
75
+ 'local.beginSwitch': () => () => void;
76
+ 'local.currentBucketId': () => string;
77
+ 'local.usesSurqlSchema': () => boolean;
78
+ 'migrator.provision': () => Promise<void>;
79
+ 'blobs.start': (bucketId: string) => Promise<void>;
80
+ 'blobs.setNamespace': (bucketId: string) => Promise<void>;
81
+ 'blobs.clear': () => Promise<void>;
82
+ 'ssp.init': () => Promise<void>;
83
+ 'ssp.setPermissions': () => void;
84
+ 'ssp.setSessionAuth': (authId: string | null, access: string | null) => void;
85
+ 'ssp.prime': (pendingIds: string[]) => Promise<void>;
86
+ 'ssp.reset': () => Promise<void>;
87
+ 'ssp.setPersistence': (enabled: boolean) => void;
88
+ 'auth.restoreSession': () => Promise<string | null>;
89
+ 'auth.init': () => Promise<void>;
90
+ 'auth.sessionAuthId': () => string | null;
91
+ 'auth.access': () => string | null;
92
+ 'auth.token': () => string | null;
93
+ 'auth.currentUser': () => Record<string, unknown> | null;
94
+ 'remote.connect': () => Promise<void>;
95
+ 'remote.releaseViews': (ids: unknown[]) => void;
96
+ 'supervisor.start': () => void;
97
+ 'tabs.start': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
98
+ 'tabs.moveToBucket': (bucketId: string) => Promise<'solo' | 'leader' | 'follower'>;
99
+ 'crdt.setSessionId': (sessionId: string) => void;
100
+ 'crdt.closeAll': (flush: boolean) => void;
101
+ 'persistence.set': (key: string, value: unknown) => Promise<void>;
102
+ 'features.init': () => void;
103
+ 'releases.init': () => void;
104
+ 'window.attach': () => void;
105
+ }
106
+ export type ServiceName = keyof ServiceCalls;
107
+
108
+ /** Typed constructors. Each is one line so the saga reads like the plan. */
109
+ export const fx = {
110
+ local: {
111
+ query: (sql: string, vars?: Vars, epoch?: number): Effect => ({ kind: 'local.query', sql, vars, epoch }),
112
+ select: (plan: QueryPlan, params?: Vars): Effect => ({ kind: 'local.select', plan, params }),
113
+ execute: (query: SealedQuery<unknown>, vars?: Vars, epoch?: number): Effect => ({
114
+ kind: 'local.execute',
115
+ query,
116
+ vars,
117
+ epoch,
118
+ }),
119
+ getById: (table: string, id: unknown): Effect => ({ kind: 'local.getById', table, id }),
120
+ upsert: (table: string, id: unknown, data: Record<string, unknown>, mode: 'replace' | 'merge'): Effect => ({
121
+ kind: 'local.upsert',
122
+ table,
123
+ id,
124
+ data,
125
+ mode,
126
+ }),
127
+ delete: (table: string, id: unknown): Effect => ({ kind: 'local.delete', table, id }),
128
+ /** The store's current epoch; a write fenced with it is dropped after a bucket switch or transport failover. */
129
+ epoch: (): Effect => ({ kind: 'local.epoch' }),
130
+ },
131
+ remote: {
132
+ query: (sql: string, vars?: Vars, timeoutMs?: number): Effect => ({ kind: 'remote.query', sql, vars, timeoutMs }),
133
+ /** Subscribe to `LIVE SELECT * FROM <table>`; resolves to the live uuid. */
134
+ live: (table: string): Effect => ({ kind: 'remote.live', table }),
135
+ kill: (uuid: string): Effect => ({ kind: 'remote.kill', uuid }),
136
+ },
137
+ ssp: {
138
+ register: (plan: RegisterPlan): Effect => ({ kind: 'ssp.register', plan }),
139
+ unregister: (hash: string): Effect => ({ kind: 'ssp.unregister', hash }),
140
+ ingest: (records: IngestRecord[]): Effect => ({ kind: 'ssp.ingest', records }),
141
+ },
142
+ timer: {
143
+ set: (key: string, ms: number, event: RuntimeEvent): Effect => ({ kind: 'timer.set', key, ms, event }),
144
+ clear: (key: string): Effect => ({ kind: 'timer.clear', key }),
145
+ },
146
+ state: {
147
+ read: <T>(select: (s: ClientState) => T): Effect => ({ kind: 'state.read', select }),
148
+ update: (fn: (s: ClientState) => ClientState): Effect => ({ kind: 'state.update', fn }),
149
+ /** Suspend until `until(state)` holds (checked after every state.update). */
150
+ wait: (until: (s: ClientState) => boolean): Effect => ({ kind: 'state.wait', until }),
151
+ },
152
+ now: (): Effect => ({ kind: 'now' }),
153
+ id: (scope: 'mutation' | 'salt'): Effect => ({ kind: 'id', scope }),
154
+ hash: (input: string): Effect => ({ kind: 'hash', input }),
155
+ emit: (event: OutEvent): Effect => ({ kind: 'emit', event }),
156
+ dispatch: (event: RuntimeEvent): Effect => ({ kind: 'dispatch', event }),
157
+ all: (effects: Effect[]): Effect => ({ kind: 'all', effects }),
158
+ service: <N extends ServiceName>(name: N, ...args: Parameters<ServiceCalls[N]>): Effect => ({ kind: 'service', name, args }),
159
+ } as const;
@@ -0,0 +1,55 @@
1
+ import type { ConnectionState, QueryHash, QueryStatus, SyncHealth } from '../types';
2
+ import type { StreamUpdate } from '../services/stream-processor/index';
3
+
4
+ /**
5
+ * Inbound events. Everything that can start a saga arrives as one of these
6
+ * through the runtime router: public API calls, adapter callbacks, timers,
7
+ * and `dispatch` effects from other sagas.
8
+ */
9
+ export type RuntimeEvent =
10
+ | { type: 'EnsureRegistered'; requireAuth?: boolean; attempt?: number }
11
+ | { type: 'RegisterRemote'; hash: QueryHash; retry?: boolean }
12
+ | { type: 'SyncOutcome'; ok: boolean; error?: unknown }
13
+ | { type: 'AckPrune' }
14
+ | { type: 'ReadDirtyMembership' }
15
+ | { type: 'ReadMembership'; hashes: QueryHash[] }
16
+ | { type: 'FetchRows' }
17
+ | { type: 'Materialize'; hash: QueryHash }
18
+ | { type: 'MaterializeDirty' }
19
+ | { type: 'LifecycleTick' }
20
+ | { type: 'GcTick' }
21
+ | { type: 'Drain' }
22
+ | { type: 'FlushWrite'; key: string }
23
+ | { type: 'PollTick' }
24
+ | { type: 'SelfHealTick' }
25
+ | { type: 'HeartbeatNow' }
26
+ | { type: 'StartRemote' }
27
+ | { type: 'PrimeCircuit' }
28
+ | { type: 'VersionsPrimed'; entries: Array<readonly [string, number]> }
29
+ | { type: 'WarmBlobs' }
30
+ | { type: 'AuthFlip'; userId: string | null }
31
+ | { type: 'BucketSwitch'; target: string }
32
+ | { type: 'PageHide' }
33
+ | { type: 'ConnectionChanged'; state: ConnectionState }
34
+ | { type: 'StreamUpdate'; update: StreamUpdate }
35
+ | { type: 'LiveStart' }
36
+ | { type: 'LiveChange'; hashes: QueryHash[] }
37
+ | { type: 'TabRole'; role: 'solo' | 'leader' | 'follower' }
38
+ | { type: 'TabMessage'; message: unknown };
39
+
40
+ export type OutEvent =
41
+ | { type: 'query:records'; hash: QueryHash; records: ReadonlyArray<Record<string, unknown>> }
42
+ | { type: 'query:status'; hash: QueryHash; status: QueryStatus }
43
+ | { type: 'query:authority'; hash: QueryHash; known: boolean }
44
+ | { type: 'query:view-lost'; hash: QueryHash }
45
+ | { type: 'query:evicted'; hash: QueryHash }
46
+ | { type: 'mutation:event'; event: unknown }
47
+ | { type: 'mutation:settled'; mutationId: string; recordId: string; eventType: string }
48
+ | { type: 'mutation:rolled-back'; mutationId: string; recordId: string; eventType: string; error: string }
49
+ | { type: 'tray:changed'; count: number }
50
+ | { type: 'health:changed'; health: SyncHealth }
51
+ | { type: 'activity:changed'; fetching: number; pending: number }
52
+ | { type: 'tabs:broadcast'; message: unknown }
53
+ | { type: 'tabs:sendTo'; tabId: string; message: unknown }
54
+ | { type: 'devtools'; name: string; data?: unknown }
55
+ | { type: 'log'; level: 'debug' | 'info' | 'warn' | 'error'; message: string; data?: unknown };
@@ -0,0 +1,116 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
3
+ import { fakeAdapters, fakeHost } from '../testing/adapters';
4
+ import { createInterpreter } from './interpreter';
5
+ import { fx } from './effects';
6
+ import { setFailedCount } from '../state/reducers';
7
+
8
+ describe('interpreter', () => {
9
+ it('routes store, remote, ssp and service effects to the adapters', async () => {
10
+ const a = fakeAdapters({
11
+ remote: { queryResponses: async () => [{ status: 'OK', result: 1 }] },
12
+ ssp: {
13
+ registerQueryPlan: (plan) => ({ queryHash: plan.queryHash, localArray: [['t:1', 1]], registration: { parseMs: 1, planMs: 2, snapshotMs: 3 } }),
14
+ },
15
+ services: { 'hint.read': () => 'u1' },
16
+ });
17
+ const h = fakeHost();
18
+ const run = createInterpreter(a.adapters, h.host);
19
+ const sealed = { sql: 'SELECT 1;', extract: (r: unknown[]) => r };
20
+ await run(fx.local.query('SELECT 1', { a: 1 }, 2));
21
+ await run(fx.local.query('SELECT 2'));
22
+ await run(fx.local.execute(sealed, {}, 1));
23
+ await run(fx.local.select({ table: 't' } as any, {}));
24
+ await run(fx.local.getById('t', 'x'));
25
+ await run(fx.local.upsert('t', 'x', { a: 1 }, 'merge'));
26
+ await run(fx.local.delete('t', 'x'));
27
+ expect(await run(fx.local.epoch())).toBe(0);
28
+ expect(await run(fx.remote.query('RETURN 1'))).toEqual([{ status: 'OK', result: 1 }]);
29
+ expect(await run(fx.remote.live('_00_list_ref'))).toBe('live-uuid');
30
+ await run(fx.remote.kill('live-uuid'));
31
+ const reg = await run(fx.ssp.register({ queryHash: 'h', surql: 's', params: {}, ttl: '10m', tableName: 't' }));
32
+ expect(reg).toEqual({ localArray: [['t:1', 1]], timings: { parseMs: 1, planMs: 2, snapshotMs: 3, wallMs: null } });
33
+ await run(fx.ssp.unregister('h'));
34
+ await run(fx.ssp.ingest([]));
35
+ expect(await run(fx.service('hint.read'))).toBe('u1');
36
+ expect(a.names()).toEqual([
37
+ 'local.query', 'local.query', 'local.execute', 'local.select', 'local.getById', 'local.upsert', 'local.delete',
38
+ 'remote.live', 'remote.kill', 'ssp.unregister', 'ssp.ingest', 'service.hint.read',
39
+ ]);
40
+ expect(a.calls[0]).toEqual(['local.query', ['SELECT 1', { a: 1 }]]);
41
+ });
42
+
43
+ it('ssp.register without a result throws; ssp.register uses default timings when the SSP reports none', async () => {
44
+ const empty = fakeAdapters({ ssp: { registerQueryPlan: () => undefined } });
45
+ const h = fakeHost();
46
+ await expect(createInterpreter(empty.adapters, h.host)(fx.ssp.register({ queryHash: 'h', surql: 's', params: {}, ttl: '1m', tableName: 't' }))).rejects.toThrow(/not initialized/);
47
+ const bare = fakeAdapters();
48
+ const reg = await createInterpreter(bare.adapters, h.host)(fx.ssp.register({ queryHash: 'h', surql: 's', params: {}, ttl: '1m', tableName: 't' }));
49
+ expect(reg).toEqual({ localArray: [], timings: { parseMs: null, planMs: null, snapshotMs: null, wallMs: null } });
50
+ });
51
+
52
+ it('remote.query honours the per-effect timeout', async () => {
53
+ const slow = fakeAdapters({ remote: { queryResponses: () => new Promise(() => {}) } });
54
+ const h = fakeHost();
55
+ await expect(createInterpreter(slow.adapters, h.host)(fx.remote.query('SLOW', undefined, 5))).rejects.toThrow(/timed out/);
56
+ });
57
+
58
+ it('state, wait, clock, ids, hash, timers, emit, dispatch, all', async () => {
59
+ const a = fakeAdapters({ now: 42 });
60
+ const h = fakeHost();
61
+ const run = createInterpreter(a.adapters, h.host);
62
+ expect(await run(fx.state.read((s) => s.tabId))).toBe('tab-a');
63
+ await run(fx.state.update(setFailedCount(2)));
64
+ expect(h.state.failedCount).toBe(2);
65
+ await run(fx.state.wait((s) => s.failedCount === 2));
66
+ const waiting = run(fx.state.wait((s) => s.failedCount === 3));
67
+ h.host.setState(setFailedCount(3)(h.state));
68
+ await waiting;
69
+ const ctrl = new AbortController();
70
+ const aborted = run(fx.state.wait(() => false), { signal: ctrl.signal });
71
+ ctrl.abort();
72
+ await expect(aborted).rejects.toThrow('aborted');
73
+ expect(await run(fx.now())).toBe(42);
74
+ expect(String(await run(fx.id('mutation')))).toMatch(/^_00_pending_mutations:/);
75
+ expect(String(await run(fx.id('salt')))).toMatch(/^salt-/);
76
+ expect(await run(fx.hash('abc'))).toMatch(/^ba7816bf/);
77
+ await run(fx.timer.set('k', 10, { type: 'Drain' }));
78
+ expect(a.timers.pending.has('k')).toBe(true);
79
+ a.timers.fire('k');
80
+ expect(h.dispatched).toEqual([{ type: 'Drain' }]);
81
+ await run(fx.timer.set('j', 1, { type: 'FetchRows' }));
82
+ await run(fx.timer.clear('j'));
83
+ expect(a.timers.pending.has('j')).toBe(false);
84
+ await run(fx.emit({ type: 'tray:changed', count: 1 }));
85
+ expect(h.emitted).toEqual([{ type: 'tray:changed', count: 1 }]);
86
+ await run(fx.dispatch({ type: 'PollTick' }));
87
+ expect(h.dispatched.at(-1)).toEqual({ type: 'PollTick' });
88
+ const settled = await run(fx.all([fx.now(), fx.remote.query('x'), fx.service('hint.read')]));
89
+ expect(settled).toEqual([{ ok: true, value: 42 }, { ok: true, value: [] }, { ok: true, value: undefined }]);
90
+ const failing = fakeAdapters({
91
+ remote: {
92
+ queryResponses: async () => {
93
+ throw new Error('boom');
94
+ },
95
+ },
96
+ });
97
+ const mixed = await createInterpreter(failing.adapters, h.host)(fx.all([fx.remote.query('x'), fx.now()]));
98
+ expect(mixed).toEqual([{ ok: false, error: new Error('boom') }, { ok: true, value: 1_700_000_000_000 }]);
99
+ });
100
+
101
+ it('live events reach the host as LiveChange dispatches', async () => {
102
+ let onChange: ((h: string[]) => void) | null = null;
103
+ const a = fakeAdapters({
104
+ remote: {
105
+ live: async (_t, cb) => {
106
+ onChange = cb;
107
+ return 'u';
108
+ },
109
+ },
110
+ });
111
+ const h = fakeHost();
112
+ await createInterpreter(a.adapters, h.host)(fx.remote.live('_00_list_ref'));
113
+ onChange!(['a', 'b']);
114
+ expect(h.dispatched).toEqual([{ type: 'LiveChange', hashes: ['a', 'b'] }]);
115
+ });
116
+ });
@@ -0,0 +1,143 @@
1
+ import { Duration } from 'surrealdb';
2
+ import type { LocalStore } from '../services/database/cache-engine';
3
+ import type { IngestRecord, StreamUpdate } from '../services/stream-processor/index';
4
+ import type { ClientState } from '../state/client-state';
5
+ import { withTimeout } from '../utils/index';
6
+ import type { Effect, RegisterResult, ServiceCalls, Settled, StatementResult } from './effects';
7
+ import type { OutEvent, RuntimeEvent } from './events';
8
+
9
+ /** The five adapters plus the pure ports, as the interpreter sees them. */
10
+ export interface Adapters {
11
+ local: Pick<LocalStore, 'query' | 'execute' | 'select' | 'getById' | 'upsert' | 'delete'> & { readonly epoch: number };
12
+ remote: {
13
+ queryResponses(sql: string, vars?: Record<string, unknown>): Promise<StatementResult[]>;
14
+ /** Subscribe to `LIVE SELECT * FROM <table>`; the callback receives the changed query hashes. */
15
+ live(table: string, onChange: (hashes: string[]) => void): Promise<string>;
16
+ kill(uuid: string): Promise<void>;
17
+ };
18
+ ssp: {
19
+ registerQueryPlan(plan: {
20
+ queryHash: string;
21
+ surql: string;
22
+ params: Record<string, unknown>;
23
+ ttl: Duration;
24
+ lastActiveAt: Date;
25
+ localArray: [];
26
+ remoteArray: [];
27
+ meta: { tableName: string; involvedTables?: string[] };
28
+ }): StreamUpdate | undefined;
29
+ unregisterQueryPlan(hash: string): void;
30
+ ingestMany(records: IngestRecord[]): unknown;
31
+ };
32
+ timers: { set(key: string, ms: number, fire: () => void): void; clear(key: string): void };
33
+ clock: { now(): number };
34
+ ids: { mutation(): string; salt(): string };
35
+ hash(input: string): Promise<string>;
36
+ services: ServiceCalls;
37
+ }
38
+
39
+ /** What the interpreter needs from the runtime: state, waiting, emitting, dispatching. */
40
+ export interface InterpreterHost {
41
+ getState(): ClientState;
42
+ setState(next: ClientState): void;
43
+ waitFor(until: (s: ClientState) => boolean, signal?: AbortSignal): Promise<void>;
44
+ emit(event: OutEvent): void;
45
+ dispatch(event: RuntimeEvent): void;
46
+ }
47
+
48
+ export interface RunContext {
49
+ signal?: AbortSignal;
50
+ }
51
+
52
+ export type Interpreter = (effect: Effect, ctx?: RunContext) => Promise<unknown>;
53
+
54
+ /** Effects become adapter calls here and nowhere else. */
55
+ export function createInterpreter(adapters: Adapters, host: InterpreterHost): Interpreter {
56
+ const interpret: Interpreter = async (effect, ctx) => {
57
+ switch (effect.kind) {
58
+ case 'local.query':
59
+ return adapters.local.query(effect.sql, effect.vars, effect.epoch === undefined ? undefined : { epoch: effect.epoch });
60
+ case 'local.select':
61
+ return adapters.local.select(effect.plan, effect.params);
62
+ case 'local.execute':
63
+ return adapters.local.execute(effect.query, effect.vars, effect.epoch === undefined ? undefined : { epoch: effect.epoch });
64
+ case 'local.getById':
65
+ return adapters.local.getById(effect.table, effect.id);
66
+ case 'local.upsert':
67
+ return adapters.local.upsert(effect.table, effect.id, effect.data, effect.mode);
68
+ case 'local.delete':
69
+ return adapters.local.delete(effect.table, effect.id);
70
+ case 'local.epoch':
71
+ return adapters.local.epoch;
72
+ case 'remote.query': {
73
+ const pending = adapters.remote.queryResponses(effect.sql, effect.vars);
74
+ return effect.timeoutMs
75
+ ? withTimeout(pending, effect.timeoutMs, () => new Error(`Remote request timed out after ${effect.timeoutMs}ms`))
76
+ : pending;
77
+ }
78
+ case 'remote.live':
79
+ return adapters.remote.live(effect.table, (hashes) => host.dispatch({ type: 'LiveChange', hashes }));
80
+ case 'remote.kill':
81
+ return adapters.remote.kill(effect.uuid);
82
+ case 'ssp.register': {
83
+ const update = adapters.ssp.registerQueryPlan({
84
+ queryHash: effect.plan.queryHash,
85
+ surql: effect.plan.surql,
86
+ params: effect.plan.params,
87
+ ttl: new Duration(effect.plan.ttl),
88
+ lastActiveAt: new Date(adapters.clock.now()),
89
+ localArray: [],
90
+ remoteArray: [],
91
+ meta: { tableName: effect.plan.tableName, involvedTables: effect.plan.involvedTables },
92
+ });
93
+ if (!update) throw new Error('Stream processor is not initialized');
94
+ const result: RegisterResult = {
95
+ localArray: update.localArray,
96
+ timings: {
97
+ parseMs: update.registration?.parseMs ?? null,
98
+ planMs: update.registration?.planMs ?? null,
99
+ snapshotMs: update.registration?.snapshotMs ?? null,
100
+ wallMs: null,
101
+ },
102
+ };
103
+ return result;
104
+ }
105
+ case 'ssp.unregister':
106
+ return adapters.ssp.unregisterQueryPlan(effect.hash);
107
+ case 'ssp.ingest':
108
+ return adapters.ssp.ingestMany(effect.records);
109
+ case 'timer.set':
110
+ return adapters.timers.set(effect.key, effect.ms, () => host.dispatch(effect.event));
111
+ case 'timer.clear':
112
+ return adapters.timers.clear(effect.key);
113
+ case 'state.read':
114
+ return effect.select(host.getState());
115
+ case 'state.update': {
116
+ const next = effect.fn(host.getState());
117
+ host.setState(next);
118
+ return next;
119
+ }
120
+ case 'state.wait':
121
+ return host.waitFor(effect.until, ctx?.signal);
122
+ case 'now':
123
+ return adapters.clock.now();
124
+ case 'id':
125
+ return effect.scope === 'mutation' ? adapters.ids.mutation() : adapters.ids.salt();
126
+ case 'hash':
127
+ return adapters.hash(effect.input);
128
+ case 'emit':
129
+ return host.emit(effect.event);
130
+ case 'dispatch':
131
+ return host.dispatch(effect.event);
132
+ case 'all': {
133
+ const settled = await Promise.allSettled(effect.effects.map((e) => interpret(e, ctx)));
134
+ return settled.map((r): Settled => (r.status === 'fulfilled' ? { ok: true, value: r.value } : { ok: false, error: r.reason }));
135
+ }
136
+ case 'service': {
137
+ const fn = adapters.services[effect.name] as (...args: unknown[]) => unknown;
138
+ return fn(...effect.args);
139
+ }
140
+ }
141
+ };
142
+ return interpret;
143
+ }
@@ -0,0 +1,89 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { Effect } from './effects';
3
+ import { fx } from './effects';
4
+ import { acquire, emptyLanes, release, runSaga } from './saga';
5
+ import type { Saga } from './saga';
6
+
7
+ describe('runSaga', () => {
8
+ it('threads effect results back into the generator in order', async () => {
9
+ const seen: Effect[] = [];
10
+ function* saga(): Saga<number> {
11
+ const a = (yield fx.now()) as number;
12
+ const b = (yield fx.hash('x')) as number;
13
+ return a + b;
14
+ }
15
+ const result = await runSaga(saga(), async (e) => {
16
+ seen.push(e);
17
+ return e.kind === 'now' ? 1 : 2;
18
+ });
19
+ expect(result).toBe(3);
20
+ expect(seen.map((e) => e.kind)).toEqual(['now', 'hash']);
21
+ });
22
+
23
+ it('throws a rejected effect into the saga so it can catch it', async () => {
24
+ function* saga(): Saga<string> {
25
+ try {
26
+ yield fx.now();
27
+ return 'unreachable';
28
+ } catch (err) {
29
+ return `caught:${(err as Error).message}`;
30
+ }
31
+ }
32
+ await expect(runSaga(saga(), async () => Promise.reject(new Error('boom')))).resolves.toBe('caught:boom');
33
+ });
34
+
35
+ it('propagates an error the saga does not catch', async () => {
36
+ function* saga(): Saga<void> {
37
+ yield fx.now();
38
+ }
39
+ await expect(runSaga(saga(), async () => Promise.reject(new Error('boom')))).rejects.toThrow('boom');
40
+ });
41
+
42
+ it('returns immediately for a saga that yields nothing', async () => {
43
+ // oxlint-disable-next-line require-yield
44
+ function* saga(): Saga<number> {
45
+ return 7;
46
+ }
47
+ await expect(runSaga(saga(), async () => undefined)).resolves.toBe(7);
48
+ });
49
+ });
50
+
51
+ describe('lanes', () => {
52
+ it('serial: first acquires, second waits, release hands over, final release frees', () => {
53
+ const lane = { kind: 'serial', key: 'outbox' } as const;
54
+ const a = acquire(emptyLanes(), lane);
55
+ expect(a.decision).toBe('start');
56
+ const b = acquire(a.state, lane);
57
+ expect(b.decision).toBe('wait');
58
+ const c = acquire(b.state, lane);
59
+ expect(c.decision).toBe('wait');
60
+ expect(c.state.waiting.get('outbox')).toBe(2);
61
+ const r1 = release(c.state, 'outbox');
62
+ expect(r1.startNext).toBe(true);
63
+ expect(r1.state.waiting.get('outbox')).toBe(1);
64
+ expect(r1.state.running.has('outbox')).toBe(true);
65
+ const r2 = release(r1.state, 'outbox');
66
+ expect(r2.startNext).toBe(true);
67
+ expect(r2.state.waiting.has('outbox')).toBe(false);
68
+ const r3 = release(r2.state, 'outbox');
69
+ expect(r3.startNext).toBe(false);
70
+ expect(r3.state.running.has('outbox')).toBe(false);
71
+ });
72
+
73
+ it('dedupe: a request during a run joins it and does not queue', () => {
74
+ const lane = { kind: 'dedupe', key: 'mat:h' } as const;
75
+ const a = acquire(emptyLanes(), lane);
76
+ const b = acquire(a.state, lane);
77
+ expect(b.decision).toBe('join');
78
+ expect(b.state).toBe(a.state);
79
+ const r = release(b.state, 'mat:h');
80
+ expect(r.startNext).toBe(false);
81
+ expect(r.state.running.size).toBe(0);
82
+ });
83
+
84
+ it('keys are independent', () => {
85
+ const a = acquire(emptyLanes(), { kind: 'serial', key: 'x' });
86
+ const b = acquire(a.state, { kind: 'serial', key: 'y' });
87
+ expect(b.decision).toBe('start');
88
+ });
89
+ });
@@ -0,0 +1,73 @@
1
+ import type { Effect } from './effects';
2
+
3
+ /**
4
+ * A saga is a generator that yields effects and receives their results. It
5
+ * holds no references to adapters or state, so it can be driven by the real
6
+ * interpreter or by `testing/run-pure` with canned results.
7
+ */
8
+ export type Saga<R> = Generator<Effect, R, any>;
9
+ export type Interpret = (effect: Effect) => Promise<unknown>;
10
+
11
+ /**
12
+ * Drive a saga to completion. A rejected effect is thrown back into the saga
13
+ * at the `yield`, so sagas use ordinary `try/catch`; an error the saga does
14
+ * not catch propagates to the caller.
15
+ */
16
+ export async function runSaga<R>(saga: Saga<R>, interpret: Interpret): Promise<R> {
17
+ let step = saga.next();
18
+ while (!step.done) {
19
+ let result: unknown;
20
+ try {
21
+ result = await interpret(step.value);
22
+ } catch (error) {
23
+ step = saga.throw(error);
24
+ continue;
25
+ }
26
+ step = saga.next(result);
27
+ }
28
+ return step.value;
29
+ }
30
+
31
+ /**
32
+ * Lanes bound concurrency without a queue object per lane:
33
+ * - `serial`: runs strictly one at a time per key, in arrival order.
34
+ * - `dedupe`: a request while one run is active joins that run instead of
35
+ * starting another.
36
+ * The bookkeeping is a pure value so the policy is unit-testable; the runtime
37
+ * owns the promises.
38
+ */
39
+ export type Lane = { kind: 'serial'; key: string } | { kind: 'dedupe'; key: string };
40
+
41
+ export interface LaneState {
42
+ readonly running: ReadonlySet<string>;
43
+ readonly waiting: ReadonlyMap<string, number>;
44
+ }
45
+
46
+ export const emptyLanes = (): LaneState => ({ running: new Set(), waiting: new Map() });
47
+
48
+ export type LaneDecision = 'start' | 'wait' | 'join';
49
+
50
+ export function acquire(state: LaneState, lane: Lane): { decision: LaneDecision; state: LaneState } {
51
+ if (!state.running.has(lane.key)) {
52
+ const running = new Set(state.running);
53
+ running.add(lane.key);
54
+ return { decision: 'start', state: { running, waiting: state.waiting } };
55
+ }
56
+ if (lane.kind === 'dedupe') return { decision: 'join', state };
57
+ const waiting = new Map(state.waiting);
58
+ waiting.set(lane.key, (waiting.get(lane.key) ?? 0) + 1);
59
+ return { decision: 'wait', state: { running: state.running, waiting } };
60
+ }
61
+
62
+ export function release(state: LaneState, key: string): { startNext: boolean; state: LaneState } {
63
+ const pending = state.waiting.get(key) ?? 0;
64
+ if (pending > 0) {
65
+ const waiting = new Map(state.waiting);
66
+ if (pending === 1) waiting.delete(key);
67
+ else waiting.set(key, pending - 1);
68
+ return { startNext: true, state: { running: state.running, waiting } };
69
+ }
70
+ const running = new Set(state.running);
71
+ running.delete(key);
72
+ return { startNext: false, state: { running, waiting: state.waiting } };
73
+ }
@@ -1,6 +1,4 @@
1
1
  import type { SchemaStructure } from '@spooky-sync/query-builder';
2
- import type { DataModule } from '../data/index';
3
- import type { Sp00kySync } from '../sync/index';
4
2
  import type { AuthService } from '../auth/index';
5
3
  import type { Logger } from '../../services/logger/index';
6
4
  import type { QueryTimeToLive } from '../../types';
@@ -89,10 +87,20 @@ export class AppReleaseHandle {
89
87
  }
90
88
  }
91
89
 
90
+ /** The slice of the query engine this module drives: register a live query
91
+ * locally, ask for its remote registration, subscribe to its rows. */
92
+ export interface LiveQueryPort {
93
+ query(table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive): Promise<string>;
94
+ subscribe(hash: string, cb: (records: Record<string, any>[]) => void, options?: { immediate?: boolean }): () => void;
95
+ }
96
+ export interface RemoteRegisterPort {
97
+ enqueueDownEvent(event: { type: 'register'; payload: { hash: string } }): void;
98
+ }
99
+
92
100
  export interface AppReleaseModuleDeps<S extends SchemaStructure> {
93
- dataModule: DataModule<S>;
94
- sync: Sp00kySync<S>;
95
- auth: AuthService<S>;
101
+ dataModule: LiveQueryPort;
102
+ sync: RemoteRegisterPort;
103
+ auth: Pick<AuthService<S>, 'subscribe'>;
96
104
  logger: Logger;
97
105
  }
98
106