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