@livestore/common 0.4.0 → 0.5.0-dev.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 (421) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/ClientSessionLeaderThreadProxy.d.ts +1 -1
  3. package/dist/ClientSessionLeaderThreadProxy.d.ts.map +1 -1
  4. package/dist/MaterializationJournal.d.ts +44 -0
  5. package/dist/MaterializationJournal.d.ts.map +1 -0
  6. package/dist/MaterializationJournal.js +112 -0
  7. package/dist/MaterializationJournal.js.map +1 -0
  8. package/dist/StateHead.d.ts +26 -0
  9. package/dist/StateHead.d.ts.map +1 -0
  10. package/dist/StateHead.js +50 -0
  11. package/dist/StateHead.js.map +1 -0
  12. package/dist/WorkerTransportError.d.ts +3 -3
  13. package/dist/WorkerTransportError.d.ts.map +1 -1
  14. package/dist/WorkerTransportError.js +3 -3
  15. package/dist/WorkerTransportError.js.map +1 -1
  16. package/dist/__tests__/fixture.d.ts +1 -1
  17. package/dist/__tests__/fixture.d.ts.map +1 -1
  18. package/dist/__tests__/fixture.js +3 -3
  19. package/dist/__tests__/fixture.js.map +1 -1
  20. package/dist/adapter-types.d.ts +29 -57
  21. package/dist/adapter-types.d.ts.map +1 -1
  22. package/dist/adapter-types.js +20 -37
  23. package/dist/adapter-types.js.map +1 -1
  24. package/dist/debug-info.d.ts +56 -56
  25. package/dist/debug-info.d.ts.map +1 -1
  26. package/dist/debug-info.js +28 -41
  27. package/dist/debug-info.js.map +1 -1
  28. package/dist/defs.d.ts +9 -9
  29. package/dist/defs.js +2 -2
  30. package/dist/devtools/devtools-compatibility.test.js +1 -0
  31. package/dist/devtools/devtools-compatibility.test.js.map +1 -1
  32. package/dist/devtools/devtools-messages-client-session.d.ts +520 -332
  33. package/dist/devtools/devtools-messages-client-session.d.ts.map +1 -1
  34. package/dist/devtools/devtools-messages-client-session.js +76 -74
  35. package/dist/devtools/devtools-messages-client-session.js.map +1 -1
  36. package/dist/devtools/devtools-messages-common.d.ts +27 -27
  37. package/dist/devtools/devtools-messages-common.d.ts.map +1 -1
  38. package/dist/devtools/devtools-messages-common.js +5 -5
  39. package/dist/devtools/devtools-messages-common.js.map +1 -1
  40. package/dist/devtools/devtools-messages-leader.d.ts +405 -343
  41. package/dist/devtools/devtools-messages-leader.d.ts.map +1 -1
  42. package/dist/devtools/devtools-messages-leader.js +101 -89
  43. package/dist/devtools/devtools-messages-leader.js.map +1 -1
  44. package/dist/devtools/devtools-sessioninfo.d.ts +18 -19
  45. package/dist/devtools/devtools-sessioninfo.d.ts.map +1 -1
  46. package/dist/devtools/devtools-sessioninfo.js +8 -5
  47. package/dist/devtools/devtools-sessioninfo.js.map +1 -1
  48. package/dist/devtools/mod.d.ts +4 -5
  49. package/dist/devtools/mod.d.ts.map +1 -1
  50. package/dist/devtools/mod.js +9 -5
  51. package/dist/devtools/mod.js.map +1 -1
  52. package/dist/errors.d.ts +45 -69
  53. package/dist/errors.d.ts.map +1 -1
  54. package/dist/errors.js +18 -16
  55. package/dist/errors.js.map +1 -1
  56. package/dist/index.d.ts +4 -1
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +4 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/leader-thread/LeaderSyncProcessor.d.ts +66 -18
  61. package/dist/leader-thread/LeaderSyncProcessor.d.ts.map +1 -1
  62. package/dist/leader-thread/LeaderSyncProcessor.js +519 -461
  63. package/dist/leader-thread/LeaderSyncProcessor.js.map +1 -1
  64. package/dist/leader-thread/RejectedPushError.d.ts +67 -36
  65. package/dist/leader-thread/RejectedPushError.d.ts.map +1 -1
  66. package/dist/leader-thread/RejectedPushError.js +24 -5
  67. package/dist/leader-thread/RejectedPushError.js.map +1 -1
  68. package/dist/leader-thread/connection.d.ts +1 -0
  69. package/dist/leader-thread/connection.d.ts.map +1 -1
  70. package/dist/leader-thread/connection.js +9 -8
  71. package/dist/leader-thread/connection.js.map +1 -1
  72. package/dist/leader-thread/eventlog.d.ts +4 -4
  73. package/dist/leader-thread/eventlog.d.ts.map +1 -1
  74. package/dist/leader-thread/eventlog.js +6 -6
  75. package/dist/leader-thread/eventlog.js.map +1 -1
  76. package/dist/leader-thread/leader-worker-devtools.d.ts +1 -1
  77. package/dist/leader-thread/leader-worker-devtools.d.ts.map +1 -1
  78. package/dist/leader-thread/leader-worker-devtools.js +33 -17
  79. package/dist/leader-thread/leader-worker-devtools.js.map +1 -1
  80. package/dist/leader-thread/make-leader-thread-layer.d.ts +9 -5
  81. package/dist/leader-thread/make-leader-thread-layer.d.ts.map +1 -1
  82. package/dist/leader-thread/make-leader-thread-layer.js +25 -35
  83. package/dist/leader-thread/make-leader-thread-layer.js.map +1 -1
  84. package/dist/leader-thread/make-leader-thread-layer.test.js +7 -7
  85. package/dist/leader-thread/make-leader-thread-layer.test.js.map +1 -1
  86. package/dist/leader-thread/materialize-event.d.ts +2 -1
  87. package/dist/leader-thread/materialize-event.d.ts.map +1 -1
  88. package/dist/leader-thread/materialize-event.js +4 -0
  89. package/dist/leader-thread/materialize-event.js.map +1 -1
  90. package/dist/leader-thread/recreate-db.d.ts.map +1 -1
  91. package/dist/leader-thread/recreate-db.js +18 -39
  92. package/dist/leader-thread/recreate-db.js.map +1 -1
  93. package/dist/leader-thread/shutdown-channel.d.ts +2 -6
  94. package/dist/leader-thread/shutdown-channel.d.ts.map +1 -1
  95. package/dist/leader-thread/shutdown-channel.js +2 -3
  96. package/dist/leader-thread/shutdown-channel.js.map +1 -1
  97. package/dist/leader-thread/stream-events.d.ts +4 -7
  98. package/dist/leader-thread/stream-events.d.ts.map +1 -1
  99. package/dist/leader-thread/stream-events.js +13 -16
  100. package/dist/leader-thread/stream-events.js.map +1 -1
  101. package/dist/leader-thread/types.d.ts +32 -69
  102. package/dist/leader-thread/types.d.ts.map +1 -1
  103. package/dist/leader-thread/types.js +5 -5
  104. package/dist/leader-thread/types.js.map +1 -1
  105. package/dist/logging.d.ts +5 -30
  106. package/dist/logging.d.ts.map +1 -1
  107. package/dist/logging.js +1 -32
  108. package/dist/logging.js.map +1 -1
  109. package/dist/make-client-session.d.ts +1 -2
  110. package/dist/make-client-session.d.ts.map +1 -1
  111. package/dist/make-client-session.js +3 -3
  112. package/dist/make-client-session.js.map +1 -1
  113. package/dist/materializer-helper.d.ts +0 -1
  114. package/dist/materializer-helper.d.ts.map +1 -1
  115. package/dist/materializer-helper.js +7 -35
  116. package/dist/materializer-helper.js.map +1 -1
  117. package/dist/otel.d.ts +2 -3
  118. package/dist/otel.d.ts.map +1 -1
  119. package/dist/otel.js +2 -7
  120. package/dist/otel.js.map +1 -1
  121. package/dist/rematerialize-from-eventlog.d.ts.map +1 -1
  122. package/dist/rematerialize-from-eventlog.js +28 -26
  123. package/dist/rematerialize-from-eventlog.js.map +1 -1
  124. package/dist/schema/EventDef/define.d.ts +4 -4
  125. package/dist/schema/EventDef/define.d.ts.map +1 -1
  126. package/dist/schema/EventDef/define.js +5 -5
  127. package/dist/schema/EventDef/define.js.map +1 -1
  128. package/dist/schema/EventDef/define.test.d.ts +2 -0
  129. package/dist/schema/EventDef/define.test.d.ts.map +1 -0
  130. package/dist/schema/EventDef/define.test.js +23 -0
  131. package/dist/schema/EventDef/define.test.js.map +1 -0
  132. package/dist/schema/EventDef/deprecated.d.ts +8 -13
  133. package/dist/schema/EventDef/deprecated.d.ts.map +1 -1
  134. package/dist/schema/EventDef/deprecated.js +12 -13
  135. package/dist/schema/EventDef/deprecated.js.map +1 -1
  136. package/dist/schema/EventDef/deprecated.test.js +1 -1
  137. package/dist/schema/EventDef/deprecated.test.js.map +1 -1
  138. package/dist/schema/EventDef/event-def.d.ts +1 -1
  139. package/dist/schema/EventDef/event-def.d.ts.map +1 -1
  140. package/dist/schema/EventSequenceNumber/client.d.ts +12 -12
  141. package/dist/schema/EventSequenceNumber/client.d.ts.map +1 -1
  142. package/dist/schema/EventSequenceNumber/client.js +8 -9
  143. package/dist/schema/EventSequenceNumber/client.js.map +1 -1
  144. package/dist/schema/EventSequenceNumber/global.d.ts +2 -2
  145. package/dist/schema/EventSequenceNumber/global.d.ts.map +1 -1
  146. package/dist/schema/EventSequenceNumber/global.js +1 -1
  147. package/dist/schema/EventSequenceNumber/global.js.map +1 -1
  148. package/dist/schema/EventSequenceNumber.test.js +5 -5
  149. package/dist/schema/EventSequenceNumber.test.js.map +1 -1
  150. package/dist/schema/LiveStoreEvent/client.d.ts +50 -179
  151. package/dist/schema/LiveStoreEvent/client.d.ts.map +1 -1
  152. package/dist/schema/LiveStoreEvent/client.js +32 -29
  153. package/dist/schema/LiveStoreEvent/client.js.map +1 -1
  154. package/dist/schema/LiveStoreEvent/client.test.js +11 -2
  155. package/dist/schema/LiveStoreEvent/client.test.js.map +1 -1
  156. package/dist/schema/LiveStoreEvent/for-event-def.d.ts +7 -7
  157. package/dist/schema/LiveStoreEvent/for-event-def.d.ts.map +1 -1
  158. package/dist/schema/LiveStoreEvent/global.d.ts +6 -6
  159. package/dist/schema/LiveStoreEvent/global.d.ts.map +1 -1
  160. package/dist/schema/LiveStoreEvent/global.js +1 -1
  161. package/dist/schema/LiveStoreEvent/global.js.map +1 -1
  162. package/dist/schema/LiveStoreEvent/input.d.ts +5 -5
  163. package/dist/schema/LiveStoreEvent/input.d.ts.map +1 -1
  164. package/dist/schema/LiveStoreEvent/input.js +3 -3
  165. package/dist/schema/LiveStoreEvent/input.js.map +1 -1
  166. package/dist/schema/mod.d.ts +1 -0
  167. package/dist/schema/mod.d.ts.map +1 -1
  168. package/dist/schema/mod.js +1 -0
  169. package/dist/schema/mod.js.map +1 -1
  170. package/dist/schema/schema.d.ts.map +1 -1
  171. package/dist/schema/schema.js +3 -2
  172. package/dist/schema/schema.js.map +1 -1
  173. package/dist/schema/state/sqlite/client-document-def.d.ts +12 -17
  174. package/dist/schema/state/sqlite/client-document-def.d.ts.map +1 -1
  175. package/dist/schema/state/sqlite/client-document-def.js +23 -20
  176. package/dist/schema/state/sqlite/client-document-def.js.map +1 -1
  177. package/dist/schema/state/sqlite/client-document-def.test.js +29 -8
  178. package/dist/schema/state/sqlite/client-document-def.test.js.map +1 -1
  179. package/dist/schema/state/sqlite/column-annotations.d.ts +13 -13
  180. package/dist/schema/state/sqlite/column-annotations.d.ts.map +1 -1
  181. package/dist/schema/state/sqlite/column-annotations.js +13 -15
  182. package/dist/schema/state/sqlite/column-annotations.js.map +1 -1
  183. package/dist/schema/state/sqlite/column-annotations.test.js +19 -43
  184. package/dist/schema/state/sqlite/column-annotations.test.js.map +1 -1
  185. package/dist/schema/state/sqlite/column-def.d.ts +1 -1
  186. package/dist/schema/state/sqlite/column-def.d.ts.map +1 -1
  187. package/dist/schema/state/sqlite/column-def.js +57 -31
  188. package/dist/schema/state/sqlite/column-def.js.map +1 -1
  189. package/dist/schema/state/sqlite/column-def.test.js +118 -72
  190. package/dist/schema/state/sqlite/column-def.test.js.map +1 -1
  191. package/dist/schema/state/sqlite/column-spec.js.map +1 -1
  192. package/dist/schema/state/sqlite/column-spec.test.js +2 -2
  193. package/dist/schema/state/sqlite/db-schema/ast/sqlite.d.ts +2 -2
  194. package/dist/schema/state/sqlite/db-schema/ast/sqlite.d.ts.map +1 -1
  195. package/dist/schema/state/sqlite/db-schema/ast/sqlite.js +13 -4
  196. package/dist/schema/state/sqlite/db-schema/ast/sqlite.js.map +1 -1
  197. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.d.ts +9 -9
  198. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.d.ts.map +1 -1
  199. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.js +8 -13
  200. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.js.map +1 -1
  201. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.test.js +27 -16
  202. package/dist/schema/state/sqlite/db-schema/dsl/field-defs.test.js.map +1 -1
  203. package/dist/schema/state/sqlite/db-schema/dsl/mod.d.ts +13 -11
  204. package/dist/schema/state/sqlite/db-schema/dsl/mod.d.ts.map +1 -1
  205. package/dist/schema/state/sqlite/db-schema/dsl/mod.js +5 -3
  206. package/dist/schema/state/sqlite/db-schema/dsl/mod.js.map +1 -1
  207. package/dist/schema/state/sqlite/mod.d.ts +1 -3
  208. package/dist/schema/state/sqlite/mod.d.ts.map +1 -1
  209. package/dist/schema/state/sqlite/mod.js +1 -1
  210. package/dist/schema/state/sqlite/mod.js.map +1 -1
  211. package/dist/schema/state/sqlite/persistence.d.ts +11 -0
  212. package/dist/schema/state/sqlite/persistence.d.ts.map +1 -0
  213. package/dist/schema/state/sqlite/persistence.js +10 -0
  214. package/dist/schema/state/sqlite/persistence.js.map +1 -0
  215. package/dist/schema/state/sqlite/query-builder/api.d.ts +7 -7
  216. package/dist/schema/state/sqlite/query-builder/api.d.ts.map +1 -1
  217. package/dist/schema/state/sqlite/query-builder/astToSql.d.ts.map +1 -1
  218. package/dist/schema/state/sqlite/query-builder/astToSql.js +27 -23
  219. package/dist/schema/state/sqlite/query-builder/astToSql.js.map +1 -1
  220. package/dist/schema/state/sqlite/query-builder/impl.d.ts +3 -1
  221. package/dist/schema/state/sqlite/query-builder/impl.d.ts.map +1 -1
  222. package/dist/schema/state/sqlite/query-builder/impl.js +16 -14
  223. package/dist/schema/state/sqlite/query-builder/impl.js.map +1 -1
  224. package/dist/schema/state/sqlite/query-builder/impl.test.js +362 -596
  225. package/dist/schema/state/sqlite/query-builder/impl.test.js.map +1 -1
  226. package/dist/schema/state/sqlite/schema-helpers.js +1 -1
  227. package/dist/schema/state/sqlite/schema-helpers.js.map +1 -1
  228. package/dist/schema/state/sqlite/system-tables/eventlog-tables.d.ts +102 -134
  229. package/dist/schema/state/sqlite/system-tables/eventlog-tables.d.ts.map +1 -1
  230. package/dist/schema/state/sqlite/system-tables/eventlog-tables.js +2 -2
  231. package/dist/schema/state/sqlite/system-tables/eventlog-tables.js.map +1 -1
  232. package/dist/schema/state/sqlite/system-tables/state-tables.d.ts +328 -106
  233. package/dist/schema/state/sqlite/system-tables/state-tables.d.ts.map +1 -1
  234. package/dist/schema/state/sqlite/system-tables/state-tables.js +33 -1
  235. package/dist/schema/state/sqlite/system-tables/state-tables.js.map +1 -1
  236. package/dist/schema/state/sqlite/table-def.d.ts +16 -19
  237. package/dist/schema/state/sqlite/table-def.d.ts.map +1 -1
  238. package/dist/schema/state/sqlite/table-def.js +53 -3
  239. package/dist/schema/state/sqlite/table-def.js.map +1 -1
  240. package/dist/schema/state/sqlite/table-def.test.js +153 -36
  241. package/dist/schema/state/sqlite/table-def.test.js.map +1 -1
  242. package/dist/schema/unknown-events.d.ts.map +1 -1
  243. package/dist/schema/unknown-events.js +2 -1
  244. package/dist/schema/unknown-events.js.map +1 -1
  245. package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js +2 -2
  246. package/dist/session-id-symbol.d.ts +29 -0
  247. package/dist/session-id-symbol.d.ts.map +1 -0
  248. package/dist/session-id-symbol.js +44 -0
  249. package/dist/session-id-symbol.js.map +1 -0
  250. package/dist/sql-queries/sql-queries.d.ts.map +1 -1
  251. package/dist/sql-queries/sql-queries.js +8 -10
  252. package/dist/sql-queries/sql-queries.js.map +1 -1
  253. package/dist/sql-queries/types.d.ts +6 -7
  254. package/dist/sql-queries/types.d.ts.map +1 -1
  255. package/dist/sql-queries/types.js.map +1 -1
  256. package/dist/sqlite-db-helper.d.ts +21 -1
  257. package/dist/sqlite-db-helper.d.ts.map +1 -1
  258. package/dist/sqlite-db-helper.js +37 -2
  259. package/dist/sqlite-db-helper.js.map +1 -1
  260. package/dist/sqlite-types.d.ts +3 -6
  261. package/dist/sqlite-types.d.ts.map +1 -1
  262. package/dist/sqlite-types.js +3 -3
  263. package/dist/sqlite-types.js.map +1 -1
  264. package/dist/sync/ClientSessionSyncProcessor.d.ts +38 -16
  265. package/dist/sync/ClientSessionSyncProcessor.d.ts.map +1 -1
  266. package/dist/sync/ClientSessionSyncProcessor.js +196 -66
  267. package/dist/sync/ClientSessionSyncProcessor.js.map +1 -1
  268. package/dist/sync/errors.d.ts +12 -18
  269. package/dist/sync/errors.d.ts.map +1 -1
  270. package/dist/sync/errors.js +2 -2
  271. package/dist/sync/errors.js.map +1 -1
  272. package/dist/sync/mock-sync-backend.d.ts +2 -3
  273. package/dist/sync/mock-sync-backend.d.ts.map +1 -1
  274. package/dist/sync/mock-sync-backend.js +54 -33
  275. package/dist/sync/mock-sync-backend.js.map +1 -1
  276. package/dist/sync/mock-sync-backend.test.d.ts +2 -0
  277. package/dist/sync/mock-sync-backend.test.d.ts.map +1 -0
  278. package/dist/sync/mock-sync-backend.test.js +49 -0
  279. package/dist/sync/mock-sync-backend.test.js.map +1 -0
  280. package/dist/sync/next/history-dag-common.d.ts +4 -0
  281. package/dist/sync/next/history-dag-common.d.ts.map +1 -1
  282. package/dist/sync/next/history-dag-common.js +52 -31
  283. package/dist/sync/next/history-dag-common.js.map +1 -1
  284. package/dist/sync/next/history-dag.d.ts.map +1 -1
  285. package/dist/sync/next/history-dag.js +2 -1
  286. package/dist/sync/next/history-dag.js.map +1 -1
  287. package/dist/sync/next/test/compact-events.calculator.test.js +2 -2
  288. package/dist/sync/next/test/event-fixtures.d.ts +7 -7
  289. package/dist/sync/next/test/event-fixtures.js +1 -1
  290. package/dist/sync/next/test/event-fixtures.js.map +1 -1
  291. package/dist/sync/next/test/history-dag-common.test.d.ts +2 -0
  292. package/dist/sync/next/test/history-dag-common.test.d.ts.map +1 -0
  293. package/dist/sync/next/test/history-dag-common.test.js +73 -0
  294. package/dist/sync/next/test/history-dag-common.test.js.map +1 -0
  295. package/dist/sync/sync-backend-kv.d.ts.map +1 -1
  296. package/dist/sync/sync-backend-kv.js +4 -2
  297. package/dist/sync/sync-backend-kv.js.map +1 -1
  298. package/dist/sync/sync-backend.d.ts +15 -15
  299. package/dist/sync/sync-backend.d.ts.map +1 -1
  300. package/dist/sync/sync-backend.js +9 -5
  301. package/dist/sync/sync-backend.js.map +1 -1
  302. package/dist/sync/sync.d.ts +1 -1
  303. package/dist/sync/sync.d.ts.map +1 -1
  304. package/dist/sync/syncstate.d.ts +97 -173
  305. package/dist/sync/syncstate.d.ts.map +1 -1
  306. package/dist/sync/syncstate.js +34 -37
  307. package/dist/sync/syncstate.js.map +1 -1
  308. package/dist/sync/syncstate.test.js +100 -61
  309. package/dist/sync/syncstate.test.js.map +1 -1
  310. package/dist/sync/transport-chunking.d.ts +15 -16
  311. package/dist/sync/transport-chunking.d.ts.map +1 -1
  312. package/dist/sync/transport-chunking.js +23 -32
  313. package/dist/sync/transport-chunking.js.map +1 -1
  314. package/dist/util.d.ts +11 -4
  315. package/dist/util.d.ts.map +1 -1
  316. package/dist/util.js +19 -2
  317. package/dist/util.js.map +1 -1
  318. package/dist/version.d.ts.map +1 -1
  319. package/dist/version.js.map +1 -1
  320. package/package.json +19 -37
  321. package/src/ClientSessionLeaderThreadProxy.ts +1 -1
  322. package/src/MaterializationJournal.ts +184 -0
  323. package/src/StateHead.ts +80 -0
  324. package/src/WorkerTransportError.ts +4 -4
  325. package/src/__tests__/fixture.ts +3 -3
  326. package/src/adapter-types.ts +24 -61
  327. package/src/debug-info.ts +50 -70
  328. package/src/defs.ts +2 -2
  329. package/src/devtools/devtools-compatibility.test.ts +1 -0
  330. package/src/devtools/devtools-messages-client-session.ts +56 -65
  331. package/src/devtools/devtools-messages-common.ts +12 -11
  332. package/src/devtools/devtools-messages-leader.ts +71 -69
  333. package/src/devtools/devtools-sessioninfo.ts +13 -11
  334. package/src/devtools/mod.ts +4 -5
  335. package/src/errors.ts +46 -34
  336. package/src/index.ts +8 -1
  337. package/src/leader-thread/LeaderSyncProcessor.ts +794 -691
  338. package/src/leader-thread/RejectedPushError.ts +40 -27
  339. package/src/leader-thread/connection.ts +12 -8
  340. package/src/leader-thread/eventlog.ts +7 -7
  341. package/src/leader-thread/leader-worker-devtools.ts +37 -19
  342. package/src/leader-thread/make-leader-thread-layer.test.ts +7 -7
  343. package/src/leader-thread/make-leader-thread-layer.ts +56 -53
  344. package/src/leader-thread/materialize-event.ts +13 -8
  345. package/src/leader-thread/recreate-db.ts +24 -59
  346. package/src/leader-thread/shutdown-channel.ts +3 -14
  347. package/src/leader-thread/stream-events.ts +104 -101
  348. package/src/leader-thread/types.ts +24 -62
  349. package/src/logging.ts +5 -52
  350. package/src/make-client-session.ts +6 -6
  351. package/src/materializer-helper.ts +8 -37
  352. package/src/otel.ts +5 -14
  353. package/src/rematerialize-from-eventlog.ts +97 -94
  354. package/src/schema/EventDef/define.test.ts +28 -0
  355. package/src/schema/EventDef/define.ts +20 -19
  356. package/src/schema/EventDef/deprecated.test.ts +1 -8
  357. package/src/schema/EventDef/deprecated.ts +17 -20
  358. package/src/schema/EventDef/event-def.ts +2 -4
  359. package/src/schema/EventSequenceNumber/client.ts +8 -9
  360. package/src/schema/EventSequenceNumber/global.ts +1 -1
  361. package/src/schema/EventSequenceNumber.test.ts +5 -5
  362. package/src/schema/LiveStoreEvent/client.test.ts +17 -4
  363. package/src/schema/LiveStoreEvent/client.ts +36 -35
  364. package/src/schema/LiveStoreEvent/for-event-def.ts +7 -7
  365. package/src/schema/LiveStoreEvent/global.ts +1 -1
  366. package/src/schema/LiveStoreEvent/input.ts +6 -6
  367. package/src/schema/mod.ts +1 -0
  368. package/src/schema/schema.ts +3 -2
  369. package/src/schema/state/sqlite/client-document-def.test.ts +32 -13
  370. package/src/schema/state/sqlite/client-document-def.ts +95 -80
  371. package/src/schema/state/sqlite/column-annotations.test.ts +26 -45
  372. package/src/schema/state/sqlite/column-annotations.ts +26 -30
  373. package/src/schema/state/sqlite/column-def.test.ts +132 -77
  374. package/src/schema/state/sqlite/column-def.ts +72 -37
  375. package/src/schema/state/sqlite/column-spec.test.ts +2 -2
  376. package/src/schema/state/sqlite/column-spec.ts +3 -2
  377. package/src/schema/state/sqlite/db-schema/ast/sqlite.ts +15 -5
  378. package/src/schema/state/sqlite/db-schema/dsl/__snapshots__/field-defs.test.ts.snap +123 -63
  379. package/src/schema/state/sqlite/db-schema/dsl/field-defs.test.ts +35 -16
  380. package/src/schema/state/sqlite/db-schema/dsl/field-defs.ts +25 -31
  381. package/src/schema/state/sqlite/db-schema/dsl/mod.ts +35 -21
  382. package/src/schema/state/sqlite/mod.ts +2 -4
  383. package/src/schema/state/sqlite/persistence.ts +11 -0
  384. package/src/schema/state/sqlite/query-builder/api.ts +9 -9
  385. package/src/schema/state/sqlite/query-builder/astToSql.ts +31 -26
  386. package/src/schema/state/sqlite/query-builder/impl.test.ts +433 -669
  387. package/src/schema/state/sqlite/query-builder/impl.ts +19 -15
  388. package/src/schema/state/sqlite/schema-helpers.ts +1 -1
  389. package/src/schema/state/sqlite/system-tables/eventlog-tables.ts +2 -2
  390. package/src/schema/state/sqlite/system-tables/state-tables.ts +41 -1
  391. package/src/schema/state/sqlite/table-def.test.ts +204 -66
  392. package/src/schema/state/sqlite/table-def.ts +96 -45
  393. package/src/schema/unknown-events.ts +3 -2
  394. package/src/schema-management/__tests__/migrations-autoincrement-quoting.test.ts +2 -2
  395. package/src/session-id-symbol.ts +59 -0
  396. package/src/sql-queries/sql-queries.ts +8 -12
  397. package/src/sql-queries/types.ts +6 -7
  398. package/src/sqlite-db-helper.ts +64 -2
  399. package/src/sqlite-types.ts +5 -8
  400. package/src/sync/ClientSessionSyncProcessor.ts +303 -119
  401. package/src/sync/errors.ts +14 -12
  402. package/src/sync/mock-sync-backend.test.ts +78 -0
  403. package/src/sync/mock-sync-backend.ts +93 -47
  404. package/src/sync/next/history-dag-common.ts +60 -34
  405. package/src/sync/next/history-dag.ts +4 -1
  406. package/src/sync/next/test/compact-events.calculator.test.ts +2 -2
  407. package/src/sync/next/test/event-fixtures.ts +1 -1
  408. package/src/sync/next/test/history-dag-common.test.ts +87 -0
  409. package/src/sync/sync-backend-kv.ts +4 -2
  410. package/src/sync/sync-backend.ts +15 -15
  411. package/src/sync/sync.ts +1 -1
  412. package/src/sync/syncstate.test.ts +191 -140
  413. package/src/sync/syncstate.ts +63 -53
  414. package/src/sync/transport-chunking.ts +34 -39
  415. package/src/util.ts +18 -9
  416. package/src/version.ts +1 -2
  417. package/dist/sql-queries/misc.d.ts +0 -2
  418. package/dist/sql-queries/misc.d.ts.map +0 -1
  419. package/dist/sql-queries/misc.js +0 -2
  420. package/dist/sql-queries/misc.js.map +0 -1
  421. package/src/sql-queries/misc.ts +0 -2
