@kairos-es/core 1.0.0-alpha.4 → 1.0.0-alpha.6

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 (114) hide show
  1. package/README.md +3 -3
  2. package/dist/cjs/AppendCondition.js +1 -3
  3. package/dist/cjs/AppendCondition.js.map +1 -1
  4. package/dist/cjs/AppendIsOwned.js +6 -6
  5. package/dist/cjs/AppendIsOwned.js.map +1 -1
  6. package/dist/cjs/ContractStore.js +2 -2
  7. package/dist/cjs/ContractStore.js.map +1 -1
  8. package/dist/cjs/DcbEventStore.js +1 -1
  9. package/dist/cjs/DcbEventStore.js.map +1 -1
  10. package/dist/cjs/Event.js +29 -13
  11. package/dist/cjs/Event.js.map +1 -1
  12. package/dist/cjs/Query.js +1 -1
  13. package/dist/cjs/Query.js.map +1 -1
  14. package/dist/cjs/SubscribeMachine.js +158 -67
  15. package/dist/cjs/SubscribeMachine.js.map +1 -1
  16. package/dist/cjs/inMemory.js +4 -4
  17. package/dist/cjs/inMemory.js.map +1 -1
  18. package/dist/cjs/retryOnConflict.js +4 -10
  19. package/dist/cjs/retryOnConflict.js.map +1 -1
  20. package/dist/cjs/testing.js +2 -2
  21. package/dist/cjs/testing.js.map +1 -1
  22. package/dist/{dts → dts-cjs}/AppendCondition.d.ts +5 -7
  23. package/dist/{dts → dts-cjs}/AppendCondition.d.ts.map +1 -1
  24. package/dist/{dts → dts-cjs}/AppendIsOwned.d.ts +6 -6
  25. package/dist/{dts → dts-cjs}/AppendIsOwned.d.ts.map +1 -1
  26. package/dist/{dts → dts-cjs}/ContractStore.d.ts +3 -2
  27. package/dist/dts-cjs/ContractStore.d.ts.map +1 -0
  28. package/dist/{dts → dts-cjs}/DcbEventStore.d.ts +2 -2
  29. package/dist/{dts → dts-cjs}/DcbEventStore.d.ts.map +1 -1
  30. package/dist/{dts → dts-cjs}/Event.d.ts +31 -20
  31. package/dist/dts-cjs/Event.d.ts.map +1 -0
  32. package/dist/{dts → dts-cjs}/Query.d.ts +5 -5
  33. package/dist/dts-cjs/SubscribeMachine.d.ts +289 -0
  34. package/dist/dts-cjs/SubscribeMachine.d.ts.map +1 -0
  35. package/dist/{dts → dts-cjs}/inMemory.d.ts.map +1 -1
  36. package/dist/{dts → dts-cjs}/index.d.ts +1 -1
  37. package/dist/dts-cjs/package.json +3 -0
  38. package/dist/{dts → dts-cjs}/retryOnConflict.d.ts +1 -7
  39. package/dist/dts-cjs/retryOnConflict.d.ts.map +1 -0
  40. package/dist/{dts → dts-cjs}/testing.d.ts +1 -1
  41. package/dist/dts-esm/AppendCondition.d.ts +21 -0
  42. package/dist/dts-esm/AppendCondition.d.ts.map +1 -0
  43. package/dist/dts-esm/AppendIsOwned.d.ts +78 -0
  44. package/dist/dts-esm/AppendIsOwned.d.ts.map +1 -0
  45. package/dist/dts-esm/ContractStore.d.ts +62 -0
  46. package/dist/dts-esm/ContractStore.d.ts.map +1 -0
  47. package/dist/dts-esm/DcbEventStore.d.ts +64 -0
  48. package/dist/dts-esm/DcbEventStore.d.ts.map +1 -0
  49. package/dist/dts-esm/Event.d.ts +174 -0
  50. package/dist/dts-esm/Event.d.ts.map +1 -0
  51. package/dist/dts-esm/Projection.d.ts +124 -0
  52. package/dist/dts-esm/Projection.d.ts.map +1 -0
  53. package/dist/dts-esm/Query.d.ts +180 -0
  54. package/dist/dts-esm/Query.d.ts.map +1 -0
  55. package/dist/dts-esm/SubscribeMachine.d.ts +289 -0
  56. package/dist/dts-esm/SubscribeMachine.d.ts.map +1 -0
  57. package/dist/dts-esm/errors.d.ts +17 -0
  58. package/dist/dts-esm/errors.d.ts.map +1 -0
  59. package/dist/dts-esm/inMemory.d.ts +76 -0
  60. package/dist/dts-esm/inMemory.d.ts.map +1 -0
  61. package/dist/dts-esm/index.d.ts +40 -0
  62. package/dist/dts-esm/index.d.ts.map +1 -0
  63. package/dist/dts-esm/package.json +3 -0
  64. package/dist/dts-esm/retryOnConflict.d.ts +64 -0
  65. package/dist/dts-esm/retryOnConflict.d.ts.map +1 -0
  66. package/dist/dts-esm/testing.d.ts +39 -0
  67. package/dist/dts-esm/testing.d.ts.map +1 -0
  68. package/dist/esm/AppendCondition.js +1 -3
  69. package/dist/esm/AppendCondition.js.map +1 -1
  70. package/dist/esm/AppendIsOwned.js +6 -6
  71. package/dist/esm/AppendIsOwned.js.map +1 -1
  72. package/dist/esm/ContractStore.js +2 -2
  73. package/dist/esm/ContractStore.js.map +1 -1
  74. package/dist/esm/DcbEventStore.js +1 -1
  75. package/dist/esm/DcbEventStore.js.map +1 -1
  76. package/dist/esm/Event.js +30 -14
  77. package/dist/esm/Event.js.map +1 -1
  78. package/dist/esm/Query.js +1 -1
  79. package/dist/esm/Query.js.map +1 -1
  80. package/dist/esm/SubscribeMachine.js +157 -67
  81. package/dist/esm/SubscribeMachine.js.map +1 -1
  82. package/dist/esm/inMemory.js +5 -5
  83. package/dist/esm/inMemory.js.map +1 -1
  84. package/dist/esm/index.js +1 -1
  85. package/dist/esm/retryOnConflict.js +4 -10
  86. package/dist/esm/retryOnConflict.js.map +1 -1
  87. package/dist/esm/testing.js +2 -2
  88. package/dist/esm/testing.js.map +1 -1
  89. package/package.json +21 -11
  90. package/src/AppendCondition.ts +1 -1
  91. package/src/AppendIsOwned.ts +7 -7
  92. package/src/ContractStore.ts +5 -4
  93. package/src/DcbEventStore.ts +3 -3
  94. package/src/Event.ts +49 -14
  95. package/src/Query.ts +1 -1
  96. package/src/SubscribeMachine.ts +278 -96
  97. package/src/inMemory.ts +6 -6
  98. package/src/index.ts +1 -1
  99. package/src/retryOnConflict.ts +6 -11
  100. package/src/testing.ts +2 -2
  101. package/testing/package.json +1 -1
  102. package/dist/dts/ContractStore.d.ts.map +0 -1
  103. package/dist/dts/Event.d.ts.map +0 -1
  104. package/dist/dts/SubscribeMachine.d.ts +0 -179
  105. package/dist/dts/SubscribeMachine.d.ts.map +0 -1
  106. package/dist/dts/retryOnConflict.d.ts.map +0 -1
  107. /package/dist/{dts → dts-cjs}/Projection.d.ts +0 -0
  108. /package/dist/{dts → dts-cjs}/Projection.d.ts.map +0 -0
  109. /package/dist/{dts → dts-cjs}/Query.d.ts.map +0 -0
  110. /package/dist/{dts → dts-cjs}/errors.d.ts +0 -0
  111. /package/dist/{dts → dts-cjs}/errors.d.ts.map +0 -0
  112. /package/dist/{dts → dts-cjs}/inMemory.d.ts +0 -0
  113. /package/dist/{dts → dts-cjs}/index.d.ts.map +0 -0
  114. /package/dist/{dts → dts-cjs}/testing.d.ts.map +0 -0
