@effect-agent/storage-memory 0.1.0-beta.38 → 0.1.0-beta.40

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.
@@ -0,0 +1,921 @@
1
+ import {
2
+ AcceptedEvent,
3
+ applySubscriptionDeliveryChange,
4
+ compareScheduleNames,
5
+ DeliveryChange,
6
+ Digest,
7
+ SourcePartition,
8
+ SubscriptionDelivery,
9
+ SubscriptionDeliveryKey,
10
+ SubscriptionError,
11
+ SubscriptionFailpoint,
12
+ SubscriptionKey,
13
+ SubscriptionLimits,
14
+ SubscriptionName,
15
+ SubscriptionRecord,
16
+ SubscriptionScanCursors,
17
+ SubscriptionStore,
18
+ subscriptionCanSelect,
19
+ subscriptionDeliveryCanSelect,
20
+ subscriptionDeliveryKeyString,
21
+ subscriptionKeyString,
22
+ } from "@effect-agent/thread";
23
+ import { Clock, Effect, Layer, Ref, Result, Schema } from "effect";
24
+
25
+ interface MemorySubscriptionState {
26
+ readonly sequence: number;
27
+ readonly registrations: ReadonlyMap<string, string>;
28
+ readonly events: ReadonlyMap<string, string>;
29
+ readonly deliveries: ReadonlyMap<string, string>;
30
+ readonly registrationIndex: ReadonlyMap<string, RegistrationIndex>;
31
+ readonly candidateIndex: ReadonlyMap<string, ReadonlyArray<string>>;
32
+ readonly ownerRegistrationCounts: ReadonlyMap<string, number>;
33
+ readonly eventIndex: ReadonlyMap<string, EventIndex>;
34
+ readonly deliveryIndex: ReadonlyMap<string, DeliveryIndex>;
35
+ readonly ownerDeliveryCounts: ReadonlyMap<string, number>;
36
+ readonly scanCursors: SubscriptionScanCursors;
37
+ }
38
+
39
+ interface RegistrationIndex {
40
+ readonly key: SubscriptionKey;
41
+ readonly ordinal: number;
42
+ readonly state: SubscriptionRecord["state"];
43
+ readonly recoveryAt: number | null;
44
+ }
45
+ interface EventIndex {
46
+ readonly routingComplete: boolean;
47
+ readonly nextAttemptAtMillis: number;
48
+ }
49
+ interface DeliveryIndex {
50
+ readonly key: SubscriptionDeliveryKey;
51
+ readonly state: SubscriptionDelivery["state"];
52
+ readonly nextAttemptAtMillis: number;
53
+ }
54
+
55
+ const error = (reason: SubscriptionError["reason"], code: string) =>
56
+ SubscriptionError.make({ reason, code });
57
+
58
+ const samePartition = (left: SourcePartition, right: SourcePartition): boolean =>
59
+ left.tenantId === right.tenantId && left.address === right.address;
60
+
61
+ const sameSource = (left: AcceptedEvent["source"], right: AcceptedEvent["source"]): boolean =>
62
+ left.name === right.name && left.version === right.version;
63
+
64
+ const encode = <A, I>(
65
+ schema: Schema.Codec<A, I>,
66
+ value: A,
67
+ code: string,
68
+ ): Result.Result<string, SubscriptionError> =>
69
+ Result.try({
70
+ try: () => Schema.encodeSync(Schema.fromJsonString(schema))(value),
71
+ catch: () => error("corrupt", code),
72
+ });
73
+
74
+ const decode = <A, I>(
75
+ schema: Schema.Codec<A, I>,
76
+ value: string,
77
+ code: string,
78
+ ): Result.Result<A, SubscriptionError> =>
79
+ Result.try({
80
+ try: () => Schema.decodeSync(Schema.fromJsonString(schema))(value),
81
+ catch: () => error("corrupt", code),
82
+ });
83
+
84
+ const decodeEffect = <A, I>(schema: Schema.Codec<A, I>, value: string, code: string) =>
85
+ Effect.fromResult(decode(schema, value, code));
86
+
87
+ const validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>
88
+ Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error("validation", code)));
89
+
90
+ const jsonBytes = (value: unknown): number =>
91
+ new TextEncoder().encode(JSON.stringify(value)).byteLength;
92
+
93
+ const sameDeliveryIdentity = (left: SubscriptionDelivery, right: SubscriptionDelivery): boolean =>
94
+ subscriptionDeliveryKeyString(left.key) === subscriptionDeliveryKeyString(right.key) &&
95
+ left.deliveryId === right.deliveryId &&
96
+ left.source.name === right.source.name &&
97
+ left.source.version === right.source.version &&
98
+ left.threadId === right.threadId &&
99
+ left.admissionKey === right.admissionKey &&
100
+ left.subscriptionFingerprint === right.subscriptionFingerprint &&
101
+ left.eventDigest === right.eventDigest;
102
+
103
+ const candidateIndexKey = (record: SubscriptionRecord): string =>
104
+ JSON.stringify([
105
+ record.configuration.source.name,
106
+ record.configuration.source.version,
107
+ record.configuration.matchingKey,
108
+ ]);
109
+ const eventCandidateIndexKey = (event: AcceptedEvent): string =>
110
+ JSON.stringify([event.source.name, event.source.version, event.matchingKey]);
111
+
112
+ const sameEventIdentity = (left: AcceptedEvent, right: AcceptedEvent): boolean =>
113
+ samePartition(left.partition, right.partition) &&
114
+ left.eventId === right.eventId &&
115
+ sameSource(left.source, right.source) &&
116
+ left.matchingKey === right.matchingKey &&
117
+ left.payloadDigest === right.payloadDigest;
118
+
119
+ const deliveryBelongsTo = (
120
+ delivery: SubscriptionDelivery,
121
+ record: SubscriptionRecord,
122
+ event: AcceptedEvent,
123
+ ): boolean =>
124
+ subscriptionKeyString(delivery.key.subscription) === subscriptionKeyString(record.key) &&
125
+ delivery.key.eventId === event.eventId &&
126
+ sameSource(delivery.source, event.source);
127
+
128
+ const makeMemorySubscriptionStore = Effect.fn("makeMemorySubscriptionStore")(function* (
129
+ ownedPartition: SourcePartition,
130
+ ) {
131
+ const partition = yield* validate(SourcePartition, ownedPartition, "partition");
132
+ const state = yield* Ref.make<MemorySubscriptionState>({
133
+ sequence: 0,
134
+ registrations: new Map(),
135
+ events: new Map(),
136
+ deliveries: new Map(),
137
+ registrationIndex: new Map(),
138
+ candidateIndex: new Map(),
139
+ ownerRegistrationCounts: new Map(),
140
+ eventIndex: new Map(),
141
+ deliveryIndex: new Map(),
142
+ ownerDeliveryCounts: new Map(),
143
+ scanCursors: { events: "", deliveries: "", recovery: 0 },
144
+ });
145
+ const failpoint = yield* SubscriptionFailpoint;
146
+
147
+ const requirePartition = <A extends { readonly partition: SourcePartition }>(
148
+ value: A,
149
+ code: string,
150
+ ) =>
151
+ samePartition(value.partition, partition)
152
+ ? Effect.succeed(value)
153
+ : Effect.fail(error("validation", code));
154
+
155
+ const requireKey = (key: SubscriptionKey, code: string) =>
156
+ validate(SubscriptionKey, key, code).pipe(
157
+ Effect.flatMap((decoded) => requirePartition(decoded, code)),
158
+ );
159
+
160
+ const register: SubscriptionStore["Service"]["register"] = Effect.fn(
161
+ "MemorySubscriptionStore.register",
162
+ )(function* (input, inputLimits) {
163
+ const record = yield* validate(SubscriptionRecord, input, "register-record");
164
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "register-limits");
165
+ yield* requirePartition(record.key, "register-partition");
166
+ yield* failpoint.hit("subscription:register:before");
167
+ const result = yield* Effect.uninterruptible(
168
+ Ref.modify(
169
+ state,
170
+ (
171
+ current,
172
+ ): readonly [
173
+ Result.Result<SubscriptionRecord, SubscriptionError>,
174
+ MemorySubscriptionState,
175
+ ] => {
176
+ const key = subscriptionKeyString(record.key);
177
+ const existingText = current.registrations.get(key);
178
+ if (existingText !== undefined) {
179
+ const existing = decode(SubscriptionRecord, existingText, "register-existing");
180
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];
181
+ return existing.success.creationFingerprint === record.creationFingerprint
182
+ ? [Result.succeed(existing.success), current]
183
+ : [Result.fail(error("conflict", "registration-identity")), current];
184
+ }
185
+ if (jsonBytes(record.configuration.context) > limits.maxContextBytes)
186
+ return [Result.fail(error("capacity", "context-bytes")), current];
187
+ if (jsonBytes(record.configuration.parameters) > limits.maxPayloadBytes)
188
+ return [Result.fail(error("capacity", "parameters-bytes")), current];
189
+ if (
190
+ record.configuration.expiresAtMillis - record.createdAtMillis >
191
+ limits.maxLifetimeMillis
192
+ )
193
+ return [Result.fail(error("capacity", "lifetime")), current];
194
+ if (current.registrations.size >= limits.maxRegistrations)
195
+ return [Result.fail(error("capacity", "registrations")), current];
196
+ const ownerCount = current.ownerRegistrationCounts.get(record.key.ownerId) ?? 0;
197
+ if (ownerCount >= limits.maxRegistrationsPerOwner)
198
+ return [Result.fail(error("capacity", "owner-registrations")), current];
199
+ const assigned = { ...record, ordinal: current.sequence + 1 };
200
+ const encoded = encode(SubscriptionRecord, assigned, "register-encode");
201
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];
202
+ const registrations = new Map(current.registrations);
203
+ registrations.set(key, encoded.success);
204
+ const registrationIndex = new Map(current.registrationIndex);
205
+ registrationIndex.set(key, {
206
+ key: assigned.key,
207
+ ordinal: assigned.ordinal,
208
+ state: assigned.state,
209
+ recoveryAt: assigned.recovery?.nextAttemptAtMillis ?? null,
210
+ });
211
+ const candidateIndex = new Map(current.candidateIndex);
212
+ const candidateKey = candidateIndexKey(assigned);
213
+ candidateIndex.set(candidateKey, [...(candidateIndex.get(candidateKey) ?? []), key]);
214
+ const ownerRegistrationCounts = new Map(current.ownerRegistrationCounts);
215
+ ownerRegistrationCounts.set(assigned.key.ownerId, ownerCount + 1);
216
+ return [
217
+ Result.succeed(assigned),
218
+ {
219
+ ...current,
220
+ sequence: assigned.ordinal,
221
+ registrations,
222
+ registrationIndex,
223
+ candidateIndex,
224
+ ownerRegistrationCounts,
225
+ },
226
+ ];
227
+ },
228
+ ),
229
+ ).pipe(Effect.flatMap(Effect.fromResult));
230
+ yield* failpoint.hit("subscription:register:after");
231
+ return result;
232
+ });
233
+
234
+ const get: SubscriptionStore["Service"]["get"] = Effect.fn("MemorySubscriptionStore.get")(
235
+ function* (input) {
236
+ const key = yield* requireKey(input, "get-key");
237
+ const text = (yield* Ref.get(state)).registrations.get(subscriptionKeyString(key));
238
+ return text === undefined
239
+ ? null
240
+ : yield* decodeEffect(SubscriptionRecord, text, "get-record");
241
+ },
242
+ );
243
+
244
+ const list: SubscriptionStore["Service"]["list"] = Effect.fn("MemorySubscriptionStore.list")(
245
+ function* (ownerId, after, limit) {
246
+ if (!Number.isSafeInteger(after) || after < 0 || !Number.isSafeInteger(limit) || limit <= 0)
247
+ return yield* error("validation", "list-page");
248
+ const current = yield* Ref.get(state);
249
+ const records: Array<SubscriptionRecord> = [];
250
+ for (const [storageKey, indexed] of current.registrationIndex) {
251
+ if (indexed.key.ownerId !== ownerId || indexed.ordinal <= after) continue;
252
+ const text = current.registrations.get(storageKey);
253
+ if (text === undefined) return yield* error("corrupt", "list-index");
254
+ records.push(yield* decodeEffect(SubscriptionRecord, text, "list-record"));
255
+ }
256
+ records.sort((a, b) => a.ordinal - b.ordinal);
257
+ return records.slice(0, limit);
258
+ },
259
+ );
260
+
261
+ const cancel: SubscriptionStore["Service"]["cancel"] = Effect.fn(
262
+ "MemorySubscriptionStore.cancel",
263
+ )(function* (input) {
264
+ const key = yield* requireKey(input, "cancel-key");
265
+ yield* failpoint.hit("subscription:cancel:before");
266
+ const result = yield* Effect.uninterruptible(
267
+ Ref.modify(
268
+ state,
269
+ (
270
+ current,
271
+ ): readonly [
272
+ Result.Result<SubscriptionRecord, SubscriptionError>,
273
+ MemorySubscriptionState,
274
+ ] => {
275
+ const storageKey = subscriptionKeyString(key);
276
+ const text = current.registrations.get(storageKey);
277
+ if (text === undefined) return [Result.fail(error("not-found", "subscription")), current];
278
+ const decoded = decode(SubscriptionRecord, text, "cancel-record");
279
+ if (Result.isFailure(decoded)) return [decoded, current];
280
+ if (decoded.success.state === "cancelled")
281
+ return [Result.succeed(decoded.success), current];
282
+ const cancelled = { ...decoded.success, state: "cancelled" as const, recovery: null };
283
+ const encoded = encode(SubscriptionRecord, cancelled, "cancel-encode");
284
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];
285
+ const registrations = new Map(current.registrations);
286
+ registrations.set(storageKey, encoded.success);
287
+ const registrationIndex = new Map(current.registrationIndex);
288
+ const indexed = registrationIndex.get(storageKey);
289
+ if (indexed === undefined)
290
+ return [Result.fail(error("corrupt", "cancel-index")), current];
291
+ registrationIndex.set(storageKey, { ...indexed, state: "cancelled", recoveryAt: null });
292
+ return [Result.succeed(cancelled), { ...current, registrations, registrationIndex }];
293
+ },
294
+ ),
295
+ ).pipe(Effect.flatMap(Effect.fromResult));
296
+ yield* failpoint.hit("subscription:cancel:after");
297
+ return result;
298
+ });
299
+
300
+ const accept: SubscriptionStore["Service"]["accept"] = Effect.fn(
301
+ "MemorySubscriptionStore.accept",
302
+ )(function* (input, inputLimits) {
303
+ const event = yield* validate(AcceptedEvent, input, "accept-event");
304
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "accept-limits");
305
+ yield* requirePartition(event, "accept-partition");
306
+ yield* failpoint.hit("subscription:accept:before");
307
+ const result = yield* Effect.uninterruptible(
308
+ Ref.modify(
309
+ state,
310
+ (
311
+ current,
312
+ ): readonly [Result.Result<AcceptedEvent, SubscriptionError>, MemorySubscriptionState] => {
313
+ const existingText = current.events.get(event.eventId);
314
+ if (existingText !== undefined) {
315
+ const existing = decode(AcceptedEvent, existingText, "accept-existing");
316
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];
317
+ return sameEventIdentity(existing.success, event)
318
+ ? [Result.succeed(existing.success), current]
319
+ : [Result.fail(error("conflict", "event-identity")), current];
320
+ }
321
+ if (jsonBytes(event.payload) > limits.maxPayloadBytes)
322
+ return [Result.fail(error("capacity", "payload-bytes")), current];
323
+ if (current.events.size >= limits.maxEvents)
324
+ return [Result.fail(error("capacity", "events")), current];
325
+ const accepted: AcceptedEvent = {
326
+ ...event,
327
+ cutoff: current.sequence + 1,
328
+ cursor: 0,
329
+ routingComplete: false,
330
+ routingFailure: null,
331
+ };
332
+ const encoded = encode(AcceptedEvent, accepted, "accept-encode");
333
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];
334
+ const events = new Map(current.events);
335
+ events.set(accepted.eventId, encoded.success);
336
+ const eventIndex = new Map(current.eventIndex);
337
+ eventIndex.set(accepted.eventId, {
338
+ routingComplete: false,
339
+ nextAttemptAtMillis: accepted.nextAttemptAtMillis,
340
+ });
341
+ return [
342
+ Result.succeed(accepted),
343
+ { ...current, sequence: accepted.cutoff, events, eventIndex },
344
+ ];
345
+ },
346
+ ),
347
+ ).pipe(Effect.flatMap(Effect.fromResult));
348
+ yield* failpoint.hit("subscription:accept:after");
349
+ return result;
350
+ });
351
+
352
+ const event: SubscriptionStore["Service"]["event"] = Effect.fn("MemorySubscriptionStore.event")(
353
+ function* (eventId) {
354
+ const text = (yield* Ref.get(state)).events.get(eventId);
355
+ return text === undefined ? null : yield* decodeEffect(AcceptedEvent, text, "event-record");
356
+ },
357
+ );
358
+
359
+ const pendingEvents: SubscriptionStore["Service"]["pendingEvents"] = Effect.fn(
360
+ "MemorySubscriptionStore.pendingEvents",
361
+ )(function* (nowMillis, after, limit) {
362
+ const events: Array<string> = [];
363
+ for (const [eventId, indexed] of (yield* Ref.get(state)).eventIndex) {
364
+ if (
365
+ !indexed.routingComplete &&
366
+ indexed.nextAttemptAtMillis <= nowMillis &&
367
+ compareScheduleNames(eventId, after) > 0
368
+ )
369
+ events.push(eventId);
370
+ }
371
+ events.sort(compareScheduleNames);
372
+ return events.slice(0, limit);
373
+ });
374
+
375
+ const candidates: SubscriptionStore["Service"]["candidates"] = Effect.fn(
376
+ "MemorySubscriptionStore.candidates",
377
+ )(function* (input, limit) {
378
+ const accepted = yield* validate(AcceptedEvent, input, "candidates-event");
379
+ yield* requirePartition(accepted, "candidates-partition");
380
+ const stored = yield* event(accepted.eventId);
381
+ if (stored === null || !sameEventIdentity(stored, accepted))
382
+ return yield* error(stored === null ? "not-found" : "conflict", "event");
383
+ const current = yield* Ref.get(state);
384
+ const records: Array<SubscriptionRecord> = [];
385
+ for (const storageKey of current.candidateIndex.get(eventCandidateIndexKey(stored)) ?? []) {
386
+ const indexed = current.registrationIndex.get(storageKey);
387
+ if (indexed === undefined) return yield* error("corrupt", "candidate-index");
388
+ if (indexed.ordinal <= stored.cursor || indexed.ordinal > stored.cutoff) continue;
389
+ const text = current.registrations.get(storageKey);
390
+ if (text === undefined) return yield* error("corrupt", "candidate-record");
391
+ records.push(yield* decodeEffect(SubscriptionRecord, text, "candidate-record"));
392
+ }
393
+ records.sort((a, b) => a.ordinal - b.ordinal);
394
+ return records.slice(0, limit);
395
+ });
396
+
397
+ const select: SubscriptionStore["Service"]["select"] = Effect.fn(
398
+ "MemorySubscriptionStore.select",
399
+ )(function* (inputEvent, inputDeliveries, cursor, complete, nowMillis, inputLimits) {
400
+ const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, "select-event");
401
+ const deliveries = yield* validate(
402
+ Schema.Array(SubscriptionDelivery),
403
+ inputDeliveries,
404
+ "select-deliveries",
405
+ );
406
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "select-limits");
407
+ yield* requirePartition(suppliedEvent, "select-partition");
408
+ yield* failpoint.hit("subscription:select:before");
409
+ const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);
410
+ yield* Effect.uninterruptible(
411
+ Ref.modify(
412
+ state,
413
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
414
+ const eventText = current.events.get(suppliedEvent.eventId);
415
+ if (eventText === undefined) return [Result.fail(error("not-found", "event")), current];
416
+ const decodedEvent = decode(AcceptedEvent, eventText, "select-event-record");
417
+ if (Result.isFailure(decodedEvent)) return [Result.fail(decodedEvent.failure), current];
418
+ const accepted = decodedEvent.success;
419
+ if (
420
+ !sameEventIdentity(accepted, suppliedEvent) ||
421
+ suppliedEvent.cursor !== accepted.cursor
422
+ )
423
+ return [Result.fail(error("conflict", "event-cursor")), current];
424
+ if (accepted.routingComplete)
425
+ return [
426
+ complete && cursor === accepted.cursor
427
+ ? Result.void
428
+ : Result.fail(error("conflict", "routing-complete")),
429
+ current,
430
+ ];
431
+ if (!Number.isSafeInteger(cursor) || cursor < accepted.cursor || cursor > accepted.cutoff)
432
+ return [Result.fail(error("validation", "cursor")), current];
433
+
434
+ const additions: Array<readonly [string, string]> = [];
435
+ const updates: Array<readonly [string, string]> = [];
436
+ const additionIndex: Array<readonly [string, DeliveryIndex, string]> = [];
437
+ const registrationUpdates: Array<readonly [string, RegistrationIndex]> = [];
438
+ const owners = new Map(current.ownerDeliveryCounts);
439
+ for (const delivery of deliveries) {
440
+ const recordText = current.registrations.get(
441
+ subscriptionKeyString(delivery.key.subscription),
442
+ );
443
+ if (recordText === undefined)
444
+ return [Result.fail(error("not-found", "subscription")), current];
445
+ const record = decode(SubscriptionRecord, recordText, "select-registration");
446
+ if (Result.isFailure(record)) return [Result.fail(record.failure), current];
447
+ if (
448
+ !deliveryBelongsTo(delivery, record.success, accepted) ||
449
+ !subscriptionDeliveryCanSelect(delivery, record.success, accepted) ||
450
+ record.success.ordinal <= accepted.cursor ||
451
+ record.success.ordinal > cursor
452
+ )
453
+ return [Result.fail(error("conflict", "selection")), current];
454
+ if (!subscriptionCanSelect(record.success, accepted, effectiveNowMillis, false))
455
+ continue;
456
+ const deliveryKey = subscriptionDeliveryKeyString(delivery.key);
457
+ const existingText = current.deliveries.get(deliveryKey);
458
+ if (existingText !== undefined) {
459
+ const existing = decode(SubscriptionDelivery, existingText, "select-existing");
460
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];
461
+ if (!sameDeliveryIdentity(existing.success, delivery))
462
+ return [Result.fail(error("conflict", "delivery-identity")), current];
463
+ continue;
464
+ }
465
+ const encodedDelivery = encode(
466
+ SubscriptionDelivery,
467
+ delivery,
468
+ "select-delivery-encode",
469
+ );
470
+ if (Result.isFailure(encodedDelivery))
471
+ return [Result.fail(encodedDelivery.failure), current];
472
+ additions.push([deliveryKey, encodedDelivery.success]);
473
+ additionIndex.push([
474
+ deliveryKey,
475
+ {
476
+ key: delivery.key,
477
+ state: delivery.state,
478
+ nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,
479
+ },
480
+ record.success.key.ownerId,
481
+ ]);
482
+ const ownerId = record.success.key.ownerId;
483
+ owners.set(ownerId, (owners.get(ownerId) ?? 0) + 1);
484
+ if ((owners.get(ownerId) ?? 0) > limits.maxDeliveriesPerOwner)
485
+ return [Result.fail(error("capacity", "owner-deliveries")), current];
486
+ if (record.success.configuration.mode === "once") {
487
+ const consumed = { ...record.success, state: "consumed" as const, recovery: null };
488
+ const encodedRecord = encode(
489
+ SubscriptionRecord,
490
+ consumed,
491
+ "select-registration-encode",
492
+ );
493
+ if (Result.isFailure(encodedRecord))
494
+ return [Result.fail(encodedRecord.failure), current];
495
+ const consumedKey = subscriptionKeyString(consumed.key);
496
+ updates.push([consumedKey, encodedRecord.success]);
497
+ const indexed = current.registrationIndex.get(consumedKey);
498
+ if (indexed === undefined)
499
+ return [Result.fail(error("corrupt", "selection-index")), current];
500
+ registrationUpdates.push([
501
+ consumedKey,
502
+ { ...indexed, state: "consumed", recoveryAt: null },
503
+ ]);
504
+ }
505
+ }
506
+ if (current.deliveries.size + additions.length > limits.maxDeliveries)
507
+ return [Result.fail(error("capacity", "deliveries")), current];
508
+ const registrations = new Map(current.registrations);
509
+ for (const [key, value] of updates) registrations.set(key, value);
510
+ const nextDeliveries = new Map(current.deliveries);
511
+ for (const [key, value] of additions) nextDeliveries.set(key, value);
512
+ const deliveryIndex = new Map(current.deliveryIndex);
513
+ for (const [key, value] of additionIndex) deliveryIndex.set(key, value);
514
+ const registrationIndex = new Map(current.registrationIndex);
515
+ for (const [key, value] of registrationUpdates) registrationIndex.set(key, value);
516
+ const nextEvent: AcceptedEvent = {
517
+ ...accepted,
518
+ cursor,
519
+ routingComplete: complete,
520
+ routingFailure: null,
521
+ };
522
+ const encodedEvent = encode(AcceptedEvent, nextEvent, "select-event-encode");
523
+ if (Result.isFailure(encodedEvent)) return [Result.fail(encodedEvent.failure), current];
524
+ const events = new Map(current.events);
525
+ events.set(nextEvent.eventId, encodedEvent.success);
526
+ const eventIndex = new Map(current.eventIndex);
527
+ eventIndex.set(nextEvent.eventId, {
528
+ routingComplete: nextEvent.routingComplete,
529
+ nextAttemptAtMillis: nextEvent.nextAttemptAtMillis,
530
+ });
531
+ return [
532
+ Result.void,
533
+ {
534
+ ...current,
535
+ registrations,
536
+ registrationIndex,
537
+ events,
538
+ eventIndex,
539
+ deliveries: nextDeliveries,
540
+ deliveryIndex,
541
+ ownerDeliveryCounts: owners,
542
+ },
543
+ ];
544
+ },
545
+ ),
546
+ ).pipe(Effect.flatMap(Effect.fromResult));
547
+ yield* failpoint.hit("subscription:select:after");
548
+ });
549
+
550
+ const catchUp: SubscriptionStore["Service"]["catchUp"] = Effect.fn(
551
+ "MemorySubscriptionStore.catchUp",
552
+ )(function* (inputEvent, inputDelivery, nowMillis, inputLimits) {
553
+ const suppliedEvent = yield* validate(AcceptedEvent, inputEvent, "catch-up-event");
554
+ const delivery = yield* validate(SubscriptionDelivery, inputDelivery, "catch-up-delivery");
555
+ const limits = yield* validate(SubscriptionLimits, inputLimits, "catch-up-limits");
556
+ yield* requirePartition(suppliedEvent, "catch-up-partition");
557
+ yield* failpoint.hit("subscription:catch-up:before");
558
+ const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);
559
+ yield* Effect.uninterruptible(
560
+ Ref.modify(
561
+ state,
562
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
563
+ const eventText = current.events.get(suppliedEvent.eventId);
564
+ const recordText = current.registrations.get(
565
+ subscriptionKeyString(delivery.key.subscription),
566
+ );
567
+ if (eventText === undefined || recordText === undefined)
568
+ return [
569
+ Result.fail(error("not-found", eventText === undefined ? "event" : "subscription")),
570
+ current,
571
+ ];
572
+ const accepted = decode(AcceptedEvent, eventText, "catch-up-event-record");
573
+ if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current];
574
+ const record = decode(SubscriptionRecord, recordText, "catch-up-registration");
575
+ if (Result.isFailure(record)) return [Result.fail(record.failure), current];
576
+ if (
577
+ !sameEventIdentity(accepted.success, suppliedEvent) ||
578
+ !deliveryBelongsTo(delivery, record.success, accepted.success) ||
579
+ !subscriptionDeliveryCanSelect(delivery, record.success, accepted.success) ||
580
+ record.success.configuration.mode !== "once"
581
+ )
582
+ return [Result.fail(error("conflict", "catch-up-identity")), current];
583
+ const key = subscriptionDeliveryKeyString(delivery.key);
584
+ const existingText = current.deliveries.get(key);
585
+ if (existingText !== undefined) {
586
+ const existing = decode(SubscriptionDelivery, existingText, "catch-up-existing");
587
+ if (Result.isFailure(existing)) return [Result.fail(existing.failure), current];
588
+ return sameDeliveryIdentity(existing.success, delivery)
589
+ ? [Result.void, current]
590
+ : [Result.fail(error("conflict", "delivery-identity")), current];
591
+ }
592
+ if (!subscriptionCanSelect(record.success, accepted.success, effectiveNowMillis, true))
593
+ return [Result.fail(error("conflict", "catch-up-eligibility")), current];
594
+ if (current.deliveries.size >= limits.maxDeliveries)
595
+ return [Result.fail(error("capacity", "deliveries")), current];
596
+ const ownerCount = current.ownerDeliveryCounts.get(record.success.key.ownerId) ?? 0;
597
+ if (ownerCount >= limits.maxDeliveriesPerOwner)
598
+ return [Result.fail(error("capacity", "owner-deliveries")), current];
599
+ const encodedDelivery = encode(
600
+ SubscriptionDelivery,
601
+ delivery,
602
+ "catch-up-delivery-encode",
603
+ );
604
+ if (Result.isFailure(encodedDelivery))
605
+ return [Result.fail(encodedDelivery.failure), current];
606
+ const consumed = { ...record.success, state: "consumed" as const, recovery: null };
607
+ const encodedRecord = encode(
608
+ SubscriptionRecord,
609
+ consumed,
610
+ "catch-up-registration-encode",
611
+ );
612
+ if (Result.isFailure(encodedRecord)) return [Result.fail(encodedRecord.failure), current];
613
+ const deliveries = new Map(current.deliveries);
614
+ deliveries.set(key, encodedDelivery.success);
615
+ const registrations = new Map(current.registrations);
616
+ const consumedKey = subscriptionKeyString(consumed.key);
617
+ registrations.set(consumedKey, encodedRecord.success);
618
+ const registrationIndex = new Map(current.registrationIndex);
619
+ const indexed = registrationIndex.get(consumedKey);
620
+ if (indexed === undefined)
621
+ return [Result.fail(error("corrupt", "catch-up-index")), current];
622
+ registrationIndex.set(consumedKey, { ...indexed, state: "consumed", recoveryAt: null });
623
+ const deliveryIndex = new Map(current.deliveryIndex);
624
+ deliveryIndex.set(key, {
625
+ key: delivery.key,
626
+ state: delivery.state,
627
+ nextAttemptAtMillis: delivery.retry.nextAttemptAtMillis,
628
+ });
629
+ const ownerDeliveryCounts = new Map(current.ownerDeliveryCounts);
630
+ ownerDeliveryCounts.set(consumed.key.ownerId, ownerCount + 1);
631
+ return [
632
+ Result.void,
633
+ {
634
+ ...current,
635
+ deliveries,
636
+ deliveryIndex,
637
+ ownerDeliveryCounts,
638
+ registrations,
639
+ registrationIndex,
640
+ },
641
+ ];
642
+ },
643
+ ),
644
+ ).pipe(Effect.flatMap(Effect.fromResult));
645
+ yield* failpoint.hit("subscription:catch-up:after");
646
+ });
647
+
648
+ const deferEvent: SubscriptionStore["Service"]["deferEvent"] = Effect.fn(
649
+ "MemorySubscriptionStore.deferEvent",
650
+ )(function* (eventId, nextAttemptAtMillis, code) {
651
+ const routingFailure =
652
+ code === undefined
653
+ ? "routing-failed"
654
+ : yield* validate(SubscriptionName, code, "routing-failure");
655
+ yield* failpoint.hit("subscription:defer-event:before");
656
+ yield* Effect.uninterruptible(
657
+ Ref.modify(
658
+ state,
659
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
660
+ const text = current.events.get(eventId);
661
+ if (text === undefined) return [Result.fail(error("not-found", "event")), current];
662
+ const accepted = decode(AcceptedEvent, text, "defer-event-record");
663
+ if (Result.isFailure(accepted)) return [Result.fail(accepted.failure), current];
664
+ const updated = { ...accepted.success, nextAttemptAtMillis, routingFailure };
665
+ const encoded = encode(AcceptedEvent, updated, "defer-event-encode");
666
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];
667
+ const events = new Map(current.events);
668
+ events.set(eventId, encoded.success);
669
+ const eventIndex = new Map(current.eventIndex);
670
+ const indexed = eventIndex.get(eventId);
671
+ if (indexed === undefined)
672
+ return [Result.fail(error("corrupt", "defer-event-index")), current];
673
+ eventIndex.set(eventId, { ...indexed, nextAttemptAtMillis });
674
+ return [Result.void, { ...current, events, eventIndex }];
675
+ },
676
+ ),
677
+ ).pipe(Effect.flatMap(Effect.fromResult));
678
+ yield* failpoint.hit("subscription:defer-event:after");
679
+ });
680
+
681
+ const delivery: SubscriptionStore["Service"]["delivery"] = Effect.fn(
682
+ "MemorySubscriptionStore.delivery",
683
+ )(function* (input) {
684
+ const key = yield* validate(SubscriptionDeliveryKey, input, "delivery-key");
685
+ yield* requirePartition(key.subscription, "delivery-partition");
686
+ const text = (yield* Ref.get(state)).deliveries.get(subscriptionDeliveryKeyString(key));
687
+ return text === undefined
688
+ ? null
689
+ : yield* decodeEffect(SubscriptionDelivery, text, "delivery-record");
690
+ });
691
+
692
+ const pendingDeliveries: SubscriptionStore["Service"]["pendingDeliveries"] = Effect.fn(
693
+ "MemorySubscriptionStore.pendingDeliveries",
694
+ )(function* (nowMillis, after, limit) {
695
+ const items: Array<SubscriptionDeliveryKey> = [];
696
+ for (const [storageKey, item] of (yield* Ref.get(state)).deliveryIndex) {
697
+ if (
698
+ item.state !== "delivered" &&
699
+ item.state !== "refused" &&
700
+ item.nextAttemptAtMillis <= nowMillis &&
701
+ compareScheduleNames(storageKey, after) > 0
702
+ )
703
+ items.push(item.key);
704
+ }
705
+ items.sort((a, b) =>
706
+ compareScheduleNames(subscriptionDeliveryKeyString(a), subscriptionDeliveryKeyString(b)),
707
+ );
708
+ return items.slice(0, limit);
709
+ });
710
+
711
+ const listDeliveries: SubscriptionStore["Service"]["listDeliveries"] = Effect.fn(
712
+ "MemorySubscriptionStore.listDeliveries",
713
+ )(function* (input, after, limit) {
714
+ const key = yield* requireKey(input, "list-deliveries-key");
715
+ const items: Array<SubscriptionDelivery> = [];
716
+ for (const text of (yield* Ref.get(state)).deliveries.values()) {
717
+ const item = yield* decodeEffect(SubscriptionDelivery, text, "list-delivery");
718
+ const itemKey = subscriptionDeliveryKeyString(item.key);
719
+ if (
720
+ subscriptionKeyString(item.key.subscription) === subscriptionKeyString(key) &&
721
+ compareScheduleNames(itemKey, after) > 0
722
+ )
723
+ items.push(item);
724
+ }
725
+ items.sort((a, b) =>
726
+ compareScheduleNames(
727
+ subscriptionDeliveryKeyString(a.key),
728
+ subscriptionDeliveryKeyString(b.key),
729
+ ),
730
+ );
731
+ return items.slice(0, limit);
732
+ });
733
+
734
+ const changeDelivery: SubscriptionStore["Service"]["changeDelivery"] = Effect.fn(
735
+ "MemorySubscriptionStore.changeDelivery",
736
+ )(function* (inputKey, inputDeliveryId, inputChange) {
737
+ const key = yield* validate(SubscriptionDeliveryKey, inputKey, "change-delivery-key");
738
+ const deliveryId = yield* validate(Digest, inputDeliveryId, "change-delivery-id");
739
+ const change = yield* validate(DeliveryChange, inputChange, "change-delivery-change");
740
+ yield* requirePartition(key.subscription, "change-delivery-partition");
741
+ yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:before`);
742
+ const effectiveChange =
743
+ change._tag === "Prepare"
744
+ ? { ...change, nowMillis: Math.max(change.nowMillis, yield* Clock.currentTimeMillis) }
745
+ : change;
746
+ const result = yield* Effect.uninterruptible(
747
+ Ref.modify(
748
+ state,
749
+ (
750
+ current,
751
+ ): readonly [
752
+ Result.Result<SubscriptionDelivery, SubscriptionError>,
753
+ MemorySubscriptionState,
754
+ ] => {
755
+ const storageKey = subscriptionDeliveryKeyString(key);
756
+ const text = current.deliveries.get(storageKey);
757
+ if (text === undefined) return [Result.fail(error("not-found", "delivery")), current];
758
+ const decoded = decode(SubscriptionDelivery, text, "change-delivery-record");
759
+ if (Result.isFailure(decoded)) return [decoded, current];
760
+ const registrationText = current.registrations.get(
761
+ subscriptionKeyString(key.subscription),
762
+ );
763
+ if (registrationText === undefined)
764
+ return [Result.fail(error("corrupt", "delivery-registration")), current];
765
+ const registration = decode(
766
+ SubscriptionRecord,
767
+ registrationText,
768
+ "delivery-registration",
769
+ );
770
+ if (Result.isFailure(registration)) return [Result.fail(registration.failure), current];
771
+ const transition = applySubscriptionDeliveryChange(
772
+ decoded.success,
773
+ registration.success,
774
+ deliveryId,
775
+ effectiveChange,
776
+ );
777
+ if (Result.isFailure(transition)) return [Result.fail(transition.failure), current];
778
+ if (transition.success === decoded.success)
779
+ return [Result.succeed(decoded.success), current];
780
+ const updated = transition.success;
781
+ const encoded = encode(SubscriptionDelivery, updated, "change-delivery-encode");
782
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];
783
+ const deliveries = new Map(current.deliveries);
784
+ deliveries.set(storageKey, encoded.success);
785
+ const deliveryIndex = new Map(current.deliveryIndex);
786
+ const indexed = deliveryIndex.get(storageKey);
787
+ if (indexed === undefined)
788
+ return [Result.fail(error("corrupt", "delivery-index")), current];
789
+ deliveryIndex.set(storageKey, {
790
+ ...indexed,
791
+ state: updated.state,
792
+ nextAttemptAtMillis: updated.retry.nextAttemptAtMillis,
793
+ });
794
+ return [Result.succeed(updated), { ...current, deliveries, deliveryIndex }];
795
+ },
796
+ ),
797
+ ).pipe(Effect.flatMap(Effect.fromResult));
798
+ yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:after`);
799
+ return result;
800
+ });
801
+
802
+ const recovering: SubscriptionStore["Service"]["recovering"] = Effect.fn(
803
+ "MemorySubscriptionStore.recovering",
804
+ )(function* (nowMillis, after, limit) {
805
+ const records: Array<{ readonly key: SubscriptionKey; readonly ordinal: number }> = [];
806
+ for (const item of (yield* Ref.get(state)).registrationIndex.values()) {
807
+ if (
808
+ item.ordinal > after &&
809
+ item.state === "active" &&
810
+ item.recoveryAt !== null &&
811
+ item.recoveryAt <= nowMillis
812
+ )
813
+ records.push({ key: item.key, ordinal: item.ordinal });
814
+ }
815
+ records.sort((a, b) => a.ordinal - b.ordinal);
816
+ return records.slice(0, limit);
817
+ });
818
+
819
+ const deferRecovery: SubscriptionStore["Service"]["deferRecovery"] = Effect.fn(
820
+ "MemorySubscriptionStore.deferRecovery",
821
+ )(function* (input, recovery) {
822
+ const key = yield* requireKey(input, "defer-recovery-key");
823
+ yield* failpoint.hit("subscription:defer-recovery:before");
824
+ yield* Effect.uninterruptible(
825
+ Ref.modify(
826
+ state,
827
+ (current): readonly [Result.Result<void, SubscriptionError>, MemorySubscriptionState] => {
828
+ const storageKey = subscriptionKeyString(key);
829
+ const text = current.registrations.get(storageKey);
830
+ if (text === undefined) return [Result.fail(error("not-found", "subscription")), current];
831
+ const record = decode(SubscriptionRecord, text, "defer-recovery-record");
832
+ if (Result.isFailure(record)) return [Result.fail(record.failure), current];
833
+ const updated = {
834
+ ...record.success,
835
+ recovery: record.success.state === "active" ? recovery : null,
836
+ };
837
+ const encoded = encode(SubscriptionRecord, updated, "defer-recovery-encode");
838
+ if (Result.isFailure(encoded)) return [Result.fail(encoded.failure), current];
839
+ const registrations = new Map(current.registrations);
840
+ registrations.set(storageKey, encoded.success);
841
+ const registrationIndex = new Map(current.registrationIndex);
842
+ const indexed = registrationIndex.get(storageKey);
843
+ if (indexed === undefined)
844
+ return [Result.fail(error("corrupt", "recovery-index")), current];
845
+ registrationIndex.set(storageKey, {
846
+ ...indexed,
847
+ recoveryAt: updated.recovery?.nextAttemptAtMillis ?? null,
848
+ });
849
+ return [Result.void, { ...current, registrations, registrationIndex }];
850
+ },
851
+ ),
852
+ ).pipe(Effect.flatMap(Effect.fromResult));
853
+ yield* failpoint.hit("subscription:defer-recovery:after");
854
+ });
855
+
856
+ const readScanCursors: SubscriptionStore["Service"]["readScanCursors"] = Ref.get(state).pipe(
857
+ Effect.map((current) => current.scanCursors),
858
+ );
859
+
860
+ const advanceScanCursors: SubscriptionStore["Service"]["advanceScanCursors"] = Effect.fn(
861
+ "MemorySubscriptionStore.advanceScanCursors",
862
+ )(function* (input) {
863
+ const cursors = yield* validate(SubscriptionScanCursors, input, "scan-cursors");
864
+ yield* failpoint.hit("subscription:advance-scan-cursors:before");
865
+ yield* Effect.uninterruptible(
866
+ Ref.update(state, (current) => ({ ...current, scanCursors: cursors })),
867
+ );
868
+ yield* failpoint.hit("subscription:advance-scan-cursors:after");
869
+ });
870
+
871
+ const nextDeadline = Effect.gen(function* () {
872
+ let deadline: number | null = null;
873
+ const current = yield* Ref.get(state);
874
+ if (
875
+ current.scanCursors.events !== "" ||
876
+ current.scanCursors.deliveries !== "" ||
877
+ current.scanCursors.recovery !== 0
878
+ )
879
+ return 0;
880
+ const consider = (value: number) => {
881
+ if (deadline === null || value < deadline) deadline = value;
882
+ };
883
+ for (const accepted of current.eventIndex.values())
884
+ if (!accepted.routingComplete) consider(accepted.nextAttemptAtMillis);
885
+ for (const item of current.deliveryIndex.values())
886
+ if (item.state !== "delivered" && item.state !== "refused")
887
+ consider(item.nextAttemptAtMillis);
888
+ for (const record of current.registrationIndex.values())
889
+ if (record.state === "active" && record.recoveryAt !== null) consider(record.recoveryAt);
890
+ return deadline;
891
+ }).pipe(Effect.withSpan("MemorySubscriptionStore.nextDeadline"));
892
+
893
+ return SubscriptionStore.of({
894
+ partition,
895
+ register,
896
+ get,
897
+ list,
898
+ cancel,
899
+ accept,
900
+ event,
901
+ pendingEvents,
902
+ candidates,
903
+ select,
904
+ catchUp,
905
+ deferEvent,
906
+ delivery,
907
+ pendingDeliveries,
908
+ listDeliveries,
909
+ changeDelivery,
910
+ recovering,
911
+ deferRecovery,
912
+ readScanCursors,
913
+ advanceScanCursors,
914
+ nextDeadline,
915
+ });
916
+ });
917
+
918
+ export const memorySubscriptionStoreLayer = (
919
+ partition: SourcePartition,
920
+ ): Layer.Layer<SubscriptionStore, SubscriptionError> =>
921
+ Layer.effect(SubscriptionStore, makeMemorySubscriptionStore(partition));