@@ -1,18 +1,18 @@
1
- import { casesHandled, isNotUndefined, LS_DEV, TRACE_VERBOSE } from '@livestore/utils';
2
- import { BucketQueue, Cause, Deferred, Duration, Effect, Exit, FiberHandle, Layer, Option, Queue, ReadonlyArray, Schedule, Schema, Stream, Subscribable, SubscriptionRef, } from '@livestore/utils/effect';
3
- import { UnknownError } from "../adapter-types.js";
1
+ import { casesHandled, LS_DEV, TRACE_VERBOSE } from '@livestore/utils';
2
+ import { Cause, Context, Deferred, Duration, Effect, Exit, FiberHandle, Layer, Option, Predicate, Queue, ReadonlyArray, References, Result, Schedule, Schema, Semaphore, Stream, Subscribable, SubscriptionRef, TxQueue, } from '@livestore/utils/effect';
3
+ import { MaterializeError, UnknownError } from "../adapter-types.js";
4
4
  import { IntentionalShutdownCause } from "../errors.js";
5
5
  import { makeMaterializerHash } from "../materializer-helper.js";
6
6
  import { EventSequenceNumber, LiveStoreEvent, resolveEventDef, SystemTables } from "../schema/mod.js";
7
7
  import { EVENTLOG_META_TABLE, SYNC_STATUS_TABLE } from "../schema/state/sqlite/system-tables/eventlog-tables.js";