@@ -5,6 +5,15 @@
5
5
  * the cursor's exclusive lower bound) and the poll loop that together turn a paged
6
6
  * read into a live subscription.
7
7
  *
8
+ * The algorithm is `subscribeItems`, generic over the item `A` it delivers and the
9
+ * cursor `C` it resumes from, because nothing in it is about an event: any source
10
+ * that can page-read strictly after a cursor and name the cursor of what it
11
+ * returned is subscribable by the same loop. `subscribeStream` is the event-store
12
+ * shape — `SequencedEvent` ordered by `Position` — over the same loop, and it is
13
+ * what every engine calls, unchanged by the generalisation. A second kind of
14
+ * source reuses the loop rather than growing a second one, for the reason the next
15
+ * paragraph gives.
16
+ *
8
17
  * It lives in core because delivery semantics are contract semantics. An engine
9
18
  * supplies TRANSPORT through two STUBBABLE seams — `fetch`, a paged read strictly
10
19
  * after a cursor, and `listen`, an optional wake source — and inherits the delivery
@@ -15,48 +24,52 @@
15
24
  * Both seams take plain in-memory values in a test, so the wake/poll/de-dup logic
16
25
  * is exercisable with no live backend at all.
17
26
  *
18
- * All THREE are the callers, and the count matters to a reader here: it means there
19
- * is exactly ONE delivery algorithm in this repo, and it is the code below. The
27
+ * All THREE engines are callers, and the count matters to a reader here: it means
28
+ * there is exactly ONE delivery algorithm in this repo, and it is the code below. The
20
29
  * in-memory store is a caller like the rest — it hands in a `fetch` over its log
21
30
  * `Ref` and its append `PubSub` as a wake source and keeps no delivery logic of its
22
31
  * own — which is what makes the shared contract suite's subscribe cases a comparison
23
32
  * of two BACKENDS rather than of two delivery algorithms.
24
33
  *
25
- * Correctness rests on the periodic position-based reconcile — a re-read from the
34
+ * Correctness rests on the periodic cursor-based reconcile — a re-read from the
26
35
  * cursor every poll interval — and NEVER on the wake source, which only lowers
27
36
  * delivery latency below that interval. A subscription with no wake source at all
28
37
  * is therefore complete and correct, merely slower, which is why `listen` is
29
38
  * optional in the TYPE rather than by the convention of passing `Stream.never`:
30
39
  * poll-only delivery is a supported shape, not a degraded one.
31
40
  *
32
- * ## The precondition every engine inherits: ASCENDING COMMIT ORDER
41
+ * ## The precondition every caller inherits: ASCENDING COMMIT ORDER
33
42
  *
34
- * A position that is committed and VISIBLE must never be below one already
35
- * delivered. Gaps are fine: the cursor is an ascending exclusive lower bound, so a
36
- * number that is allocated and never committed, or never allocated at all, is
37
- * simply a number the machine never sees. Out-of-order commits are not fine. If one
43
+ * It binds EVERY caller, over whatever cursor it chose — an engine's `Position`, or
44
+ * any other `C` handed to `subscribeItems` — and the example below is written in
45
+ * positions only because the engines are the callers it was first written for. A
46
+ * cursor that is committed and VISIBLE must never be below one already delivered.
47
+ * Gaps are fine: the cursor is an ascending exclusive lower bound, so a number
48
+ * that is allocated and never committed, or never allocated at all, is simply a
49
+ * number the machine never sees. Out-of-order commits are not fine. If one
38
50
  * writer allocates position 5 and another allocates 6, and 6 commits first, a poll
