@systemfsoftware/agent-storage-memory 0.0.0-bootstrap.0 → 0.1.0-beta.192

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs +609 -0
  3. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs.map +1 -0
  4. package/dist/MemoryMessageDeliveryStore-BmLntoBA.d.mts +18 -0
  5. package/dist/MemoryMessageDeliveryStore.d.mts +2 -0
  6. package/dist/MemoryMessageDeliveryStore.mjs +1 -0
  7. package/dist/MemoryScheduleStore-Bb85CXg1.mjs +163 -0
  8. package/dist/MemoryScheduleStore-Bb85CXg1.mjs.map +1 -0
  9. package/dist/MemoryScheduleStore-C_ll7Xyr.d.mts +8 -0
  10. package/dist/MemoryScheduleStore.d.mts +2 -0
  11. package/dist/MemoryScheduleStore.mjs +1 -0
  12. package/dist/MemorySemanticIndex-DYljUBy4.mjs +224 -0
  13. package/dist/MemorySemanticIndex-DYljUBy4.mjs.map +1 -0
  14. package/dist/MemorySemanticIndex-DrcJ7UG4.d.mts +20 -0
  15. package/dist/MemorySemanticIndex.d.mts +2 -0
  16. package/dist/MemorySemanticIndex.mjs +1 -0
  17. package/dist/MemorySubmissionLedger-DO-F22Gu.d.mts +28 -0
  18. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs +1566 -0
  19. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs.map +1 -0
  20. package/dist/MemorySubmissionLedger.d.mts +2 -0
  21. package/dist/MemorySubmissionLedger.mjs +1 -0
  22. package/dist/MemorySubscriptionStore-BWZ9lcIY.d.mts +7 -0
  23. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs +929 -0
  24. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs.map +1 -0
  25. package/dist/MemorySubscriptionStore.d.mts +2 -0
  26. package/dist/MemorySubscriptionStore.mjs +1 -0
  27. package/dist/MemoryThreadStore-BX3sRYhE.d.mts +21 -0
  28. package/dist/MemoryThreadStore-Dtwe-7h4.mjs +1415 -0
  29. package/dist/MemoryThreadStore-Dtwe-7h4.mjs.map +1 -0
  30. package/dist/MemoryThreadStore.d.mts +2 -0
  31. package/dist/MemoryThreadStore.mjs +1 -0
  32. package/dist/MemoryThreadStoreKernel-5ya9AJvL.d.mts +85 -0
  33. package/dist/WorkSelection-Xr9mCon_.mjs +29 -0
  34. package/dist/WorkSelection-Xr9mCon_.mjs.map +1 -0
  35. package/dist/index.d.mts +7 -0
  36. package/dist/index.mjs +7 -0
  37. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  38. package/package.json +67 -5
  39. package/src/MemoryMessageDeliveryStore.ts +1004 -0
  40. package/src/MemoryScheduleStore.ts +324 -0
  41. package/src/MemorySemanticIndex.ts +360 -0
  42. package/src/MemorySubmissionLedger.ts +3590 -0
  43. package/src/MemorySubscriptionStore.ts +1762 -0
  44. package/src/MemoryThreadStore.ts +2810 -0
  45. package/src/index.ts +6 -0
  46. package/src/internal/MemoryThreadStoreKernel.ts +156 -0
  47. package/src/internal/WorkSelection.ts +29 -0
  48. package/README.md +0 -3
