@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,482 @@
1
+ import type { Surreal } from 'surrealdb';
2
+ import type {
3
+ BackendNames,
4
+ BackendRoutes,
5
+ FinalQuery,
6
+ GetTable,
7
+ InnerQuery,
8
+ QueryOptions,
9
+ RoutePayload,
10
+ SchemaStructure,
11
+ TableModel,
12
+ TableNames,
13
+ BucketNames,
14
+ } from '@spooky-sync/query-builder';
15
+ import { QueryBuilder } from '@spooky-sync/query-builder';
16
+ import type {
17
+ PreloadOptions,
18
+ QueryAuthorityCallback,
19
+ QueryStatusCallback,
20
+ QueryTimeToLive,
21
+ RunOptions,
22
+ Sp00kyConfig,
23
+ Sp00kyQueryResultPromise,
24
+ StorageHealth,
25
+ SyncHealth,
26
+ UpdateOptions,
27
+ } from '../types';
28
+ import type { TabRole } from '../services/tabs/protocol';
29
+ import { StreamProcessorService } from '../services/stream-processor/index';
30
+ import type { StreamUpdateReceiver } from '../services/stream-processor/index';
31
+ import { AuthService } from '../modules/auth/index';
32
+ import { CrdtField } from '../modules/crdt/index';
33
+ import { FeatureFlagModule, FeatureFlagHandle } from '../modules/feature-flag/index';
34
+ import type { FeatureFlagOptions, FeatureFlagOverride } from '../modules/feature-flag/index';
35
+ import { AppReleaseModule, AppReleaseHandle } from '../modules/app-release/index';
36
+ import type { AppReleaseOptions } from '../modules/app-release/index';
37
+ import { DevToolsService } from '../modules/devtools/index';
38
+ import type { DevToolsQuerySource } from '../modules/devtools/index';
39
+ import { parseQueryParams, generateId } from '../utils/index';
40
+ import type { OutEvent, RuntimeEvent } from '../kernel/events';
41
+ import type { ClientState } from '../state/client-state';
42
+ import * as R from '../state/reducers';
43
+ import { pendingMutationCount, fetchingQueryCount, phaseTimings, toQueryState } from '../state/selectors';
44
+ import { defaultEnv, type SagaEnv } from '../query/env';
45
+ import { registerLocal, type RegisterInput } from '../query/register.saga';
46
+ import { evictQuery } from '../query/lifecycle.saga';
47
+ import { write } from '../mutation/write.saga';
48
+ import { discardFailed, listFailed, retryFailed } from '../mutation/tray.saga';
49
+ import type { FailedMutationRow } from '../mutation/rows';
50
+ import { buildJobRecord } from '../mutation/jobs';
51
+ import { boot } from '../boot/boot.saga';
52
+ import { preload } from '../boot/preload.saga';
53
+ import { DEGRADE_AFTER_FAILURES, OUTBOX_BATCH_SIZE, PUSH_TIMEOUT_MS } from '../kernel/constants';
54
+ import { Runtime } from './runtime';
55
+ import { createAdapters, createServices, createTabsCoordinator, type ServiceHost, type Services } from './services';
56
+ import { BucketHandle } from './bucket-handle';
57
+ import type { LeaderSyncHub, SyncForwarder } from '../services/tabs/coordinator';
58
+
59
+ const UNKNOWN_STORAGE_HEALTH: StorageHealth = Object.freeze({ status: 'unknown', fallback: false });
60
+
61
+ export interface Sp00kyClientDeps<S extends SchemaStructure> {
62
+ services?: Services<S>;
63
+ runtime?: Runtime;
64
+ env?: Partial<SagaEnv>;
65
+ }
66
+
67
+ /**
68
+ * The public client. Every method is a thin translation into a saga run, a
69
+ * state read, or a subscription on the runtime; the engine's behaviour lives
70
+ * in the sagas.
71
+ */
72
+ export class Sp00kyClient<S extends SchemaStructure> {
73
+ public readonly auth: AuthService<S>;
74
+ public readonly streamProcessor: StreamProcessorService;
75
+
76
+ private readonly services: Services<S>;
77
+ private readonly env: SagaEnv;
78
+ private readonly runtime: Runtime;
79
+ private readonly featureFlags: FeatureFlagModule<S>;
80
+ private readonly appReleases: AppReleaseModule<S>;
81
+ private readonly devTools: DevToolsService;
82
+ private hub: LeaderSyncHub | null = null;
83
+ private forwarder: SyncForwarder | null = null;
84
+ private detachWindow: (() => void) | null = null;
85
+ private sharedActive = false;
86
+
87
+ constructor(
88
+ private readonly config: Sp00kyConfig<S>,
89
+ deps: Sp00kyClientDeps<S> = {}
90
+ ) {
91
+ this.services = deps.services ?? createServices(config);
92
+ const s = this.services;
93
+ this.env = defaultEnv(config.schema, {
94
+ anonLive: config.enableAnonymousLiveQueries === true,
95
+ remoteTimeoutMs: Math.max(0, config.database.queryTimeoutMs ?? 60_000),
96
+ pushTimeoutMs: config.pushTimeoutMs ?? PUSH_TIMEOUT_MS,
97
+ outboxBatchSize: OUTBOX_BATCH_SIZE,
98
+ degradeAfter: config.syncHealth === false ? 0 : (config.syncHealth?.degradeAfterConsecutiveFailures ?? DEGRADE_AFTER_FAILURES),
99
+ materializeDebounceMs: config.streamDebounceTime ?? 50,
100
+ pollBaseMs: config.refSyncIntervalMs && config.refSyncIntervalMs > 0 ? config.refSyncIntervalMs : 500,
101
+ ...deps.env,
102
+ });
103
+ const host: ServiceHost = {
104
+ dispatch: (event) => void this.runtime.dispatch(event),
105
+ setTabsChannel: ({ hub, forwarder }) => {
106
+ this.hub = hub;
107
+ this.forwarder = forwarder;
108
+ this.sharedActive = hub !== null || forwarder !== null;
109
+ },
110
+ initModules: () => undefined,
111
+ detachWindow: () => this.detachWindow?.(),
112
+ setDetachWindow: (fn) => (this.detachWindow = fn),
113
+ };
114
+ if (!deps.runtime && s.tabs === null && s.tabsUnsupportedReason === undefined) {
115
+ s.tabs = createTabsCoordinator(config, s, host);
116
+ }
117
+ this.runtime =
118
+ deps.runtime ??
119
+ new Runtime({
120
+ env: this.env,
121
+ adapters: createAdapters(config, s, host, () => [this.featureFlags, this.appReleases]),
122
+ logger: s.logger,
123
+ tabId: s.tabId,
124
+ });
125
+ this.auth = s.auth;
126
+ this.streamProcessor = s.streamProcessor;
127
+
128
+ const liveQueryPort = {
129
+ query: (table: string, surql: string, params: Record<string, unknown>, ttl: QueryTimeToLive) =>
130
+ this.runtime.run(registerLocal(this.env, { tableName: table, surql, params, ttl })),
131
+ subscribe: (hash: string, cb: (records: Record<string, any>[]) => void, options?: { immediate?: boolean }) =>
132
+ this.runtime.subscribe(hash, cb, options),
133
+ };
134
+ const remoteRegisterPort = { enqueueDownEvent: () => void this.runtime.dispatch({ type: 'EnsureRegistered' }) };
135
+ this.featureFlags = new FeatureFlagModule<S>({ dataModule: liveQueryPort, sync: remoteRegisterPort, auth: s.auth, logger: s.logger });
136
+ this.appReleases = new AppReleaseModule<S>({ dataModule: liveQueryPort, sync: remoteRegisterPort, auth: s.auth, logger: s.logger });
137
+
138
+ const querySource: DevToolsQuerySource = {
139
+ getActiveQueries: () => [...this.runtime.state.queries.values()].map(toQueryState),
140
+ getQueryById: (id) => {
141
+ const entry = [...this.runtime.state.queries.values()].find((e) => String(e.def.id) === String(id));
142
+ return entry ? toQueryState(entry) : undefined;
143
+ },
144
+ phaseTimings: (q) => {
145
+ const entry = this.runtime.state.queries.get(q.config.id.id as string) ?? [...this.runtime.state.queries.values()].find((e) => String(e.def.id) === String(q.config.id));
146
+ return entry ? phaseTimings(entry) : ({} as never);
147
+ },
148
+ };
149
+ this.devTools = new DevToolsService(s.local, s.remote, s.logger, config.schema, s.auth, querySource);
150
+ this.devTools.setFeatureFlagOverrides(this.featureFlags);
151
+ s.streamProcessor.addReceiver(this.devTools);
152
+ this.devTools.setBlobInfoProvider(() => s.blobs.stats());
153
+ if (config.sharedTabs) {
154
+ this.devTools.setTabsInfoProvider(() => {
155
+ const c = s.tabs;
156
+ if (!this.sharedActive || !c) return { active: false, reason: s.tabsUnsupportedReason ?? 'fell-back' };
157
+ return {
158
+ active: true,
159
+ role: c.role,
160
+ tabId: c.tabId,
161
+ leadershipId: c.leadershipId,
162
+ leaderTabId: c.role === 'leader' ? c.tabId : c.leaderTabId,
163
+ ...(this.hub ? { followers: this.hub.followerCount, relayedBatches: this.hub.relayedBatches } : {}),
164
+ };
165
+ });
166
+ }
167
+ this.wireAdapters();
168
+ }
169
+
170
+ /** Adapter callbacks become runtime events; runtime events reach the legacy services. */
171
+ private wireAdapters(): void {
172
+ const s = this.services;
173
+ const receiver: StreamUpdateReceiver = { onStreamUpdate: (update) => void this.runtime.dispatch({ type: 'StreamUpdate', update }) };
174
+ s.streamProcessor.addReceiver(receiver);
175
+ s.connectionSupervisor.subscribe((state) => void this.runtime.dispatch({ type: 'ConnectionChanged', state }));
176
+ s.auth.subscribe((userId) => void this.runtime.dispatch({ type: 'AuthFlip', userId }));
177
+ this.runtime.on('tabs:broadcast', (e) => {
178
+ if (e.type !== 'tabs:broadcast') return;
179
+ const msg = e.message as { type: string; records?: unknown[]; mutationId?: string };
180
+ if (this.hub) {
181
+ if (msg.type === 'ingest') this.hub.relayIngest(msg.records as never);
182
+ else this.hub.broadcast(msg as never);
183
+ } else if (this.forwarder) {
184
+ if (msg.type === 'ingest') this.forwarder.ingest(msg.records as never);
185
+ else if (msg.type === 'outbox-changed' && msg.mutationId) this.forwarder.mutationEnqueued(msg.mutationId);
186
+ }
187
+ });
188
+ this.runtime.on('tabs:sendTo', (e) => {
189
+ if (e.type === 'tabs:sendTo' && this.hub) this.hub.sendTo(e.tabId, e.message as never);
190
+ });
191
+ this.runtime.on('*', (e) => this.forwardToDevTools(e));
192
+ s.local.getEvents().subscribe('DATABASE_LOCAL_QUERY', (event: any) => this.devTools.logEvent('LOCAL_QUERY', event.payload));
193
+ s.remote.getEvents().subscribe('DATABASE_REMOTE_QUERY', (event: any) => this.devTools.logEvent('REMOTE_QUERY', event.payload));
194
+ }
195
+
196
+ private forwardToDevTools(e: OutEvent): void {
197
+ switch (e.type) {
198
+ case 'query:status':
199
+ this.devTools.logEvent('QUERY_STATUS_CHANGED', { queryHash: e.hash, status: e.status });
200
+ break;
201
+ case 'query:authority':
202
+ this.devTools.logEvent('QUERY_AUTHORITY_CHANGED', { queryHash: e.hash, known: e.known });
203
+ break;
204
+ case 'query:view-lost':
205
+ this.devTools.logEvent('QUERY_VIEW_LOST', { queryHash: e.hash });
206
+ break;
207
+ case 'mutation:event':
208
+ this.devTools.onMutation([e.event]);
209
+ break;
210
+ case 'devtools':
211
+ this.devTools.logEvent(e.name, e.data);
212
+ break;
213
+ default:
214
+ break;
215
+ }
216
+ }
217
+
218
+ // ---- lifecycle ---------------------------------------------------------------
219
+
220
+ async init(): Promise<void> {
221
+ await this.runtime.run(boot(this.env, { sharedTabs: this.services.tabs !== null }));
222
+ }
223
+
224
+ async close(): Promise<void> {
225
+ const s = this.services;
226
+ s.connectionSupervisor.dispose();
227
+ this.runtime.dispose();
228
+ await this.featureFlags.closeAll();
229
+ await this.appReleases.closeAll();
230
+ s.crdt.closeAll();
231
+ s.crdt.dispose();
232
+ await s.blobs.close().catch(() => {});
233
+ await s.streamProcessor.checkpoint('close').catch(() => {});
234
+ if (s.tabs) await s.tabs.stop();
235
+ this.detachWindow?.();
236
+ this.detachWindow = null;
237
+ await s.local.close();
238
+ await s.remote.close();
239
+ s.streamProcessor.dispose();
240
+ }
241
+
242
+ isLocalReady(): boolean {
243
+ return this.runtime.state.localReady;
244
+ }
245
+
246
+ // ---- queries -----------------------------------------------------------------
247
+
248
+ query<Table extends TableNames<S>>(
249
+ table: Table,
250
+ options: QueryOptions<TableModel<GetTable<S, Table>>, false>,
251
+ ttl: QueryTimeToLive = '10m'
252
+ ): QueryBuilder<S, Table, Sp00kyQueryResultPromise> {
253
+ return new QueryBuilder<S, Table, Sp00kyQueryResultPromise>(this.config.schema, table, async (q) => ({ hash: await this.initQuery(table, q, ttl) }), options);
254
+ }
255
+
256
+ private registerInput(table: string, q: InnerQuery<any, any, any>, ttl: QueryTimeToLive): RegisterInput {
257
+ const tableSchema = this.config.schema.tables.find((t) => t.name === table);
258
+ if (!tableSchema) throw new Error(`Table ${table} not found`);
259
+ return {
260
+ tableName: table,
261
+ surql: q.selectQuery.query,
262
+ params: parseQueryParams(tableSchema.columns, q.selectQuery.vars ?? {}),
263
+ ttl,
264
+ plan: q.selectQuery.plan,
265
+ };
266
+ }
267
+
268
+ private initQuery(table: string, q: InnerQuery<any, any, any>, ttl: QueryTimeToLive): Promise<string> {
269
+ return this.runtime.run(registerLocal(this.env, this.registerInput(table, q, ttl)));
270
+ }
271
+
272
+ async queryRaw(sql: string, params: Record<string, any>, ttl: QueryTimeToLive): Promise<string> {
273
+ const tableName = sql.split('FROM ')[1]?.split(' ')[0] ?? '';
274
+ return this.runtime.run(registerLocal(this.env, { tableName, surql: sql, params, ttl }));
275
+ }
276
+
277
+ /**
278
+ * Preload = register a query nobody subscribes to. Resolved before on this
279
+ * device: returns at once. Never resolved: resolves when the server's
280
+ * membership and every body are local. `signal` aborts the wait.
281
+ */
282
+ async preload(finalQuery: FinalQuery<S, any, any, any, any, any>, options?: PreloadOptions): Promise<void> {
283
+ const q = finalQuery.innerQuery;
284
+ await this.runtime.run(preload(this.env, this.registerInput(q.tableName, q, '10m')), { signal: options?.signal });
285
+ }
286
+
287
+ async subscribe(queryHash: string, callback: (records: Record<string, any>[]) => void, options?: { immediate?: boolean }): Promise<() => void> {
288
+ return this.runtime.subscribe(queryHash, callback, options);
289
+ }
290
+
291
+ deregisterQuery(queryHash: string): void {
292
+ const entry = this.runtime.state.queries.get(queryHash);
293
+ if (!entry || entry.subscribers > 0) return;
294
+ void this.runtime.run(evictQuery(queryHash), { lane: { kind: 'serial', key: `mat:${queryHash}` } });
295
+ }
296
+
297
+ subscribeQueryStatus(queryHash: string, callback: QueryStatusCallback, options?: { immediate?: boolean }): () => void {
298
+ return this.runtime.subscribeStatus(queryHash, callback, options);
299
+ }
300
+
301
+ subscribeQueryAuthority(queryHash: string, callback: QueryAuthorityCallback, options?: { immediate?: boolean }): () => void {
302
+ return this.runtime.subscribeAuthority(queryHash, callback, options);
303
+ }
304
+
305
+ reportFrontendTiming(queryHash: string, ms: number): void {
306
+ if (Number.isFinite(ms)) this.runtime.update(R.recordPhase(queryHash, 'frontend', ms));
307
+ }
308
+
309
+ // ---- mutations ---------------------------------------------------------------
310
+
311
+ async create<T extends Record<string, unknown>>(id: string, data: T): Promise<T> {
312
+ const out = await this.runtime.run(write(this.env, { kind: 'create', recordId: id, data }));
313
+ return (out.record ?? data) as T;
314
+ }
315
+
316
+ async update<T extends Record<string, unknown>>(_table: string, id: string, data: Partial<T>, options?: UpdateOptions): Promise<T> {
317
+ const out = await this.runtime.run(write(this.env, { kind: 'update', recordId: id, data: data as Record<string, unknown>, options }));
318
+ return (out.record ?? data) as T;
319
+ }
320
+
321
+ async delete(_table: string, id: string): Promise<void> {
322
+ await this.runtime.run(write(this.env, { kind: 'delete', recordId: id }));
323
+ }
324
+
325
+ async run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(backend: B, path: R, payload: RoutePayload<S, B, R>, options?: RunOptions): Promise<void> {
326
+ const { tableName, record } = buildJobRecord(this.config.schema, String(backend), String(path), payload as Record<string, unknown>, options);
327
+ await this.create(`${tableName}:${generateId()}`, record);
328
+ }
329
+
330
+ // ---- failed-writes tray -------------------------------------------------------
331
+
332
+ get failedMutationCount(): number {
333
+ return this.runtime.state.failedCount;
334
+ }
335
+
336
+ subscribeToFailedMutations(cb: (count: number) => void): () => void {
337
+ cb(this.runtime.state.failedCount);
338
+ return this.runtime.on('tray:changed', (e) => {
339
+ if (e.type === 'tray:changed') cb(e.count);
340
+ });
341
+ }
342
+
343
+ listFailedMutations(): Promise<FailedMutationRow[]> {
344
+ return this.runtime.run(listFailed());
345
+ }
346
+
347
+ async retryFailedMutation(mutationId: string): Promise<boolean> {
348
+ return this.runtime.run(retryFailed(this.env, mutationId), { lane: { kind: 'serial', key: 'tray' } });
349
+ }
350
+
351
+ async discardFailedMutation(mutationId: string): Promise<boolean> {
352
+ return this.runtime.run(discardFailed(mutationId), { lane: { kind: 'serial', key: 'tray' } });
353
+ }
354
+
355
+ // ---- observability -----------------------------------------------------------
356
+
357
+ get tabRole(): TabRole | null {
358
+ return this.sharedActive && this.services.tabs ? this.services.tabs.role : null;
359
+ }
360
+
361
+ get remoteClient(): Surreal {
362
+ return this.services.remote.getClient();
363
+ }
364
+
365
+ get localClient(): unknown {
366
+ return this.services.local.getClient();
367
+ }
368
+
369
+ get pendingMutationCount(): number {
370
+ return pendingMutationCount(this.runtime.state);
371
+ }
372
+
373
+ /** Kept for the e2e suite; the saga core has no LIVE retry ladder. */
374
+ get liveRetryCount(): number {
375
+ return 0;
376
+ }
377
+
378
+ subscribeToPendingMutations(cb: (count: number) => void): () => void {
379
+ cb(this.pendingMutationCount);
380
+ return this.runtime.on('activity:changed', (e) => {
381
+ if (e.type === 'activity:changed') cb(e.pending);
382
+ });
383
+ }
384
+
385
+ get fetchingQueryCount(): number {
386
+ return fetchingQueryCount(this.runtime.state);
387
+ }
388
+
389
+ subscribeToFetchActivity(cb: (fetching: number) => void): () => void {
390
+ cb(this.fetchingQueryCount);
391
+ return this.runtime.on('activity:changed', (e) => {
392
+ if (e.type === 'activity:changed') cb(e.fetching);
393
+ });
394
+ }
395
+
396
+ get syncHealth(): SyncHealth {
397
+ return this.runtime.state.sync.health;
398
+ }
399
+
400
+ subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void {
401
+ cb(this.syncHealth);
402
+ return this.runtime.on('health:changed', (e) => {
403
+ if (e.type === 'health:changed') cb(e.health);
404
+ });
405
+ }
406
+
407
+ get storageHealth(): StorageHealth {
408
+ return this.services.local.storageHealth ?? UNKNOWN_STORAGE_HEALTH;
409
+ }
410
+
411
+ subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void {
412
+ if (this.services.local.subscribeToStorageHealth) return this.services.local.subscribeToStorageHealth(cb);
413
+ cb(UNKNOWN_STORAGE_HEALTH);
414
+ return () => {};
415
+ }
416
+
417
+ /** The engine state, read-only. For tests and DevTools. */
418
+ get state(): ClientState {
419
+ return this.runtime.state;
420
+ }
421
+
422
+ /** Feed an event into the engine. For adapters, tests and DevTools. */
423
+ dispatch(event: RuntimeEvent): Promise<void> {
424
+ return this.runtime.dispatch(event);
425
+ }
426
+
427
+ // ---- auth / remote / crdt / flags / buckets ------------------------------------
428
+
429
+ authenticate(token: string) {
430
+ this.services.remote.setAuthToken(token);
431
+ return this.services.remote.getClient().authenticate(token);
432
+ }
433
+
434
+ deauthenticate() {
435
+ return this.services.remote.getClient().invalidate();
436
+ }
437
+
438
+ async useRemote<T>(fn: (client: Surreal) => Promise<T> | T): Promise<T> {
439
+ return fn(this.services.remote.getClient());
440
+ }
441
+
442
+ async remoteQuery<T extends unknown[]>(sql: string, vars?: Record<string, unknown>): Promise<T> {
443
+ return this.services.remote.query<T>(sql, vars);
444
+ }
445
+
446
+ feature(key: string, options?: FeatureFlagOptions): FeatureFlagHandle {
447
+ return this.featureFlags.feature(key, options);
448
+ }
449
+
450
+ setFeatureOverride(key: string, variant: string | null, payload?: unknown): void {
451
+ this.featureFlags.setLocalOverride(key, variant, payload);
452
+ }
453
+
454
+ clearFeatureOverrides(): void {
455
+ this.featureFlags.clearLocalOverrides();
456
+ }
457
+
458
+ getFeatureOverrides(): Record<string, FeatureFlagOverride> {
459
+ return this.featureFlags.getLocalOverrides();
460
+ }
461
+
462
+ appRelease(app: string, options?: AppReleaseOptions): AppReleaseHandle {
463
+ return this.appReleases.release(app, options);
464
+ }
465
+
466
+ async openCrdtField(table: string, recordId: string, field: string, fallbackText?: string): Promise<CrdtField> {
467
+ return this.services.crdt.open(table, recordId, field, fallbackText);
468
+ }
469
+
470
+ closeCrdtField(table: string, recordId: string, field: string): void {
471
+ this.services.crdt.close(table, recordId, field);
472
+ }
473
+
474
+ bucket<B extends BucketNames<S>>(name: B): BucketHandle {
475
+ return new BucketHandle(name, this.services.remote, this.services.blobs, { blurhash: this.config.blurhash, logger: this.services.logger });
476
+ }
477
+
478
+ getBlobCacheStats() {
479
+ return this.services.blobs.stats();
480
+ }
481
+ }
482
+
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ export type {
22
22
  BlobReadOptions,
23
23
  BlobUrlLease,
24
24
  } from './services/blobs/index';