39
51
  * landing between the two commits delivers 6 and advances the cursor past it — and
40
52
  * 5 is then lost forever, because no later read looks below the cursor and nothing
41
- * anywhere notices the hole. An engine whose concurrent writers can commit out of
53
+ * anywhere notices the hole. A caller whose concurrent writers can commit out of
42
54
  * order MUST serialise them, or this machine will silently skip. An engine that
43
55
  * takes an exclusive lock on both of its append paths discharges the obligation
44
56
  * that way; an engine whose append is a single statement discharges it
45
57
  * structurally.
46
58
  *
47
59
  * The obligation is written down HERE, in the algorithm that depends on it, rather
48
- * than in whichever engine happens to satisfy it. It is a property of this delivery
49
- * loop and of nothing else, so an engine author reading only their own source has
60
+ * than in whichever caller happens to satisfy it. It is a property of this delivery
61
+ * loop and of nothing else, so an author reading only their own source has
50
62
  * no way to discover that anything downstream needs it — and the failure mode is
51
63
  * the worst kind there is: no error, no defect, no failing test, just an event that
52
64
  * a subscriber never receives. A single engine owning both its append path and its
53
65
  * own wake loop can leave the assumption implicit; a shared machine cannot.
54
66
  *
55
- * ## `catchUpPageSize` bounds the READ, not the emission
67
+ * ## `catchUpPageSize` bounds the READ, not the emission — unless `emit: 'page'`
56
68
  *
57
- * `drainFrom` below PAGES the catch-up read — `catchUpPageSize` bounds each
58
- * `fetch` — but it COLLECTS every page into one array, which is emitted as a SINGLE
59
- * chunk. So peak memory at subscription start is O(backlog) rather than O(page): a
69
+ * Under the default `emit: 'backlog'`, which is what `subscribeStream` and so every
70
+ * engine uses, `drainFrom` below PAGES the catch-up read — `catchUpPageSize` bounds
71
+ * each `fetch` — but it COLLECTS every page into one array, which is emitted as a
72
+ * SINGLE chunk. So peak memory at subscription start is O(backlog) rather than O(page): a
60
73
  * subscriber joining behind a large log materialises the whole backlog before its
61
74
  * consumer sees the first element.
62
75
  *
@@ -67,9 +80,21 @@
67
80
  * stay small even against a one-chunk catch-up. The cost therefore lands on backlog
68
81
  * memory alone, and it lands hardest on the durable-log-with-in-memory-view mode,
69
82
  * where an ephemeral view re-catches-up the entire log on every boot.
83
+ *
84
+ * `emit: 'page'` changes exactly that and nothing else. Each fetched page is
85
+ * emitted as its own chunk and the cursor advances past it before the next read, so
86
+ * peak memory is O(page) and the consumer sees the first item after ONE read rather
87
+ * than after the whole backlog. Delivery is unchanged: the same items in the same
88
+ * order, the same de-dup, the same wake and poll. What a caller gives up is the
89
+ * one-chunk catch-up, so it must not read meaning into chunk boundaries under
90
+ * either mode. It is for a consumer that does NOT re-chunk downstream and whose
91
+ * catch-up can be the whole of a large source — a full resync of a table, say —
92
+ * where holding the backlog would be the cost the paging was meant to avoid. The
93
+ * engines keep `'backlog'` because the read side's re-chunking already bounds what
94
+ * they commit, and changing their emission would move a behaviour nobody asked to
95
+ * move.
70
96
  */