@@ -0,0 +1,1762 @@
1
+ import { Digest } from '@systemfsoftware/agent/records'
2
+ import { compareScheduleNames } from '@systemfsoftware/agent/schedule-transition'
3
+ import {
4
+ AcceptedEvent,
5
+ defaultSubscriptionLimits,
6
+ DeliveryChange,
7
+ SourcePartition,
8
+ SubscriptionChange,
9
+ SubscriptionDelivery,
10
+ SubscriptionDeliveryKey,
11
+ subscriptionDeliveryKeyString,
12
+ SubscriptionError,
13
+ SubscriptionFailpoint,
14
+ SubscriptionKey,
15
+ subscriptionKeyString,
16
+ SubscriptionLimits,
17
+ SubscriptionName,
18
+ SubscriptionRecord,
19
+ SubscriptionRetentionPolicy,
20
+ SubscriptionScanCursors,
21
+ SubscriptionStore,
22
+ } from '@systemfsoftware/agent/subscription'
23
+ import {
24
+ applySubscriptionChange,
25
+ applySubscriptionDeliveryChange,
26
+ sameAcceptedEventIdentity,
27
+ subscriptionCanSelect,
28
+ subscriptionDeliveryCanSelect,
29
+ subscriptionDeliveryUsesCapacity,
30
+ subscriptionUsesCapacity,
31
+ validateEventRetention,
32
+ } from '@systemfsoftware/agent/subscription-transition'
33
+ import * as Clock from 'effect/Clock'
34
+ import * as Effect from 'effect/Effect'
35
+ import * as Layer from 'effect/Layer'
36
+ import * as Ref from 'effect/Ref'
37
+ import * as Result from 'effect/Result'
38
+ import * as Schema from 'effect/Schema'
39
+
40
+ interface RegistrationCapacity {
41
+ readonly registrationExpiries: ReadonlyArray<number>
42
+ readonly ownerRegistrationExpiries: ReadonlyMap<string, ReadonlyArray<number>>
43
+ }
44
+
45
+ interface MemorySubscriptionState extends RegistrationCapacity {
46
+ readonly sequence: number
47
+ readonly retentionDeadline: number | null
48
+ readonly tombstoneCount: number
49
+ readonly eventKeys: ReadonlyArray<string>
50
+ readonly deliveryKeys: ReadonlyArray<string>
51
+ readonly maintenanceEvents: string
52
+ readonly maintenanceDeliveries: string
53
+ readonly recoveryCounts: ReadonlyMap<string, number>
54
+ readonly eventDeliveryCounts: ReadonlyMap<string, number>
55
+ readonly retentionHorizon: number | null
56
+ readonly registrations: ReadonlyMap<string, string>
57
+ readonly events: ReadonlyMap<string, string>
58
+ readonly deliveries: ReadonlyMap<string, string>
59
+ readonly registrationIndex: ReadonlyMap<string, RegistrationIndex>
60
+ readonly candidateIndex: ReadonlyMap<string, ReadonlyArray<string>>
61
+ readonly eventIndex: ReadonlyMap<string, EventIndex>
62
+ readonly deliveryIndex: ReadonlyMap<string, DeliveryIndex>
63
+ readonly ownerDeliveryCounts: ReadonlyMap<string, number>
64
+ readonly liveDeliveryCount: number
65
+ readonly pendingEventCount: number
66
+ readonly scanCursors: SubscriptionScanCursors
67
+ }
68
+
69
+ interface RegistrationIndex {
70
+ readonly key: SubscriptionKey
71
+ readonly ordinal: number
72
+ readonly state: SubscriptionRecord['state']
73
+ readonly recoveryKey: string | null
74
+ readonly recoveryAt: number | null
75
+ }
76
+ interface EventIndex {
77
+ readonly routingComplete: boolean
78
+ readonly nextAttemptAtMillis: number
79
+ }
80
+ interface DeliveryIndex {
81
+ readonly key: SubscriptionDeliveryKey
82
+ readonly state: SubscriptionDelivery['state']
83
+ readonly parked?: boolean
84
+ readonly observeSettlement?: boolean
85
+ readonly nextAttemptAtMillis: number
86
+ }
87
+
88
+ const error = (reason: SubscriptionError['reason'], code: string) => SubscriptionError.make({ reason, code })
89
+
90
+ const samePartition = (left: SourcePartition, right: SourcePartition): boolean =>
91
+ left.tenantId === right.tenantId && left.address === right.address
92
+
93
+ const sameSource = (left: AcceptedEvent['source'], right: AcceptedEvent['source']): boolean =>
94
+ left.name === right.name && left.version === right.version
95
+
96
+ const encode = <A, I>(
97
+ schema: Schema.Codec<A, I>,
98
+ value: A,
99
+ code: string,
100
+ ): Result.Result<string, SubscriptionError> =>
101
+ Result.try({
102
+ try: () => Schema.encodeSync(Schema.fromJsonString(schema))(value),
103
+ catch: () => error('corrupt', code),
104
+ })
105
+
106
+ const decode = <A, I>(
107
+ schema: Schema.Codec<A, I>,
108
+ value: string,
109
+ code: string,
110
+ ): Result.Result<A, SubscriptionError> =>
111
+ Result.try({
112
+ try: () => Schema.decodeSync(Schema.fromJsonString(schema))(value),
113
+ catch: () => error('corrupt', code),
114
+ })
115
+
116
+ const decodeEffect = <A, I>(schema: Schema.Codec<A, I>, value: string, code: string) =>
117
+ Effect.fromResult(decode(schema, value, code))
118
+
119
+ const validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>
120
+ Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error('validation', code)))
121
+
122
+ const jsonBytes = (value: unknown): number => new TextEncoder().encode(JSON.stringify(value)).byteLength
123
+
124
+ const sameDeliveryIdentity = (left: SubscriptionDelivery, right: SubscriptionDelivery): boolean =>
125
+ subscriptionDeliveryKeyString(left.key) === subscriptionDeliveryKeyString(right.key) &&
126
+ left.deliveryId === right.deliveryId &&
127
+ left.source.name === right.source.name &&
128
+ left.source.version === right.source.version &&
129
+ left.threadId === right.threadId &&
130
+ left.admissionKey === right.admissionKey &&
131
+ left.subscriptionFingerprint === right.subscriptionFingerprint &&
132
+ left.eventDigest === right.eventDigest
133
+
134
+ const candidateIndexKey = (record: SubscriptionRecord): string =>
135
+ JSON.stringify([
136
+ record.configuration.source.name,
137
+ record.configuration.source.version,
138
+ record.configuration.matchingKey,
139
+ ])
140
+
141
+ const eventCandidateIndexKey = (event: AcceptedEvent): string =>
142
+ JSON.stringify([event.source.name, event.source.version, event.matchingKey])
143
+
144
+ const sameEventIdentity = sameAcceptedEventIdentity
145
+
146
+ const deliveryBelongsTo = (
147
+ delivery: SubscriptionDelivery,
148
+ record: SubscriptionRecord,
149
+ event: AcceptedEvent,
150
+ ): boolean =>
151
+ subscriptionKeyString(delivery.key.subscription) === subscriptionKeyString(record.key) &&
152
+ delivery.key.eventId === event.eventId &&
153
+ sameSource(delivery.source, event.source)
154
+
155
+ // Ordered in-memory indexes allow bounded maintenance pages without scanning retained values.
156
+ const removeKeys = (
157
+ keys: ReadonlyArray<string>,
158
+ removed: ReadonlySet<string>,
159
+ ): ReadonlyArray<string> => {
160
+ if (removed.size === 0) return keys
161
+ const result = [...keys]
162
+
163
+ for (const key of removed) {
164
+ const index = upperBound(result, key) - 1
165
+
166
+ if (result[index] === key) result.splice(index, 1)
167
+ }
168
+
169
+ return result
170
+ }
171
+
172
+ const upperBound = (keys: ReadonlyArray<string>, after: string): number => {
173
+ let low = 0
174
+ let high = keys.length
175
+
176
+ while (low < high) {
177
+ const middle = Math.floor((low + high) / 2)
178
+ const key = keys[middle]
179
+
180
+ if (key !== undefined && compareScheduleNames(key, after) <= 0) low = middle + 1
181
+ else high = middle
182
+ }
183
+
184
+ return low
185
+ }
186
+
187
+ const insertKey = (keys: ReadonlyArray<string>, key: string): ReadonlyArray<string> => {
188
+ const at = upperBound(keys, key)
189
+
190
+ if (at > 0 && keys[at - 1] === key) return keys
191
+
192
+ return [...keys.slice(0, at), key, ...keys.slice(at)]
193
+ }
194
+
195
+ // Count unexpired registrations without reading retained history. Keeping sorted expiry values
196
+ // also makes clock changes safe; expiry alone never deletes or rewrites the canonical record.
197
+ const expiryUpperBound = (expiries: ReadonlyArray<number>, nowMillis: number): number => {
198
+ let low = 0
199
+ let high = expiries.length
200
+
201
+ while (low < high) {
202
+ const middle = Math.floor((low + high) / 2)
203
+ const expiry = expiries[middle]
204
+
205
+ if (expiry !== undefined && expiry <= nowMillis) low = middle + 1
206
+ else high = middle
207
+ }
208
+
209
+ return low
210
+ }
211
+
212
+ const registrationCount = (
213
+ current: MemorySubscriptionState,
214
+ nowMillis: number,
215
+ ownerId?: string,
216
+ ): number => {
217
+ const expiries = ownerId === undefined
218
+ ? current.registrationExpiries
219
+ : (current.ownerRegistrationExpiries.get(ownerId) ?? [])
220
+
221
+ return expiries.length - expiryUpperBound(expiries, nowMillis)
222
+ }
223
+
224
+ const registrationExpiriesAfter = (
225
+ current: RegistrationCapacity,
226
+ before: SubscriptionRecord | undefined,
227
+ after: SubscriptionRecord,
228
+ ): RegistrationCapacity => {
229
+ const expiry = (record: SubscriptionRecord | undefined) =>
230
+ record !== undefined && (record.state === 'active' || record.state === 'paused')
231
+ ? (record.configuration.expiresAtMillis ?? Number.POSITIVE_INFINITY)
232
+ : null
233
+
234
+ const previous = expiry(before)
235
+ const next = expiry(after)
236
+
237
+ const replace = (expiries: ReadonlyArray<number>): ReadonlyArray<number> => {
238
+ if (previous === next) return expiries
239
+ const updated = [...expiries]
240
+
241
+ if (previous !== null) updated.splice(expiryUpperBound(updated, previous) - 1, 1)
242
+ if (next !== null) updated.splice(expiryUpperBound(updated, next), 0, next)
243
+
244
+ return updated
245
+ }
246
+
247
+ const owners = new Map(current.ownerRegistrationExpiries)
248
+ const expiries = replace(owners.get(after.key.ownerId) ?? [])
249
+
250
+ if (expiries.length === 0) owners.delete(after.key.ownerId)
251
+ else owners.set(after.key.ownerId, expiries)
252
+
253
+ return {
254
+ registrationExpiries: replace(current.registrationExpiries),
255
+ ownerRegistrationExpiries: owners,
256
+ }
257
+ }
258
+
259
+ const recoveryCountsAfter = (
260
+ current: MemorySubscriptionState,
261
+ next: ReadonlyMap<string, RegistrationIndex>,
262
+ keys: ReadonlyArray<string>,
263
+ ): ReadonlyMap<string, number> => {
264
+ const counts = new Map(current.recoveryCounts)
265
+
266
+ for (const key of keys) {
267
+ const before = current.registrationIndex.get(key)?.recoveryKey
268
+ const after = next.get(key)?.recoveryKey
269
+
270
+ if (before === after) continue
271
+ if (before !== null && before !== undefined) counts.set(before, (counts.get(before) ?? 0) - 1)
272
+ if (after !== null && after !== undefined) counts.set(after, (counts.get(after) ?? 0) + 1)
273
+ }
274
+
275
+ return counts
276
+ }
277
+
278
+ const makeMemorySubscriptionStore = Effect.fnUntraced(function*(ownedPartition: SourcePartition) {
279
+ const partition = yield* validate(SourcePartition, ownedPartition, 'partition')
280
+
281
+ const state = yield* Ref.make<MemorySubscriptionState>({
282
+ sequence: 0,
283
+ retentionDeadline: null,
284
+ tombstoneCount: 0,
285
+ eventKeys: [],
286
+ deliveryKeys: [],
287
+ maintenanceEvents: '',
288
+ maintenanceDeliveries: '',
289
+ recoveryCounts: new Map(),
290
+ eventDeliveryCounts: new Map(),
291
+ retentionHorizon: null,
292
+ registrations: new Map(),
293
+ events: new Map(),
294
+ deliveries: new Map(),
295
+ registrationIndex: new Map(),
296
+ candidateIndex: new Map(),
297
+ registrationExpiries: [],
298
+ ownerRegistrationExpiries: new Map(),
299
+ eventIndex: new Map(),
300
+ deliveryIndex: new Map(),
301
+ ownerDeliveryCounts: new Map(),
302
+ liveDeliveryCount: 0,
303
+ pendingEventCount: 0,
304
+ scanCursors: { events: '', deliveries: '', recovery: 0 },
305
+ })
306
+
307
+ const failpoint = yield* SubscriptionFailpoint
308
+
309
+ const requirePartition = <A extends { readonly partition: SourcePartition }>(
310
+ value: A,
311
+ code: string,
312
+ ) =>
313
+ samePartition(value.partition, partition)
314
+ ? Effect.succeed(value)
315
+ : Effect.fail(error('validation', code))
316
+
317
+ const requireKey = (key: SubscriptionKey, code: string) =>
318
+ validate(SubscriptionKey, key, code).pipe(
319
+ Effect.flatMap((decoded) => requirePartition(decoded, code)),
320
+ )
321
+
322
+ const register: SubscriptionStore['Service']['register'] = Effect.fnUntraced(
323
+ function*(input, inputLimits) {
324
+ const record = yield* validate(SubscriptionRecord, input, 'register-record')
325
+ const limits = yield* validate(SubscriptionLimits, inputLimits, 'register-limits')
326
+
327
+ yield* requirePartition(record.key, 'register-partition')
328
+ yield* failpoint.hit('subscription:register:before')
329
+ const nowMillis = yield* Clock.currentTimeMillis
330
+
331
+ const result = yield* Effect.uninterruptible(
332
+ Ref.modify(
333
+ state,
334
+ (
335
+ current,
336
+ ): readonly [
337
+ Result.Result<SubscriptionRecord, SubscriptionError>,
338
+ MemorySubscriptionState,
339
+ ] => {
340
+ const key = subscriptionKeyString(record.key)
341
+ const existingText = current.registrations.get(key)
342
+
343
+ if (existingText !== undefined) {
344
+ const existing = decode(SubscriptionRecord, existingText, 'register-existing')
345
+
346
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current]
347
+
348
+ return existing.success.creationFingerprint === record.creationFingerprint
349
+ ? [Result.succeed(existing.success), current]
350
+ : [Result.fail(error('conflict', 'registration-identity')), current]
351
+ }
352
+ if (jsonBytes(record.configuration.context) > limits.maxContextBytes) {
353
+ return [Result.fail(error('capacity', 'context-bytes')), current]
354
+ }
355
+ if (jsonBytes(record.configuration.parameters) > limits.maxPayloadBytes) {
356
+ return [Result.fail(error('capacity', 'parameters-bytes')), current]
357
+ }
358
+ if (
359
+ record.configuration.expiresAtMillis !== null &&
360
+ record.configuration.expiresAtMillis - record.createdAtMillis >
361
+ limits.maxLifetimeMillis
362
+ ) {
363
+ return [Result.fail(error('capacity', 'lifetime')), current]
364
+ }
365
+ if (
366
+ subscriptionUsesCapacity(record, nowMillis) &&
367
+ registrationCount(current, nowMillis) >= limits.maxRegistrations
368
+ ) {
369
+ return [Result.fail(error('capacity', 'registrations')), current]
370
+ }
371
+ if (
372
+ subscriptionUsesCapacity(record, nowMillis) &&
373
+ registrationCount(current, nowMillis, record.key.ownerId) >=
374
+ limits.maxRegistrationsPerOwner
375
+ ) {
376
+ return [Result.fail(error('capacity', 'owner-registrations')), current]
377
+ }
378
+ const assigned = { ...record, ordinal: current.sequence + 1 }
379
+ const encoded = encode(SubscriptionRecord, assigned, 'register-encode')
380
+
381
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current]
382
+ const registrations = new Map(current.registrations)
383
+
384
+ registrations.set(key, encoded.success)
385
+ const registrationIndex = new Map(current.registrationIndex)
386
+
387
+ registrationIndex.set(key, {
388
+ key: assigned.key,
389
+ ordinal: assigned.ordinal,
390
+ state: assigned.state,
391
+ recoveryKey: assigned.recovery === null ? null : candidateIndexKey(assigned),
392
+ recoveryAt: assigned.recovery?.nextAttemptAtMillis ?? null,
393
+ })
394
+ const candidateIndex = new Map(current.candidateIndex)
395
+ const candidateKey = candidateIndexKey(assigned)
396
+
397
+ candidateIndex.set(candidateKey, [...(candidateIndex.get(candidateKey) ?? []), key])
398
+
399
+ return [
400
+ Result.succeed(assigned),
401
+ {
402
+ ...current,
403
+ sequence: assigned.ordinal,
404
+ registrations,
405
+ registrationIndex,
406
+ recoveryCounts: recoveryCountsAfter(current, registrationIndex, [key]),
407
+ candidateIndex,
408
+ ...registrationExpiriesAfter(current, undefined, assigned),
409
+ },
410
+ ]
411
+ },
412
+ ),
413
+ ).pipe(Effect.flatMap(Effect.fromResult))
414
+
415
+ yield* failpoint.hit('subscription:register:after')
416
+
417
+ return result
418
+ },
419
+ )
420
+
421
+ const get: SubscriptionStore['Service']['get'] = Effect.fnUntraced(function*(input) {
422
+ const key = yield* requireKey(input, 'get-key')
423
+ const text = (yield* Ref.get(state)).registrations.get(subscriptionKeyString(key))
424
+
425
+ return text === undefined ? null : yield* decodeEffect(SubscriptionRecord, text, 'get-record')
426
+ })
427
+
428
+ const list: SubscriptionStore['Service']['list'] = Effect.fnUntraced(
429
+ function*(ownerId, after, limit) {
430
+ if (!Number.isSafeInteger(after) || after < 0 || !Number.isSafeInteger(limit) || limit <= 0) {
431
+ return yield* error('validation', 'list-page')
432
+ }
433
+ const current = yield* Ref.get(state)
434
+ const records: Array<SubscriptionRecord> = []
435
+
436
+ for (const [storageKey, indexed] of current.registrationIndex) {
437
+ if (indexed.key.ownerId !== ownerId || indexed.ordinal <= after) continue
438
+ const text = current.registrations.get(storageKey)
439
+
440
+ if (text === undefined) return yield* error('corrupt', 'list-index')
441
+ records.push(yield* decodeEffect(SubscriptionRecord, text, 'list-record'))
442
+ }
443
+ records.sort((a, b) => a.ordinal - b.ordinal)
444
+
445
+ return records.slice(0, limit)
446
+ },
447
+ )
448
+
449
+ const change: SubscriptionStore['Service']['change'] = Effect.fnUntraced(function*(
450
+ input,
451
+ expectedRevision,
452
+ inputChange,
453
+ inputLimits = defaultSubscriptionLimits,
454
+ ) {
455
+ const key = yield* requireKey(input, 'change-key')
456
+ const change = yield* validate(SubscriptionChange, inputChange, 'change')
457
+ const limits = yield* validate(SubscriptionLimits, inputLimits, 'change-limits')
458
+
459
+ yield* validate(Schema.Int.check(Schema.isGreaterThan(0)), expectedRevision, 'revision')
460
+ yield* failpoint.hit('subscription:change:before')
461
+ const nowMillis = yield* Clock.currentTimeMillis
462
+
463
+ const updated = yield* Effect.uninterruptible(
464
+ Ref.modify(
465
+ state,
466
+ (
467
+ current,
468
+ ): readonly [
469
+ Result.Result<SubscriptionRecord, SubscriptionError>,
470
+ MemorySubscriptionState,
471
+ ] => {
472
+ const storageKey = subscriptionKeyString(key)
473
+ const text = current.registrations.get(storageKey)
474
+
475
+ if (text === undefined) return [Result.fail(error('not-found', 'subscription')), current]
476
+ const existing = decode(SubscriptionRecord, text, 'change-record')
477
+
478
+ if (Result.isFailure(existing)) return [existing, current]
479
+ const updated = applySubscriptionChange(existing.success, expectedRevision, change)
480
+
481
+ if (Result.isFailure(updated)) return [updated, current]
482
+ if (
483
+ !subscriptionUsesCapacity(existing.success, nowMillis) &&
484
+ subscriptionUsesCapacity(updated.success, nowMillis)
485
+ ) {
486
+ if (registrationCount(current, nowMillis) >= limits.maxRegistrations) {
487
+ return [Result.fail(error('capacity', 'registrations')), current]
488
+ }
489
+ if (
490
+ registrationCount(current, nowMillis, key.ownerId) >= limits.maxRegistrationsPerOwner
491
+ ) {
492
+ return [Result.fail(error('capacity', 'owner-registrations')), current]
493
+ }
494
+ }
495
+ const revised = { ...updated.success, ordinal: current.sequence + 1 }
496
+ const encoded = encode(SubscriptionRecord, revised, 'change-encode')
497
+
498
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current]
499
+ const registrations = new Map(current.registrations)
500
+
501
+ registrations.set(storageKey, encoded.success)
502
+ const registrationIndex = new Map(current.registrationIndex)
503
+
504
+ registrationIndex.set(storageKey, {
505
+ key,
506
+ ordinal: revised.ordinal,
507
+ state: revised.state,
508
+ recoveryKey: revised.recovery === null ? null : candidateIndexKey(revised),
509
+ recoveryAt: revised.recovery?.nextAttemptAtMillis ?? null,
510
+ })
511
+ const candidateIndex = new Map(current.candidateIndex)
512
+ const oldKey = candidateIndexKey(existing.success)
513
+ const nextKey = candidateIndexKey(revised)
514
+
515
+ {
516
+ candidateIndex.set(
517
+ oldKey,
518
+ (candidateIndex.get(oldKey) ?? []).filter((key) => key !== storageKey),
519
+ )
520
+ candidateIndex.set(
521
+ nextKey,
522
+ [...(candidateIndex.get(nextKey) ?? []), storageKey].sort(
523
+ (a, b) =>
524
+ (registrationIndex.get(a)?.ordinal ?? 0) -
525
+ (registrationIndex.get(b)?.ordinal ?? 0),
526
+ ),
527
+ )
528
+ }
529
+
530
+ return [
531
+ Result.succeed(revised),
532
+ {
533
+ ...current,
534
+ sequence: revised.ordinal,
535
+ registrations,
536
+ registrationIndex,
537
+ candidateIndex,
538
+ ...registrationExpiriesAfter(current, existing.success, revised),
539
+ recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),
540
+ },
541
+ ]
542
+ },
543
+ ),
544
+ ).pipe(Effect.flatMap(Effect.fromResult))
545
+
546
+ yield* failpoint.hit('subscription:change:after')
547
+
548
+ return updated
549
+ })
550
+
551
+ const cancel: SubscriptionStore['Service']['cancel'] = Effect.fnUntraced(
552
+ function*(input, expectedRevision) {
553
+ const key = yield* requireKey(input, 'cancel-key')
554
+
555
+ yield* failpoint.hit('subscription:cancel:before')
556
+
557
+ const result = yield* Effect.uninterruptible(
558
+ Ref.modify(
559
+ state,
560
+ (
561
+ current,
562
+ ): readonly [
563
+ Result.Result<SubscriptionRecord, SubscriptionError>,
564
+ MemorySubscriptionState,
565
+ ] => {
566
+ const storageKey = subscriptionKeyString(key)
567
+ const text = current.registrations.get(storageKey)
568
+
569
+ if (text === undefined) {
570
+ return [Result.fail(error('not-found', 'subscription')), current]
571
+ }
572
+ const decoded = decode(SubscriptionRecord, text, 'cancel-record')
573
+
574
+ if (Result.isFailure(decoded)) return [decoded, current]
575
+ if (
576
+ expectedRevision !== undefined &&
577
+ expectedRevision !== decoded.success.configurationRevision &&
578
+ !(
579
+ decoded.success.state === 'cancelled' &&
580
+ expectedRevision + 1 === decoded.success.configurationRevision
581
+ )
582
+ ) {
583
+ return [
584
+ Result.fail(
585
+ SubscriptionError.make({
586
+ reason: 'conflict',
587
+ code: 'configuration-revision',
588
+ currentRevision: decoded.success.configurationRevision,
589
+ currentState: decoded.success.state,
590
+ }),
591
+ ),
592
+ current,
593
+ ]
594
+ }
595
+ if (decoded.success.state === 'cancelled') {
596
+ return [Result.succeed(decoded.success), current]
597
+ }
598
+
599
+ const cancelled = {
600
+ ...decoded.success,
601
+ configurationRevision: decoded.success.configurationRevision + 1,
602
+ state: 'cancelled' as const,
603
+ recovery: null,
604
+ }
605
+
606
+ const encoded = encode(SubscriptionRecord, cancelled, 'cancel-encode')
607
+
608
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current]
609
+ const registrations = new Map(current.registrations)
610
+
611
+ registrations.set(storageKey, encoded.success)
612
+ const registrationIndex = new Map(current.registrationIndex)
613
+ const indexed = registrationIndex.get(storageKey)
614
+
615
+ if (indexed === undefined) {
616
+ return [Result.fail(error('corrupt', 'cancel-index')), current]
617
+ }
618
+ registrationIndex.set(storageKey, {
619
+ ...indexed,
620
+ state: 'cancelled',
621
+ recoveryAt: null,
622
+ recoveryKey: null,
623
+ })
624
+
625
+ return [
626
+ Result.succeed(cancelled),
627
+ {
628
+ ...current,
629
+ registrations,
630
+ registrationIndex,
631
+ ...registrationExpiriesAfter(current, decoded.success, cancelled),
632
+ recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),
633
+ },
634
+ ]
635
+ },
636
+ ),
637
+ ).pipe(Effect.flatMap(Effect.fromResult))
638
+
639
+ yield* failpoint.hit('subscription:cancel:after')
640
+
641
+ return result
642
+ },
643
+ )
644
+
645
+ const accept: SubscriptionStore['Service']['accept'] = Effect.fnUntraced(
646
+ function*(input, inputLimits) {
647
+ const event = yield* validate(AcceptedEvent, input, 'accept-event')
648
+ const currentTimeMillis = yield* Clock.currentTimeMillis
649
+ const limits = yield* validate(SubscriptionLimits, inputLimits, 'accept-limits')
650
+
651
+ yield* requirePartition(event, 'accept-partition')
652
+ yield* failpoint.hit('subscription:accept:before')
653
+
654
+ const result = yield* Effect.uninterruptible(
655
+ Ref.modify(
656
+ state,
657
+ (
658
+ current,
659
+ ): readonly [
660
+ Result.Result<AcceptedEvent, SubscriptionError>,
661
+ MemorySubscriptionState,
662
+ ] => {
663
+ const existingText = current.events.get(event.eventId)
664
+
665
+ if (existingText !== undefined) {
666
+ const existing = decode(AcceptedEvent, existingText, 'accept-existing')
667
+
668
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current]
669
+
670
+ return sameEventIdentity(existing.success, event)
671
+ ? [Result.succeed(existing.success), current]
672
+ : [Result.fail(error('conflict', 'event-identity')), current]
673
+ }
674
+ if (
675
+ current.retentionHorizon !== null &&
676
+ current.retentionHorizon !== limits.retention?.replayHorizonMillis
677
+ ) {
678
+ return [Result.fail(error('conflict', 'retention-horizon')), current]
679
+ }
680
+ const horizon = validateEventRetention(event, limits, currentTimeMillis)
681
+
682
+ if (Result.isFailure(horizon)) return [Result.fail(horizon.failure), current]
683
+ if (jsonBytes(event.payload) > limits.maxPayloadBytes) {
684
+ return [Result.fail(error('capacity', 'payload-bytes')), current]
685
+ }
686
+ if (current.pendingEventCount >= limits.maxEvents) {
687
+ return [Result.fail(error('capacity', 'events')), current]
688
+ }
689
+
690
+ const accepted: AcceptedEvent = {
691
+ ...event,
692
+ cutoff: current.sequence + 1,
693
+ cursor: 0,
694
+ routingComplete: false,
695
+ routingFailure: null,
696
+ }
697
+
698
+ const encoded = encode(AcceptedEvent, accepted, 'accept-encode')
699
+
700
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current]
701
+ const events = new Map(current.events)
702
+
703
+ events.set(accepted.eventId, encoded.success)
704
+ const eventIndex = new Map(current.eventIndex)
705
+
706
+ eventIndex.set(accepted.eventId, {
707
+ routingComplete: false,
708
+ nextAttemptAtMillis: accepted.nextAttemptAtMillis,
709
+ })
710
+
711
+ return [
712
+ Result.succeed(accepted),
713
+ {
714
+ ...current,
715
+ sequence: accepted.cutoff,
716
+ events,
717
+ eventIndex,
718
+ pendingEventCount: current.pendingEventCount + 1,
719
+ eventKeys: insertKey(current.eventKeys, accepted.eventId),
720
+ retentionHorizon: limits.retention?.replayHorizonMillis ?? current.retentionHorizon,
721
+ retentionDeadline: limits.retention === undefined
722
+ ? current.retentionDeadline
723
+ : accepted.acceptedAtMillis,
724
+ },
725
+ ]
726
+ },
727
+ ),
728
+ ).pipe(Effect.flatMap(Effect.fromResult))
729
+
730
+ yield* failpoint.hit('subscription:accept:after')
731
+
732
+ return result
733
+ },
734
+ )
735
+
736
+ const event: SubscriptionStore['Service']['event'] = Effect.fnUntraced(function*(eventId) {
737
+ const text = (yield* Ref.get(state)).events.get(eventId)
738
+
739
+ return text === undefined ? null : yield* decodeEffect(AcceptedEvent, text, 'event-record')
740
+ })
741
+
742
+ const pendingEvents: SubscriptionStore['Service']['pendingEvents'] = Effect.fnUntraced(
743
+ function*(nowMillis, after, limit) {
744
+ const events: Array<string> = []
745
+
746
+ for (const [eventId, indexed] of (yield* Ref.get(state)).eventIndex) {
747
+ if (
748
+ !indexed.routingComplete &&
749
+ indexed.nextAttemptAtMillis <= nowMillis &&
750
+ compareScheduleNames(eventId, after) > 0
751
+ ) {
752
+ events.push(eventId)
753
+ }
754
+ }
755
+ events.sort(compareScheduleNames)
756
+
757
+ return events.slice(0, limit)
758
+ },
759
+ )
760
+
761
+ const candidates: SubscriptionStore['Service']['candidates'] = Effect.fnUntraced(
762
+ function*(input, limit) {
763
+ const accepted = yield* validate(AcceptedEvent, input, 'candidates-event')
764
+
765
+ yield* requirePartition(accepted, 'candidates-partition')
766
+ const stored = yield* event(accepted.eventId)
767
+
768
+ if (stored === null || !sameEventIdentity(stored, accepted)) {
769
+ return yield* error(stored === null ? 'not-found' : 'conflict', 'event')
770
+ }
771
+ const current = yield* Ref.get(state)
772
+ const records: Array<SubscriptionRecord> = []
773
+
774
+ for (const storageKey of current.candidateIndex.get(eventCandidateIndexKey(stored)) ?? []) {
775
+ const indexed = current.registrationIndex.get(storageKey)
776
+
777
+ if (indexed === undefined) return yield* error('corrupt', 'candidate-index')
778
+ if (indexed.ordinal <= stored.cursor || indexed.ordinal > stored.cutoff) continue
779
+ const text = current.registrations.get(storageKey)
780
+
781
+ if (text === undefined) return yield* error('corrupt', 'candidate-record')
782
+ records.push(yield* decodeEffect(SubscriptionRecord, text, 'candidate-record'))
783
+ }
784
+ records.sort((a, b) => a.ordinal - b.ordinal)
785
+
786
+ return records.slice(0, limit)
787
+ },
788
+ )
789
+
790
+ const select: SubscriptionStore['Service']['select'] = Effect.fnUntraced(
791
+ function*(inputEvent, inputDeliveries, cursor, complete, nowMillis, inputLimits) {
792
+ const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, 'select-event')
793
+
794
+ const deliveries = yield* validate(
795
+ Schema.Array(SubscriptionDelivery),
796
+ inputDeliveries,
797
+ 'select-deliveries',
798
+ )
799
+
800
+ if (
801
+ new Set(deliveries.map((delivery) => subscriptionDeliveryKeyString(delivery.key))).size !==
802
+ deliveries.length
803
+ ) {
804
+ return yield* error('validation', 'duplicate-delivery')
805
+ }
806
+ const limits = yield* validate(SubscriptionLimits, inputLimits, 'select-limits')
807
+
808
+ yield* requirePartition(suppliedEvent, 'select-partition')
809
+ yield* failpoint.hit('subscription:select:before')
810
+ const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis)
811
+
812
+ yield* Effect.uninterruptible(
813
+ Ref.modify(
814
+ state,
815
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
816
+ const eventText = current.events.get(suppliedEvent.eventId)
817
+
818
+ if (eventText === undefined) return [Result.fail(error('not-found', 'event')), current]
819
+ const decodedEvent = decode(AcceptedEvent, eventText, 'select-event-record')
820
+
821
+ if (Result.isFailure(decodedEvent)) return [Result.fail(decodedEvent.failure), current]
822
+ const accepted = decodedEvent.success
823
+
824
+ if (
825
+ !sameEventIdentity(accepted, suppliedEvent) ||
826
+ suppliedEvent.cursor !== accepted.cursor
827
+ ) {
828
+ return [Result.fail(error('conflict', 'event-cursor')), current]
829
+ }
830
+ if (accepted.routingComplete) {
831
+ return [
832
+ complete && cursor === accepted.cursor
833
+ ? Result.void
834
+ : Result.fail(error('conflict', 'routing-complete')),
835
+ current,
836
+ ]
837
+ }
838
+ if (
839
+ !Number.isSafeInteger(cursor) ||
840
+ cursor < accepted.cursor ||
841
+ cursor > accepted.cutoff
842
+ ) {
843
+ return [Result.fail(error('validation', 'cursor')), current]
844
+ }
845
+
846
+ const additions: Array<readonly [string, string]> = []
847
+ const updates: Array<readonly [string, string]> = []
848
+ const additionIndex: Array<readonly [string, DeliveryIndex, string]> = []
849
+ const registrationUpdates: Array<readonly [string, RegistrationIndex]> = []
850
+ const owners = new Map(current.ownerDeliveryCounts)
851
+
852
+ let registrationCapacity: RegistrationCapacity = {
853
+ registrationExpiries: current.registrationExpiries,
854
+ ownerRegistrationExpiries: current.ownerRegistrationExpiries,
855
+ }
856
+
857
+ for (const delivery of deliveries) {
858
+ const recordText = current.registrations.get(
859
+ subscriptionKeyString(delivery.key.subscription),
860
+ )
861
+
862
+ if (recordText === undefined) {
863
+ return [Result.fail(error('not-found', 'subscription')), current]
864
+ }
865
+ const record = decode(SubscriptionRecord, recordText, 'select-registration')
866
+
867
+ if (Result.isFailure(record)) return [Result.fail(record.failure), current]
868
+ if (
869
+ !deliveryBelongsTo(delivery, record.success, accepted) ||
870
+ !subscriptionDeliveryCanSelect(delivery, record.success, accepted) ||
871
+ record.success.ordinal <= accepted.cursor ||
872
+ record.success.ordinal > cursor
873
+ ) {
874
+ return [Result.fail(error('conflict', 'selection')), current]
875
+ }
876
+ if (!subscriptionCanSelect(record.success, accepted, effectiveNowMillis, false)) {
877
+ continue
878
+ }
879
+ const deliveryKey = subscriptionDeliveryKeyString(delivery.key)
880
+ const existingText = current.deliveries.get(deliveryKey)
881
+
882
+ if (existingText !== undefined) {
883
+ const existing = decode(SubscriptionDelivery, existingText, 'select-existing')
884
+
885
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current]
886
+ if (!sameDeliveryIdentity(existing.success, delivery)) {
887
+ return [Result.fail(error('conflict', 'delivery-identity')), current]
888
+ }
889
+ continue
890
+ }
891
+
892
+ const encodedDelivery = encode(
893
+ SubscriptionDelivery,
894
+ delivery,
895
+ 'select-delivery-encode',
896
+ )
897
+
898
+ if (Result.isFailure(encodedDelivery)) {
899
+ return [Result.fail(encodedDelivery.failure), current]
900
+ }
901
+ additions.push([deliveryKey, encodedDelivery.success])
902
+ additionIndex.push([
903
+ deliveryKey,
904
+ {
905
+ key: delivery.key,
906
+ state: delivery.state,
907
+ nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,
908
+ },
909
+ record.success.key.ownerId,
910
+ ])
911
+ const ownerId = record.success.key.ownerId
912
+
913
+ owners.set(ownerId, (owners.get(ownerId) ?? 0) + 1)
914
+ if ((owners.get(ownerId) ?? 0) > limits.maxDeliveriesPerOwner) {
915
+ return [Result.fail(error('capacity', 'owner-deliveries')), current]
916
+ }
917
+ if (record.success.configuration.mode === 'once') {
918
+ const consumed = { ...record.success, state: 'consumed' as const, recovery: null }
919
+
920
+ const encodedRecord = encode(
921
+ SubscriptionRecord,
922
+ consumed,
923
+ 'select-registration-encode',
924
+ )
925
+
926
+ if (Result.isFailure(encodedRecord)) {
927
+ return [Result.fail(encodedRecord.failure), current]
928
+ }
929
+ const consumedKey = subscriptionKeyString(consumed.key)
930
+
931
+ updates.push([consumedKey, encodedRecord.success])
932
+ const indexed = current.registrationIndex.get(consumedKey)
933
+
934
+ if (indexed === undefined) {
935
+ return [Result.fail(error('corrupt', 'selection-index')), current]
936
+ }
937
+ registrationUpdates.push([
938
+ consumedKey,
939
+ { ...indexed, state: 'consumed', recoveryAt: null, recoveryKey: null },
940
+ ])
941
+ registrationCapacity = registrationExpiriesAfter(
942
+ registrationCapacity,
943
+ record.success,
944
+ consumed,
945
+ )
946
+ }
947
+ }
948
+ if (current.liveDeliveryCount + additions.length > limits.maxDeliveries) {
949
+ return [Result.fail(error('capacity', 'deliveries')), current]
950
+ }
951
+ const registrations = new Map(current.registrations)
952
+
953
+ for (const [key, value] of updates) registrations.set(key, value)
954
+ const nextDeliveries = new Map(current.deliveries)
955
+
956
+ for (const [key, value] of additions) nextDeliveries.set(key, value)
957
+ const deliveryIndex = new Map(current.deliveryIndex)
958
+
959
+ for (const [key, value] of additionIndex) deliveryIndex.set(key, value)
960
+ const registrationIndex = new Map(current.registrationIndex)
961
+
962
+ for (const [key, value] of registrationUpdates) registrationIndex.set(key, value)
963
+
964
+ const eventDeliveryCounts = new Map(current.eventDeliveryCounts)
965
+
966
+ eventDeliveryCounts.set(
967
+ accepted.eventId,
968
+ (eventDeliveryCounts.get(accepted.eventId) ?? 0) + additions.length,
969
+ )
970
+
971
+ const nextEvent: AcceptedEvent = {
972
+ ...accepted,
973
+ cursor,
974
+ routingComplete: complete,
975
+ routingFailure: null,
976
+ }
977
+
978
+ const encodedEvent = encode(AcceptedEvent, nextEvent, 'select-event-encode')
979
+
980
+ if (Result.isFailure(encodedEvent)) return [Result.fail(encodedEvent.failure), current]
981
+ const events = new Map(current.events)
982
+
983
+ events.set(nextEvent.eventId, encodedEvent.success)
984
+ const eventIndex = new Map(current.eventIndex)
985
+
986
+ eventIndex.set(nextEvent.eventId, {
987
+ routingComplete: nextEvent.routingComplete,
988
+ nextAttemptAtMillis: nextEvent.nextAttemptAtMillis,
989
+ })
990
+
991
+ return [
992
+ Result.void,
993
+ {
994
+ ...current,
995
+ registrations,
996
+ registrationIndex,
997
+ recoveryCounts: recoveryCountsAfter(
998
+ current,
999
+ registrationIndex,
1000
+ registrationUpdates.map(([key]) => key),
1001
+ ),
1002
+ eventDeliveryCounts,
1003
+ events,
1004
+ eventIndex,
1005
+ deliveries: nextDeliveries,
1006
+ liveDeliveryCount: current.liveDeliveryCount + additions.length,
1007
+ pendingEventCount: current.pendingEventCount - Number(complete),
1008
+ deliveryKeys: additions.reduce(
1009
+ (keys, [key]) => insertKey(keys, key),
1010
+ current.deliveryKeys,
1011
+ ),
1012
+ deliveryIndex,
1013
+ ownerDeliveryCounts: owners,
1014
+ ...registrationCapacity,
1015
+ },
1016
+ ]
1017
+ },
1018
+ ),
1019
+ ).pipe(Effect.flatMap(Effect.fromResult))
1020
+ yield* failpoint.hit('subscription:select:after')
1021
+ },
1022
+ )
1023
+
1024
+ const catchUp: SubscriptionStore['Service']['catchUp'] = Effect.fnUntraced(
1025
+ function*(inputEvent, inputDelivery, nowMillis, inputLimits) {
1026
+ const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, 'catch-up-event')
1027
+ const delivery = yield* validate(SubscriptionDelivery, inputDelivery, 'catch-up-delivery')
1028
+ const limits = yield* validate(SubscriptionLimits, inputLimits, 'catch-up-limits')
1029
+
1030
+ yield* requirePartition(suppliedEvent, 'catch-up-partition')
1031
+ yield* failpoint.hit('subscription:catch-up:before')
1032
+ const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis)
1033
+
1034
+ yield* Effect.uninterruptible(
1035
+ Ref.modify(
1036
+ state,
1037
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
1038
+ const eventText = current.events.get(suppliedEvent.eventId)
1039
+
1040
+ const recordText = current.registrations.get(
1041
+ subscriptionKeyString(delivery.key.subscription),
1042
+ )
1043
+
1044
+ if (eventText === undefined || recordText === undefined) {
1045
+ return [
1046
+ Result.fail(error('not-found', eventText === undefined ? 'event' : 'subscription')),
1047
+ current,
1048
+ ]
1049
+ }
1050
+ const accepted = decode(AcceptedEvent, eventText, 'catch-up-event-record')
1051
+
1052
+ if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current]
1053
+ const record = decode(SubscriptionRecord, recordText, 'catch-up-registration')
1054
+
1055
+ if (Result.isFailure(record)) return [Result.fail(record.failure), current]
1056
+ if (
1057
+ !sameEventIdentity(accepted.success, suppliedEvent) ||
1058
+ !deliveryBelongsTo(delivery, record.success, accepted.success) ||
1059
+ !subscriptionDeliveryCanSelect(delivery, record.success, accepted.success) ||
1060
+ record.success.configuration.mode !== 'once'
1061
+ ) {
1062
+ return [Result.fail(error('conflict', 'catch-up-identity')), current]
1063
+ }
1064
+ const key = subscriptionDeliveryKeyString(delivery.key)
1065
+ const existingText = current.deliveries.get(key)
1066
+
1067
+ if (existingText !== undefined) {
1068
+ const existing = decode(SubscriptionDelivery, existingText, 'catch-up-existing')
1069
+
1070
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current]
1071
+
1072
+ return sameDeliveryIdentity(existing.success, delivery)
1073
+ ? [Result.void, current]
1074
+ : [Result.fail(error('conflict', 'delivery-identity')), current]
1075
+ }
1076
+ if (!subscriptionCanSelect(record.success, accepted.success, effectiveNowMillis, true)) {
1077
+ return [Result.fail(error('conflict', 'catch-up-eligibility')), current]
1078
+ }
1079
+ if (current.liveDeliveryCount >= limits.maxDeliveries) {
1080
+ return [Result.fail(error('capacity', 'deliveries')), current]
1081
+ }
1082
+ const ownerCount = current.ownerDeliveryCounts.get(record.success.key.ownerId) ?? 0
1083
+
1084
+ if (ownerCount >= limits.maxDeliveriesPerOwner) {
1085
+ return [Result.fail(error('capacity', 'owner-deliveries')), current]
1086
+ }
1087
+
1088
+ const encodedDelivery = encode(
1089
+ SubscriptionDelivery,
1090
+ delivery,
1091
+ 'catch-up-delivery-encode',
1092
+ )
1093
+
1094
+ if (Result.isFailure(encodedDelivery)) {
1095
+ return [Result.fail(encodedDelivery.failure), current]
1096
+ }
1097
+ const consumed = { ...record.success, state: 'consumed' as const, recovery: null }
1098
+
1099
+ const encodedRecord = encode(
1100
+ SubscriptionRecord,
1101
+ consumed,
1102
+ 'catch-up-registration-encode',
1103
+ )
1104
+
1105
+ if (Result.isFailure(encodedRecord)) {
1106
+ return [Result.fail(encodedRecord.failure), current]
1107
+ }
1108
+ const deliveries = new Map(current.deliveries)
1109
+
1110
+ deliveries.set(key, encodedDelivery.success)
1111
+ const registrations = new Map(current.registrations)
1112
+ const consumedKey = subscriptionKeyString(consumed.key)
1113
+
1114
+ registrations.set(consumedKey, encodedRecord.success)
1115
+ const registrationIndex = new Map(current.registrationIndex)
1116
+ const indexed = registrationIndex.get(consumedKey)
1117
+
1118
+ if (indexed === undefined) {
1119
+ return [Result.fail(error('corrupt', 'catch-up-index')), current]
1120
+ }
1121
+ registrationIndex.set(consumedKey, {
1122
+ ...indexed,
1123
+ state: 'consumed',
1124
+ recoveryAt: null,
1125
+ recoveryKey: null,
1126
+ })
1127
+ const deliveryIndex = new Map(current.deliveryIndex)
1128
+
1129
+ deliveryIndex.set(key, {
1130
+ key: delivery.key,
1131
+ state: delivery.state,
1132
+ nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,
1133
+ })
1134
+ const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts)
1135
+ const eventDeliveryCounts = new Map(current.eventDeliveryCounts)
1136
+
1137
+ eventDeliveryCounts.set(
1138
+ accepted.success.eventId,
1139
+ (eventDeliveryCounts.get(accepted.success.eventId) ?? 0) + 1,
1140
+ )
1141
+
1142
+ ownerDeliveryCounts.set(consumed.key.ownerId, ownerCount + 1)
1143
+
1144
+ return [
1145
+ Result.void,
1146
+ {
1147
+ ...current,
1148
+ deliveries,
1149
+ deliveryIndex,
1150
+ deliveryKeys: insertKey(current.deliveryKeys, key),
1151
+ ownerDeliveryCounts,
1152
+ ...registrationExpiriesAfter(current, record.success, consumed),
1153
+ liveDeliveryCount: current.liveDeliveryCount + 1,
1154
+ registrations,
1155
+ registrationIndex,
1156
+ recoveryCounts: recoveryCountsAfter(current, registrationIndex, [consumedKey]),
1157
+ eventDeliveryCounts,
1158
+ },
1159
+ ]
1160
+ },
1161
+ ),
1162
+ ).pipe(Effect.flatMap(Effect.fromResult))
1163
+ yield* failpoint.hit('subscription:catch-up:after')
1164
+ },
1165
+ )
1166
+
1167
+ const deferEvent: SubscriptionStore['Service']['deferEvent'] = Effect.fnUntraced(
1168
+ function*(eventId, nextAttemptAtMillis, code) {
1169
+ const routingFailure = code === undefined
1170
+ ? 'routing-failed'
1171
+ : yield* validate(SubscriptionName, code, 'routing-failure')
1172
+
1173
+ yield* failpoint.hit('subscription:defer-event:before')
1174
+ yield* Effect.uninterruptible(
1175
+ Ref.modify(
1176
+ state,
1177
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
1178
+ const text = current.events.get(eventId)
1179
+
1180
+ if (text === undefined) return [Result.fail(error('not-found', 'event')), current]
1181
+ const accepted = decode(AcceptedEvent, text, 'defer-event-record')
1182
+
1183
+ if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current]
1184
+ const updated = { ...accepted.success, nextAttemptAtMillis, routingFailure }
1185
+ const encoded = encode(AcceptedEvent, updated, 'defer-event-encode')
1186
+
1187
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current]
1188
+ const events = new Map(current.events)
1189
+
1190
+ events.set(eventId, encoded.success)
1191
+ const eventIndex = new Map(current.eventIndex)
1192
+ const indexed = eventIndex.get(eventId)
1193
+
1194
+ if (indexed === undefined) {
1195
+ return [Result.fail(error('corrupt', 'defer-event-index')), current]
1196
+ }
1197
+ eventIndex.set(eventId, { ...indexed, nextAttemptAtMillis })
1198
+
1199
+ return [Result.void, { ...current, events, eventIndex }]
1200
+ },
1201
+ ),
1202
+ ).pipe(Effect.flatMap(Effect.fromResult))
1203
+ yield* failpoint.hit('subscription:defer-event:after')
1204
+ },
1205
+ )
1206
+
1207
+ const delivery: SubscriptionStore['Service']['delivery'] = Effect.fnUntraced(function*(input) {
1208
+ const key = yield* validate(SubscriptionDeliveryKey, input, 'delivery-key')
1209
+
1210
+ yield* requirePartition(key.subscription, 'delivery-partition')
1211
+ const text = (yield* Ref.get(state)).deliveries.get(subscriptionDeliveryKeyString(key))
1212
+
1213
+ return text === undefined
1214
+ ? null
1215
+ : yield* decodeEffect(SubscriptionDelivery, text, 'delivery-record')
1216
+ })
1217
+
1218
+ const pendingDeliveries: SubscriptionStore['Service']['pendingDeliveries'] = Effect.fnUntraced(
1219
+ function*(nowMillis, after, limit) {
1220
+ const items: Array<SubscriptionDeliveryKey> = []
1221
+
1222
+ for (const [storageKey, item] of (yield* Ref.get(state)).deliveryIndex) {
1223
+ if (
1224
+ ((item.state !== 'delivered' && item.state !== 'refused' && item.parked !== true) ||
1225
+ (item.state === 'delivered' && item.observeSettlement === true)) &&
1226
+ item.nextAttemptAtMillis <= nowMillis &&
1227
+ compareScheduleNames(storageKey, after) > 0
1228
+ ) {
1229
+ items.push(item.key)
1230
+ }
1231
+ }
1232
+ items.sort((a, b) => compareScheduleNames(subscriptionDeliveryKeyString(a), subscriptionDeliveryKeyString(b)))
1233
+
1234
+ return items.slice(0, limit)
1235
+ },
1236
+ )
1237
+
1238
+ const listDeliveries: SubscriptionStore['Service']['listDeliveries'] = Effect.fnUntraced(
1239
+ function*(input, after, limit) {
1240
+ const key = yield* requireKey(input, 'list-deliveries-key')
1241
+ const items: Array<SubscriptionDelivery> = []
1242
+
1243
+ for (const text of (yield* Ref.get(state)).deliveries.values()) {
1244
+ const item = yield* decodeEffect(SubscriptionDelivery, text, 'list-delivery')
1245
+ const itemKey = subscriptionDeliveryKeyString(item.key)
1246
+
1247
+ if (
1248
+ subscriptionKeyString(item.key.subscription) === subscriptionKeyString(key) &&
1249
+ compareScheduleNames(itemKey, after) > 0
1250
+ ) {
1251
+ items.push(item)
1252
+ }
1253
+ }
1254
+ items.sort((a, b) =>
1255
+ compareScheduleNames(
1256
+ subscriptionDeliveryKeyString(a.key),
1257
+ subscriptionDeliveryKeyString(b.key),
1258
+ )
1259
+ )
1260
+
1261
+ return items.slice(0, limit)
1262
+ },
1263
+ )
1264
+
1265
+ const changeDelivery: SubscriptionStore['Service']['changeDelivery'] = Effect.fnUntraced(
1266
+ function*(inputKey, inputDeliveryId, inputChange, inputLimits = defaultSubscriptionLimits) {
1267
+ const key = yield* validate(SubscriptionDeliveryKey, inputKey, 'change-delivery-key')
1268
+ const deliveryId = yield* validate(Digest, inputDeliveryId, 'change-delivery-id')
1269
+ const change = yield* validate(DeliveryChange, inputChange, 'change-delivery-change')
1270
+ const limits = yield* validate(SubscriptionLimits, inputLimits, 'change-delivery-limits')
1271
+
1272
+ yield* requirePartition(key.subscription, 'change-delivery-partition')
1273
+ yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:before`)
1274
+
1275
+ const effectiveChange = change._tag === 'Prepare'
1276
+ ? { ...change, nowMillis: Math.max(change.nowMillis, yield* Clock.currentTimeMillis) }
1277
+ : change
1278
+
1279
+ const result = yield* Effect.uninterruptible(
1280
+ Ref.modify(
1281
+ state,
1282
+ (
1283
+ current,
1284
+ ): readonly [
1285
+ Result.Result<SubscriptionDelivery, SubscriptionError>,
1286
+ MemorySubscriptionState,
1287
+ ] => {
1288
+ const storageKey = subscriptionDeliveryKeyString(key)
1289
+ const text = current.deliveries.get(storageKey)
1290
+
1291
+ if (text === undefined) return [Result.fail(error('not-found', 'delivery')), current]
1292
+ const decoded = decode(SubscriptionDelivery, text, 'change-delivery-record')
1293
+
1294
+ if (Result.isFailure(decoded)) return [decoded, current]
1295
+
1296
+ const registrationText = current.registrations.get(
1297
+ subscriptionKeyString(key.subscription),
1298
+ )
1299
+
1300
+ if (registrationText === undefined) {
1301
+ return [Result.fail(error('corrupt', 'delivery-registration')), current]
1302
+ }
1303
+
1304
+ const registration = decode(
1305
+ SubscriptionRecord,
1306
+ registrationText,
1307
+ 'delivery-registration',
1308
+ )
1309
+
1310
+ if (Result.isFailure(registration)) return [Result.fail(registration.failure), current]
1311
+
1312
+ const transition = applySubscriptionDeliveryChange(
1313
+ decoded.success,
1314
+ registration.success,
1315
+ deliveryId,
1316
+ effectiveChange,
1317
+ )
1318
+
1319
+ if (Result.isFailure(transition)) return [Result.fail(transition.failure), current]
1320
+ if (transition.success === decoded.success) {
1321
+ return [Result.succeed(decoded.success), current]
1322
+ }
1323
+ const updated = transition.success
1324
+
1325
+ const capacityDelta = Number(subscriptionDeliveryUsesCapacity(updated)) -
1326
+ Number(subscriptionDeliveryUsesCapacity(decoded.success))
1327
+
1328
+ const ownerId = key.subscription.ownerId
1329
+ const ownerCount = current.ownerDeliveryCounts.get(ownerId) ?? 0
1330
+
1331
+ if (capacityDelta > 0) {
1332
+ if (current.liveDeliveryCount >= limits.maxDeliveries) {
1333
+ return [Result.fail(error('capacity', 'deliveries')), current]
1334
+ }
1335
+ if (ownerCount >= limits.maxDeliveriesPerOwner) {
1336
+ return [Result.fail(error('capacity', 'owner-deliveries')), current]
1337
+ }
1338
+ }
1339
+ const encoded = encode(SubscriptionDelivery, updated, 'change-delivery-encode')
1340
+
1341
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current]
1342
+ const deliveries = new Map(current.deliveries)
1343
+
1344
+ deliveries.set(storageKey, encoded.success)
1345
+ const deliveryIndex = new Map(current.deliveryIndex)
1346
+ const indexed = deliveryIndex.get(storageKey)
1347
+
1348
+ if (indexed === undefined) {
1349
+ return [Result.fail(error('corrupt', 'delivery-index')), current]
1350
+ }
1351
+ deliveryIndex.set(storageKey, {
1352
+ ...indexed,
1353
+ state: updated.state,
1354
+ parked: updated.retry.parked ?? false,
1355
+ observeSettlement: updated.observeSettlement ?? false,
1356
+ nextAttemptAtMillis: updated.retry.nextAttemptAtMillis,
1357
+ })
1358
+ const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts)
1359
+
1360
+ if (ownerCount + capacityDelta === 0) ownerDeliveryCounts.delete(ownerId)
1361
+ else ownerDeliveryCounts.set(ownerId, ownerCount + capacityDelta)
1362
+
1363
+ return [
1364
+ Result.succeed(updated),
1365
+ {
1366
+ ...current,
1367
+ deliveries,
1368
+ deliveryIndex,
1369
+ ownerDeliveryCounts,
1370
+ liveDeliveryCount: current.liveDeliveryCount + capacityDelta,
1371
+ },
1372
+ ]
1373
+ },
1374
+ ),
1375
+ ).pipe(Effect.flatMap(Effect.fromResult))
1376
+
1377
+ yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:after`)
1378
+
1379
+ return result
1380
+ },
1381
+ )
1382
+
1383
+ const recovering: SubscriptionStore['Service']['recovering'] = Effect.fnUntraced(
1384
+ function*(nowMillis, after, limit) {
1385
+ const records: Array<{ readonly key: SubscriptionKey; readonly ordinal: number }> = []
1386
+
1387
+ for (const item of (yield* Ref.get(state)).registrationIndex.values()) {
1388
+ if (
1389
+ item.ordinal > after &&
1390
+ item.state === 'active' &&
1391
+ item.recoveryAt !== null &&
1392
+ item.recoveryAt <= nowMillis
1393
+ ) {
1394
+ records.push({ key: item.key, ordinal: item.ordinal })
1395
+ }
1396
+ }
1397
+ records.sort((a, b) => a.ordinal - b.ordinal)
1398
+
1399
+ return records.slice(0, limit)
1400
+ },
1401
+ )
1402
+
1403
+ const deferRecovery: SubscriptionStore['Service']['deferRecovery'] = Effect.fnUntraced(
1404
+ function*(input, expectedRevision, recovery) {
1405
+ const key = yield* requireKey(input, 'defer-recovery-key')
1406
+
1407
+ yield* failpoint.hit('subscription:defer-recovery:before')
1408
+ yield* Effect.uninterruptible(
1409
+ Ref.modify(
1410
+ state,
1411
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
1412
+ const storageKey = subscriptionKeyString(key)
1413
+ const text = current.registrations.get(storageKey)
1414
+
1415
+ if (text === undefined) {
1416
+ return [Result.fail(error('not-found', 'subscription')), current]
1417
+ }
1418
+ const record = decode(SubscriptionRecord, text, 'defer-recovery-record')
1419
+
1420
+ if (Result.isFailure(record)) return [Result.fail(record.failure), current]
1421
+
1422
+ if (record.success.configurationRevision !== expectedRevision) {
1423
+ return [Result.void, current]
1424
+ }
1425
+
1426
+ const updated = {
1427
+ ...record.success,
1428
+ recovery: record.success.state === 'active' || record.success.state === 'paused'
1429
+ ? recovery
1430
+ : null,
1431
+ }
1432
+
1433
+ const encoded = encode(SubscriptionRecord, updated, 'defer-recovery-encode')
1434
+
1435
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current]
1436
+ const registrations = new Map(current.registrations)
1437
+
1438
+ registrations.set(storageKey, encoded.success)
1439
+ const registrationIndex = new Map(current.registrationIndex)
1440
+ const indexed = registrationIndex.get(storageKey)
1441
+
1442
+ if (indexed === undefined) {
1443
+ return [Result.fail(error('corrupt', 'recovery-index')), current]
1444
+ }
1445
+ registrationIndex.set(storageKey, {
1446
+ ...indexed,
1447
+ recoveryKey: updated.recovery === null ? null : candidateIndexKey(updated),
1448
+ recoveryAt: updated.recovery?.nextAttemptAtMillis ?? null,
1449
+ })
1450
+
1451
+ return [
1452
+ Result.void,
1453
+ {
1454
+ ...current,
1455
+ registrations,
1456
+ registrationIndex,
1457
+ recoveryCounts: recoveryCountsAfter(current, registrationIndex, [storageKey]),
1458
+ },
1459
+ ]
1460
+ },
1461
+ ),
1462
+ ).pipe(Effect.flatMap(Effect.fromResult))
1463
+ yield* failpoint.hit('subscription:defer-recovery:after')
1464
+ },
1465
+ )
1466
+
1467
+ const readScanCursors: SubscriptionStore['Service']['readScanCursors'] = Ref.get(state).pipe(
1468
+ Effect.map((current) => current.scanCursors),
1469
+ )
1470
+
1471
+ const advanceScanCursors: SubscriptionStore['Service']['advanceScanCursors'] = Effect.fnUntraced(
1472
+ function*(input) {
1473
+ const cursors = yield* validate(SubscriptionScanCursors, input, 'scan-cursors')
1474
+
1475
+ yield* failpoint.hit('subscription:advance-scan-cursors:before')
1476
+ yield* Effect.uninterruptible(
1477
+ Ref.update(state, (current) => ({ ...current, scanCursors: cursors })),
1478
+ )
1479
+ yield* failpoint.hit('subscription:advance-scan-cursors:after')
1480
+ },
1481
+ )
1482
+
1483
+ const nextDeadline = Effect.gen(function*() {
1484
+ let deadline: number | null = null
1485
+ const current = yield* Ref.get(state)
1486
+
1487
+ if (
1488
+ current.scanCursors.events !== '' ||
1489
+ current.scanCursors.deliveries !== '' ||
1490
+ current.scanCursors.recovery !== 0
1491
+ ) {
1492
+ return 0
1493
+ }
1494
+
1495
+ const consider = (value: number) => {
1496
+ if (deadline === null || value < deadline) deadline = value
1497
+ }
1498
+
1499
+ if (current.retentionDeadline !== null) consider(current.retentionDeadline)
1500
+ for (const accepted of current.eventIndex.values()) {
1501
+ if (!accepted.routingComplete) consider(accepted.nextAttemptAtMillis)
1502
+ }
1503
+ for (const item of current.deliveryIndex.values()) {
1504
+ if (
1505
+ (item.state !== 'delivered' && item.state !== 'refused' && item.parked !== true) ||
1506
+ (item.state === 'delivered' && item.observeSettlement === true)
1507
+ ) {
1508
+ consider(item.nextAttemptAtMillis)
1509
+ }
1510
+ }
1511
+ for (const record of current.registrationIndex.values()) {
1512
+ if (record.state === 'active' && record.recoveryAt !== null) consider(record.recoveryAt)
1513
+ }
1514
+
1515
+ return deadline
1516
+ })
1517
+
1518
+ const compact: SubscriptionStore['Service']['compact'] = Effect.fnUntraced(
1519
+ function*(nowMillis, inputPolicy, requestedLimit) {
1520
+ nowMillis = Math.min(nowMillis, yield* Clock.currentTimeMillis)
1521
+ const policy = yield* validate(SubscriptionRetentionPolicy, inputPolicy, 'retention-policy')
1522
+
1523
+ const limit = yield* validate(
1524
+ Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 })),
1525
+ requestedLimit,
1526
+ 'maintenance-limit',
1527
+ )
1528
+
1529
+ yield* failpoint.hit('subscription:compact:before')
1530
+ let corruptCandidates = 0
1531
+
1532
+ const result = yield* Effect.uninterruptible(
1533
+ Ref.modify(
1534
+ state,
1535
+ (
1536
+ current,
1537
+ ): readonly [Result.Result<number, SubscriptionError>, MemorySubscriptionState] => {
1538
+ if (
1539
+ current.retentionHorizon !== null &&
1540
+ current.retentionHorizon !== policy.replayHorizonMillis
1541
+ ) {
1542
+ return [Result.fail(error('conflict', 'retention-horizon')), current]
1543
+ }
1544
+ const events = new Map(current.events)
1545
+ const eventIndex = new Map(current.eventIndex)
1546
+ const deliveries = new Map(current.deliveries)
1547
+ const deliveryIndex = new Map(current.deliveryIndex)
1548
+ const eventDeliveryCounts = new Map(current.eventDeliveryCounts)
1549
+ const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts)
1550
+ let liveDeliveryCount = current.liveDeliveryCount
1551
+
1552
+ // Page indexes before decoding. Each pass reads at most 2 * limit event values and
1553
+ // limit delivery values; relationship checks use maintained reference counts.
1554
+ const deliveryPage = current.deliveryKeys.slice(
1555
+ upperBound(current.deliveryKeys, current.maintenanceDeliveries),
1556
+ upperBound(current.deliveryKeys, current.maintenanceDeliveries) + limit,
1557
+ )
1558
+
1559
+ const eventPage = current.eventKeys.slice(
1560
+ upperBound(current.eventKeys, current.maintenanceEvents),
1561
+ upperBound(current.eventKeys, current.maintenanceEvents) + limit,
1562
+ )
1563
+
1564
+ const cutoff = nowMillis - policy.completedRetentionMillis
1565
+ let removed = 0
1566
+ const removedEvents = new Set<string>()
1567
+ const removedDeliveries = new Set<string>()
1568
+
1569
+ for (const key of deliveryPage) {
1570
+ const text = deliveries.get(key)
1571
+
1572
+ if (text === undefined) continue
1573
+ const decoded = decode(SubscriptionDelivery, text, 'compact-delivery')
1574
+
1575
+ if (Result.isFailure(decoded)) {
1576
+ corruptCandidates++
1577
+ continue
1578
+ }
1579
+ const delivery = decoded.success
1580
+
1581
+ if (
1582
+ subscriptionDeliveryKeyString(delivery.key) !== key ||
1583
+ !samePartition(delivery.key.subscription.partition, partition)
1584
+ ) {
1585
+ corruptCandidates++
1586
+ continue
1587
+ }
1588
+
1589
+ if (
1590
+ delivery.state !== 'refused' &&
1591
+ (delivery.state !== 'delivered' || delivery.settledAtMillis === undefined)
1592
+ ) {
1593
+ continue
1594
+ }
1595
+ if (
1596
+ (delivery.settledAtMillis ??
1597
+ delivery.completedAtMillis ??
1598
+ delivery.selectedAtMillis) > cutoff
1599
+ ) {
1600
+ continue
1601
+ }
1602
+ const eventText = events.get(delivery.key.eventId)
1603
+
1604
+ if (eventText === undefined) continue
1605
+ const accepted = decode(AcceptedEvent, eventText, 'compact-delivery-event')
1606
+
1607
+ if (Result.isFailure(accepted)) {
1608
+ corruptCandidates++
1609
+ continue
1610
+ }
1611
+ const event = accepted.success
1612
+
1613
+ if (
1614
+ event.eventId !== delivery.key.eventId ||
1615
+ !samePartition(event.partition, partition)
1616
+ ) {
1617
+ corruptCandidates++
1618
+ continue
1619
+ }
1620
+
1621
+ if (
1622
+ !event.routingComplete ||
1623
+ event.occurredAtMillis === undefined ||
1624
+ event.acceptedAtMillis > cutoff ||
1625
+ (current.recoveryCounts.get(eventCandidateIndexKey(event)) ?? 0) > 0
1626
+ ) {
1627
+ continue
1628
+ }
1629
+ deliveries.delete(key)
1630
+ removedDeliveries.add(key)
1631
+ deliveryIndex.delete(key)
1632
+ eventDeliveryCounts.set(
1633
+ event.eventId,
1634
+ (eventDeliveryCounts.get(event.eventId) ?? 1) - 1,
1635
+ )
1636
+ if (subscriptionDeliveryUsesCapacity(delivery)) {
1637
+ liveDeliveryCount--
1638
+ const owner = delivery.key.subscription.ownerId
1639
+ const count = (ownerDeliveryCounts.get(owner) ?? 1) - 1
1640
+
1641
+ if (count === 0) ownerDeliveryCounts.delete(owner)
1642
+ else ownerDeliveryCounts.set(owner, count)
1643
+ }
1644
+ }
1645
+ let tombstones = current.tombstoneCount
1646
+
1647
+ for (const key of eventPage) {
1648
+ const text = events.get(key)
1649
+
1650
+ if (text === undefined) continue
1651
+ const decoded = decode(AcceptedEvent, text, 'compact-event')
1652
+
1653
+ if (Result.isFailure(decoded)) {
1654
+ corruptCandidates++
1655
+ continue
1656
+ }
1657
+ const event = decoded.success
1658
+
1659
+ if (event.eventId !== key || !samePartition(event.partition, partition)) {
1660
+ corruptCandidates++
1661
+ continue
1662
+ }
1663
+
1664
+ if (!event.routingComplete || event.occurredAtMillis === undefined) continue
1665
+ const expired = event.occurredAtMillis <= nowMillis - policy.replayHorizonMillis
1666
+
1667
+ if (event.tombstone === true && !expired) continue
1668
+ if (
1669
+ event.acceptedAtMillis > cutoff ||
1670
+ (eventDeliveryCounts.get(key) ?? 0) > 0 ||
1671
+ (current.recoveryCounts.get(eventCandidateIndexKey(event)) ?? 0) > 0
1672
+ ) {
1673
+ continue
1674
+ }
1675
+ if (expired) {
1676
+ events.delete(key)
1677
+ removedEvents.add(key)
1678
+ eventIndex.delete(key)
1679
+ eventDeliveryCounts.delete(key)
1680
+ if (event.tombstone === true) tombstones--
1681
+ } else {
1682
+ if (tombstones >= policy.maxTombstones) continue
1683
+
1684
+ const encoded = encode(
1685
+ AcceptedEvent,
1686
+ { ...event, payload: null, tombstone: true },
1687
+ 'compact-tombstone',
1688
+ )
1689
+
1690
+ if (Result.isFailure(encoded)) continue
1691
+ events.set(key, encoded.success)
1692
+ tombstones++
1693
+ }
1694
+ removed++
1695
+ }
1696
+
1697
+ return [
1698
+ Result.succeed(removed),
1699
+ {
1700
+ ...current,
1701
+ events,
1702
+ eventIndex,
1703
+ deliveries,
1704
+ deliveryIndex,
1705
+ eventDeliveryCounts,
1706
+ ownerDeliveryCounts,
1707
+ liveDeliveryCount,
1708
+ eventKeys: removeKeys(current.eventKeys, removedEvents),
1709
+ deliveryKeys: removeKeys(current.deliveryKeys, removedDeliveries),
1710
+ tombstoneCount: tombstones,
1711
+ maintenanceEvents: eventPage.length < limit ? '' : (eventPage.at(-1) ?? ''),
1712
+ maintenanceDeliveries: deliveryPage.length < limit ? '' : (deliveryPage.at(-1) ?? ''),
1713
+ retentionHorizon: policy.replayHorizonMillis,
1714
+ retentionDeadline: events.size === 0 ? null : nowMillis + 60_000,
1715
+ },
1716
+ ]
1717
+ },
1718
+ ),
1719
+ ).pipe(Effect.flatMap(Effect.fromResult))
1720
+
1721
+ if (corruptCandidates > 0) {
1722
+ yield* Effect.logWarning('Subscription retention preserved corrupt candidates', {
1723
+ count: corruptCandidates,
1724
+ })
1725
+ }
1726
+ yield* failpoint.hit('subscription:compact:after')
1727
+
1728
+ return result
1729
+ },
1730
+ )
1731
+
1732
+ return SubscriptionStore.of({
1733
+ partition,
1734
+ compact,
1735
+ register,
1736
+ get,
1737
+ list,
1738
+ cancel,
1739
+ change,
1740
+ accept,
1741
+ event,
1742
+ pendingEvents,
1743
+ candidates,
1744
+ select,
1745
+ catchUp,
1746
+ deferEvent,
1747
+ delivery,
1748
+ pendingDeliveries,
1749
+ listDeliveries,
1750
+ changeDelivery,
1751
+ recovering,
1752
+ deferRecovery,
1753
+ readScanCursors,
1754
+ advanceScanCursors,
1755
+ nextDeadline,
1756
+ })
1757
+ })
1758
+
1759
+ export const memorySubscriptionStoreLayer = (
1760
+ partition: SourcePartition,
1761
+ ): Layer.Layer<SubscriptionStore, SubscriptionError> =>
1762
+ Layer.effect(SubscriptionStore, makeMemorySubscriptionStore(partition))