25
+ export type { FailedMutationRow as FailedMutation } from './mutation/rows';
25
26
  export { semverGt } from './utils/semver';
26
27
  export { LocalOpTimeoutError, DEFAULT_LOCAL_OP_TIMEOUT_MS } from './services/database/errors';
27
28
  export { fileToUint8Array, textToHtml } from './utils/index';
@@ -0,0 +1,19 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { backoffMs, RETRY_BASE_MS, RETRY_MAX_MS } from './constants';
3
+
4
+ describe('backoffMs', () => {
5
+ it('doubles from the base and caps at the max', () => {
6
+ expect(backoffMs(0)).toBe(RETRY_BASE_MS);
7
+ expect(backoffMs(1)).toBe(RETRY_BASE_MS * 2);
8
+ expect(backoffMs(3)).toBe(RETRY_BASE_MS * 8);
9
+ expect(backoffMs(20)).toBe(RETRY_MAX_MS);
10
+ });
11
+ it('clamps negative and huge attempts', () => {
12
+ expect(backoffMs(-5)).toBe(RETRY_BASE_MS);
13
+ expect(backoffMs(10_000)).toBe(RETRY_MAX_MS);
14
+ });
15
+ it('honours custom base and max', () => {
16
+ expect(backoffMs(2, 100, 250)).toBe(250);
17
+ expect(backoffMs(1, 100, 250)).toBe(200);
18
+ });
19
+ });
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Every timing constant of the saga core in one place. Sagas never call
3
+ * `setTimeout`; they yield `timer.set` effects with one of these delays, so a
4
+ * test can pin the schedule by asserting the effect log.
5
+ */
6
+
7
+ /** Trailing coalesce for materialization after a state change. */
8
+ export const MATERIALIZE_DEBOUNCE_MS = 50;
9
+ /** Coalesce window for LIVE membership dirt before the batched edge re-read. */
10
+ export const MEMBERSHIP_COALESCE_MS = 50;
11
+ /** Re-read ladder while the server reports a view as `materializing`. */
12
+ export const MATERIALIZING_REREAD_LADDER_MS: readonly number[] = [150, 400, 1000];
13
+ /** How long an acked outbox item stays in the overlay when membership never names it. */
14
+ export const ACK_GRACE_MS = 30_000;
15
+ /** Ids per body-fetch statement. */
16
+ export const FETCH_CHUNK = 500;
17
+ /** Outbox statements per push request. */
18
+ export const OUTBOX_BATCH_SIZE = 50;
19
+ /** Push deadline per outbox batch. */
20
+ export const PUSH_TIMEOUT_MS = 30_000;
21
+ /** Exponential backoff for outbox / fetch / registration retries. */
22
+ export const RETRY_BASE_MS = 500;
23
+ export const RETRY_MAX_MS = 15_000;
24
+ /** Registration attempts before a query is reported as failed to settle. */
25
+ export const REGISTER_MAX_RETRIES = 3;
26
+ /** `_00_list_ref` poll cadence (fallback when LIVE is quiet). */
27
+ export const LIST_REF_POLL_BASE_MS = 500;
28
+ export const LIST_REF_POLL_MAX_MS = 5_000;
29
+ export const LIST_REF_ROW_BUDGET = 1_500;
30
+ export const LIST_REF_LARGE_VIEW_EDGES = 1_000;
31
+ export const LIST_REF_LARGE_VIEW_POLL_MS = 15_000;
32
+ /** Self-heal cadence while sync health is degraded. */
33
+ export const SELF_HEAL_BASE_MS = 2_000;
34
+ export const SELF_HEAL_MAX_MS = 30_000;
35
+ /** Consecutive failed rounds before health flips to degraded. */
36
+ export const DEGRADE_AFTER_FAILURES = 3;
37
+ /** Burst coalescing of reconnects. */
38
+ export const RECONNECT_REFETCH_COOLDOWN_MS = 10_000;
39
+ /** Waiting for `$auth.id` to be visible after a reconnect. */
40
+ export const AUTH_READY_RETRY_MS = 500;
41
+ export const AUTH_READY_MAX_ATTEMPTS = 10;
42
+ /** Heartbeat at this fraction of the shortest ttl in state. */
43
+ export const TTL_HEARTBEAT_FRACTION = 0.5;
44
+ /** Orphan body garbage collection cadence. */
45
+ export const GC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
46
+ /** Remote adapter slot limit. */
47
+ export const REMOTE_CONCURRENCY = 16;
48
+ /** Rolling telemetry sample window per query. */
49
+ export const TELEMETRY_SAMPLE_WINDOW = 100;
50
+
51
+ export function backoffMs(attempt: number, base = RETRY_BASE_MS, max = RETRY_MAX_MS): number {
52
+ const n = Math.max(0, Math.min(attempt, 30));
53
+ return Math.min(max, base * 2 ** n);
54
+ }
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { fx } from './effects';
3
+
4
+ describe('effect constructors', () => {
5
+ it('build every effect kind as plain data', () => {
6
+ const sealed = { sql: 'x;', extract: (r: unknown[]) => r[0] };
7
+ const plan = { table: 't' } as any;
8
+ const cases: Array<[ReturnType<typeof fx.now>, string]> = [
9
+ [fx.local.query('SELECT 1', { a: 1 }, 3), 'local.query'],
10
+ [fx.local.select(plan, { b: 2 }), 'local.select'],
11
+ [fx.local.execute(sealed, {}, 1), 'local.execute'],
12
+ [fx.local.getById('t', 'x'), 'local.getById'],
13
+ [fx.local.upsert('t', 'x', { a: 1 }, 'merge'), 'local.upsert'],
14
+ [fx.local.delete('t', 'x'), 'local.delete'],
15
+ [fx.remote.query('RETURN true', undefined, 10), 'remote.query'],
16
+ [fx.remote.live('_00_list_ref'), 'remote.live'],
17
+ [fx.remote.kill('u'), 'remote.kill'],
18
+ [fx.ssp.register({ queryHash: 'h', surql: 's', params: {}, ttl: '10m', tableName: 't' }), 'ssp.register'],
19
+ [fx.ssp.unregister('h'), 'ssp.unregister'],
20
+ [fx.ssp.ingest([]), 'ssp.ingest'],
21
+ [fx.timer.set('k', 5, { type: 'Drain' }), 'timer.set'],
22
+ [fx.timer.clear('k'), 'timer.clear'],
23
+ [fx.state.read((s) => s.tabId), 'state.read'],
24
+ [fx.state.update((s) => s), 'state.update'],
25
+ [fx.state.wait((s) => s.primed), 'state.wait'],
26
+ [fx.now(), 'now'],
27
+ [fx.id('mutation'), 'id'],
28
+ [fx.hash('abc'), 'hash'],
29
+ [fx.emit({ type: 'tray:changed', count: 1 }), 'emit'],
30
+ [fx.dispatch({ type: 'FetchRows' }), 'dispatch'],
31
+ [fx.all([fx.now()]), 'all'],
32
+ [fx.service('local.connect', 'anon'), 'service'],
33
+ ];
34
+ for (const [effect, kind] of cases) expect(effect.kind).toBe(kind);
35
+ expect(fx.local.query('SELECT 1', { a: 1 }, 3)).toEqual({ kind: 'local.query', sql: 'SELECT 1', vars: { a: 1 }, epoch: 3 });
36
+ expect(fx.local.epoch()).toEqual({ kind: 'local.epoch' });
37
+ expect(fx.timer.set('k', 5, { type: 'Drain' })).toEqual({ kind: 'timer.set', key: 'k', ms: 5, event: { type: 'Drain' } });
38
+ expect(fx.service('hint.write', 'u1')).toEqual({ kind: 'service', name: 'hint.write', args: ['u1'] });
39
+ });
40
+ });