71
97
  import {
72
- Chunk,
73
98
  Effect,
74
99
  Option,
75
100
  Queue,
@@ -108,6 +133,15 @@ export const DEFAULT_CATCH_UP_PAGE_SIZE = 512
108
133
  */
109
134
  export const DEFAULT_POLL_INTERVAL_MILLIS = 1000
110
135
 
136
+ /** A usable `pollInterval`: see `subscriptionTuningFields` for the bounds' argument. */
137
+ const PollIntervalMillis = Schema.Number.check(
138
+ Schema.isGreaterThan(0),
139
+ Schema.isFinite(),
140
+ )
141
+
142
+ /** A usable `catchUpPageSize`: see `subscriptionTuningFields` for the bounds' argument. */
143
+ const CatchUpPageSize = Schema.Int.check(Schema.isGreaterThan(0))
144
+
111
145
  /**
112
146
  * The two subscribe-tuning config FIELDS, for an engine whose config is a `Schema`
113
147
  * to spread into its own struct.
@@ -120,12 +154,12 @@ export const DEFAULT_POLL_INTERVAL_MILLIS = 1000
120
154
  * the key NAME, the VALIDATION and the DEFAULT from one place, so a caller who has
121
155
  * tuned one engine's subscribe reads another's without translating, and the two
122
156
  * cannot drift in what they ACCEPT any more than in what they assume. Two engines
123
- * hand-authoring the identical `Schema.optionalWith(…)` twice were identical only
157
+ * hand-authoring the identical `Schema.optionalKey(…)` twice were identical only
124
158
  * by inspection.
125
159
  *
126
160
  * The bounds differ between the two because the quantities do. `pollInterval` is a
127
- * duration, so a fraction of a millisecond is meaningful and only `positive` and
128
- * `finite` matter: at zero or below the loop would spin without ever waiting for a
161
+ * duration, so a fraction of a millisecond is meaningful and only `isGreaterThan(0)`
162
+ * and `isFinite` matter: at zero or below the loop would spin without ever waiting for a
129
163
  * wake, and at `Infinity` the periodic re-read — the half that carries delivery —
130
164
  * would never come, which silently converts the wake source from an optimisation
131
165
  * into the guarantee. `catchUpPageSize` is a COUNT, so it must be an integer
@@ -133,20 +167,41 @@ export const DEFAULT_POLL_INTERVAL_MILLIS = 1000
133
167
  * length against it to decide the tail is drained, and a page of zero would report
134
168
  * "drained" forever without reading anything.
135
169
  *
136
- * `exact: true` on both keeps the decoded type at `key?: T` rather than
170
+ * `optionalKey` on both keeps the decoded type at `key?: T` rather than
137
171
  * `T | undefined`, matching the repo's `exactOptionalPropertyTypes` discipline — an
138
172
  * absent key, never an explicit `undefined`.
139
173
  */
140
174
  export const subscriptionTuningFields = {
141
- pollInterval: Schema.optionalWith(
142
- Schema.Number.pipe(Schema.positive(), Schema.finite()),
143
- { exact: true },
144
- ),
145
- catchUpPageSize: Schema.optionalWith(Schema.Int.pipe(Schema.positive()), {
146
- exact: true,
147
- }),
175
+ pollInterval: Schema.optionalKey(PollIntervalMillis),
176
+ catchUpPageSize: Schema.optionalKey(CatchUpPageSize),
148
177
  } as const
149
178
 
179
+ /**
180
+ * Why a caller-supplied tuning knob is unusable, naming the field and the value, or
181
+ * `undefined` when both are usable or absent. It judges with the SAME two schemas
182
+ * the config fields are built from, so `subscribeItems`, whose caller may have no
183
+ * config to decode, accepts exactly what an engine's config accepts and the bounds
184
+ * have one home.
185
+ */
186
+ const tuningFault = (deps: {
187
+ readonly pollInterval?: number
188
+ readonly catchUpPageSize?: number
189
+ }): string | undefined => {
190
+ if (
191
+ deps.pollInterval !== undefined &&
192
+ !Schema.is(PollIntervalMillis)(deps.pollInterval)
193
+ ) {
194
+ return `subscribeItems: pollInterval must be a finite number of milliseconds greater than 0, got ${deps.pollInterval}`
195
+ }
196
+ if (
197
+ deps.catchUpPageSize !== undefined &&
198
+ !Schema.is(CatchUpPageSize)(deps.catchUpPageSize)
199
+ ) {
200
+ return `subscribeItems: catchUpPageSize must be an integer greater than 0, got ${deps.catchUpPageSize}`
201
+ }
202
+ return undefined
203
+ }
204
+
150
205
  /**
151
206
  * Retry a TRANSIENT poll fault (an `E` from one reconcile read) on a capped
152
207
  * exponential backoff rather than letting `Stream.orDie` kill a subscription that
@@ -154,19 +209,92 @@ export const subscriptionTuningFields = {
154
209
  * past the cap propagates (the decorator dies it) — infrastructure stays off the
155
210
  * contract channel while the stream survives ordinary transients.
156
211
  */
157
- const POLL_RETRY_SCHEDULE = Schedule.exponential('100 millis', 2).pipe(
158
- Schedule.union(Schedule.spaced('2 seconds')),
159
- Schedule.intersect(Schedule.recurs(20)),
160
- )
212
+ const POLL_RETRY_SCHEDULE = Schedule.max([
213
+ Schedule.min([
214
+ Schedule.exponential('100 millis', 2),
215
+ Schedule.spaced('2 seconds'),
216
+ ]),
217
+ Schedule.recurs(20),
218
+ ])
219
+
220
+ /**
221
+ * How a subscription hands its catch-up to the consumer: the whole backlog as ONE
222
+ * chunk (`'backlog'`), or each fetched page as a chunk of its own (`'page'`). The
223
+ * module doc's "`catchUpPageSize` bounds the READ" section owns what each costs.
224
+ *
225
+ * A closed union of two words rather than a boolean, so a call site says WHICH
226
+ * behaviour it chose instead of what it turned off, and a third shape, should one
227
+ * ever be argued for, is added beside these rather than encoded in a second flag.
228
+ */
229
+ export type SubscriptionEmission = 'backlog' | 'page'
230
+
231
+ /**
232
+ * The machine's inputs over ANY item `A` with an ascending cursor `C`: the two seams,
233
+ * where the cursor comes from and starts, and the tuning.
234
+ *
235
+ * Generic in the item and the cursor because nothing in the algorithm is about an
236
+ * EVENT. The wake queue, the poll, the paged reconcile and the exclusive-lower-bound
237
+ * de-dup need only three things of what they deliver: a page-read strictly after a
238
+ * cursor, a way to read the cursor OFF a delivered item, and a starting cursor. A
239
+ * log of `SequencedEvent`s ordered by `Position` is one such source; a feed of rows
240
+ * ordered by a feed-local sequence is another, and a second copy of this loop for it
241
+ * would be exactly the divergence the module doc argues against.
242
+ *
243
+ * The machine never COMPARES two cursors. `fetch` is the only thing that interprets
244
+ * one — its exclusive lower bound is what does the de-dup — so `C` needs no ordering
245
+ * instance here, and the ascending-commit-order obligation in the module doc is the
246
+ * caller's, stated over whatever `C` it chose.
247
+ *
248
+ * `initial` is REQUIRED, unlike `subscribeStream`'s `after`. Only a cursor type the
249
+ * machine knows can have a default — `ORIGIN` for `Position` — and for any other the
250
+ * caller is the only party that knows what "before everything" is.
251
+ *
252
+ * `pollInterval` and `catchUpPageSize` are optional here and fall back to
253
+ * `DEFAULT_POLL_INTERVAL_MILLIS` and `DEFAULT_CATCH_UP_PAGE_SIZE`: a caller with no
254
+ * config of its own takes the same figures every engine does, from the same place.
255
+ * The event-store shape, `SubscriptionDeps`, keeps them required, because every
256
+ * engine already resolves them from its config and that type is unchanged.
257
+ */
258
+ export interface ItemSubscriptionDeps<A, C, E> {
259
+ /**
260
+ * Page-read the items strictly after `after`, up to `limit`, ascending by cursor.
261
+ * Returning FEWER than `limit` signals the tail is drained. The exclusive lower
262
+ * bound IS the de-dup: a re-read from the cursor never returns what was delivered.
263
+ */
264
+ readonly fetch: (
265
+ after: C,
266
+ limit: ReadLimit,
267
+ ) => Effect.Effect<ReadonlyArray<A>, E>
268
+ /** The cursor of a delivered item: the next `fetch` starts strictly after it. */
269
+ readonly cursorOf: (item: A) => C
270
+ /** The cursor to start from, exclusive: the first `fetch` reads strictly after it. */
271
+ readonly initial: C
272
+ /** The raw wake source — see `SubscriptionDeps.listen`, whose rules it shares. */
273
+ readonly listen?: Stream.Stream<unknown, E>
274
+ /**
275
+ * The poll interval in milliseconds (default `DEFAULT_POLL_INTERVAL_MILLIS`):
276
+ * finite and greater than 0, or `subscribeItems` dies.
277
+ */
278
+ readonly pollInterval?: number
279
+ /**
280
+ * The catch-up page size (default `DEFAULT_CATCH_UP_PAGE_SIZE`): an integer
281
+ * greater than 0, or `subscribeItems` dies.
282
+ */
283
+ readonly catchUpPageSize?: number
284
+ /** The catch-up's chunking (default `'backlog'`); see `SubscriptionEmission`. */
285
+ readonly emit?: SubscriptionEmission
286
+ }
161
287
 
162
288
  /**
163
- * The two seams the subscribe machine runs over, plus the two tuning knobs. `E` is
164
- * the engine's own infrastructure error — whatever its reads fail with — and it
165
- * stays on the channel through to `makeContractStore`, which dies it.
289
+ * The two seams the event-store subscribe machine runs over, plus the two tuning
290
+ * knobs: `ItemSubscriptionDeps` fixed to `SequencedEvent` and `Position`, the shape
291
+ * every engine's `subscribe` already hands to `subscribeStream`. `E` is the engine's
292
+ * own infrastructure error — whatever its reads fail with — and it stays on the
293
+ * channel through to `makeContractStore`, which dies it.
166
294
  *
167
295
  * ONE type parameter and not two, deliberately: a wake source with an error type of
168
296
  * its own is `Stream.orDie`d by the caller, yielding a `Stream<unknown, never>`
169
- * that is assignable here under Effect v3's covariant error channel. A second
297
+ * that is assignable here under Effect's covariant error channel. A second
170
298
  * parameter would buy nothing and would have to be spelled at every call site. Nor
171
299
  * is there an `R`: neither seam contributes a requirement, and unused generality is
172
300
  * not free.
@@ -198,19 +326,47 @@ export interface SubscriptionDeps<E> {
198
326
  }
199
327
 
200
328
  /**
201
- * Build the subscription `Stream`: catch up from `after`, then track the live tail.
202
- * The cursor threads through the `unfoldChunkEffect` unfold state, starting at
203
- * `after` and advancing to the last delivered position each batch; the stream never
204
- * completes on its own (always `Option.some`), so the enclosing scope interrupts it
205
- * on close. An `E` mid-stream stays on the channel; `makeContractStore` dies it
206
- * (subscribe is `E = never` on the contract).
329
+ * Build a subscription `Stream` over any ascending-cursor source: catch up from
330
+ * `initial`, then track the live tail. The cursor threads through the
331
+ * `Stream.paginate` state, starting at `initial` and advancing to the cursor of the
332
+ * last delivered item each batch; the stream never completes on its own (the next
333
+ * state is always `Option.some`), so the enclosing scope interrupts it on close. An
334
+ * `E` mid-stream stays on the channel, for the caller to die or to supervise.
335
+ *
336
+ * This is THE delivery algorithm, and `subscribeStream` runs the same machine. Under
337
+ * `emit: 'backlog'` a batch is everything a drain to the tail returned; under
338
+ * `'page'` it is one fetched page, so the paginate step and the page coincide and a
339
+ * full page is followed at once by the next read rather than by a wait.
340
+ *
341
+ * A `pollInterval` or `catchUpPageSize` the config fields would refuse is a DEFECT
342
+ * here, raised by the stream before it reads or forks anything, with a message
343
+ * naming the field. This caller may have no config whose decode would have caught
344
+ * it, and unchecked the two failures are silent or late: a page size of 0 gives a
345
+ * stream that never emits and never fails, and 1.5 dies only at the first read,
346
+ * inside `ReadLimit`, in words that name neither knob.
207
347
  */
208
- export const subscribeStream = <E>(
209
- deps: SubscriptionDeps<E>,
210
- after: Position | undefined,
211
- ): Stream.Stream<SequencedEvent, E, Scope.Scope> =>
212
- Stream.unwrapScoped(
348
+ export const subscribeItems = <A, C, E>(
349
+ deps: ItemSubscriptionDeps<A, C, E>,
350
+ ): Stream.Stream<A, E, Scope.Scope> => {
351
+ const fault = tuningFault(deps)
352
+ return fault === undefined ? machine(deps) : Stream.die(new Error(fault))
353
+ }
354
+
355
+ /**
356
+ * The machine itself, with no check of its tuning. `subscribeStream` runs it
357
+ * directly, and deliberately: the event path stays exactly as it was, with no
358
+ * second check of figures each SQL engine has already decoded from its config
359
+ * through the same bounds, and the in-memory store's are a test's own options.
360
+ */
361
+ const machine = <A, C, E>(
362
+ deps: ItemSubscriptionDeps<A, C, E>,
363
+ ): Stream.Stream<A, E, Scope.Scope> =>
364
+ Stream.unwrap(
213
365
  Effect.gen(function* () {
366
+ const pageSize = deps.catchUpPageSize ?? DEFAULT_CATCH_UP_PAGE_SIZE
367
+ const pollInterval = deps.pollInterval ?? DEFAULT_POLL_INTERVAL_MILLIS
368
+ const limit = ReadLimit.make(pageSize)
369
+
214
370
  // The wake primitive: a sliding(1) queue holding at most one pending
215
371
  // signal. The wake source `offer`s an opaque wake on every notification;
216
372
  // the poll loop `take`s (with a timeout). The lost-wakeup guard is
@@ -230,9 +386,10 @@ export const subscribeStream = <E>(
230
386
  const listener = (deps.listen ?? Stream.never).pipe(
231
387
  Stream.tap(() => Queue.offer(wake, undefined)),
232
388
  Stream.retry(
233
- Schedule.exponential('50 millis').pipe(
234
- Schedule.union(Schedule.spaced('1 seconds')),
235
- ),
389
+ Schedule.min([
390
+ Schedule.exponential('50 millis'),
391
+ Schedule.spaced('1 seconds'),
392
+ ]),
236
393
  ),
237
394
  )
238
395
  // Drain the wake source into the wake queue on a background fibre; the
@@ -240,77 +397,102 @@ export const subscribeStream = <E>(
240
397
  // notification is an opaque wake signal.
241
398
  yield* listener.pipe(Stream.runDrain, Effect.forkScoped)
242
399
 
400
+ // One page strictly after `from`: the step `drainFrom` loops, and the whole
401
+ // of a `'page'` read.
402
+ const fetchPage = (from: C): Effect.Effect<ReadonlyArray<A>, E> =>
403
+ deps.fetch(from, limit)
404
+
243
405
  // Reconcile: page-read from `from` until a short page, advancing to the last
244
- // delivered position. Retries a TRANSIENT poll fault on a capped schedule so
406
+ // delivered cursor. Retries a TRANSIENT poll fault on a capped schedule so
245
407
  // a single connection blip does not kill a days-long subscription; a
246
- // persistent fault propagates and dies.
247
- const drainFrom = (
248
- from: Position,
249
- ): Effect.Effect<
250
- {
251
- readonly events: ReadonlyArray<SequencedEvent>
252
- readonly last: Position
253
- },
254
- E
255
- > =>
408
+ // persistent fault propagates. The retry wraps the WHOLE drain, so a fault on
409
+ // page three re-reads pages one and two: nothing has been emitted yet, so
410
+ // that costs reads and never a duplicate.
411
+ const drainFrom = (from: C): Effect.Effect<ReadonlyArray<A>, E> =>
256
412
  Effect.gen(function* () {
257
- const collected: Array<SequencedEvent> = []
413
+ const collected: Array<A> = []
258
414
  let cursor = from
259
415
  // Loop pages until a short page signals the tail is drained.
260
416
  while (true) {
261
- const events = yield* deps.fetch(
262
- cursor,
263
- ReadLimit.make(deps.catchUpPageSize),
264
- )
265
- for (const event of events) {
266
- collected.push(event)
417
+ const items = yield* fetchPage(cursor)
418
+ for (const item of items) {
419
+ collected.push(item)
267
420
  }
268
- const lastEvent = events.at(-1)
269
- if (
270
- lastEvent === undefined ||
271
- events.length < deps.catchUpPageSize
272
- ) {
421
+ const lastItem = items.at(-1)
422
+ if (lastItem === undefined || items.length < pageSize) {
273
423
  break
274
424
  }
275
- cursor = lastEvent.position
425
+ cursor = deps.cursorOf(lastItem)
276
426
  }
277
- const last = collected.at(-1)?.position ?? from
278
- return { events: collected, last }
427
+ return collected
279
428
  }).pipe(Effect.retry(POLL_RETRY_SCHEDULE))
280
429
 
430
+ // The read one paginate step performs, by emission mode. Under `'page'` the
431
+ // retry wraps the single page, which is the whole of what is unemitted.
432
+ const read =
433
+ (deps.emit ?? 'backlog') === 'page'
434
+ ? (from: C) => fetchPage(from).pipe(Effect.retry(POLL_RETRY_SCHEDULE))
435
+ : drainFrom
436
+
281
437
  /**
282
- * Produce the NEXT non-empty batch from a cursor position, together with
283
- * the advanced cursor — a pure `Position → Effect<[Chunk, next]>`. The
284
- * `> boundary` de-dup is enforced by `fetch`'s exclusive lower bound, so a
285
- * live re-read after a wake never re-emits an already-delivered position.
438
+ * Produce the NEXT non-empty batch from a cursor, together with the advanced
439
+ * cursor — a pure `C → Effect<[items, next]>`. The `> boundary` de-dup is
440
+ * enforced by `fetch`'s exclusive lower bound, so a live re-read after a wake
441
+ * never re-emits an already-delivered item.
286
442
  *
287
- * Drain the wake queue BEFORE reading (lost-wakeup guard), then drain from
288
- * the cursor. If a drain yields nothing, wait for a wake but only up to the
289
- * poll interval, then loop and re-read ANYWAY — the periodic position-based
290
- * poll that makes delivery correct independently of any wake. This effect
291
- * only completes by returning a non-empty chunk; the scope interrupts it on
292
- * close.
443
+ * Drain the wake queue BEFORE reading (lost-wakeup guard), then read from the
444
+ * cursor. If a read yields nothing, wait for a wake but only up to the poll
445
+ * interval, then loop and re-read ANYWAY — the periodic cursor-based poll that
446
+ * makes delivery correct independently of any wake. This effect only
447
+ * completes by returning a non-empty batch; the scope interrupts it on close.
293
448
  */
294
449
  const nextBatch = (
295
- from: Position,
296
- ): Effect.Effect<readonly [Chunk.Chunk<SequencedEvent>, Position], E> =>
450
+ from: C,
451
+ ): Effect.Effect<readonly [ReadonlyArray<A>, C], E> =>
297
452
  Effect.gen(function* () {
298
453
  while (true) {
299
- yield* Queue.takeAll(wake)
300
- const { events, last } = yield* drainFrom(from)
301
- if (events.length > 0) {
302
- return [Chunk.fromIterable(events), last] as const
454
+ // `Queue.clear` and not `Queue.takeAll`: the drain must NOT wait, and
455
+ // `takeAll` suspends until at least one signal is present.
456
+ yield* Queue.clear(wake)
457
+ const items = yield* read(from)
458
+ const last = items.at(-1)
459
+ if (last !== undefined) {
460
+ return [items, deps.cursorOf(last)] as const
303
461
  }
304
462
  // Nothing new: block on a wake, but only up to the poll interval — on
305
463
  // timeout we fall through and the loop re-reads regardless.
306
- yield* Effect.ignore(
307
- Effect.timeout(Queue.take(wake), deps.pollInterval),
308
- )
464
+ yield* Effect.ignore(Effect.timeout(Queue.take(wake), pollInterval))
309
465
  }
310
466
  })
311
467
 
312
- return Stream.unfoldChunkEffect(after ?? ORIGIN, (from) =>
313
- Effect.map(nextBatch(from), Option.some),
468
+ return Stream.paginate(deps.initial, (from) =>
469
+ Effect.map(
470
+ nextBatch(from),
471
+ ([items, next]) => [items, Option.some(next)] as const,
472
+ ),
314
473
  )
315
474
  }),
316
475
  )
476
+
477
+ /**
478
+ * Build the event subscription `Stream`: catch up from `after`, then track the live
479
+ * tail. A THIN wrapper over the machine `subscribeItems` runs, fixing the item to
480
+ * `SequencedEvent`, the cursor to its `position`, the start to `ORIGIN` when `after`
481
+ * is absent, and the emission to the default `'backlog'` — so every engine's call
482
+ * site, and every figure it delivers, is what it was before the machine became
483
+ * generic. It skips `subscribeItems`' tuning check, for the reason on `machine`. An `E`
484
+ * mid-stream stays on the channel; `makeContractStore` dies it (subscribe is
485
+ * `E = never` on the contract).
486
+ */
487
+ export const subscribeStream = <E>(
488
+ deps: SubscriptionDeps<E>,
489
+ after: Position | undefined,
490
+ ): Stream.Stream<SequencedEvent, E, Scope.Scope> =>
491
+ machine<SequencedEvent, Position, E>({
492
+ fetch: deps.fetch,
493
+ cursorOf: (event) => event.position,
494
+ initial: after ?? ORIGIN,
495
+ ...(deps.listen === undefined ? {} : { listen: deps.listen }),
496
+ pollInterval: deps.pollInterval,
497
+ catchUpPageSize: deps.catchUpPageSize,
498
+ })
package/src/inMemory.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * The log is a `Ref<ReadonlyArray<SequencedEvent>>` in ascending position
6
6
  * order. The whole check-then-append is run inside a single
7
- * `Effect.makeSemaphore(1)`+`withPermits(1)` critical section: the conditional
7
+ * `Semaphore.make(1)`+`withPermits(1)` critical section: the conditional
8
8
  * read and the commit must not be separable, and that atomicity is the entire
9
9
  * concurrency guarantee (exactly-one-wins under a race). Positions come from a
10
10
  * monotonic counter starting at 1n (contiguous here; the contract only promises
@@ -25,7 +25,7 @@
25
25
  * discharges the ascending-commit-order precondition `SubscribeMachine.ts` states.
26
26
  */
27
27
  import type { Array as Arr, Scope } from 'effect'
28
- import { DateTime, Effect, Layer, PubSub, Ref, Stream } from 'effect'
28
+ import { DateTime, Effect, Layer, PubSub, Ref, Semaphore, Stream } from 'effect'
29
29
  import type { AppendCondition } from './AppendCondition'
30
30
  import { makeContractStore, type RawDcbEventStore } from './ContractStore'
31
31
  import type { ReadOptions, ReadResponse } from './DcbEventStore'
@@ -73,7 +73,7 @@ const copyEvent = (event: DcbEvent): DcbEvent => ({
73
73
  data: new Uint8Array(event.data),
74
74
  tags: [...event.tags],
75
75
  uuid: event.uuid,
76
- occurredAt: DateTime.unsafeMake(DateTime.toEpochMillis(event.occurredAt)),
76
+ occurredAt: DateTime.makeUnsafe(DateTime.toEpochMillis(event.occurredAt)),
77
77
  metadata: { ...event.metadata },
78
78
  })
79
79
 
@@ -288,7 +288,7 @@ const make = (
288
288
  options?.catchUpPageSize ?? DEFAULT_CATCH_UP_PAGE_SIZE
289
289
  const pollInterval = options?.pollInterval ?? DEFAULT_POLL_INTERVAL_MILLIS
290
290
  const log = yield* Ref.make<ReadonlyArray<SequencedEvent>>([])
291
- const mutex = yield* Effect.makeSemaphore(1)
291
+ const mutex = yield* Semaphore.make(1)
292
292
  const hub = yield* PubSub.unbounded<SequencedEvent>()
293
293
  const nextPosition = yield* Ref.make<bigint>(1n)
294
294
 
@@ -381,7 +381,7 @@ const make = (
381
381
  // exclusive cursor is what makes the catch-up/live seam exactly-once, so there
382
382
  // is nothing left here for a critical section to protect. `append` keeps its
383
383
  // permit, which is the whole exactly-one-wins guarantee.
384
- Stream.unwrapScoped(
384
+ Stream.unwrap(
385
385
  Effect.gen(function* () {
386
386
  // Taken when the subscription starts, as the SQL engines compile theirs
387
387
  // (see `copyQuery`).
@@ -393,7 +393,7 @@ const make = (
393
393
  Effect.map(Ref.get(log), (snapshot) =>
394
394
  fetchPage(snapshot, judged, from, limit),
395
395
  ),
396
- listen: Stream.fromQueue(wakes),
396
+ listen: Stream.fromSubscription(wakes),
397
397
  pollInterval,
398
398
  catchUpPageSize,
399
399
  },
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * @kairos-es/core: DCB-first event-sourcing contract and in-memory store for
3
- * Effect v3.
3
+ * Effect.
4
4
  *
5
5
  * Exposes the domain types (`DcbEvent`, `SequencedEvent`, `Position`, `Tag`,
6
6
  * `EventType`), the selection language (`Query`, `QueryItem`, the pure match
@@ -35,12 +35,6 @@
35
35
  * jitter draws from `Random.next`, a default service on the same footing as the
36
36
  * clock rather than a host `Math.random`. No `node:*`, no wall-clock reading, no
37
37
  * ungoverned RNG.
38
- *
39
- * Effect v3 caveat: the `Schedule` API below is the THREE-type-parameter
40
- * `Schedule<Out, In, R>` that `effect@3` exports, with `Schedule.intersect`. The
41
- * currently-published docs show a newer four-type-parameter `Schedule` without
42
- * `intersect` — do not copy them; this file is written against the installed
43
- * `effect@3` type definitions.
44
38
  */
45
39
  import { Effect, Predicate, Schedule } from 'effect'
46
40
  import type { AppendConditionFailed } from './errors'
@@ -49,9 +43,9 @@ import type { AppendConditionFailed } from './errors'
49
43
  * The default conflict backoff: exponential from 20ms, jittered, capped at five
50
44
  * retries.
51
45
  *
52
- * `Schedule.intersect` continues only while BOTH schedules continue, so the
53
- * `recurs(5)` arm is what bounds the attempts and the exponential arm is what
54
- * spaces them. Jitter matters more here than in a typical backoff: contending
46
+ * `Schedule.max` continues only while BOTH schedules continue, waiting the longer
47
+ * of their two delays, so the `recurs(5)` arm is what bounds the attempts and the
48
+ * exponential arm is what spaces them. Jitter matters more here than in a typical backoff: contending
55
49
  * deciders conflict precisely because they read the same boundary at the same
56
50
  * time, so an unjittered backoff would re-synchronise them into the same conflict
57
51
  * on every round. The figures are the conventional starting point (Emmett,
@@ -59,10 +53,10 @@ import type { AppendConditionFailed } from './errors'
59
53
  * command with a tighter latency budget, or one contending harder, should pass its
60
54
  * own schedule.
61
55
  */
62
- const conflictBackoff = Schedule.intersect(
56
+ const conflictBackoff = Schedule.max([
63
57
  Schedule.jittered(Schedule.exponential('20 millis', 2)),
64
58
  Schedule.recurs(5),
65
- )
59
+ ])
66
60
 
67
61
  /**
68
62
  * Retry `command` while — and only while — it fails `AppendConditionFailed`.
@@ -91,6 +85,7 @@ export const retryOnConflict = <A, E, R>(
91
85
  schedule: Schedule.Schedule<
92
86
  unknown,
93
87
  AppendConditionFailed | E,
88
+ never,
94
89
  R
95
90
  > = conflictBackoff,
96
91
  ): Effect.Effect<A, AppendConditionFailed | E, R> =>
package/src/testing.ts CHANGED
@@ -21,10 +21,10 @@ import { DateTime } from 'effect'
21
21
  *
22
22
  * Ordering in the log is by `position` alone, so an event's `occurredAt` is
23
23
  * informational; pinning it to the epoch keeps serialised bytes and comparisons
24
- * stable across runs. Built via `DateTime.unsafeMake(0)` (the value is a
24
+ * stable across runs. Built via `DateTime.makeUnsafe(0)` (the value is a
25
25
  * compile-time constant, not read from the host clock).
26
26
  */
27
- export const EPOCH = DateTime.unsafeMake(0)
27
+ export const EPOCH = DateTime.makeUnsafe(0)
28
28
 
29
29
  /**
30
30
  * Build a fresh, deterministic uuid generator: a zero-based counter producing
@@ -2,5 +2,5 @@
2
2
  "sideEffects": [],
3
3
  "main": "../dist/cjs/testing.js",
4
4
  "module": "../dist/esm/testing.js",
5
- "types": "../dist/dts/testing.d.ts"
5
+ "types": "../dist/dts-cjs/testing.d.ts"
6
6
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"ContractStore.d.ts","sourceRoot":"","sources":["../../src/ContractStore.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,OAAO,KAAK,EAAE,KAAK,IAAI,GAAG,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAA;AACjD,OAAO,EAAE,MAAM,EAAqB,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAEnD,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAC/E,OAAO,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAEjE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAA;AACrD,OAAO,EAAuB,KAAK,KAAK,EAAE,MAAM,SAAS,CAAA;AAKzD;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB,CAAC,CAAC;IACjC,QAAQ,CAAC,IAAI,EAAE,CACb,KAAK,EAAE,KAAK,EACZ,OAAO,CAAC,EAAE,WAAW,KAClB,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC,CAAA;IACnC,QAAQ,CAAC,MAAM,EAAE,CACf,MAAM,EAAE,GAAG,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAC3C,SAAS,CAAC,EAAE,eAAe,KACxB,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,qBAAqB,GAAG,CAAC,CAAC,CAAA;IACvD,QAAQ,CAAC,SAAS,EAAE,CAClB,KAAK,EAAE,KAAK,EACZ,KAAK,CAAC,EAAE,QAAQ,KACb,MAAM,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,CAAA;CACnD;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,GAAI,CAAC,EACjC,KAAK,gBAAgB,CAAC,CAAC,CAAC,KACvB,aAAa,CAAC,MAAM,CAoGrB,CAAA"}