@terreno/syncdb 56.0.0-beta.0

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 (317) hide show
  1. package/README.md +419 -0
  2. package/dist/auth/betterAuthAdapter.d.ts +22 -0
  3. package/dist/auth/betterAuthAdapter.d.ts.map +1 -0
  4. package/dist/auth/betterAuthAdapter.js +181 -0
  5. package/dist/auth/betterAuthAdapter.js.map +1 -0
  6. package/dist/auth/betterAuthAdapter.test.d.ts +2 -0
  7. package/dist/auth/betterAuthAdapter.test.d.ts.map +1 -0
  8. package/dist/auth/betterAuthAdapter.test.js +350 -0
  9. package/dist/auth/betterAuthAdapter.test.js.map +1 -0
  10. package/dist/auth/types.d.ts +42 -0
  11. package/dist/auth/types.d.ts.map +1 -0
  12. package/dist/auth/types.js +9 -0
  13. package/dist/auth/types.js.map +1 -0
  14. package/dist/client.d.ts +246 -0
  15. package/dist/client.d.ts.map +1 -0
  16. package/dist/client.js +1415 -0
  17. package/dist/client.js.map +1 -0
  18. package/dist/client.test.d.ts +2 -0
  19. package/dist/client.test.d.ts.map +1 -0
  20. package/dist/client.test.js +2310 -0
  21. package/dist/client.test.js.map +1 -0
  22. package/dist/crypto/aesGcmCodec.d.ts +33 -0
  23. package/dist/crypto/aesGcmCodec.d.ts.map +1 -0
  24. package/dist/crypto/aesGcmCodec.js +80 -0
  25. package/dist/crypto/aesGcmCodec.js.map +1 -0
  26. package/dist/crypto/aesGcmCodec.test.d.ts +2 -0
  27. package/dist/crypto/aesGcmCodec.test.d.ts.map +1 -0
  28. package/dist/crypto/aesGcmCodec.test.js +83 -0
  29. package/dist/crypto/aesGcmCodec.test.js.map +1 -0
  30. package/dist/crypto/identityCodec.d.ts +7 -0
  31. package/dist/crypto/identityCodec.d.ts.map +1 -0
  32. package/dist/crypto/identityCodec.js +9 -0
  33. package/dist/crypto/identityCodec.js.map +1 -0
  34. package/dist/crypto/keyProviders.d.ts +34 -0
  35. package/dist/crypto/keyProviders.d.ts.map +1 -0
  36. package/dist/crypto/keyProviders.js +102 -0
  37. package/dist/crypto/keyProviders.js.map +1 -0
  38. package/dist/crypto/keyProviders.test.d.ts +2 -0
  39. package/dist/crypto/keyProviders.test.d.ts.map +1 -0
  40. package/dist/crypto/keyProviders.test.js +189 -0
  41. package/dist/crypto/keyProviders.test.js.map +1 -0
  42. package/dist/crypto/types.d.ts +24 -0
  43. package/dist/crypto/types.d.ts.map +1 -0
  44. package/dist/crypto/types.js +8 -0
  45. package/dist/crypto/types.js.map +1 -0
  46. package/dist/debug/debugChannel.d.ts +52 -0
  47. package/dist/debug/debugChannel.d.ts.map +1 -0
  48. package/dist/debug/debugChannel.js +73 -0
  49. package/dist/debug/debugChannel.js.map +1 -0
  50. package/dist/debug/debugChannel.test.d.ts +2 -0
  51. package/dist/debug/debugChannel.test.d.ts.map +1 -0
  52. package/dist/debug/debugChannel.test.js +105 -0
  53. package/dist/debug/debugChannel.test.js.map +1 -0
  54. package/dist/debug/debugLog.d.ts +111 -0
  55. package/dist/debug/debugLog.d.ts.map +1 -0
  56. package/dist/debug/debugLog.js +150 -0
  57. package/dist/debug/debugLog.js.map +1 -0
  58. package/dist/debug/debugLog.test.d.ts +2 -0
  59. package/dist/debug/debugLog.test.d.ts.map +1 -0
  60. package/dist/debug/debugLog.test.js +121 -0
  61. package/dist/debug/debugLog.test.js.map +1 -0
  62. package/dist/index.d.ts +46 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +51 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts +2 -0
  67. package/dist/isolated/defaultPersisterFactoryNative.isolated.d.ts.map +1 -0
  68. package/dist/isolated/defaultPersisterFactoryNative.isolated.js +38 -0
  69. package/dist/isolated/defaultPersisterFactoryNative.isolated.js.map +1 -0
  70. package/dist/mutations/conflicts.d.ts +31 -0
  71. package/dist/mutations/conflicts.d.ts.map +1 -0
  72. package/dist/mutations/conflicts.js +73 -0
  73. package/dist/mutations/conflicts.js.map +1 -0
  74. package/dist/mutations/outbox.d.ts +174 -0
  75. package/dist/mutations/outbox.d.ts.map +1 -0
  76. package/dist/mutations/outbox.js +385 -0
  77. package/dist/mutations/outbox.js.map +1 -0
  78. package/dist/mutations/outbox.test.d.ts +2 -0
  79. package/dist/mutations/outbox.test.d.ts.map +1 -0
  80. package/dist/mutations/outbox.test.js +643 -0
  81. package/dist/mutations/outbox.test.js.map +1 -0
  82. package/dist/mutations/resolveConflict.d.ts +32 -0
  83. package/dist/mutations/resolveConflict.d.ts.map +1 -0
  84. package/dist/mutations/resolveConflict.js +101 -0
  85. package/dist/mutations/resolveConflict.js.map +1 -0
  86. package/dist/mutations/resolveConflict.test.d.ts +2 -0
  87. package/dist/mutations/resolveConflict.test.d.ts.map +1 -0
  88. package/dist/mutations/resolveConflict.test.js +282 -0
  89. package/dist/mutations/resolveConflict.test.js.map +1 -0
  90. package/dist/persisters/defaultPersisterFactory.d.ts +9 -0
  91. package/dist/persisters/defaultPersisterFactory.d.ts.map +1 -0
  92. package/dist/persisters/defaultPersisterFactory.js +9 -0
  93. package/dist/persisters/defaultPersisterFactory.js.map +1 -0
  94. package/dist/persisters/defaultPersisterFactory.native.d.ts +10 -0
  95. package/dist/persisters/defaultPersisterFactory.native.d.ts.map +1 -0
  96. package/dist/persisters/defaultPersisterFactory.native.js +44 -0
  97. package/dist/persisters/defaultPersisterFactory.native.js.map +1 -0
  98. package/dist/persisters/defaultPersisterFactory.test.d.ts +2 -0
  99. package/dist/persisters/defaultPersisterFactory.test.d.ts.map +1 -0
  100. package/dist/persisters/defaultPersisterFactory.test.js +177 -0
  101. package/dist/persisters/defaultPersisterFactory.test.js.map +1 -0
  102. package/dist/persisters/defaultPersisterFactory.web.d.ts +17 -0
  103. package/dist/persisters/defaultPersisterFactory.web.d.ts.map +1 -0
  104. package/dist/persisters/defaultPersisterFactory.web.js +65 -0
  105. package/dist/persisters/defaultPersisterFactory.web.js.map +1 -0
  106. package/dist/persisters/encryptedIndexedDbPersister.d.ts +46 -0
  107. package/dist/persisters/encryptedIndexedDbPersister.d.ts.map +1 -0
  108. package/dist/persisters/encryptedIndexedDbPersister.js +171 -0
  109. package/dist/persisters/encryptedIndexedDbPersister.js.map +1 -0
  110. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts +2 -0
  111. package/dist/persisters/encryptedIndexedDbPersister.test.d.ts.map +1 -0
  112. package/dist/persisters/encryptedIndexedDbPersister.test.js +352 -0
  113. package/dist/persisters/encryptedIndexedDbPersister.test.js.map +1 -0
  114. package/dist/persisters/memoryPersister.d.ts +19 -0
  115. package/dist/persisters/memoryPersister.d.ts.map +1 -0
  116. package/dist/persisters/memoryPersister.js +31 -0
  117. package/dist/persisters/memoryPersister.js.map +1 -0
  118. package/dist/persisters/memoryPersister.test.d.ts +2 -0
  119. package/dist/persisters/memoryPersister.test.d.ts.map +1 -0
  120. package/dist/persisters/memoryPersister.test.js +113 -0
  121. package/dist/persisters/memoryPersister.test.js.map +1 -0
  122. package/dist/persisters/types.d.ts +65 -0
  123. package/dist/persisters/types.d.ts.map +1 -0
  124. package/dist/persisters/types.js +2 -0
  125. package/dist/persisters/types.js.map +1 -0
  126. package/dist/react/hooks.d.ts +132 -0
  127. package/dist/react/hooks.d.ts.map +1 -0
  128. package/dist/react/hooks.js +269 -0
  129. package/dist/react/hooks.js.map +1 -0
  130. package/dist/react/hooks.test.d.ts +2 -0
  131. package/dist/react/hooks.test.d.ts.map +1 -0
  132. package/dist/react/hooks.test.js +645 -0
  133. package/dist/react/hooks.test.js.map +1 -0
  134. package/dist/react/index.d.ts +11 -0
  135. package/dist/react/index.d.ts.map +1 -0
  136. package/dist/react/index.js +11 -0
  137. package/dist/react/index.js.map +1 -0
  138. package/dist/react/provider.d.ts +11 -0
  139. package/dist/react/provider.d.ts.map +1 -0
  140. package/dist/react/provider.js +17 -0
  141. package/dist/react/provider.js.map +1 -0
  142. package/dist/storage/idb.d.ts +27 -0
  143. package/dist/storage/idb.d.ts.map +1 -0
  144. package/dist/storage/idb.js +72 -0
  145. package/dist/storage/idb.js.map +1 -0
  146. package/dist/storage/idb.test.d.ts +2 -0
  147. package/dist/storage/idb.test.d.ts.map +1 -0
  148. package/dist/storage/idb.test.js +100 -0
  149. package/dist/storage/idb.test.js.map +1 -0
  150. package/dist/storage/purgeUnknownStream.test.d.ts +2 -0
  151. package/dist/storage/purgeUnknownStream.test.d.ts.map +1 -0
  152. package/dist/storage/purgeUnknownStream.test.js +64 -0
  153. package/dist/storage/purgeUnknownStream.test.js.map +1 -0
  154. package/dist/storage/schema.d.ts +33 -0
  155. package/dist/storage/schema.d.ts.map +1 -0
  156. package/dist/storage/schema.js +92 -0
  157. package/dist/storage/schema.js.map +1 -0
  158. package/dist/storage/store.d.ts +136 -0
  159. package/dist/storage/store.d.ts.map +1 -0
  160. package/dist/storage/store.js +275 -0
  161. package/dist/storage/store.js.map +1 -0
  162. package/dist/storage/store.test.d.ts +2 -0
  163. package/dist/storage/store.test.d.ts.map +1 -0
  164. package/dist/storage/store.test.js +357 -0
  165. package/dist/storage/store.test.js.map +1 -0
  166. package/dist/storage/types.d.ts +146 -0
  167. package/dist/storage/types.d.ts.map +1 -0
  168. package/dist/storage/types.js +32 -0
  169. package/dist/storage/types.js.map +1 -0
  170. package/dist/storage/wipe.d.ts +22 -0
  171. package/dist/storage/wipe.d.ts.map +1 -0
  172. package/dist/storage/wipe.js +43 -0
  173. package/dist/storage/wipe.js.map +1 -0
  174. package/dist/storage/wipe.test.d.ts +2 -0
  175. package/dist/storage/wipe.test.d.ts.map +1 -0
  176. package/dist/storage/wipe.test.js +95 -0
  177. package/dist/storage/wipe.test.js.map +1 -0
  178. package/dist/sync/bootstrap.d.ts +64 -0
  179. package/dist/sync/bootstrap.d.ts.map +1 -0
  180. package/dist/sync/bootstrap.js +160 -0
  181. package/dist/sync/bootstrap.js.map +1 -0
  182. package/dist/sync/bootstrap.test.d.ts +2 -0
  183. package/dist/sync/bootstrap.test.d.ts.map +1 -0
  184. package/dist/sync/bootstrap.test.js +447 -0
  185. package/dist/sync/bootstrap.test.js.map +1 -0
  186. package/dist/sync/cursor.d.ts +67 -0
  187. package/dist/sync/cursor.d.ts.map +1 -0
  188. package/dist/sync/cursor.js +74 -0
  189. package/dist/sync/cursor.js.map +1 -0
  190. package/dist/sync/cursor.test.d.ts +2 -0
  191. package/dist/sync/cursor.test.d.ts.map +1 -0
  192. package/dist/sync/cursor.test.js +73 -0
  193. package/dist/sync/cursor.test.js.map +1 -0
  194. package/dist/sync/deltaApplier.d.ts +30 -0
  195. package/dist/sync/deltaApplier.d.ts.map +1 -0
  196. package/dist/sync/deltaApplier.js +61 -0
  197. package/dist/sync/deltaApplier.js.map +1 -0
  198. package/dist/sync/deltaApplier.test.d.ts +2 -0
  199. package/dist/sync/deltaApplier.test.d.ts.map +1 -0
  200. package/dist/sync/deltaApplier.test.js +212 -0
  201. package/dist/sync/deltaApplier.test.js.map +1 -0
  202. package/dist/sync/entityRepair.d.ts +45 -0
  203. package/dist/sync/entityRepair.d.ts.map +1 -0
  204. package/dist/sync/entityRepair.js +91 -0
  205. package/dist/sync/entityRepair.js.map +1 -0
  206. package/dist/sync/entityRepair.test.d.ts +2 -0
  207. package/dist/sync/entityRepair.test.d.ts.map +1 -0
  208. package/dist/sync/entityRepair.test.js +146 -0
  209. package/dist/sync/entityRepair.test.js.map +1 -0
  210. package/dist/sync/httpChannel.d.ts +74 -0
  211. package/dist/sync/httpChannel.d.ts.map +1 -0
  212. package/dist/sync/httpChannel.js +123 -0
  213. package/dist/sync/httpChannel.js.map +1 -0
  214. package/dist/sync/httpChannel.test.d.ts +2 -0
  215. package/dist/sync/httpChannel.test.d.ts.map +1 -0
  216. package/dist/sync/httpChannel.test.js +215 -0
  217. package/dist/sync/httpChannel.test.js.map +1 -0
  218. package/dist/sync/replayCoordinator.d.ts +212 -0
  219. package/dist/sync/replayCoordinator.d.ts.map +1 -0
  220. package/dist/sync/replayCoordinator.js +1110 -0
  221. package/dist/sync/replayCoordinator.js.map +1 -0
  222. package/dist/sync/replayCoordinator.test.d.ts +2 -0
  223. package/dist/sync/replayCoordinator.test.d.ts.map +1 -0
  224. package/dist/sync/replayCoordinator.test.js +1496 -0
  225. package/dist/sync/replayCoordinator.test.js.map +1 -0
  226. package/dist/sync/socketTransport.d.ts +56 -0
  227. package/dist/sync/socketTransport.d.ts.map +1 -0
  228. package/dist/sync/socketTransport.js +292 -0
  229. package/dist/sync/socketTransport.js.map +1 -0
  230. package/dist/sync/socketTransport.test.d.ts +2 -0
  231. package/dist/sync/socketTransport.test.d.ts.map +1 -0
  232. package/dist/sync/socketTransport.test.js +346 -0
  233. package/dist/sync/socketTransport.test.js.map +1 -0
  234. package/dist/sync/transport.d.ts +80 -0
  235. package/dist/sync/transport.d.ts.map +1 -0
  236. package/dist/sync/transport.js +5 -0
  237. package/dist/sync/transport.js.map +1 -0
  238. package/dist/testing/fakeTransport.d.ts +55 -0
  239. package/dist/testing/fakeTransport.d.ts.map +1 -0
  240. package/dist/testing/fakeTransport.js +139 -0
  241. package/dist/testing/fakeTransport.js.map +1 -0
  242. package/dist/testing/fakeTransport.test.d.ts +2 -0
  243. package/dist/testing/fakeTransport.test.d.ts.map +1 -0
  244. package/dist/testing/fakeTransport.test.js +112 -0
  245. package/dist/testing/fakeTransport.test.js.map +1 -0
  246. package/dist/testing/index.d.ts +13 -0
  247. package/dist/testing/index.d.ts.map +1 -0
  248. package/dist/testing/index.js +13 -0
  249. package/dist/testing/index.js.map +1 -0
  250. package/dist/types.d.ts +271 -0
  251. package/dist/types.d.ts.map +1 -0
  252. package/dist/types.js +9 -0
  253. package/dist/types.js.map +1 -0
  254. package/package.json +71 -0
  255. package/src/auth/betterAuthAdapter.test.ts +455 -0
  256. package/src/auth/betterAuthAdapter.ts +214 -0
  257. package/src/auth/types.ts +49 -0
  258. package/src/client.test.ts +2670 -0
  259. package/src/client.ts +1748 -0
  260. package/src/crypto/aesGcmCodec.test.ts +103 -0
  261. package/src/crypto/aesGcmCodec.ts +98 -0
  262. package/src/crypto/identityCodec.ts +10 -0
  263. package/src/crypto/keyProviders.test.ts +228 -0
  264. package/src/crypto/keyProviders.ts +153 -0
  265. package/src/crypto/types.ts +23 -0
  266. package/src/debug/debugChannel.test.ts +121 -0
  267. package/src/debug/debugChannel.ts +112 -0
  268. package/src/debug/debugLog.test.ts +139 -0
  269. package/src/debug/debugLog.ts +272 -0
  270. package/src/index.ts +157 -0
  271. package/src/isolated/defaultPersisterFactoryNative.isolated.ts +45 -0
  272. package/src/mutations/conflicts.ts +108 -0
  273. package/src/mutations/outbox.test.ts +754 -0
  274. package/src/mutations/outbox.ts +585 -0
  275. package/src/mutations/resolveConflict.test.ts +338 -0
  276. package/src/mutations/resolveConflict.ts +115 -0
  277. package/src/persisters/defaultPersisterFactory.native.ts +53 -0
  278. package/src/persisters/defaultPersisterFactory.test.ts +207 -0
  279. package/src/persisters/defaultPersisterFactory.ts +12 -0
  280. package/src/persisters/defaultPersisterFactory.web.ts +78 -0
  281. package/src/persisters/encryptedIndexedDbPersister.test.ts +381 -0
  282. package/src/persisters/encryptedIndexedDbPersister.ts +218 -0
  283. package/src/persisters/memoryPersister.test.ts +136 -0
  284. package/src/persisters/memoryPersister.ts +52 -0
  285. package/src/persisters/types.ts +71 -0
  286. package/src/react/hooks.test.tsx +761 -0
  287. package/src/react/hooks.ts +409 -0
  288. package/src/react/index.ts +11 -0
  289. package/src/react/provider.tsx +27 -0
  290. package/src/storage/idb.test.ts +116 -0
  291. package/src/storage/idb.ts +112 -0
  292. package/src/storage/purgeUnknownStream.test.ts +74 -0
  293. package/src/storage/schema.ts +103 -0
  294. package/src/storage/store.test.ts +424 -0
  295. package/src/storage/store.ts +461 -0
  296. package/src/storage/types.ts +159 -0
  297. package/src/storage/wipe.test.ts +111 -0
  298. package/src/storage/wipe.ts +58 -0
  299. package/src/sync/bootstrap.test.ts +486 -0
  300. package/src/sync/bootstrap.ts +217 -0
  301. package/src/sync/cursor.test.ts +84 -0
  302. package/src/sync/cursor.ts +113 -0
  303. package/src/sync/deltaApplier.test.ts +237 -0
  304. package/src/sync/deltaApplier.ts +84 -0
  305. package/src/sync/entityRepair.test.ts +161 -0
  306. package/src/sync/entityRepair.ts +124 -0
  307. package/src/sync/httpChannel.test.ts +265 -0
  308. package/src/sync/httpChannel.ts +220 -0
  309. package/src/sync/replayCoordinator.test.ts +1709 -0
  310. package/src/sync/replayCoordinator.ts +1370 -0
  311. package/src/sync/socketTransport.test.ts +413 -0
  312. package/src/sync/socketTransport.ts +379 -0
  313. package/src/sync/transport.ts +76 -0
  314. package/src/testing/fakeTransport.test.ts +125 -0
  315. package/src/testing/fakeTransport.ts +206 -0
  316. package/src/testing/index.ts +18 -0
  317. package/src/types.ts +284 -0