8
- import { isRejectedPushError, LeaderAheadError, NonMonotonicBatchError, StaleRebaseGenerationError } from "./RejectedPushError.js";
8
+ import * as StateHead from "../StateHead.js";
9
9
  import * as SyncState from "../sync/syncstate.js";
10
10
  import { sql } from "../util.js";
11
11
  import * as Eventlog from "./eventlog.js";
12
12
  import { rollback } from "./materialize-event.js";
13
+ import { isRejectedPushError, LeaderAheadError, NonContiguousBatchError, NonMonotonicBatchError, StaleRebaseGenerationError, } from "./RejectedPushError.js";
13
14
  import { LeaderThreadCtx } from "./types.js";
14
- /** Serialize value to JSON string for trace attributes */
15
- const jsonStringify = Schema.encodeSync(Schema.parseJson());
15
+ export const TypeId = '~@livestore/common/LeaderSyncProcessor';
16
16
  /**
17
17
  * The LeaderSyncProcessor manages synchronization of events between
18
18
  * the local state and the sync backend, ensuring efficient and orderly processing.
@@ -43,310 +43,499 @@ const jsonStringify = Schema.encodeSync(Schema.parseJson());
43
43
  *
44
44
  * See ClientSessionSyncProcessor for how the leader and session sync processors are similar/different.
45
45
  */