@@ -0,0 +1,1110 @@
1
+ import { listConflicts, writeConflict } from "../mutations/conflicts";
2
+ import { AuthRequiredError } from "./httpChannel";
3
+ import { DEFAULT_BATCH_SIZE, } from "./transport";
4
+ /**
5
+ * Parse a mutation's JSON-serialized `args` back into the create/update body for
6
+ * display in the debug event stream. Falls back to the raw string if it is not
7
+ * valid JSON. Only ever evaluated when the debug log is enabled — optional
8
+ * chaining (`debug?.record({...})`) short-circuits the argument object entirely
9
+ * when `debug` is undefined, so this stays free in production.
10
+ */
11
+ const debugBody = (mutation) => {
12
+ try {
13
+ return JSON.parse(mutation.args);
14
+ }
15
+ catch {
16
+ return mutation.args;
17
+ }
18
+ };
19
+ /** Error-nack retries beyond this attempt count become terminal failures. */
20
+ export const MAX_ERROR_NACK_ATTEMPTS = 5;
21
+ /** Base delay for the error-nack exponential backoff (doubles per attempt). */
22
+ export const ERROR_NACK_BASE_BACKOFF_MS = 1000;
23
+ /** Base delay for transport-failure backoff (unlimited retries, same cap/jitter shape). */
24
+ export const TRANSPORT_FAILURE_BASE_BACKOFF_MS = 1000;
25
+ /** Cap applied to every jittered backoff (error-nack and transport-failure alike). */
26
+ export const MAX_BACKOFF_MS = 30000;
27
+ /**
28
+ * FIX 5: consecutive `unsupported` batch results required before the
29
+ * per-connection `batchUnsupported` latch engages — a single slow-but-
30
+ * supported batch (grace elapsed with no receipt is impossible once a
31
+ * receipt lands, but a genuinely borderline network hiccup could still
32
+ * produce one stray `unsupported`) must never permanently downgrade the
33
+ * session to single-sends.
34
+ */
35
+ export const BATCH_UNSUPPORTED_LATCH_THRESHOLD = 2;
36
+ /**
37
+ * FIX 5: while latched `batchUnsupported`, re-probe batch support on this
38
+ * interval even without a reconnect — a load balancer could route later
39
+ * sends to an upgraded instance, or the original instance could itself be
40
+ * upgraded, without the connection ever dropping.
41
+ */
42
+ export const BATCH_UNSUPPORTED_REPROBE_INTERVAL_MS = 60000;
43
+ const entityKey = (collection, entityId) => `${collection}:${entityId}`;
44
+ /** FIX 3: userId-scoped key for `validationBlockedEntities` — see its declaration comment. */
45
+ const userEntityKey = (userId, collection, entityId) => `${userId}|${entityKey(collection, entityId)}`;
46
+ /**
47
+ * Bridges the durable outbox and the send channel, resolving each mutation's
48
+ * server outcome:
49
+ *
50
+ * - **ack** → markAcked, clear the entity's `pendingMutationId` (when it still
51
+ * belongs to this mutation) and stamp the acked seq;
52
+ * - **nack conflict** → markConflicted + record a `_conflicts` row; the
53
+ * entity's optimistic state stays in place until the user resolves. The
54
+ * ENTITY is blocked (B4): later drains skip its other queued mutations
55
+ * until the conflict resolves, unless `haltQueueOnConflict` is set, in
56
+ * which case the whole drain halts instead;
57
+ * - **nack unauthorized** / thrown `AuthRequiredError` → back to queued and
58
+ * pause replay for the user (`{paused: "auth"}`), consuming NO retry budget
59
+ * (INV-2); the next replay call (after re-auth) retries;
60
+ * - **nack validation** → markFailed (terminal) and release the entity's
61
+ * `pendingMutationId` so future deltas are not blocked forever. The ENTITY
62
+ * is blocked (B4) — its queued successors are skipped until `retryFailed`;
63
+ * - **nack error** → back to queued with jittered exponential backoff against
64
+ * the dedicated `errorNackCount` budget, terminal markFailed after
65
+ * {@link MAX_ERROR_NACK_ATTEMPTS} attempts. HALTS THE WHOLE DRAIN (B4);
66
+ * - **send rejection** (timeout / network / disconnect) → back to queued with
67
+ * unlimited jittered exponential backoff (never terminal, never burns the
68
+ * error-nack budget) and the drain parks until the backoff elapses. HALTS
69
+ * THE WHOLE DRAIN (B4);
70
+ * - **nack rate_limited** → treated EXACTLY like a transport failure (FIX 1):
71
+ * back to queued with the same unlimited jittered backoff (respecting the
72
+ * server's `retryAfterMs` as a floor when present), NEVER touching
73
+ * `errorNackCount` or `attemptCount`'s terminality — a rate limit is never
74
+ * allowed to burn the durable-data retry budget. HALTS THE WHOLE DRAIN (B4).
75
+ *
76
+ * The drain is a SINGLE global FIFO over `enqueueOrder` (INV-1) — no more
77
+ * per-collection parallelism. `replay()` keeps re-running drain passes until
78
+ * the queue is empty or parked; when it parks on a backoff, a single
79
+ * `setTimeout` wakes the next drain automatically so callers never need to
80
+ * poll.
81
+ *
82
+ * B3 layers a batched send on top: each pass sends the next contiguous chunk
83
+ * of the FIFO queue (≤ `batchSize`, at most one mutation per entity per
84
+ * chunk) through `sendMutationBatch` when available, walking the results in
85
+ * order with the same per-outcome handlers above, then applying the B4
86
+ * stop-the-line policy to whatever the batch response implies. Chunks with no
87
+ * eligible mutations (everything blocked/backing off) fall through exactly
88
+ * like the single-send path.
89
+ */
90
+ export const createReplayCoordinator = ({ store, outbox, sendMutation, sendMutationBatch, batchSize = DEFAULT_BATCH_SIZE, haltQueueOnConflict = false, now = () => Date.now(), random = () => Math.random(), debug, setTimeoutFn = (handler, ms) => setTimeout(handler, ms), clearTimeoutFn = (handle) => clearTimeout(handle), onDrainPass, onAuthPause, onProgress, onEntityReleasedWithoutServerAck, shouldDrain = () => true, }) => {
91
+ const inFlightReplays = new Map();
92
+ /**
93
+ * Set when a `replay()` call coalesces into an already-running drain whose
94
+ * final pass may have already observed the queue as empty (a narrow race:
95
+ * the in-flight promise's cleanup runs on a later microtask than the
96
+ * enqueue that prompted this call). Consumed once the in-flight promise
97
+ * settles to schedule exactly one immediate follow-up drain, so a mutation
98
+ * enqueued mid-drain is never stranded until an unrelated external trigger.
99
+ */
100
+ const recheckRequested = new Set();
101
+ /** mutationId → earliest epoch-ms the next attempt may run (error-nack backoff). */
102
+ const retryAt = new Map();
103
+ /** mutationId → count of transport-failure attempts (in-memory only; unlimited budget). */
104
+ const transportFailures = new Map();
105
+ /** userId → armed wake-up timer handle (never more than one per user). */
106
+ const wakeTimers = new Map();
107
+ /** userId → whether onAuthPause has already fired for the current pause episode. */
108
+ const authPauseNotified = new Set();
109
+ /**
110
+ * B4: entities blocked by a terminal validation failure whose queued
111
+ * successors must be skipped until `retryFailed({entityId})`. Keyed by
112
+ * `${userId}|${collection}:${entityId}` (FIX 3 — userId-scoped so a stale
113
+ * entry from one user can never falsely block a different user reusing the
114
+ * same deterministic entity id, e.g. a singleton settings doc). Unresolved-
115
+ * conflict blocking is derived live from the `_conflicts` table instead (it
116
+ * already tracks resolution).
117
+ */
118
+ const validationBlockedEntities = new Set();
119
+ /** userId → {sent, total} progress counters for the CURRENT replay() call (B5). */
120
+ const drainProgress = new Map();
121
+ const reportProgress = (userId, sentDelta) => {
122
+ if (!onProgress) {
123
+ return;
124
+ }
125
+ const progress = drainProgress.get(userId);
126
+ if (!progress) {
127
+ return;
128
+ }
129
+ progress.sent += sentDelta;
130
+ onProgress({ sentThisDrain: progress.sent, totalThisDrain: progress.total, userId });
131
+ };
132
+ /**
133
+ * B3/FIX 5: per-connection flag set once {@link BATCH_UNSUPPORTED_LATCH_THRESHOLD}
134
+ * CONSECUTIVE batch sends report `unsupported` (HTTP 404, or socket grace
135
+ * elapsing with no `sync:batchReceived` receipt) — a single slow-but-
136
+ * supported batch must never trip this. Cleared by `notifyReconnect()` so
137
+ * a reconnect re-probes, and additionally re-probed every
138
+ * {@link BATCH_UNSUPPORTED_REPROBE_INTERVAL_MS} while latched, even
139
+ * without a reconnect (a load balancer or in-place upgrade can flip
140
+ * support without the connection ever dropping).
141
+ */
142
+ let batchUnsupported = false;
143
+ /** FIX 5: consecutive `unsupported` results observed since the last successful/real batch response. */
144
+ let consecutiveUnsupported = 0;
145
+ /** FIX 5: armed only while `batchUnsupported` is latched; re-probes on a timer. */
146
+ let reprobeTimer;
147
+ const clearReprobeTimer = () => {
148
+ if (reprobeTimer !== undefined) {
149
+ clearTimeoutFn(reprobeTimer);
150
+ reprobeTimer = undefined;
151
+ }
152
+ };
153
+ const armReprobeTimer = () => {
154
+ clearReprobeTimer();
155
+ reprobeTimer = setTimeoutFn(() => {
156
+ reprobeTimer = undefined;
157
+ // Re-probe: clear the latch and let the next drain attempt a real
158
+ // batch send again. A fresh two-strikes count applies if it fails
159
+ // again, exactly like the original latch logic.
160
+ batchUnsupported = false;
161
+ consecutiveUnsupported = 0;
162
+ }, BATCH_UNSUPPORTED_REPROBE_INTERVAL_MS);
163
+ };
164
+ const clearWakeTimer = (userId) => {
165
+ const handle = wakeTimers.get(userId);
166
+ if (handle !== undefined) {
167
+ clearTimeoutFn(handle);
168
+ wakeTimers.delete(userId);
169
+ }
170
+ };
171
+ const armWakeTimer = (userId, delayMs) => {
172
+ clearWakeTimer(userId);
173
+ const handle = setTimeoutFn(() => {
174
+ wakeTimers.delete(userId);
175
+ void replay({ userId });
176
+ }, delayMs);
177
+ wakeTimers.set(userId, handle);
178
+ };
179
+ /** Full jitter: random(0, base * 2^(attempt-1)), capped at MAX_BACKOFF_MS. */
180
+ const jitteredBackoff = (attempt, baseMs) => {
181
+ const cap = Math.min(MAX_BACKOFF_MS, baseMs * 2 ** (attempt - 1));
182
+ return Math.floor(random() * cap);
183
+ };
184
+ const buildRequest = (mutation) => {
185
+ const request = {
186
+ collection: mutation.collection,
187
+ id: mutation.entityId,
188
+ mutationId: mutation.mutationId,
189
+ operation: mutation.operation,
190
+ };
191
+ // A2: send-time baseVersion refresh. The entity's CURRENT seq is used as
192
+ // the base when it is NEWER than the value captured at enqueue time — the
193
+ // stored value is the floor, never sent lower. A prior mutation in the
194
+ // same queue may have already acked (stamping the entity's seq via
195
+ // releaseEntity) since this mutation was enqueued; reading the live seq
196
+ // here chains bases correctly through a queue of edits to one entity
197
+ // without any coalescing.
198
+ if (mutation.operation !== "create") {
199
+ const entity = store.getEntity({ collection: mutation.collection, id: mutation.entityId });
200
+ const liveSeq = entity?.seq;
201
+ const floor = mutation.baseVersion;
202
+ const base = liveSeq !== undefined && (floor === undefined || liveSeq > floor) ? liveSeq : floor;
203
+ if (base !== undefined) {
204
+ request.baseVersion = base;
205
+ }
206
+ }
207
+ else if (mutation.baseVersion !== undefined) {
208
+ request.baseVersion = mutation.baseVersion;
209
+ }
210
+ if (mutation.operation !== "delete") {
211
+ try {
212
+ request.data = JSON.parse(mutation.args);
213
+ }
214
+ catch {
215
+ request.data = {};
216
+ }
217
+ }
218
+ return request;
219
+ };
220
+ /** Clear the entity's pendingMutationId when it still points at this mutation. */
221
+ const releaseEntity = (mutation, seq) => {
222
+ const entity = store.getEntity({ collection: mutation.collection, id: mutation.entityId });
223
+ if (!entity) {
224
+ return;
225
+ }
226
+ const ownsPending = entity.pendingMutationId === mutation.mutationId;
227
+ if (!ownsPending && seq === undefined) {
228
+ return;
229
+ }
230
+ store.upsertEntity({
231
+ collection: mutation.collection,
232
+ data: entity.data,
233
+ id: mutation.entityId,
234
+ pendingMutationId: ownsPending ? "" : undefined,
235
+ seq,
236
+ });
237
+ };
238
+ const handleAck = (mutation, ack) => {
239
+ outbox.markAcked({ mutationId: mutation.mutationId });
240
+ retryAt.delete(mutation.mutationId);
241
+ transportFailures.delete(mutation.mutationId);
242
+ releaseEntity(mutation, ack.seq);
243
+ debug?.record({
244
+ collection: mutation.collection,
245
+ detail: { data: debugBody(mutation) },
246
+ direction: "inbound",
247
+ entityId: mutation.entityId,
248
+ label: `ack ${mutation.collection}/${mutation.entityId} @${ack.seq}`,
249
+ mutationId: mutation.mutationId,
250
+ ok: true,
251
+ operation: mutation.operation,
252
+ seq: ack.seq,
253
+ type: "ack",
254
+ });
255
+ };
256
+ const handleConflict = (mutation, nack) => {
257
+ outbox.markConflicted({ mutationId: mutation.mutationId });
258
+ retryAt.delete(mutation.mutationId);
259
+ transportFailures.delete(mutation.mutationId);
260
+ const entity = store.getEntity({ collection: mutation.collection, id: mutation.entityId });
261
+ writeConflict({
262
+ conflict: {
263
+ collection: mutation.collection,
264
+ dismissed: false,
265
+ entityId: mutation.entityId,
266
+ localData: JSON.stringify(entity?.data ?? null),
267
+ mutationId: mutation.mutationId,
268
+ serverData: JSON.stringify(nack.serverDoc ?? null),
269
+ // Task 9.12: preserved so `useServer` resolution knows to write a
270
+ // tombstone rather than the nack's empty server document.
271
+ serverDeleted: nack.serverDeleted === true,
272
+ serverSeq: nack.serverSeq ?? 0,
273
+ },
274
+ store,
275
+ });
276
+ debug?.record({
277
+ collection: mutation.collection,
278
+ detail: {
279
+ data: debugBody(mutation),
280
+ localData: entity?.data ?? null,
281
+ message: nack.message,
282
+ serverDoc: nack.serverDoc ?? null,
283
+ serverSeq: nack.serverSeq,
284
+ },
285
+ direction: "inbound",
286
+ entityId: mutation.entityId,
287
+ label: `conflict ${mutation.collection}/${mutation.entityId}`,
288
+ mutationId: mutation.mutationId,
289
+ ok: false,
290
+ operation: mutation.operation,
291
+ type: "conflict",
292
+ });
293
+ };
294
+ const handleTerminalFailure = (mutation, reason) => {
295
+ outbox.markFailed({ mutationId: mutation.mutationId });
296
+ retryAt.delete(mutation.mutationId);
297
+ transportFailures.delete(mutation.mutationId);
298
+ // Task 9.11a: the server rejected this mutation outright, so the optimistic
299
+ // row is backed by nothing. Absent a concurrent server write the entity's
300
+ // seq never moves, so snapshot reconcile skips it and the rejected data
301
+ // would persist locally forever. Mark needs-repair UNCONDITIONALLY (before
302
+ // the repair hook runs) so the entity converges to canonical server state —
303
+ // and so a later reconcile retries the repair if this one cannot reach the
304
+ // server. Ids the server declines to return are unmarked by the repair pass
305
+ // itself, so a rejected create never leaves a permanent mark behind.
306
+ const pendingEntity = store.getEntity({
307
+ collection: mutation.collection,
308
+ id: mutation.entityId,
309
+ });
310
+ store.markNeedsRepair({
311
+ collection: mutation.collection,
312
+ entityId: mutation.entityId,
313
+ missedSeq: pendingEntity?.seq ?? 0,
314
+ stream: pendingEntity?.stream ?? "",
315
+ });
316
+ // A failed mutation never replays; leaving pendingMutationId set would
317
+ // block server deltas for this entity forever.
318
+ releaseEntity(mutation);
319
+ onEntityReleasedWithoutServerAck?.(mutation);
320
+ debug?.record({
321
+ collection: mutation.collection,
322
+ detail: { data: debugBody(mutation), reason },
323
+ direction: "inbound",
324
+ entityId: mutation.entityId,
325
+ label: `failed ${mutation.collection}/${mutation.entityId} (${reason})`,
326
+ mutationId: mutation.mutationId,
327
+ ok: false,
328
+ operation: mutation.operation,
329
+ type: "failed",
330
+ });
331
+ };
332
+ /**
333
+ * FIX 4: an entity's validation block is garbage-collected once NO outbox
334
+ * row (queued OR still-unpruned failed) remains for it — the block exists
335
+ * only to protect the ordering of an already-queued successor (or to keep
336
+ * surfacing the failure until the user acts), not to quarantine the entity
337
+ * eternally. Checking "any row" rather than "queued only" matters: right
338
+ * after the validation failure itself, the failed row still exists (not
339
+ * yet pruned) with no successor queued yet — the block must survive that
340
+ * window so a successor enqueued moments later is still correctly blocked.
341
+ * Only once prune() removes the failed row AND nothing is queued for the
342
+ * entity does the block become stale and get dropped here. An entity WITH
343
+ * a queued successor, or an unpruned failed row, stays blocked until
344
+ * retryFailed/resolution — that remains intentional.
345
+ */
346
+ const gcStaleValidationBlocks = (userId) => {
347
+ for (const key of [...validationBlockedEntities]) {
348
+ if (!key.startsWith(`${userId}|`)) {
349
+ continue;
350
+ }
351
+ const bare = key.slice(userId.length + 1);
352
+ const separatorIndex = bare.indexOf(":");
353
+ const collection = bare.slice(0, separatorIndex);
354
+ const entityId = bare.slice(separatorIndex + 1);
355
+ if (!outbox.hasAnyRowForEntity({ collection, entityId, userId })) {
356
+ validationBlockedEntities.delete(key);
357
+ }
358
+ }
359
+ };
360
+ /**
361
+ * FIX 2: recursively scan a parsed JSON value for any string that exactly
362
+ * equals one of `blockedEntityIds` — used to detect a mutation in ANOTHER
363
+ * collection that references a currently-blocked entity's id (e.g. create
364
+ * project P conflicts → create todo T {projectId: P} must not drain while
365
+ * P is blocked). Conservative false positives are acceptable (INV-1: too
366
+ * much blocking is safe, too little is not).
367
+ */
368
+ const referencesBlockedId = (value, blockedEntityIds) => {
369
+ if (typeof value === "string") {
370
+ return blockedEntityIds.has(value);
371
+ }
372
+ if (Array.isArray(value)) {
373
+ return value.some((item) => referencesBlockedId(item, blockedEntityIds));
374
+ }
375
+ if (value && typeof value === "object") {
376
+ return Object.values(value).some((item) => referencesBlockedId(item, blockedEntityIds));
377
+ }
378
+ return false;
379
+ };
380
+ /**
381
+ * FIX 2: compute the full transitive block set for one drain pass, from
382
+ * current block state (never persisted — recomputed live each call so
383
+ * resolving a root via `resolveConflict`/`retryFailed` naturally unblocks
384
+ * its dependents on the NEXT drain). Starts from directly-blocked entities
385
+ * (unresolved conflict or skipped validation failure) and expands to any
386
+ * OTHER queued mutation belonging to the same user whose parsed `args`
387
+ * reference a blocked entity's id anywhere (recursively through nested
388
+ * objects/arrays) — repeated to a fixpoint so chains of references (P ← T
389
+ * ← further-mutation-referencing-T) are also blocked.
390
+ */
391
+ const computeBlockedEntityKeys = (userId) => {
392
+ const queued = outbox.listQueued({ userId });
393
+ const blockedKeys = new Set();
394
+ const blockedIds = new Set();
395
+ // Seed directly from recorded block state FIRST — a root entity (e.g. a
396
+ // validation failure with no queued successor of its own yet, or an
397
+ // entity whose only mutation already left `queued` — conflicted or
398
+ // failed) still needs to be in the reference set so OTHER queued
399
+ // mutations that reference its id are caught, even though the root
400
+ // itself has nothing queued to represent it in `queued` below.
401
+ for (const key of validationBlockedEntities) {
402
+ if (!key.startsWith(`${userId}|`)) {
403
+ continue;
404
+ }
405
+ const bare = key.slice(userId.length + 1);
406
+ blockedKeys.add(bare);
407
+ const separatorIndex = bare.indexOf(":");
408
+ blockedIds.add(bare.slice(separatorIndex + 1));
409
+ }
410
+ // Same seeding for unresolved conflicts (the store is scoped one-user-
411
+ // at-a-time — wiped on user switch — so `listConflicts` needs no
412
+ // additional userId filter here).
413
+ for (const conflict of listConflicts({ store })) {
414
+ blockedKeys.add(entityKey(conflict.collection, conflict.entityId));
415
+ blockedIds.add(conflict.entityId);
416
+ }
417
+ // Seeding above is exhaustive for direct blocks: a queued mutation is directly
418
+ // blocked only by a `validationBlockedEntities` entry or a recorded conflict for
419
+ // its own entity, and both sets are fully enumerated above. Re-walking `queued`
420
+ // to test each mutation individually would rescan the whole `_conflicts` table
421
+ // per mutation (O(queued × conflicts)) and could never add a key.
422
+ // Fixpoint expansion: a mutation whose args reference a currently-blocked
423
+ // id becomes blocked itself (its own entityId joins the reference set),
424
+ // which can in turn block a mutation referencing IT.
425
+ let changed = true;
426
+ while (changed) {
427
+ changed = false;
428
+ for (const mutation of queued) {
429
+ const key = entityKey(mutation.collection, mutation.entityId);
430
+ if (blockedKeys.has(key)) {
431
+ continue;
432
+ }
433
+ let parsedArgs;
434
+ try {
435
+ parsedArgs = JSON.parse(mutation.args);
436
+ }
437
+ catch {
438
+ continue;
439
+ }
440
+ if (referencesBlockedId(parsedArgs, blockedIds)) {
441
+ blockedKeys.add(key);
442
+ blockedIds.add(mutation.entityId);
443
+ changed = true;
444
+ }
445
+ }
446
+ }
447
+ return blockedKeys;
448
+ };
449
+ const applyAck = (mutation, ack) => {
450
+ handleAck(mutation, ack);
451
+ return { authPaused: false, haltDrain: false, progressed: true };
452
+ };
453
+ const applyUnauthorized = (mutation) => {
454
+ outbox.markQueued({ mutationId: mutation.mutationId });
455
+ debug?.record({
456
+ collection: mutation.collection,
457
+ detail: { code: "unauthorized", data: debugBody(mutation), paused: true },
458
+ direction: "inbound",
459
+ entityId: mutation.entityId,
460
+ label: `nack ${mutation.collection}/${mutation.entityId} (unauthorized)`,
461
+ mutationId: mutation.mutationId,
462
+ ok: false,
463
+ operation: mutation.operation,
464
+ type: "nack",
465
+ });
466
+ return { authPaused: true, haltDrain: true, progressed: false };
467
+ };
468
+ const applyConflict = (mutation, nack) => {
469
+ handleConflict(mutation, nack);
470
+ validationBlockedEntities.delete(userEntityKey(mutation.userId, mutation.collection, mutation.entityId));
471
+ // B4: per-entity blocking is the default; haltQueueOnConflict escalates to
472
+ // a whole-drain halt for apps with cross-entity ordering dependencies.
473
+ return { authPaused: false, haltDrain: haltQueueOnConflict, progressed: false };
474
+ };
475
+ const applyValidation = (mutation) => {
476
+ handleTerminalFailure(mutation, "validation");
477
+ // B4: the entity's queued successors are skipped-and-surfaced until the
478
+ // user calls retryFailed({entityId}) or resolves the underlying issue —
479
+ // other entities keep draining.
480
+ validationBlockedEntities.add(userEntityKey(mutation.userId, mutation.collection, mutation.entityId));
481
+ return { authPaused: false, haltDrain: false, progressed: false };
482
+ };
483
+ const applyErrorNack = (mutation) => {
484
+ const beforeCount = outbox.getMutation({ mutationId: mutation.mutationId })?.errorNackCount ?? 0;
485
+ const attempts = beforeCount + 1;
486
+ if (attempts >= MAX_ERROR_NACK_ATTEMPTS) {
487
+ handleTerminalFailure(mutation, "error");
488
+ return { authPaused: false, haltDrain: false, progressed: false };
489
+ }
490
+ outbox.markQueuedAfterErrorNack({ mutationId: mutation.mutationId });
491
+ const backoffMs = jitteredBackoff(attempts, ERROR_NACK_BASE_BACKOFF_MS);
492
+ const wakeAt = now() + backoffMs;
493
+ retryAt.set(mutation.mutationId, wakeAt);
494
+ debug?.record({
495
+ collection: mutation.collection,
496
+ detail: { attempt: attempts, backoffMs, data: debugBody(mutation), reason: "error" },
497
+ direction: "system",
498
+ entityId: mutation.entityId,
499
+ label: `retry ${mutation.collection}/${mutation.entityId} (error, ${backoffMs}ms)`,
500
+ mutationId: mutation.mutationId,
501
+ operation: mutation.operation,
502
+ type: "retry",
503
+ });
504
+ // B4: error nacks halt the WHOLE drain (transient — retrying without user
505
+ // action will fix it), unlike the per-entity conflict/validation policy.
506
+ return { authPaused: false, haltDrain: true, nextWakeAt: wakeAt, progressed: false };
507
+ };
508
+ /**
509
+ * Shared backoff-and-requeue path for outcomes that must NEVER burn a
510
+ * retry budget: transport failures and rate-limit nacks alike. Both track
511
+ * attempts in the same in-memory `transportFailures` map (unlimited
512
+ * retries, jittered capped backoff) and HALT THE WHOLE DRAIN (B4) — the
513
+ * remaining chunk/mutation is safe to resend (INV-3). `floorMs` (when
514
+ * present — a server-supplied `retryAfterMs`) raises the computed backoff
515
+ * so the client never retries before the server's own window clears.
516
+ */
517
+ const requeueWithUnlimitedBackoff = (mutation, { reason, floorMs }) => {
518
+ outbox.markQueued({ mutationId: mutation.mutationId });
519
+ const attempt = (transportFailures.get(mutation.mutationId) ?? 0) + 1;
520
+ transportFailures.set(mutation.mutationId, attempt);
521
+ const backoffMs = Math.max(jitteredBackoff(attempt, TRANSPORT_FAILURE_BASE_BACKOFF_MS), floorMs ?? 0);
522
+ const wakeAt = now() + backoffMs;
523
+ retryAt.set(mutation.mutationId, wakeAt);
524
+ debug?.record({
525
+ collection: mutation.collection,
526
+ detail: { attempt, backoffMs, data: debugBody(mutation), reason },
527
+ direction: "system",
528
+ entityId: mutation.entityId,
529
+ label: `retry ${mutation.collection}/${mutation.entityId} (${reason}, ${backoffMs}ms)`,
530
+ mutationId: mutation.mutationId,
531
+ operation: mutation.operation,
532
+ type: "retry",
533
+ });
534
+ return { authPaused: false, haltDrain: true, nextWakeAt: wakeAt, progressed: false };
535
+ };
536
+ /**
537
+ * `rate_limited` nacks (FIX 1): the server is asking the client to slow
538
+ * down, not reporting a durable-data problem — treat it EXACTLY like a
539
+ * transport failure. Requeue (never markFailed/terminal), never touch
540
+ * `errorNackCount`, unlimited retries with the same capped jittered
541
+ * backoff, respecting the server's `retryAfterMs` as a floor.
542
+ */
543
+ const applyRateLimited = (mutation, nack) => {
544
+ debug?.record({
545
+ collection: mutation.collection,
546
+ detail: {
547
+ code: "rate_limited",
548
+ data: debugBody(mutation),
549
+ message: nack.message,
550
+ retryAfterMs: nack.retryAfterMs,
551
+ },
552
+ direction: "inbound",
553
+ entityId: mutation.entityId,
554
+ label: `nack ${mutation.collection}/${mutation.entityId} (rate_limited)`,
555
+ mutationId: mutation.mutationId,
556
+ ok: false,
557
+ operation: mutation.operation,
558
+ type: "nack",
559
+ });
560
+ return requeueWithUnlimitedBackoff(mutation, {
561
+ floorMs: nack.retryAfterMs,
562
+ reason: "rate_limited",
563
+ });
564
+ };
565
+ /** Apply a resolved single-mutation SendMutationResult via the B4 outcome table. */
566
+ const applyResult = (mutation, result) => {
567
+ if (result.type === "ack") {
568
+ return applyAck(mutation, result.ack);
569
+ }
570
+ const { nack } = result;
571
+ if (nack.code === "conflict") {
572
+ return applyConflict(mutation, nack);
573
+ }
574
+ if (nack.code === "unauthorized") {
575
+ return applyUnauthorized(mutation);
576
+ }
577
+ if (nack.code === "validation") {
578
+ return applyValidation(mutation);
579
+ }
580
+ if (nack.code === "rate_limited") {
581
+ return applyRateLimited(mutation, nack);
582
+ }
583
+ return applyErrorNack(mutation);
584
+ };
585
+ /** Apply a transport failure (thrown send / AuthRequiredError) via the B4 outcome table. */
586
+ const applyTransportError = (mutation, error) => {
587
+ if (error instanceof AuthRequiredError) {
588
+ // INV-2: never burn a retry budget on an auth failure. Requeue and
589
+ // pause the whole drain; the caller retries after re-auth.
590
+ outbox.markQueued({ mutationId: mutation.mutationId });
591
+ debug?.record({
592
+ collection: mutation.collection,
593
+ detail: { code: "unauthorized", data: debugBody(mutation), paused: true, source: "http" },
594
+ direction: "inbound",
595
+ entityId: mutation.entityId,
596
+ label: `nack ${mutation.collection}/${mutation.entityId} (unauthorized)`,
597
+ mutationId: mutation.mutationId,
598
+ ok: false,
599
+ operation: mutation.operation,
600
+ type: "nack",
601
+ });
602
+ return { authPaused: true, haltDrain: true, progressed: false };
603
+ }
604
+ // Transport failure (timeout, network, disconnect): unlimited retries
605
+ // with jittered capped backoff, tracked separately from the error-nack
606
+ // budget. HALTS THE WHOLE DRAIN (B4) — the whole batch is safe to resend
607
+ // (INV-3).
608
+ return requeueWithUnlimitedBackoff(mutation, { reason: "transport" });
609
+ };
610
+ /**
611
+ * Single-mutation send path (used when no batch transport is configured, or
612
+ * batching is marked unsupported for this connection, or a chunk's only
613
+ * eligible mutation count is 1).
614
+ */
615
+ const sendSingle = async (userId, mutation) => {
616
+ outbox.markInFlight({ mutationId: mutation.mutationId });
617
+ debug?.record({
618
+ collection: mutation.collection,
619
+ detail: { attempt: mutation.attemptCount + 1, data: debugBody(mutation) },
620
+ direction: "outbound",
621
+ entityId: mutation.entityId,
622
+ label: `send ${mutation.operation} ${mutation.collection}/${mutation.entityId}`,
623
+ mutationId: mutation.mutationId,
624
+ operation: mutation.operation,
625
+ type: "send",
626
+ });
627
+ let result;
628
+ try {
629
+ result = await sendMutation(buildRequest(mutation));
630
+ }
631
+ catch (error) {
632
+ const decision = applyTransportError(mutation, error);
633
+ reportProgress(userId, 1);
634
+ return decision;
635
+ }
636
+ const decision = applyResult(mutation, result);
637
+ reportProgress(userId, 1);
638
+ return decision;
639
+ };
640
+ /**
641
+ * Build the next contiguous chunk of the FIFO queue eligible for a batch
642
+ * send: skips mutations whose entity is currently blocked (B4, including
643
+ * FIX 2's transitive cross-collection reference blocks against entities
644
+ * blocked BEFORE this pass — `blockedKeys` is computed once per drain pass
645
+ * by the caller) or backing off (retryAt in the future), stops BEFORE a
646
+ * backing-off mutation (INV-1 — it must remain the effective head once
647
+ * nothing ahead of it can send), and cuts the chunk short before a second
648
+ * mutation for an entity already included (B3.2) so per-entity chaining
649
+ * stays correct without guessing server-assigned seqs.
650
+ *
651
+ * FIX 2 also guards the SAME-BATCH race: a mutation whose args reference
652
+ * the entity id of another mutation already placed EARLIER in this same
653
+ * chunk is excluded too, even though that referenced entity isn't blocked
654
+ * yet (its own outcome — ack or conflict/validation nack — isn't known
655
+ * until this very batch resolves). Without this, P (create) and T (create,
656
+ * referencing P) enqueued together would land in the same chunk and could
657
+ * both be sent before P's conflict is even discovered.
658
+ */
659
+ const buildChunk = (queued, blockedKeys) => {
660
+ const chunk = [];
661
+ const seenEntities = new Set();
662
+ const chunkEntityIds = new Set();
663
+ let blockedWakeAt;
664
+ for (const mutation of queued) {
665
+ if (chunk.length >= batchSize) {
666
+ break;
667
+ }
668
+ const nextAttemptAt = retryAt.get(mutation.mutationId);
669
+ if (nextAttemptAt !== undefined && now() < nextAttemptAt) {
670
+ // INV-1: a backing-off mutation blocks the entire drain from this
671
+ // point on — stop building the chunk here.
672
+ blockedWakeAt =
673
+ blockedWakeAt === undefined ? nextAttemptAt : Math.min(blockedWakeAt, nextAttemptAt);
674
+ break;
675
+ }
676
+ const key = entityKey(mutation.collection, mutation.entityId);
677
+ if (blockedKeys.has(key)) {
678
+ // B4/FIX 2: this entity (directly or transitively, via a reference
679
+ // to another blocked entity) is blocked; skip it (stays queued) but
680
+ // keep scanning — other entities may still be eligible for this chunk.
681
+ continue;
682
+ }
683
+ if (chunkEntityIds.size > 0) {
684
+ let parsedArgs;
685
+ try {
686
+ parsedArgs = JSON.parse(mutation.args);
687
+ }
688
+ catch {
689
+ parsedArgs = undefined;
690
+ }
691
+ if (parsedArgs !== undefined && referencesBlockedId(parsedArgs, chunkEntityIds)) {
692
+ // FIX 2 same-batch guard: this mutation references an entity whose
693
+ // outcome in THIS chunk is not yet known — skip it (stays queued)
694
+ // rather than risk sending it alongside a root that may conflict.
695
+ continue;
696
+ }
697
+ }
698
+ if (seenEntities.has(key)) {
699
+ // B3.2: at most one mutation per entity per chunk — cut here.
700
+ break;
701
+ }
702
+ seenEntities.add(key);
703
+ chunkEntityIds.add(mutation.entityId);
704
+ chunk.push(mutation);
705
+ }
706
+ return { blockedWakeAt, chunk };
707
+ };
708
+ /** Send one chunk as a batch; returns the per-mutation outcome decisions and any halt reached. */
709
+ const sendChunk = async (userId, chunk) => {
710
+ const decisions = new Map();
711
+ for (const mutation of chunk) {
712
+ outbox.markInFlight({ mutationId: mutation.mutationId });
713
+ debug?.record({
714
+ collection: mutation.collection,
715
+ detail: { attempt: mutation.attemptCount + 1, batch: true, data: debugBody(mutation) },
716
+ direction: "outbound",
717
+ entityId: mutation.entityId,
718
+ label: `send ${mutation.operation} ${mutation.collection}/${mutation.entityId}`,
719
+ mutationId: mutation.mutationId,
720
+ operation: mutation.operation,
721
+ type: "send",
722
+ });
723
+ }
724
+ const request = { mutations: chunk.map(buildRequest) };
725
+ let response;
726
+ try {
727
+ // biome-ignore lint/style/noNonNullAssertion: caller only invokes sendChunk when sendMutationBatch is defined and batching is not marked unsupported.
728
+ response = await sendMutationBatch(request);
729
+ }
730
+ catch (error) {
731
+ // Transport failure for the WHOLE chunk: every mutation in it goes back
732
+ // to queued via the same transport-error handling as a single send, and
733
+ // the drain halts (INV-3 — resending the whole chunk is safe).
734
+ let haltedAt;
735
+ for (const mutation of chunk) {
736
+ const decision = applyTransportError(mutation, error);
737
+ decisions.set(mutation.mutationId, decision);
738
+ if (decision.nextWakeAt !== undefined) {
739
+ haltedAt =
740
+ haltedAt === undefined ? decision.nextWakeAt : Math.min(haltedAt, decision.nextWakeAt);
741
+ }
742
+ }
743
+ reportProgress(userId, chunk.length);
744
+ return { decisions, haltedAt, shortResponse: false, unsupported: false };
745
+ }
746
+ if (response.type === "unsupported") {
747
+ // The chunk was marked inFlight before sending (for diagnostics/debug
748
+ // symmetry with the single-send path) but never actually attempted —
749
+ // revert every mutation to queued, untouched budgets, so the fallback
750
+ // single-send pass picks them straight back up.
751
+ for (const mutation of chunk) {
752
+ outbox.markQueued({ mutationId: mutation.mutationId });
753
+ }
754
+ return { decisions, shortResponse: false, unsupported: true };
755
+ }
756
+ // Walk results in order (INV-1), applying the same per-outcome handlers as
757
+ // the single-send path, then the B4 stop-the-line policy. Per B2, the
758
+ // server itself stops at the first non-ack and truncates `results`
759
+ // accordingly — but defensively, once THIS pass decides to halt (auth
760
+ // pause in particular — nothing after it may be treated as final), every
761
+ // remaining mutation in the chunk is requeued untouched rather than left
762
+ // stranded `inFlight`, regardless of what a non-conforming server sent.
763
+ let halted = false;
764
+ let haltedAt;
765
+ let processed = 0;
766
+ const shortResponse = response.results.length < chunk.length;
767
+ for (let i = 0; i < chunk.length; i++) {
768
+ const mutation = chunk[i];
769
+ if (halted) {
770
+ // Only siblings still `inFlight` need reverting — the mutation that
771
+ // triggered the halt may already be conflicted/failed/acked.
772
+ if (outbox.getMutation({ mutationId: mutation.mutationId })?.status === "inFlight") {
773
+ outbox.markQueued({ mutationId: mutation.mutationId });
774
+ }
775
+ continue;
776
+ }
777
+ const result = response.results[i];
778
+ if (!result) {
779
+ // Server halted mid-batch (results shorter than the request): every
780
+ // mutation with no result goes back to queued, untouched budgets.
781
+ if (outbox.getMutation({ mutationId: mutation.mutationId })?.status === "inFlight") {
782
+ outbox.markQueued({ mutationId: mutation.mutationId });
783
+ }
784
+ continue;
785
+ }
786
+ processed += 1;
787
+ const decision = applyResult(mutation, result);
788
+ decisions.set(mutation.mutationId, decision);
789
+ if (decision.haltDrain) {
790
+ halted = true;
791
+ if (decision.nextWakeAt !== undefined) {
792
+ haltedAt = decision.nextWakeAt;
793
+ }
794
+ }
795
+ }
796
+ reportProgress(userId, processed);
797
+ return { decisions, haltedAt, shortResponse, unsupported: false };
798
+ };
799
+ const drainOnce = async (userId) => {
800
+ let progressed = false;
801
+ let nextWakeAt;
802
+ for (;;) {
803
+ // FIX 4: drop any validation block whose entity has no queued
804
+ // successor left (pruned/resolved-away) before computing this pass's
805
+ // eligibility — an entity must not stay quarantined once nothing
806
+ // queued depends on the ordering the block was protecting.
807
+ gcStaleValidationBlocks(userId);
808
+ const queued = outbox.listQueued({ userId });
809
+ if (queued.length === 0) {
810
+ return { authPaused: false, nextWakeAt, progressed };
811
+ }
812
+ // FIX 2: transitive block set (direct blocks + cross-collection
813
+ // references to a blocked entity's id), recomputed fresh every pass so
814
+ // resolving a root naturally unblocks its dependents on the next drain.
815
+ const blockedKeys = computeBlockedEntityKeys(userId);
816
+ const useBatch = Boolean(sendMutationBatch) && !batchUnsupported;
817
+ if (!useBatch) {
818
+ // Single-mutation fallback (no batch transport, or marked unsupported):
819
+ // send exactly the FIFO head, honoring blocked/backing-off skips.
820
+ let sentAny = false;
821
+ for (const mutation of queued) {
822
+ const nextAttemptAt = retryAt.get(mutation.mutationId);
823
+ if (nextAttemptAt !== undefined && now() < nextAttemptAt) {
824
+ nextWakeAt =
825
+ nextWakeAt === undefined ? nextAttemptAt : Math.min(nextWakeAt, nextAttemptAt);
826
+ return { authPaused: false, nextWakeAt, progressed };
827
+ }
828
+ if (blockedKeys.has(entityKey(mutation.collection, mutation.entityId))) {
829
+ continue;
830
+ }
831
+ const decision = await sendSingle(userId, mutation);
832
+ sentAny = true;
833
+ progressed = progressed || decision.progressed;
834
+ if (decision.authPaused) {
835
+ return { authPaused: true, progressed };
836
+ }
837
+ if (decision.haltDrain) {
838
+ if (decision.nextWakeAt !== undefined) {
839
+ nextWakeAt =
840
+ nextWakeAt === undefined
841
+ ? decision.nextWakeAt
842
+ : Math.min(nextWakeAt, decision.nextWakeAt);
843
+ }
844
+ // A halt with no backoff of its own (e.g. a plain conflict nack
845
+ // under haltQueueOnConflict) must still stop the CURRENT
846
+ // replay() call — otherwise the outer loop would immediately
847
+ // drain unrelated entities anyway, defeating the halt.
848
+ return {
849
+ authPaused: false,
850
+ nextWakeAt,
851
+ progressed,
852
+ stopReplayCall: decision.nextWakeAt === undefined,
853
+ };
854
+ }
855
+ break; // re-list after each send so newly-acked bases (A2) apply.
856
+ }
857
+ if (!sentAny) {
858
+ // Nothing eligible this pass (everything blocked/backing off). When
859
+ // nothing is backing off either (nextWakeAt still undefined), every
860
+ // remaining mutation is purely B4-blocked — signal that so the
861
+ // outer drain-until-empty loop stops instead of spinning forever on
862
+ // a queue that can never shrink without an external event.
863
+ return {
864
+ authPaused: false,
865
+ nextWakeAt,
866
+ progressed,
867
+ stopReplayCall: nextWakeAt === undefined,
868
+ };
869
+ }
870
+ continue;
871
+ }
872
+ const { chunk, blockedWakeAt } = buildChunk(queued, blockedKeys);
873
+ if (chunk.length === 0) {
874
+ if (blockedWakeAt !== undefined) {
875
+ nextWakeAt =
876
+ nextWakeAt === undefined ? blockedWakeAt : Math.min(nextWakeAt, blockedWakeAt);
877
+ }
878
+ return {
879
+ authPaused: false,
880
+ nextWakeAt,
881
+ progressed,
882
+ stopReplayCall: blockedWakeAt === undefined,
883
+ };
884
+ }
885
+ if (chunk.length === 1) {
886
+ // A lone eligible mutation: sending it as a "batch of one" adds no
887
+ // value and costs an extra round-trip on unsupported servers — reuse
888
+ // the single-send path directly (still counts as this pass's send).
889
+ const decision = await sendSingle(userId, chunk[0]);
890
+ progressed = progressed || decision.progressed;
891
+ if (decision.authPaused) {
892
+ return { authPaused: true, progressed };
893
+ }
894
+ if (decision.haltDrain) {
895
+ if (decision.nextWakeAt !== undefined) {
896
+ nextWakeAt =
897
+ nextWakeAt === undefined
898
+ ? decision.nextWakeAt
899
+ : Math.min(nextWakeAt, decision.nextWakeAt);
900
+ }
901
+ return {
902
+ authPaused: false,
903
+ nextWakeAt,
904
+ progressed,
905
+ stopReplayCall: decision.nextWakeAt === undefined,
906
+ };
907
+ }
908
+ continue;
909
+ }
910
+ const { decisions, unsupported, haltedAt, shortResponse } = await sendChunk(userId, chunk);
911
+ if (unsupported) {
912
+ // FIX 5: only latch after BATCH_UNSUPPORTED_LATCH_THRESHOLD
913
+ // consecutive unsupported results — a single slow-but-supported
914
+ // batch (grace elapsed without a receipt landing in time, but the
915
+ // server really does have a handler) must not permanently downgrade
916
+ // the connection to single-sends.
917
+ consecutiveUnsupported += 1;
918
+ if (consecutiveUnsupported >= BATCH_UNSUPPORTED_LATCH_THRESHOLD) {
919
+ batchUnsupported = true;
920
+ armReprobeTimer();
921
+ }
922
+ continue;
923
+ }
924
+ // A real (non-unsupported) batch response proves the server supports
925
+ // batching — reset the consecutive-failure counter so a later stray
926
+ // unsupported result starts counting from zero again.
927
+ consecutiveUnsupported = 0;
928
+ let authPaused = false;
929
+ for (const decision of decisions.values()) {
930
+ progressed = progressed || decision.progressed;
931
+ if (decision.authPaused) {
932
+ authPaused = true;
933
+ }
934
+ }
935
+ if (authPaused) {
936
+ return { authPaused: true, progressed };
937
+ }
938
+ if (haltedAt !== undefined) {
939
+ nextWakeAt = nextWakeAt === undefined ? haltedAt : Math.min(nextWakeAt, haltedAt);
940
+ }
941
+ // A halt (conflict-with-haltQueueOnConflict, error-nack backoff,
942
+ // transport failure) stops the WHOLE drain this pass, mirroring the
943
+ // single-send path — detect it by re-checking whether any decision
944
+ // requested a halt. A short response (server halted mid-batch with no
945
+ // failing nack for the boundary mutation — e.g. it hasn't finished
946
+ // ledgering yet) halts this pass too (INV-1): the tail already went
947
+ // back to queued untouched, and the next drain resumes from there.
948
+ const anyHalt = shortResponse || [...decisions.values()].some((decision) => decision.haltDrain);
949
+ if (anyHalt) {
950
+ // As above: a halt with no backoff of its own (plain conflict under
951
+ // haltQueueOnConflict, or a short response) must stop the CURRENT
952
+ // replay() call, not just this pass.
953
+ return { authPaused: false, nextWakeAt, progressed, stopReplayCall: haltedAt === undefined };
954
+ }
955
+ // Progress made and no halt: loop to build the next chunk immediately
956
+ // (drain-until-empty within this pass too, so a 120-mutation queue
957
+ // drains in ceil(120/batchSize) round-trips within ONE replay() call).
958
+ }
959
+ };
960
+ const replay = ({ userId }) => {
961
+ const existing = inFlightReplays.get(userId);
962
+ if (existing) {
963
+ // The running drain may have already taken its final "queue empty"
964
+ // snapshot before this call's mutation was enqueued; request a
965
+ // follow-up check once it settles rather than silently stranding the
966
+ // new mutation until an unrelated external trigger runs.
967
+ recheckRequested.add(userId);
968
+ return existing;
969
+ }
970
+ if (!shouldDrain()) {
971
+ // The host has gated sending off (simulated offline, client-level auth
972
+ // pause, post-stop, etc). Internally-scheduled callers (the wake timer,
973
+ // the recheck above) must respect this exactly like an external caller
974
+ // would — never send, never arm a new timer, never touch retry state.
975
+ return Promise.resolve({});
976
+ }
977
+ // A fresh replay call supersedes any pending timed wake-up — it is about
978
+ // to drain right now.
979
+ clearWakeTimer(userId);
980
+ // B5: (re)start this call's progress counters. `total` is a lower bound —
981
+ // snapshotted once at entry — since more may enqueue mid-drain; onProgress
982
+ // still reports every attempt made.
983
+ drainProgress.set(userId, { sent: 0, total: outbox.listQueued({ userId }).length });
984
+ const run = (async () => {
985
+ let authPaused = false;
986
+ let parkedAt;
987
+ // Drain-until-empty: keep re-running passes while there is still work
988
+ // and nothing has parked the queue. shouldDrain() is re-checked before
989
+ // EVERY pass (not just once at entry): a pass can be deferred onto a
990
+ // later microtask/timer tick by the time it actually runs, during which
991
+ // the host may have gone offline or paused — an internally-scheduled
992
+ // continuation must never race past that.
993
+ for (;;) {
994
+ if (!shouldDrain()) {
995
+ break;
996
+ }
997
+ const pass = await drainOnce(userId);
998
+ if (pass.progressed) {
999
+ onDrainPass?.({ userId });
1000
+ }
1001
+ if (pass.authPaused) {
1002
+ authPaused = true;
1003
+ break;
1004
+ }
1005
+ if (pass.nextWakeAt !== undefined) {
1006
+ parkedAt = pass.nextWakeAt;
1007
+ break;
1008
+ }
1009
+ if (pass.stopReplayCall) {
1010
+ // Either every remaining queued mutation is B4-blocked (nothing
1011
+ // more can happen until resolveConflict/retryFailed — looping
1012
+ // again would spin forever on a queue that never shrinks), or a
1013
+ // halting decision with no backoff of its own fired (a plain
1014
+ // conflict nack under haltQueueOnConflict) — looping again would
1015
+ // silently defeat that halt by draining unrelated entities anyway.
1016
+ break;
1017
+ }
1018
+ // Only stop looping once nothing is queued (drain-until-empty).
1019
+ if (outbox.listQueued({ userId }).length === 0) {
1020
+ break;
1021
+ }
1022
+ }
1023
+ if (authPaused) {
1024
+ if (!authPauseNotified.has(userId)) {
1025
+ authPauseNotified.add(userId);
1026
+ onAuthPause?.({ userId });
1027
+ }
1028
+ return { paused: "auth" };
1029
+ }
1030
+ authPauseNotified.delete(userId);
1031
+ if (parkedAt !== undefined) {
1032
+ // Timed wake-up: arm a single setTimeout for the earliest backoff
1033
+ // across the parked queue so callers never need to poll.
1034
+ armWakeTimer(userId, Math.max(0, parkedAt - now()));
1035
+ }
1036
+ return {};
1037
+ })();
1038
+ const tracked = run.finally(() => {
1039
+ inFlightReplays.delete(userId);
1040
+ if (recheckRequested.delete(userId)) {
1041
+ void replay({ userId });
1042
+ }
1043
+ });
1044
+ inFlightReplays.set(userId, tracked);
1045
+ return tracked;
1046
+ };
1047
+ /** FIX 3: full lifecycle reset — see the `ReplayCoordinator.reset` doc comment. */
1048
+ const reset = () => {
1049
+ for (const userId of [...wakeTimers.keys()]) {
1050
+ clearWakeTimer(userId);
1051
+ }
1052
+ clearReprobeTimer();
1053
+ retryAt.clear();
1054
+ transportFailures.clear();
1055
+ authPauseNotified.clear();
1056
+ validationBlockedEntities.clear();
1057
+ drainProgress.clear();
1058
+ recheckRequested.clear();
1059
+ batchUnsupported = false;
1060
+ consecutiveUnsupported = 0;
1061
+ };
1062
+ /**
1063
+ * FIX 3: `dispose()` is the client-stop/sign-out teardown hook, so a full
1064
+ * `reset()` is always safe here regardless of the (legacy) `userId` arg —
1065
+ * nothing else uses this coordinator instance once dispose has run for the
1066
+ * current lifecycle.
1067
+ */
1068
+ const dispose = (_args) => {
1069
+ reset();
1070
+ };
1071
+ const notifyReconnect = () => {
1072
+ clearReprobeTimer();
1073
+ batchUnsupported = false;
1074
+ consecutiveUnsupported = 0;
1075
+ };
1076
+ const retryFailed = ({ entityId }) => {
1077
+ for (const key of [...validationBlockedEntities]) {
1078
+ if (key.endsWith(`:${entityId}`)) {
1079
+ validationBlockedEntities.delete(key);
1080
+ }
1081
+ }
1082
+ };
1083
+ const getBlockedEntities = ({ userId }) => {
1084
+ // FIX 4: drop stale blocks (no queued successor left) before reporting.
1085
+ gcStaleValidationBlocks(userId);
1086
+ // FIX 2/3: report the full transitive block set (direct + cross-collection
1087
+ // references), scoped to THIS user only — a different user's stale
1088
+ // in-memory entry (or a same-id different-user block) must never surface
1089
+ // here (FIX 3: getBlockedEntities({userId}) filters accordingly).
1090
+ return [...computeBlockedEntityKeys(userId)];
1091
+ };
1092
+ const getDrainProgress = ({ userId, }) => {
1093
+ const progress = drainProgress.get(userId);
1094
+ return {
1095
+ draining: inFlightReplays.has(userId),
1096
+ sentThisDrain: progress?.sent ?? 0,
1097
+ totalThisDrain: progress?.total ?? 0,
1098
+ };
1099
+ };
1100
+ return {
1101
+ dispose,
1102
+ getBlockedEntities,
1103
+ getDrainProgress,
1104
+ notifyReconnect,
1105
+ replay,
1106
+ reset,
1107
+ retryFailed,
1108
+ };
1109
+ };
1110
+ //# sourceMappingURL=replayCoordinator.js.map