46
- export const makeLeaderSyncProcessor = ({ schema, dbState, initialBlockingSyncContext, initialSyncState, onError, onBackendIdMismatch, livePull, params, testing, }) => Effect.gen(function* () {
47
- const syncBackendPushQueue = yield* BucketQueue.make();
46
+ export class LeaderSyncProcessor extends Context.Service()('@livestore/common/LeaderSyncProcessor') {
47
+ }
48
+ export const make = Effect.fnUntraced(function* ({ schema, dbState, initialBlockingSyncContext, initialSyncState, onError, onBackendIdMismatch, livePull, params, testing, }) {
49
+ const stateHead = yield* StateHead.StateHead;
50
+ const syncBackendPushQueue = yield* TxQueue.unbounded();
48
51
  const localPushBatchSize = params.localPushBatchSize ?? 10;
49
52
  const backendPushBatchSize = params.backendPushBatchSize ?? 50;
50
53
  const syncStateSref = yield* SubscriptionRef.make(undefined);
51
- const isClientEvent = (eventEncoded) => schema.eventsDefsMap.get(eventEncoded.name)?.options.clientOnly ?? false;
54
+ const isClientOnlyEvent = (eventEncoded) => schema.eventsDefsMap.get(eventEncoded.name)?.options.clientOnly ?? false;
52
55
  const connectedClientSessionPullQueues = yield* makePullQueueSet;
53
56
  // This context depends on data from `boot`, we should find a better implementation to avoid this ref indirection.
54
57
  const ctxRef = {
55
58
  current: undefined,
56
59
  };
57
- const localPushesQueue = yield* BucketQueue.make();
60
+ const localPushesQueue = yield* TxQueue.unbounded();
61
+ // Reservations cover admitted pushes from validation until they are applied or rejected. The Set's
62
+ // insertion order mirrors admission order, so its last relevant item is the optimistic sequence head.
63
+ const reservedLocalPushItems = new Set();
58
64
  // Ensures mutual exclusion between local push and backend pull processing.
59
- const localPushBackendPullMutex = yield* Effect.makeSemaphore(1);
65
+ const localPushBackendPullMutex = yield* Semaphore.make(1);
66
+ // Serializes validation, queue admission, and prefix-fence reconciliation.
67
+ const pushAdmissionSemaphore = yield* Semaphore.make(1);
60
68
  /**
61
- * Additionally to the `syncStateSref` we also need the `pushHeadRef` in order to prevent old/duplicate
62
- * events from being pushed in a scenario like this:
63
- * - client session A pushes e1
64
- * - leader sync processor takes a bit and hasn't yet taken e1 from the localPushesQueue
65
- * - client session B also pushes e1 (which should be rejected)
69
+ * Admission fence for local pushes. Unlike `syncState.localHead`, this advances as soon as an event
70
+ * is queued, so another session cannot claim the same sequence number while that event is waiting
71
+ * to be applied. With authoritative head e0 and reserved pushes e1/e2, this points to e2.
66
72
  *
67
- * Thus the purpose of the pushHeadRef is the guard the integrity of the local push queue
73
+ * All reads and writes are protected by `pushAdmissionSemaphore` so validation and reservation are
74
+ * one atomic operation from the perspective of concurrent sessions and backend pulls.
68
75
  */
69
- const pushHeadRef = { current: EventSequenceNumber.Client.ROOT };
70
- const advancePushHead = (eventNum) => {
71
- pushHeadRef.current = EventSequenceNumber.Client.max(pushHeadRef.current, eventNum);
72
- };
73
- // NOTE: New events are only pushed to sync backend after successful local push processing
74
- const push = (newEvents, options) => Effect.gen(function* () {
75
- if (newEvents.length === 0)
76
- return;
77
- // console.debug('push', newEvents)
78
- yield* validatePushBatch(newEvents, pushHeadRef.current);
79
- advancePushHead(newEvents.at(-1).seqNum);
80
- const waitForProcessing = options?.waitForProcessing ?? false;
81
- if (waitForProcessing === true) {
82
- const deferreds = yield* Effect.forEach(newEvents, () => Deferred.make());
83
- const items = newEvents.map((eventEncoded, i) => [eventEncoded, deferreds[i]]);
84
- yield* BucketQueue.offerAll(localPushesQueue, items);
85
- yield* Effect.all(deferreds);
86
- }
87
- else {
88
- const items = newEvents.map((eventEncoded) => [eventEncoded, undefined]);
89
- yield* BucketQueue.offerAll(localPushesQueue, items);
76
+ const pushHeadRef = { current: initialSyncState.localHead };
77
+ /**
78
+ * A backend pull may advance or rebase authoritative history while local pushes remain reserved.
79
+ * Keep the fence at the newest reservation that is still valid for that history; if none remains,
80
+ * fall back to the authoritative head. Stale reservations are released later by the queue worker.
81
+ */
82
+ const reconcilePushHead = (authoritativeHead) => pushAdmissionSemaphore.withPermits(1)(Effect.gen(function* () {
83
+ const latestCurrentGenerationItem = [...reservedLocalPushItems].findLast(([event]) => event.seqNum.rebaseGeneration >= authoritativeHead.rebaseGeneration);
84
+ pushHeadRef.current = latestCurrentGenerationItem?.[0].seqNum ?? authoritativeHead;
85
+ }).pipe(Effect.uninterruptible));
86
+ /**
87
+ * Stop completed, rejected, or stale queue items from extending the admission fence, then rebuild
88
+ * the fence from any pushes that are still reserved.
89
+ */
90
+ const releasePushReservations = (items, authoritativeHead) => pushAdmissionSemaphore.withPermits(1)(Effect.gen(function* () {
91
+ for (const item of items)
92
+ reservedLocalPushItems.delete(item);
93
+ const latestCurrentGenerationItem = [...reservedLocalPushItems].findLast(([event]) => event.seqNum.rebaseGeneration >= authoritativeHead.rebaseGeneration);
94
+ pushHeadRef.current = latestCurrentGenerationItem?.[0].seqNum ?? authoritativeHead;
95
+ }).pipe(Effect.uninterruptible));
96
+ const backgroundApplyLocalPushes = Effect.gen(function* () {
97
+ while (true) {
98
+ if (testing.delays?.localPushProcessing !== undefined) {
99
+ yield* testing.delays.localPushProcessing.pipe(Effect.withSpan('localPushProcessingDelay'));
100
+ }
101
+ const batchItems = yield* TxQueue.takeBetween(localPushesQueue, 1, localPushBatchSize);
102
+ // Applies a batch of local pushes, guarded by the localPushBackendPullMutex to ensure mutual exclusion with backend pulling
103
+ yield* Effect.gen(function* () {
104
+ const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(Effect.orDieDebugger);
105
+ const currentRebaseGeneration = syncState.localHead.rebaseGeneration;
106
+ // Since the rebase generation might have changed since enqueuing, we need to filter out items with older generation
107
+ // It's important that we filter after acquiring the localPushBackendPullMutex, otherwise we might filter with the old generation
108
+ const [droppedItems, filteredItems] = ReadonlyArray.partition(batchItems, (batchItem) => batchItem[0].seqNum.rebaseGeneration >= currentRebaseGeneration
109
+ ? Result.succeed(batchItem)
110
+ : Result.fail(batchItem));
111
+ if (droppedItems.length > 0) {
112
+ yield* Effect.spanEvent(`push:drop-old-generation`, {
113
+ droppedCount: droppedItems.length,
114
+ currentRebaseGeneration,
115
+ });
116
+ yield* Effect.forEach(droppedItems, ([eventEncoded, deferred]) => Deferred.fail(deferred, StaleRebaseGenerationError.make({
117
+ currentRebaseGeneration,
118
+ providedRebaseGeneration: eventEncoded.seqNum.rebaseGeneration,
119
+ sessionId: eventEncoded.sessionId,
120
+ })));
121
+ yield* releasePushReservations(droppedItems, syncState.localHead);
122
+ }
123
+ if (filteredItems.length === 0) {
124
+ return;
125
+ }
126
+ const [newEvents, deferreds] = ReadonlyArray.unzip(filteredItems);
127
+ yield* Effect.annotateCurrentSpan({
128
+ batchSize: newEvents.length,
129
+ ...(TRACE_VERBOSE === true ? { newEvents: jsonStringify(newEvents) } : {}),
130
+ });
131
+ const mergeResult = yield* SyncState.merge({
132
+ syncState,
133
+ payload: { _tag: 'local-push', newEvents },
134
+ isClientOnlyEvent,
135
+ isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
136
+ });
137
+ switch (mergeResult._tag) {
138
+ case 'rebase': {
139
+ return yield* Effect.dieDebugger('The leader thread should never have to rebase due to a local push');
140
+ }
141
+ case 'reject': {
142
+ yield* Effect.spanEvent(`push:reject`, {
143
+ batchSize: newEvents.length,
144
+ ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
145
+ });
146
+ // TODO: how to test this?
147
+ const nextRebaseGeneration = currentRebaseGeneration + 1;
148
+ const providedNum = newEvents.at(0).seqNum;
149
+ // All subsequent pushes with same generation should be rejected as well
150
+ // We're also handling the case where the localPushQueue already contains events
151
+ // from the next generation which we preserve in the queue
152
+ const remainingEventsMatchingGeneration = yield* takePrefixUntil(localPushesQueue, ([eventEncoded]) => eventEncoded.seqNum.rebaseGeneration >= nextRebaseGeneration);
153
+ // TODO we still need to better understand and handle this scenario
154
+ const remainingLocalPushes = yield* snapshotTxQueue(localPushesQueue);
155
+ if (LS_DEV === true && remainingLocalPushes.length > 0) {
156
+ console.log('localPushesQueue is not empty', remainingLocalPushes.length);
157
+ // oxlint-disable-next-line eslint(no-debugger) -- intentional breakpoint for unexpected queue state
158
+ debugger;
159
+ }
160
+ const allDeferredsToReject = [
161
+ ...deferreds,
162
+ ...remainingEventsMatchingGeneration.map(([_, deferred]) => deferred),
163
+ ];
164
+ // The rejected batch and its drained same-generation suffix will never advance leader state,
165
+ // so release their sequence-number reservations before clients retry from the authoritative head.
166
+ yield* releasePushReservations([...filteredItems, ...remainingEventsMatchingGeneration], syncState.localHead);
167
+ yield* Effect.forEach(allDeferredsToReject, (deferred) => Deferred.fail(deferred, LeaderAheadError.make({
168
+ minimumExpectedNum: mergeResult.expectedMinimumId,
169
+ providedNum,
170
+ sessionId: newEvents.at(0).sessionId,
171
+ })));
172
+ // In this case we're skipping state update and down/upstream processing
173
+ // We've cleared the local push queue and are now waiting for new local pushes / backend pulls
174
+ return;
175
+ }
176
+ case 'advance': {
177
+ break;
178
+ }
179
+ default: {
180
+ casesHandled(mergeResult);
181
+ }
182
+ }
183
+ // For a local-push advance, `newEvents` and the appended pending suffix describe the same logical
184
+ // events but serve different roles and may be distinct instances. Materialize the retained pending
185
+ // instances so their rollback metadata remains available if a later backend event causes a rebase.
186
+ const acceptedPendingEvents = mergeResult.newSyncState.pending.slice(syncState.pending.length);
187
+ if (acceptedPendingEvents.length !== mergeResult.newEvents.length) {
188
+ return yield* Effect.dieDebugger('Local push events must be retained in pending state');
189
+ }
190
+ yield* materializeEventsBatch({ batchItems: acceptedPendingEvents });
191
+ yield* SubscriptionRef.set(syncStateSref, mergeResult.newSyncState);
192
+ yield* connectedClientSessionPullQueues.offer({
193
+ payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: acceptedPendingEvents }),
194
+ leaderHead: mergeResult.newSyncState.localHead,
195
+ });
196
+ yield* Effect.spanEvent(`push:advance`, {
197
+ batchSize: newEvents.length,
198
+ ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
199
+ });
200
+ // Don't sync client-only events
201
+ const globalOrUnknownEvents = acceptedPendingEvents.filter((e) => !isClientOnlyEvent(e));
202
+ yield* TxQueue.offerAll(syncBackendPushQueue, globalOrUnknownEvents);
203
+ yield* releasePushReservations(filteredItems, mergeResult.newSyncState.localHead);
204
+ // A push is acknowledged only after the complete batch is materialized, published in
205
+ // leader sync state, exposed to sessions, and queued for backend propagation.
206
+ yield* Effect.forEach(deferreds, (deferred) => Deferred.succeed(deferred, void 0));
207
+ }).pipe(localPushBackendPullMutex.withPermits(1));
90
208
  }
91
- }).pipe(Effect.withSpan('@livestore/common:LeaderSyncProcessor:push', {
92
- attributes: {
93
- batchSize: newEvents.length,
94
- batch: TRACE_VERBOSE === true ? newEvents : undefined,
95
- },
96
- links: ctxRef.current?.span !== undefined
97
- ? [{ _tag: 'SpanLink', span: ctxRef.current.span, attributes: {} }]
98
- : undefined,
99
- }));
100
- const pushPartial = ({ event: { name, args }, clientId, sessionId }) => Effect.gen(function* () {
101
- const syncState = yield* Effect.fromNullable(yield* syncStateSref).pipe(Effect.orDieDebugger);
102
- const resolution = yield* resolveEventDef(schema, {
103
- operation: '@livestore/common:LeaderSyncProcessor:pushPartial',
104
- event: {
105
- name,
106
- args,
107
- clientId,
108
- sessionId,
109
- seqNum: syncState.localHead,
110
- },
111
- });
112
- if (resolution._tag === 'unknown') {
113
- // Ignore partial pushes for unrecognised events – they are still
114
- // persisted server-side once a schema update ships.
209
+ });
210
+ const backgroundBackendPulling = Effect.fn('@livestore/common:LeaderSyncProcessor:backend-pulling')(function* ({ restartBackendPushing, }) {
211
+ const { syncBackend, dbState: db, dbEventlog, schema } = yield* LeaderThreadCtx;
212
+ if (syncBackend === undefined)
115
213
  return;
116
- }
117
- const eventEncoded = new LiveStoreEvent.Client.EncodedWithMeta({
118
- name,
119
- args,
120
- clientId,
121
- sessionId,
122
- ...EventSequenceNumber.Client.nextPair({
123
- seqNum: syncState.localHead,
124
- isClient: resolution.eventDef.options.clientOnly,
125
- }),
214
+ let pullMutexHeld = false;
215
+ const releasePullMutexIfHeld = Effect.gen(function* () {
216
+ if (pullMutexHeld === false)
217
+ return;
218
+ pullMutexHeld = false;
219
+ yield* localPushBackendPullMutex.release(1);
126
220
  });
127
- yield* push([eventEncoded]);
128
- }).pipe(
129
- // pushPartial constructs the event sequence number internally, so these errors should never happen.
130
- Effect.catchIf(isRejectedPushError, Effect.die));
131
- // Starts various background loops
132
- const boot = Effect.gen(function* () {
133
- const span = yield* Effect.currentSpan.pipe(Effect.orDie);
134
- const { devtools, shutdownChannel } = yield* LeaderThreadCtx;
135
- const runtime = yield* Effect.runtime();
136
- ctxRef.current = {
137
- span,
138
- devtoolsLatch: devtools.enabled === true ? devtools.syncBackendLatch : undefined,
139
- runtime,
140
- };
141
- /** State transitions need to happen atomically, so we use a Ref to track the state */
142
- yield* SubscriptionRef.set(syncStateSref, initialSyncState);
143
- // Rehydrate sync queue
144
- if (initialSyncState.pending.length > 0) {
145
- const globalPendingEvents = initialSyncState.pending
146
- // Don't sync client-local events
147
- .filter((eventEncoded) => {
148
- const eventDef = schema.eventsDefsMap.get(eventEncoded.name);
149
- return eventDef === undefined ? true : eventDef.options.clientOnly === false;
150
- });
151
- if (globalPendingEvents.length > 0) {
152
- yield* BucketQueue.offerAll(syncBackendPushQueue, globalPendingEvents);
221
+ const isPullPaginationComplete = (pageInfo) => pageInfo._tag === 'NoMore';
222
+ const onNewPullChunk = (newEvents, pageInfo) => Effect.gen(function* () {
223
+ if (ctxRef.current?.devtoolsLatch !== undefined) {
224
+ yield* ctxRef.current.devtoolsLatch.await;
153
225
  }
154
- }
155
- const handleBackendIdMismatchError = (error) => handleBackendIdMismatch({ error, onBackendIdMismatch, shutdownChannel });
156
- const maybeShutdownOnError = (cause) => Effect.gen(function* () {
157
- if (onError === 'ignore') {
158
- if (LS_DEV === true) {
159
- yield* Effect.logDebug(`Ignoring sync error (${cause._tag === 'Fail' ? cause.error._tag : cause._tag})`, Cause.pretty(cause));
226
+ if (newEvents.length === 0) {
227
+ if (isPullPaginationComplete(pageInfo) === true) {
228
+ yield* releasePullMutexIfHeld;
160
229
  }
161
230
  return;
162
231
  }
163
- const errorToSend = Cause.isFailType(cause) === true ? cause.error : UnknownError.make({ cause });
164
- yield* shutdownChannel.send(errorToSend).pipe(Effect.orDie);
165
- return yield* Effect.failCause(cause).pipe(Effect.orDie);
166
- });
167
- yield* backgroundApplyLocalPushes({
168
- localPushBackendPullMutex,
169
- localPushesQueue,
170
- syncStateSref,
171
- syncBackendPushQueue,
172
- schema,
173
- isClientEvent,
174
- connectedClientSessionPullQueues,
175
- localPushBatchSize,
176
- testing: {
177
- delay: testing?.delays?.localPushProcessing,
178
- },
179
- }).pipe(Effect.catchAllCause(maybeShutdownOnError), Effect.forkScoped);
180
- const backendPushingFiberHandle = yield* FiberHandle.make();
181
- const backendPushingEffect = backgroundBackendPushing({
182
- syncBackendPushQueue,
183
- devtoolsLatch: ctxRef.current?.devtoolsLatch,
184
- backendPushBatchSize,
185
- }).pipe(Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError), Effect.catchAllCause(maybeShutdownOnError));
186
- yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect);
187
- yield* backgroundBackendPulling({
188
- isClientEvent,
189
- restartBackendPushing: (filteredRebasedPending) => Effect.gen(function* () {
190
- // Stop current pushing fiber
191
- yield* FiberHandle.clear(backendPushingFiberHandle);
192
- // Reset the sync backend push queue
193
- yield* BucketQueue.clear(syncBackendPushQueue);
194
- yield* BucketQueue.offerAll(syncBackendPushQueue, filteredRebasedPending);
195
- // Restart pushing fiber
196
- yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect);
197
- }),
198
- syncStateSref,
199
- localPushBackendPullMutex,
200
- livePull,
201
- dbState,
202
- initialBlockingSyncContext,
203
- devtoolsLatch: ctxRef.current?.devtoolsLatch,
204
- connectedClientSessionPullQueues,
205
- advancePushHead,
206
- }).pipe(Effect.retry({
207
- // Retry pulling when we've lost connection to the sync backend
208
- // We're using `until` with a refinement instead of `while` to narrow `IsOfflineError` out of the error type.
209
- // See https://github.com/Effect-TS/effect/issues/6122
210
- until: (error) => error._tag !== 'IsOfflineError',
211
- }), Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError), Effect.catchAllCause(maybeShutdownOnError),
212
- // Needed to avoid `Fiber terminated with an unhandled error` logs which seem to happen because of the `Effect.retry` above.
213
- // This might be a bug in Effect. Only seems to happen in the browser.
214
- Effect.provide(Layer.setUnhandledErrorLogLevel(Option.none())), Effect.forkScoped);
215
- return { initialLeaderHead: initialSyncState.localHead };
216
- }).pipe(Effect.withSpanScoped('@livestore/common:LeaderSyncProcessor:boot'));
217
- const pull = ({ cursor }) => Effect.gen(function* () {
218
- const queue = yield* pullQueue({ cursor });
219
- return Stream.fromQueue(queue);
220
- }).pipe(Stream.unwrapScoped);
221
- /*
222
- Notes for a potential new `LeaderSyncProcessor.pull` implementation:
223
-
224
- - Doesn't take cursor but is "atomically called" in the leader during the snapshot phase
225
- - TODO: how is this done "atomically" in the web adapter where the snapshot is read optimistically?
226
- - Would require a new kind of "boot-phase" API which is stream based:
227
- - initial message: state snapshot + seq num head
228
- - subsequent messages: sync state payloads
229
-
230
- - alternative: instead of session pulling sync state payloads from leader, we could send
231
- - events in the "advance" case
232
- - full new state db snapshot in the "rebase" case
233
- - downside: importing the snapshot is expensive
234
- */
235
- const pullQueue = ({ cursor }) => Effect.fromNullable(ctxRef.current?.runtime).pipe(Effect.orDieDebugger, Effect.flatMap((runtime) => connectedClientSessionPullQueues.makeQueue(cursor).pipe(Effect.provide(runtime))));
236
- const syncState = Subscribable.make({
237
- get: syncStateSref.pipe(Effect.flatMap(Effect.fromNullable), Effect.orDieDebugger),
238
- changes: syncStateSref.changes.pipe(Stream.filter(isNotUndefined)),
239
- });
240
- return {
241
- pull,
242
- pullQueue,
243
- push,
244
- pushPartial,
245
- boot,
246
- syncState,
247
- };
248
- });
249
- const backgroundApplyLocalPushes = ({ localPushBackendPullMutex, localPushesQueue, syncStateSref, syncBackendPushQueue, schema, isClientEvent, connectedClientSessionPullQueues, localPushBatchSize, testing, }) => Effect.gen(function* () {
250
- while (true) {
251
- if (testing.delay !== undefined) {
252
- yield* testing.delay.pipe(Effect.withSpan('localPushProcessingDelay'));
253
- }
254
- const batchItems = yield* BucketQueue.takeBetween(localPushesQueue, 1, localPushBatchSize);
255
- // Applies a batch of local pushes, guarded by the localPushBackendPullMutex to ensure mutual exclusion with backend pulling
256
- yield* Effect.gen(function* () {
257
- const syncState = yield* Effect.fromNullable(yield* syncStateSref).pipe(Effect.orDieDebugger);
258
- const currentRebaseGeneration = syncState.localHead.rebaseGeneration;
259
- // Since the rebase generation might have changed since enqueuing, we need to filter out items with older generation
260
- // It's important that we filter after acquiring the localPushBackendPullMutex, otherwise we might filter with the old generation
261
- const [droppedItems, filteredItems] = ReadonlyArray.partition(batchItems, ([eventEncoded]) => eventEncoded.seqNum.rebaseGeneration >= currentRebaseGeneration);
262
- if (droppedItems.length > 0) {
263
- yield* Effect.spanEvent(`push:drop-old-generation`, {
264
- droppedCount: droppedItems.length,
265
- currentRebaseGeneration,
232
+ // Prevent more local pushes from being processed until this pull pagination sequence is finished.
233
+ if (pullMutexHeld === false) {
234
+ yield* localPushBackendPullMutex.take(1);
235
+ pullMutexHeld = true;
236
+ }
237
+ const chunkExit = yield* Effect.gen(function* () {
238
+ const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(Effect.orDieDebugger);
239
+ yield* Effect.annotateCurrentSpan({
240
+ 'merge.newEventsCount': newEvents.length,
241
+ ...(TRACE_VERBOSE === true ? { 'merge.newEvents': jsonStringify(newEvents) } : {}),
242
+ });
243
+ const mergeResult = yield* SyncState.merge({
244
+ syncState,
245
+ payload: SyncState.PayloadUpstreamAdvance.make({ newEvents }),
246
+ isClientOnlyEvent,
247
+ isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
248
+ ignoreClientOnlyEvents: true,
266
249
  });
267
- /**
268
- * Dropped pushes may still have a deferred awaiting completion.
269
- * Fail it so the caller learns the leader advanced and resubmits with the updated generation.
270
- */
271
- yield* Effect.forEach(droppedItems.filter((item) => item[1] !== undefined), ([eventEncoded, deferred]) => Deferred.fail(deferred, StaleRebaseGenerationError.make({
272
- currentRebaseGeneration,
273
- providedRebaseGeneration: eventEncoded.seqNum.rebaseGeneration,
274
- sessionId: eventEncoded.sessionId,
275
- })));
250
+ if (mergeResult._tag === 'reject') {
251
+ return yield* Effect.dieDebugger('The leader thread should never reject upstream advances');
252
+ }
253
+ const newBackendHead = newEvents.at(-1).seqNum;
254
+ Eventlog.updateBackendHead(dbEventlog, newBackendHead);
255
+ if (mergeResult._tag === 'rebase') {
256
+ yield* Effect.spanEvent(`pull:rebase[${mergeResult.newSyncState.localHead.rebaseGeneration}]`, {
257
+ newEventsCount: newEvents.length,
258
+ ...(TRACE_VERBOSE === true ? { newEvents: jsonStringify(newEvents) } : {}),
259
+ rollbackCount: mergeResult.rollbackEvents.length,
260
+ ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
261
+ });
262
+ const globalOrUnknownRebasedPendingEvents = mergeResult.newSyncState.pending.filter((e) => !isClientOnlyEvent(e));
263
+ yield* restartBackendPushing(globalOrUnknownRebasedPendingEvents);
264
+ if (mergeResult.rollbackEvents.length > 0) {
265
+ yield* rollback({
266
+ dbState: db,
267
+ dbEventlog,
268
+ eventNumsToRollback: mergeResult.rollbackEvents.map((_) => _.seqNum),
269
+ });
270
+ yield* stateHead
271
+ .set(mergeResult.rollbackEvents[0].parentSeqNum)
272
+ .pipe(Effect.mapError((cause) => MaterializeError.make({ cause })));
273
+ }
274
+ yield* connectedClientSessionPullQueues.offer({
275
+ payload: SyncState.payloadFromMergeResult(mergeResult),
276
+ leaderHead: mergeResult.newSyncState.localHead,
277
+ });
278
+ }
279
+ else {
280
+ yield* Effect.spanEvent(`pull:advance`, {
281
+ newEventsCount: newEvents.length,
282
+ ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
283
+ });
284
+ // Ensure push fiber is active after advance by restarting with current pending (non-client-only) events
285
+ const globalOrUnknownPendingEvents = mergeResult.newSyncState.pending.filter((e) => !isClientOnlyEvent(e));
286
+ yield* restartBackendPushing(globalOrUnknownPendingEvents);
287
+ yield* connectedClientSessionPullQueues.offer({
288
+ payload: SyncState.payloadFromMergeResult(mergeResult),
289
+ leaderHead: mergeResult.newSyncState.localHead,
290
+ });
291
+ if (mergeResult.confirmedEvents.length > 0) {
292
+ // `mergeResult.confirmedEvents` don't contain the correct sync metadata, so we need to use
293
+ // `newEvents` instead which we filter via `mergeResult.confirmedEvents`
294
+ const confirmedNewEvents = newEvents.filter((event) => mergeResult.confirmedEvents.some((confirmedEvent) => EventSequenceNumber.Client.isEqual(event.seqNum, confirmedEvent.seqNum)));
295
+ yield* Eventlog.updateSyncMetadata(confirmedNewEvents).pipe(Effect.orDieDebugger);
296
+ }
297
+ }
298
+ // Removes the changeset rows which are no longer needed as we'll never have to rollback beyond this point
299
+ trimChangesetRows(db, newBackendHead);
300
+ // The backend merge may advance or rebase the authoritative head. Realign the admission
301
+ // fence now so newly arriving pushes are validated against that history, not the pre-pull head.
302
+ yield* reconcilePushHead(mergeResult.newSyncState.localHead);
303
+ // Apply the merged events to storage before publishing the new sync state below, so readers
304
+ // cannot observe a leader head whose events have not yet been materialized.
305
+ yield* materializeEventsBatch({ batchItems: mergeResult.newEvents });
306
+ yield* SubscriptionRef.set(syncStateSref, mergeResult.newSyncState);
307
+ }).pipe(Effect.exit);
308
+ if (Exit.isFailure(chunkExit) === true) {
309
+ yield* releasePullMutexIfHeld;
310
+ return yield* Effect.failCause(chunkExit.cause);
276
311
  }
277
- if (filteredItems.length === 0) {
278
- return;
312
+ if (isPullPaginationComplete(pageInfo) === true) {
313
+ yield* releasePullMutexIfHeld;
279
314
  }
280
- const [newEvents, deferreds] = ReadonlyArray.unzip(filteredItems);
281
- yield* Effect.annotateCurrentSpan({
282
- 'batchSize': newEvents.length,
283
- ...(TRACE_VERBOSE === true ? { 'newEvents': jsonStringify(newEvents) } : {}),
284
- });
285
- const mergeResult = yield* SyncState.merge({
286
- syncState,
287
- payload: { _tag: 'local-push', newEvents },
288
- isClientEvent,
289
- isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
315
+ });
316
+ const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(Effect.orDieDebugger);
317
+ const cursorInfo = yield* Eventlog.getSyncBackendCursorInfo({ remoteHead: syncState.upstreamHead.global });
318
+ const hashMaterializerResult = makeMaterializerHash({ schema, dbState });
319
+ yield* syncBackend.pull(cursorInfo, { live: livePull }).pipe(
320
+ // TODO only take from queue while connected
321
+ Stream.tap(({ batch, pageInfo }) => Effect.gen(function* () {
322
+ // NOTE we only want to take process events when the sync backend is connected
323
+ // (e.g. needed for simulating being offline)
324
+ // TODO remove when there's a better way to handle this in stream above
325
+ yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
326
+ yield* onNewPullChunk(batch.map((_) => LiveStoreEvent.Client.EncodedWithMeta.fromGlobal(_.eventEncoded, {
327
+ syncMetadata: _.metadata,
328
+ // TODO we can't really know the materializer result here yet beyond the first event batch item as we need to materialize it one by one first
329
+ // This is a bug and needs to be fixed https://github.com/livestorejs/livestore/issues/503#issuecomment-3114533165
330
+ materializerHashLeader: hashMaterializerResult(LiveStoreEvent.Global.toClientEncoded(_.eventEncoded)),
331
+ materializerHashSession: Option.none(),
332
+ })), pageInfo);
333
+ yield* initialBlockingSyncContext.update({ processed: batch.length, pageInfo });
334
+ })), Stream.runDrain, Effect.interruptible, Effect.ensuring(releasePullMutexIfHeld));
335
+ // Should only ever happen when livePull is false
336
+ yield* Effect.logDebug('backend-pulling finished', { livePull });
337
+ });
338
+ const backgroundBackendPushing = Effect.gen(function* () {
339
+ const { syncBackend } = yield* LeaderThreadCtx;
340
+ if (syncBackend === undefined)
341
+ return;
342
+ while (true) {
343
+ yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
344
+ const queueItems = yield* TxQueue.takeBetween(syncBackendPushQueue, 1, backendPushBatchSize);
345
+ yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
346
+ if (ctxRef.current?.devtoolsLatch !== undefined) {
347
+ yield* ctxRef.current.devtoolsLatch.await;
348
+ }
349
+ yield* Effect.spanEvent('backend-push', {
350
+ batchSize: queueItems.length,
351
+ ...(TRACE_VERBOSE === true ? { batch: jsonStringify(queueItems) } : {}),
290
352
  });
291
- switch (mergeResult._tag) {
292
- case 'rebase': {
293
- return yield* Effect.dieDebugger('The leader thread should never have to rebase due to a local push');
353
+ // Push with declarative retry/backoff using Effect schedules
354
+ // - Exponential backoff starting at 1s and doubling (1s, 2s, 4s, 8s, 16s, 30s ...)
355
+ // - Delay clamped at 30s (continues retrying at 30s)
356
+ // - Resets automatically after successful push
357
+ // TODO(metrics): expose counters/gauges for retry attempts and queue health via devtools/metrics
358
+ yield* Effect.gen(function* () {
359
+ const iteration = yield* Schedule.CurrentMetadata;
360
+ const pushResult = yield* syncBackend.push(queueItems.map((_) => _.toGlobal())).pipe(Effect.result);
361
+ const retries = iteration.attempt;
362
+ if (retries > 0 && Result.isSuccess(pushResult) === true) {
363
+ yield* Effect.spanEvent('backend-push-retry-success', { retries, batchSize: queueItems.length });
294
364
  }
295
- case 'reject': {
296
- yield* Effect.spanEvent(`push:reject`, {
297
- batchSize: newEvents.length,
298
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
365
+ if (Result.isFailure(pushResult) === true) {
366
+ yield* Effect.spanEvent('backend-push-error', {
367
+ error: pushResult.failure.toString(),
368
+ retries,
369
+ batchSize: queueItems.length,
299
370
  });
300
- // TODO: how to test this?
301
- const nextRebaseGeneration = currentRebaseGeneration + 1;
302
- const providedNum = newEvents.at(0).seqNum;
303
- // All subsequent pushes with same generation should be rejected as well
304
- // We're also handling the case where the localPushQueue already contains events
305
- // from the next generation which we preserve in the queue
306
- const remainingEventsMatchingGeneration = yield* BucketQueue.takeSplitWhere(localPushesQueue, ([eventEncoded]) => eventEncoded.seqNum.rebaseGeneration >= nextRebaseGeneration);
307
- // TODO we still need to better understand and handle this scenario
308
- if (LS_DEV === true && (yield* BucketQueue.size(localPushesQueue)) > 0) {
309
- console.log('localPushesQueue is not empty', yield* BucketQueue.size(localPushesQueue));
310
- // oxlint-disable-next-line eslint(no-debugger) -- intentional breakpoint for unexpected queue state
311
- debugger;
371
+ const error = pushResult.failure;
372
+ if (error._tag === 'ServerAheadError') {
373
+ // It's a core part of the sync protocol that the sync backend will emit a new pull chunk alongside the ServerAheadError
374
+ yield* Effect.logDebug('handled backend-push-error (waiting for interupt caused by pull)', { error });
375
+ return yield* Effect.never;
312
376
  }
313
- const allDeferredsToReject = [
314
- ...deferreds,
315
- ...remainingEventsMatchingGeneration.map(([_, deferred]) => deferred),
316
- ].filter(isNotUndefined);
317
- yield* Effect.forEach(allDeferredsToReject, (deferred) => Deferred.fail(deferred, LeaderAheadError.make({ minimumExpectedNum: mergeResult.expectedMinimumId, providedNum, sessionId: newEvents.at(0).sessionId })));
318
- // In this case we're skipping state update and down/upstream processing
319
- // We've cleared the local push queue and are now waiting for new local pushes / backend pulls
320
- return;
321
- }
322
- case 'advance': {
323
- break;
377
+ return yield* error;
324
378
  }
325
- default: {
326
- casesHandled(mergeResult);
379
+ }).pipe(
380
+ // Retry transient errors
381
+ Effect.retry({
382
+ schedule: Schedule.exponential(Duration.seconds(1)).pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, Duration.seconds(30))))),
383
+ while: (error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError',
384
+ }),
385
+ // This is needed to narrow the Error type. Our retry policy runs indefinitely, but Effect.retry does not narrow the Error type.
386
+ Effect.catchIf((error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError', Effect.die));
387
+ }
388
+ }).pipe(Effect.interruptible);
389
+ // NOTE: New events are only pushed to sync backend after successful local push processing
390
+ const push = (newEvents) => Effect.gen(function* () {
391
+ if (newEvents.length === 0)
392
+ return;
393
+ const deferreds = yield* Effect.forEach(newEvents, () => Deferred.make());
394
+ const items = newEvents.map((eventEncoded, i) => [eventEncoded, deferreds[i]]);
395
+ // Validation, reservation, enqueueing, and fence advancement form one admission transaction.
396
+ // Serializing them prevents concurrent sessions from both validating against the same head and
397
+ // prevents backend reconciliation from changing the fence midway through admission.
398
+ yield* pushAdmissionSemaphore.withPermits(1)(
399
+ // Cancellation must not leave reservations, queue contents, and the admission fence disagreeing.
400
+ Effect.gen(function* () {
401
+ yield* validatePushBatch(newEvents, pushHeadRef.current, isClientOnlyEvent);
402
+ for (const item of items)
403
+ reservedLocalPushItems.add(item);
404
+ yield* TxQueue.offerAll(localPushesQueue, items);
405
+ pushHeadRef.current = newEvents.at(-1).seqNum;
406
+ if (testing.hooks?.localPushAdmitted !== undefined) {
407
+ yield* testing.hooks.localPushAdmitted(newEvents);
408
+ }
409
+ }).pipe(Effect.uninterruptible));
410
+ yield* Effect.all(deferreds.map(Deferred.await));
411
+ }).pipe(Effect.withSpan('@livestore/common:LeaderSyncProcessor:push', {
412
+ attributes: {
413
+ batchSize: newEvents.length,
414
+ batch: TRACE_VERBOSE === true ? newEvents : undefined,
415
+ },
416
+ links: ctxRef.current?.span !== undefined ? [{ span: ctxRef.current.span, attributes: {} }] : undefined,
417
+ }));
418
+ return LeaderSyncProcessor.of({
419
+ [TypeId]: TypeId,
420
+ // Starts various background loops
421
+ boot: Effect.gen(function* () {
422
+ const span = yield* Effect.currentSpan.pipe(Effect.orDie);
423
+ const { devtools, shutdownChannel } = yield* LeaderThreadCtx;
424
+ const services = yield* Effect.context();
425
+ ctxRef.current = {
426
+ span,
427
+ devtoolsLatch: devtools.enabled === true ? devtools.syncBackendLatch : undefined,
428
+ services,
429
+ };
430
+ /** State transitions need to happen atomically, so we use a Ref to track the state */
431
+ yield* SubscriptionRef.set(syncStateSref, initialSyncState);
432
+ // Rehydrate sync queue
433
+ if (initialSyncState.pending.length > 0) {
434
+ const globalOrUnknownPendingEvents = initialSyncState.pending
435
+ // Don't sync client-only events
436
+ .filter((eventEncoded) => !isClientOnlyEvent(eventEncoded));
437
+ if (globalOrUnknownPendingEvents.length > 0) {
438
+ yield* TxQueue.offerAll(syncBackendPushQueue, globalOrUnknownPendingEvents);
327
439
  }
328
440
  }
329
- yield* SubscriptionRef.set(syncStateSref, mergeResult.newSyncState);
330
- yield* connectedClientSessionPullQueues.offer({
331
- payload: SyncState.PayloadUpstreamAdvance.make({ newEvents: mergeResult.newEvents }),
332
- leaderHead: mergeResult.newSyncState.localHead,
441
+ const handleBackendIdMismatchError = (error) => handleBackendIdMismatch({ error, onBackendIdMismatch, shutdownChannel });
442
+ const maybeShutdownOnError = (cause) => Effect.gen(function* () {
443
+ if (onError === 'ignore') {
444
+ if (LS_DEV === true) {
445
+ yield* Effect.logDebug(`Ignoring sync error (${Option.getOrUndefined(Cause.findErrorOption(cause))?._tag ?? cause.toString()})`, Cause.pretty(cause));
446
+ }
447
+ return;
448
+ }
449
+ const error = Option.getOrUndefined(Cause.findErrorOption(cause));
450
+ const errorToSend = error === undefined ? UnknownError.make({ cause }) : error;
451
+ yield* shutdownChannel.send(errorToSend).pipe(Effect.orDie);
452
+ return yield* Effect.failCause(cause).pipe(Effect.orDie);
333
453
  });
334
- yield* Effect.spanEvent(`push:advance`, {
335
- batchSize: newEvents.length,
336
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
454
+ yield* backgroundApplyLocalPushes.pipe(Effect.catchCause(maybeShutdownOnError), Effect.forkScoped);
455
+ const backendPushingFiberHandle = yield* FiberHandle.make();
456
+ const backendPushingEffect = backgroundBackendPushing.pipe(Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError), Effect.catchCause(maybeShutdownOnError));
457
+ yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect);
458
+ yield* backgroundBackendPulling({
459
+ restartBackendPushing: (filteredRebasedPending) => Effect.gen(function* () {
460
+ // Stop current pushing fiber
461
+ yield* FiberHandle.clear(backendPushingFiberHandle);
462
+ // Reset the sync backend push queue
463
+ yield* TxQueue.clear(syncBackendPushQueue);
464
+ yield* TxQueue.offerAll(syncBackendPushQueue, filteredRebasedPending);
465
+ // Restart pushing fiber
466
+ yield* FiberHandle.run(backendPushingFiberHandle, backendPushingEffect);
467
+ }),
468
+ }).pipe(Effect.retry({
469
+ // Retry pulling when we've lost connection to the sync backend
470
+ // We're using `until` with a refinement instead of `while` to narrow `IsOfflineError` out of the error type.
471
+ // See https://github.com/Effect-TS/effect/issues/6122
472
+ until: (error) => error._tag !== 'IsOfflineError',
473
+ }), Effect.catchTag('BackendIdMismatchError', handleBackendIdMismatchError), Effect.catchCause(maybeShutdownOnError),
474
+ // Needed to avoid `Fiber terminated with an unhandled error` logs which seem to happen because of the `Effect.retry` above.
475
+ // This might be a bug in Effect. Only seems to happen in the browser.
476
+ Effect.provideService(References.UnhandledLogLevel, undefined), Effect.forkScoped);
477
+ return { initialLeaderHead: initialSyncState.localHead };
478
+ }).pipe(Effect.withSpanScoped('@livestore/common:LeaderSyncProcessor:boot')),
479
+ push,
480
+ pushPartial: ({ event: { name, args }, clientId, sessionId }) => Effect.gen(function* () {
481
+ const syncState = yield* Effect.fromNullishOr(yield* SubscriptionRef.get(syncStateSref)).pipe(Effect.orDieDebugger);
482
+ const resolution = yield* resolveEventDef(schema, {
483
+ operation: '@livestore/common:LeaderSyncProcessor:pushPartial',
484
+ event: {
485
+ name,
486
+ args,
487
+ clientId,
488
+ sessionId,
489
+ seqNum: syncState.localHead,
490
+ },
337
491
  });
338
- // Don't sync client-local events
339
- const filteredBatch = mergeResult.newEvents.filter((eventEncoded) => {
340
- const eventDef = schema.eventsDefsMap.get(eventEncoded.name);
341
- return eventDef === undefined ? true : eventDef.options.clientOnly === false;
492
+ if (resolution._tag === 'unknown') {
493
+ // Ignore partial pushes for unrecognised events – they are still
494
+ // persisted server-side once a schema update ships.
495
+ return;
496
+ }
497
+ const eventEncoded = new LiveStoreEvent.Client.EncodedWithMeta({
498
+ name,
499
+ args,
500
+ clientId,
501
+ sessionId,
502
+ ...EventSequenceNumber.Client.nextPair({
503
+ seqNum: syncState.localHead,
504
+ isClientOnly: resolution.eventDef.options.clientOnly,
505
+ }),
342
506
  });
343
- yield* BucketQueue.offerAll(syncBackendPushQueue, filteredBatch);
344
- yield* materializeEventsBatch({ batchItems: mergeResult.newEvents, deferreds });
345
- }).pipe(localPushBackendPullMutex.withPermits(1));
346
- }
507
+ yield* push([eventEncoded]);
508
+ }).pipe(
509
+ // pushPartial constructs the event sequence number internally, so these errors should never happen.
510
+ Effect.catchIf(isRejectedPushError, Effect.die)),
511
+ pull: ({ cursor }) => Effect.gen(function* () {
512
+ const queue = yield* Effect.fromNullishOr(ctxRef.current?.services).pipe(Effect.orDieDebugger, Effect.flatMap((services) => connectedClientSessionPullQueues.makeQueue(cursor).pipe(Effect.provide(services))));
513
+ return Stream.fromQueue(queue);
514
+ }).pipe(Stream.unwrap),
515
+ /*
516
+ Notes for a potential new `LeaderSyncProcessor.pull` implementation:
517
+
518
+ - Doesn't take cursor but is "atomically called" in the leader during the snapshot phase
519
+ - TODO: how is this done "atomically" in the web adapter where the snapshot is read optimistically?
520
+ - Would require a new kind of "boot-phase" API which is stream based:
521
+ - initial message: state snapshot + seq num head
522
+ - subsequent messages: sync state payloads
523
+
524
+ - alternative: instead of session pulling sync state payloads from leader, we could send
525
+ - events in the "advance" case
526
+ - full new state db snapshot in the "rebase" case
527
+ - downside: importing the snapshot is expensive
528
+ */
529
+ pullQueue: ({ cursor }) => Effect.fromNullishOr(ctxRef.current?.services).pipe(Effect.orDieDebugger, Effect.flatMap((services) => connectedClientSessionPullQueues.makeQueue(cursor).pipe(Effect.provide(services)))),
530
+ syncState: Subscribable.make({
531
+ get: SubscriptionRef.get(syncStateSref).pipe(Effect.flatMap(Effect.fromNullishOr), Effect.orDieDebugger),
532
+ changes: SubscriptionRef.changes(syncStateSref).pipe(Stream.filter(Predicate.isNotUndefined)),
533
+ }),
534
+ });
347
535
  });
536
+ export const layer = (options) => Layer.effect(LeaderSyncProcessor, make(options));
348
537
  // TODO how to handle errors gracefully
349
- const materializeEventsBatch = ({ batchItems, deferreds }) => Effect.gen(function* () {
538
+ const materializeEventsBatch = ({ batchItems }) => Effect.gen(function* () {
350
539
  const { dbState: db, dbEventlog, materializeEvent } = yield* LeaderThreadCtx;
351
540
  // NOTE We always start a transaction to ensure consistency between db and eventlog (even for single-item batches)
352
541
  db.execute('BEGIN TRANSACTION', undefined); // Start the transaction
@@ -362,194 +551,12 @@ const materializeEventsBatch = ({ batchItems, deferreds }) => Effect.gen(functio
362
551
  const { sessionChangeset, hash } = yield* materializeEvent(batchItems[i]);
363
552
  batchItems[i].meta.sessionChangeset = sessionChangeset;
364
553
  batchItems[i].meta.materializerHashLeader = hash;
365
- if (deferreds?.[i] !== undefined) {
366
- yield* Deferred.succeed(deferreds[i], void 0);
367
- }
368
554
  }
369
555
  db.execute('COMMIT', undefined); // Commit the transaction
370
556
  dbEventlog.execute('COMMIT', undefined); // Commit the transaction
371
557
  }).pipe(Effect.uninterruptible, Effect.scoped, Effect.withSpan('@livestore/common:LeaderSyncProcessor:materializeEventItems', {
372
558
  attributes: { batchSize: batchItems.length },
373
559
  }), Effect.tapCauseLogPretty);
374
- const backgroundBackendPulling = Effect.fn('@livestore/common:LeaderSyncProcessor:backend-pulling')(function* ({ isClientEvent, restartBackendPushing, dbState, syncStateSref, localPushBackendPullMutex, livePull, devtoolsLatch, initialBlockingSyncContext, connectedClientSessionPullQueues, advancePushHead, }) {
375
- const { syncBackend, dbState: db, dbEventlog, schema } = yield* LeaderThreadCtx;
376
- if (syncBackend === undefined)
377
- return;
378
- let pullMutexHeld = false;
379
- const releasePullMutexIfHeld = Effect.gen(function* () {
380
- if (pullMutexHeld === false)
381
- return;
382
- pullMutexHeld = false;
383
- yield* localPushBackendPullMutex.release(1);
384
- });
385
- const isPullPaginationComplete = (pageInfo) => pageInfo._tag === 'NoMore';
386
- const onNewPullChunk = (newEvents, pageInfo) => Effect.gen(function* () {
387
- if (devtoolsLatch !== undefined) {
388
- yield* devtoolsLatch.await;
389
- }
390
- if (newEvents.length === 0) {
391
- if (isPullPaginationComplete(pageInfo) === true) {
392
- yield* releasePullMutexIfHeld;
393
- }
394
- return;
395
- }
396
- // Prevent more local pushes from being processed until this pull pagination sequence is finished.
397
- if (pullMutexHeld === false) {
398
- yield* localPushBackendPullMutex.take(1);
399
- pullMutexHeld = true;
400
- }
401
- const chunkExit = yield* Effect.gen(function* () {
402
- const syncState = yield* Effect.fromNullable(yield* syncStateSref).pipe(Effect.orDieDebugger);
403
- yield* Effect.annotateCurrentSpan({
404
- 'merge.newEventsCount': newEvents.length,
405
- ...(TRACE_VERBOSE === true ? { 'merge.newEvents': jsonStringify(newEvents) } : {}),
406
- });
407
- const mergeResult = yield* SyncState.merge({
408
- syncState,
409
- payload: SyncState.PayloadUpstreamAdvance.make({ newEvents }),
410
- isClientEvent,
411
- isEqualEvent: LiveStoreEvent.Client.isEqualEncoded,
412
- ignoreClientEvents: true,
413
- });
414
- if (mergeResult._tag === 'reject') {
415
- return yield* Effect.dieDebugger('The leader thread should never reject upstream advances');
416
- }
417
- const newBackendHead = newEvents.at(-1).seqNum;
418
- Eventlog.updateBackendHead(dbEventlog, newBackendHead);
419
- if (mergeResult._tag === 'rebase') {
420
- yield* Effect.spanEvent(`pull:rebase[${mergeResult.newSyncState.localHead.rebaseGeneration}]`, {
421
- newEventsCount: newEvents.length,
422
- ...(TRACE_VERBOSE === true ? { newEvents: jsonStringify(newEvents) } : {}),
423
- rollbackCount: mergeResult.rollbackEvents.length,
424
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
425
- });
426
- const globalRebasedPendingEvents = mergeResult.newSyncState.pending.filter((event) => {
427
- const eventDef = schema.eventsDefsMap.get(event.name);
428
- return eventDef === undefined ? true : eventDef.options.clientOnly === false;
429
- });
430
- yield* restartBackendPushing(globalRebasedPendingEvents);
431
- if (mergeResult.rollbackEvents.length > 0) {
432
- yield* rollback({
433
- dbState: db,
434
- dbEventlog,
435
- eventNumsToRollback: mergeResult.rollbackEvents.map((_) => _.seqNum),
436
- });
437
- }
438
- yield* connectedClientSessionPullQueues.offer({
439
- payload: SyncState.payloadFromMergeResult(mergeResult),
440
- leaderHead: mergeResult.newSyncState.localHead,
441
- });
442
- }
443
- else {
444
- yield* Effect.spanEvent(`pull:advance`, {
445
- newEventsCount: newEvents.length,
446
- ...(TRACE_VERBOSE === true ? { mergeResult: jsonStringify(mergeResult) } : {}),
447
- });
448
- // Ensure push fiber is active after advance by restarting with current pending (non-client) events
449
- const globalPendingEvents = mergeResult.newSyncState.pending.filter((event) => {
450
- const eventDef = schema.eventsDefsMap.get(event.name);
451
- return eventDef === undefined ? true : eventDef.options.clientOnly === false;
452
- });
453
- yield* restartBackendPushing(globalPendingEvents);
454
- yield* connectedClientSessionPullQueues.offer({
455
- payload: SyncState.payloadFromMergeResult(mergeResult),
456
- leaderHead: mergeResult.newSyncState.localHead,
457
- });
458
- if (mergeResult.confirmedEvents.length > 0) {
459
- // `mergeResult.confirmedEvents` don't contain the correct sync metadata, so we need to use
460
- // `newEvents` instead which we filter via `mergeResult.confirmedEvents`
461
- const confirmedNewEvents = newEvents.filter((event) => mergeResult.confirmedEvents.some((confirmedEvent) => EventSequenceNumber.Client.isEqual(event.seqNum, confirmedEvent.seqNum)));
462
- yield* Eventlog.updateSyncMetadata(confirmedNewEvents).pipe(Effect.orDieDebugger);
463
- }
464
- }
465
- // Removes the changeset rows which are no longer needed as we'll never have to rollback beyond this point
466
- trimChangesetRows(db, newBackendHead);
467
- advancePushHead(mergeResult.newSyncState.localHead);
468
- yield* materializeEventsBatch({ batchItems: mergeResult.newEvents, deferreds: undefined });
469
- yield* SubscriptionRef.set(syncStateSref, mergeResult.newSyncState);
470
- }).pipe(Effect.exit);
471
- if (Exit.isFailure(chunkExit) === true) {
472
- yield* releasePullMutexIfHeld;
473
- return yield* Effect.failCause(chunkExit.cause);
474
- }
475
- if (isPullPaginationComplete(pageInfo) === true) {
476
- yield* releasePullMutexIfHeld;
477
- }
478
- });
479
- const syncState = yield* Effect.fromNullable(yield* syncStateSref).pipe(Effect.orDieDebugger);
480
- const cursorInfo = yield* Eventlog.getSyncBackendCursorInfo({ remoteHead: syncState.upstreamHead.global });
481
- const hashMaterializerResult = makeMaterializerHash({ schema, dbState });
482
- yield* syncBackend.pull(cursorInfo, { live: livePull }).pipe(
483
- // TODO only take from queue while connected
484
- Stream.tap(({ batch, pageInfo }) => Effect.gen(function* () {
485
- // NOTE we only want to take process events when the sync backend is connected
486
- // (e.g. needed for simulating being offline)
487
- // TODO remove when there's a better way to handle this in stream above
488
- yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
489
- yield* onNewPullChunk(batch.map((_) => LiveStoreEvent.Client.EncodedWithMeta.fromGlobal(_.eventEncoded, {
490
- syncMetadata: _.metadata,
491
- // TODO we can't really know the materializer result here yet beyond the first event batch item as we need to materialize it one by one first
492
- // This is a bug and needs to be fixed https://github.com/livestorejs/livestore/issues/503#issuecomment-3114533165
493
- materializerHashLeader: hashMaterializerResult(LiveStoreEvent.Global.toClientEncoded(_.eventEncoded)),
494
- materializerHashSession: Option.none(),
495
- })), pageInfo);
496
- yield* initialBlockingSyncContext.update({ processed: batch.length, pageInfo });
497
- })), Stream.runDrain, Effect.interruptible, Effect.ensuring(releasePullMutexIfHeld));
498
- // Should only ever happen when livePull is false
499
- yield* Effect.logDebug('backend-pulling finished', { livePull });
500
- });
501
- const backgroundBackendPushing = Effect.fn('@livestore/common:LeaderSyncProcessor:backend-pushing')(function* ({ syncBackendPushQueue, devtoolsLatch, backendPushBatchSize, }) {
502
- const { syncBackend } = yield* LeaderThreadCtx;
503
- if (syncBackend === undefined)
504
- return;
505
- while (true) {
506
- yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
507
- const queueItems = yield* BucketQueue.takeBetween(syncBackendPushQueue, 1, backendPushBatchSize);
508
- yield* SubscriptionRef.waitUntil(syncBackend.isConnected, (isConnected) => isConnected === true);
509
- if (devtoolsLatch !== undefined) {
510
- yield* devtoolsLatch.await;
511
- }
512
- yield* Effect.spanEvent('backend-push', {
513
- batchSize: queueItems.length,
514
- ...(TRACE_VERBOSE === true ? { batch: jsonStringify(queueItems) } : {}),
515
- });
516
- // Push with declarative retry/backoff using Effect schedules
517
- // - Exponential backoff starting at 1s and doubling (1s, 2s, 4s, 8s, 16s, 30s ...)
518
- // - Delay clamped at 30s (continues retrying at 30s)
519
- // - Resets automatically after successful push
520
- // TODO(metrics): expose counters/gauges for retry attempts and queue health via devtools/metrics
521
- yield* Effect.gen(function* () {
522
- const iteration = yield* Schedule.CurrentIterationMetadata;
523
- const pushResult = yield* syncBackend.push(queueItems.map((_) => _.toGlobal())).pipe(Effect.either);
524
- const retries = iteration.recurrence;
525
- if (retries > 0 && pushResult._tag === 'Right') {
526
- yield* Effect.spanEvent('backend-push-retry-success', { retries, batchSize: queueItems.length });
527
- }
528
- if (pushResult._tag === 'Left') {
529
- yield* Effect.spanEvent('backend-push-error', {
530
- error: pushResult.left.toString(),
531
- retries,
532
- batchSize: queueItems.length,
533
- });
534
- const error = pushResult.left;
535
- if (error._tag === 'ServerAheadError') {
536
- // It's a core part of the sync protocol that the sync backend will emit a new pull chunk alongside the ServerAheadError
537
- yield* Effect.logDebug('handled backend-push-error (waiting for interupt caused by pull)', { error });
538
- return yield* Effect.never;
539
- }
540
- return yield* error;
541
- }
542
- }).pipe(
543
- // Retry transient errors
544
- Effect.retry({
545
- schedule: Schedule.exponential(Duration.seconds(1)).pipe(Schedule.modifyDelay((_, delay) => Duration.min(delay, Duration.seconds(30))) // Cap delay at 30s intervals.
546
- ),
547
- while: (error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError',
548
- }),
549
- // This is needed to narrow the Error type. Our retry policy runs indefinitely, but Effect.retry does not narrow the Error type.
550
- Effect.catchIf((error) => error._tag === 'IsOfflineError' || error._tag === 'UnknownError', Effect.die));
551
- }
552
- }, Effect.interruptible);
553
560
  const trimChangesetRows = (db, newHead) => {
554
561
  // Since we're using the session changeset rows to query for the current head,
555
562
  // we're keeping at least one row for the current head, and thus are using `<` instead of `<=`
@@ -566,7 +573,7 @@ const makePullQueueSet = Effect.gen(function* () {
566
573
  set.clear();
567
574
  }));
568
575
  const makeQueue = (cursor) => Effect.gen(function* () {
569
- const queue = yield* Queue.unbounded().pipe(Effect.acquireRelease(Queue.shutdown));
576
+ const queue = yield* Effect.acquireRelease(Queue.unbounded(), Queue.shutdown);
570
577
  yield* Effect.addFinalizer(() => Effect.sync(() => set.delete(queue)));
571
578
  const payloadsSinceCursor = Array.from(cachedPayloads.entries())
572
579
  .flatMap(([seqNumStr, payloads]) => payloads.map((payload) => ({ payload, seqNum: EventSequenceNumber.Client.fromString(seqNumStr) })))
@@ -612,7 +619,7 @@ const makePullQueueSet = Effect.gen(function* () {
612
619
  // ...(payload._tag === 'upstream-rebase' ? payload.rollbackEvents.map((_) => _.toJSON()) : []),
613
620
  // ]),
614
621
  // )
615
- yield* queue.offerAll(payloadsSinceCursor);
622
+ yield* Queue.offerAll(queue, payloadsSinceCursor);
616
623
  set.add(queue);
617
624
  return queue;
618
625
  });
@@ -643,7 +650,7 @@ const makePullQueueSet = Effect.gen(function* () {
643
650
  * Ensures the numbers form a strictly increasing chain and that the first
644
651
  * event sits ahead of the current push head.
645
652
  */
646
- const validatePushBatch = (batch, pushHead) => Effect.gen(function* () {
653
+ const validatePushBatch = (batch, pushHead, isClientOnlyEvent) => Effect.gen(function* () {
647
654
  if (batch.length === 0) {
648
655
  return;
649
656
  }
@@ -667,7 +674,45 @@ const validatePushBatch = (batch, pushHead) => Effect.gen(function* () {
667
674
  sessionId: batch[0].sessionId,
668
675
  });
669
676
  }
677
+ // A rebase replaces the optimistic history that the client built on. Events from an older
678
+ // generation may now have the wrong parent and must be recreated from the leader's current head.
679
+ if (batch[0].seqNum.rebaseGeneration < pushHead.rebaseGeneration) {
680
+ return yield* StaleRebaseGenerationError.make({
681
+ currentRebaseGeneration: pushHead.rebaseGeneration,
682
+ providedRebaseGeneration: batch[0].seqNum.rebaseGeneration,
683
+ sessionId: batch[0].sessionId,
684
+ });
685
+ }
686
+ // Validate the batch as one unbroken chain starting at the admission fence. Checking only that
687
+ // numbers increase would still allow gaps or events that point at an unrelated parent.
688
+ let precedingSeqNum = pushHead;
689
+ for (let i = 0; i < batch.length; i++) {
690
+ const event = batch[i];
691
+ // Global events advance the global position; client-only events advance its client-local suffix.
692
+ const expectedPair = EventSequenceNumber.Client.nextPair({
693
+ seqNum: precedingSeqNum,
694
+ isClientOnly: isClientOnlyEvent(event),
695
+ rebaseGeneration: event.seqNum.rebaseGeneration,
696
+ });
697
+ if (EventSequenceNumber.Client.isEqual(event.seqNum, expectedPair.seqNum) === false ||
698
+ isSameSequencePosition(event.parentSeqNum, expectedPair.parentSeqNum) === false) {
699
+ return yield* NonContiguousBatchError.make({
700
+ expectedSeqNum: expectedPair.seqNum,
701
+ providedSeqNum: event.seqNum,
702
+ expectedParentSeqNum: expectedPair.parentSeqNum,
703
+ providedParentSeqNum: event.parentSeqNum,
704
+ violationIndex: i,
705
+ sessionId: event.sessionId,
706
+ });
707
+ }
708
+ precedingSeqNum = event.seqNum;
709
+ }
670
710
  });
711
+ /**
712
+ * Parent linkage identifies a position in the event chain. Rebase generation describes the version
713
+ * of optimistic history, so it is validated on the event itself rather than as part of parent identity.
714
+ */
715
+ const isSameSequencePosition = (left, right) => left.global === right.global && left.client === right.client;
671
716
  /**
672
717
  * Handles a BackendIdMismatchError based on the configured behavior.
673
718
  * This occurs when the sync backend has been reset and has a new identity.
@@ -706,4 +751,17 @@ const clearLocalDatabases = ({ dbEventlog, dbState }) => Effect.sync(() => {
706
751
  dbState.execute(`DROP TABLE IF EXISTS "${name}"`);
707
752
  }
708
753
  });
754
+ const snapshotTxQueue = (queue) => Effect.tx(Effect.gen(function* () {
755
+ const items = yield* TxQueue.clear(queue);
756
+ yield* TxQueue.offerAll(queue, items);
757
+ return items;
758
+ }));
759
+ const takePrefixUntil = (queue, predicate) => Effect.tx(Effect.gen(function* () {
760
+ const items = yield* TxQueue.clear(queue);
761
+ const [prefix, rest] = ReadonlyArray.splitWhere(items, predicate);
762
+ yield* TxQueue.offerAll(queue, rest);
763
+ return prefix;
764
+ }));
765
+ /** Serialize value to JSON string for trace attributes */
766
+ const jsonStringify = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
709
767
  //# sourceMappingURL=LeaderSyncProcessor.js.map