@yielded/agent-storage-memory 0.1.0-beta.166

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,373 @@
1
+ import { ThreadId } from "@yielded/agent/identifiers";
2
+ import {
3
+ applyMessageDeliveryChange,
4
+ defaultMessageDeliveryStoreLimits,
5
+ MessageDeliveryChange,
6
+ MessageDeliveryError,
7
+ MessageDeliveryFailpoint,
8
+ MessageDeliveryKey,
9
+ MessageDeliveryPageRequest,
10
+ MessageDeliveryRecord,
11
+ MessageDeliveryStore,
12
+ MessageDeliveryStoreLimits,
13
+ messageDeliveryDeadline,
14
+ messageDeliveryKeyString,
15
+ messageDeliveryUsesCapacity,
16
+ isWorkerUpdateDelivery,
17
+ messageDeliveryCapacity,
18
+ sameMessageDeliveryIdentity,
19
+ validateMessageDelivery,
20
+ } from "@yielded/agent/message-delivery";
21
+ import { ScheduleInstant } from "@yielded/agent/schedule";
22
+ import { Effect, Layer, Ref, Schema, Semaphore } from "effect";
23
+
24
+ const codec = Schema.fromJsonString(MessageDeliveryRecord);
25
+
26
+ const decode = (text: string) =>
27
+ Schema.decodeEffect(codec)(text).pipe(
28
+ Effect.mapError(() => MessageDeliveryError.make({ reason: "corrupt", operation: "decode" })),
29
+ );
30
+
31
+ const Scan = Schema.Struct({
32
+ nowMillis: ScheduleInstant,
33
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),
34
+ ownerThreadId: Schema.optionalKey(ThreadId),
35
+ });
36
+
37
+ export interface MemoryMessageDeliveryStoreOptions {
38
+ /** UTF-8 bound on the complete stored record, including a processed Settlement. */
39
+ readonly maxStoredValueBytes?: number;
40
+ }
41
+
42
+ /** Reference adapter. All retained rows are bounded; completed deduplication evidence is never evicted. */
43
+ export const memoryMessageDeliveryStoreLayer = (
44
+ limits: MessageDeliveryStoreLimits = defaultMessageDeliveryStoreLimits,
45
+ options: MemoryMessageDeliveryStoreOptions = {},
46
+ ): Layer.Layer<MessageDeliveryStore, MessageDeliveryError> =>
47
+ Layer.effect(
48
+ MessageDeliveryStore,
49
+ Effect.gen(function* () {
50
+ const config = yield* validateMessageDelivery(MessageDeliveryStoreLimits, limits, "limits");
51
+
52
+ const maxStoredValueBytes = yield* validateMessageDelivery(
53
+ Schema.Int.check(Schema.isGreaterThan(0)),
54
+ options.maxStoredValueBytes ?? 16 * 1_024 * 1_024,
55
+ "stored-value-limit",
56
+ );
57
+
58
+ const state = yield* Ref.make({
59
+ records: new Map<string, string>(),
60
+ pending: new Map<ThreadId, ReadonlySet<MessageDeliveryKey["messageId"]>>(),
61
+ workers: new Map<string, ReadonlySet<MessageDeliveryKey["messageId"]>>(),
62
+ });
63
+
64
+ const commit = (record: MessageDeliveryRecord, encoded: string) =>
65
+ Ref.update(state, (current) => {
66
+ const key = messageDeliveryKeyString(record.key);
67
+ const keys = new Set(current.pending.get(record.key.ownerThreadId));
68
+
69
+ if (messageDeliveryUsesCapacity(record)) keys.add(record.key.messageId);
70
+ else keys.delete(record.key.messageId);
71
+ const pending = new Map(current.pending);
72
+
73
+ if (keys.size === 0) pending.delete(record.key.ownerThreadId);
74
+ else pending.set(record.key.ownerThreadId, keys);
75
+
76
+ const workers = new Map(current.workers);
77
+ const admission = record.envelope.workerAdmission;
78
+
79
+ if (admission !== undefined) {
80
+ const worker = admission.origin.worker;
81
+
82
+ const startKey = JSON.stringify([
83
+ record.key.ownerThreadId,
84
+ worker.delegationId,
85
+ worker.targetAgentId,
86
+ ]);
87
+
88
+ if (record.key.messageId === admission.origin.firstMessageId)
89
+ workers.set(
90
+ startKey,
91
+ new Set([...(workers.get(startKey) ?? []), record.key.messageId]),
92
+ );
93
+ const pendingKey = JSON.stringify([record.key.ownerThreadId, worker.threadId]);
94
+ const inputs = new Set(workers.get(pendingKey));
95
+
96
+ if (
97
+ (record.status === "pending" || record.status === "parked") &&
98
+ record.receipt === null
99
+ )
100
+ inputs.add(record.key.messageId);
101
+ else inputs.delete(record.key.messageId);
102
+ workers.set(pendingKey, inputs);
103
+ }
104
+
105
+ return { records: new Map(current.records).set(key, encoded), pending, workers };
106
+ });
107
+
108
+ const lock = yield* Semaphore.make(1);
109
+ const failpoint = yield* MessageDeliveryFailpoint;
110
+
111
+ const encode = Effect.fn("MemoryMessageDeliveryStore.encode")(function* (
112
+ record: MessageDeliveryRecord,
113
+ ) {
114
+ const text = yield* Schema.encodeEffect(codec)(record).pipe(
115
+ Effect.mapError(() =>
116
+ MessageDeliveryError.make({ reason: "corrupt", operation: "encode" }),
117
+ ),
118
+ );
119
+
120
+ if (new TextEncoder().encode(text).byteLength > maxStoredValueBytes) {
121
+ return yield* MessageDeliveryError.make({
122
+ reason: "capacity",
123
+ operation: "stored-value-bytes",
124
+ });
125
+ }
126
+
127
+ return text;
128
+ });
129
+
130
+ const all = Effect.fn("MemoryMessageDeliveryStore.all")(function* () {
131
+ return yield* Effect.forEach((yield* Ref.get(state)).records.values(), decode);
132
+ });
133
+
134
+ const insert: MessageDeliveryStore["Service"]["insert"] = Effect.fn(
135
+ "MemoryMessageDeliveryStore.insert",
136
+ )(function* (record) {
137
+ const encoded = yield* encode(record);
138
+ const input = yield* decode(encoded);
139
+
140
+ if (
141
+ input.version !== 1 ||
142
+ input.status !== "pending" ||
143
+ input.leaseUntilMillis !== null ||
144
+ input.retry.attempts !== 0 ||
145
+ input.retry.generation !== 0 ||
146
+ input.retry.automaticAttempts !== 0 ||
147
+ input.retry.nextAttemptAtMillis !== input.createdAtMillis ||
148
+ input.retry.lastAttemptAtMillis !== null ||
149
+ input.retry.lastFailure !== null ||
150
+ input.deadlineAtMillis !== input.initialDeadlineAtMillis
151
+ ) {
152
+ return yield* MessageDeliveryError.make({
153
+ reason: "validation",
154
+ operation: "insert-state",
155
+ });
156
+ }
157
+ if (
158
+ new TextEncoder().encode(JSON.stringify(input.envelope)).byteLength >
159
+ config.maxEnvelopeBytes
160
+ ) {
161
+ return yield* MessageDeliveryError.make({
162
+ reason: "capacity",
163
+ operation: "envelope-bytes",
164
+ });
165
+ }
166
+ yield* failpoint.hit("message-delivery:insert:before");
167
+
168
+ const inserted = yield* lock.withPermit(
169
+ Effect.uninterruptible(
170
+ Effect.gen(function* () {
171
+ const { records } = yield* Ref.get(state);
172
+ const key = messageDeliveryKeyString(input.key);
173
+ const existingText = records.get(key);
174
+
175
+ if (existingText !== undefined) {
176
+ const existing = yield* decode(existingText);
177
+
178
+ if (!sameMessageDeliveryIdentity(existing, input))
179
+ return yield* MessageDeliveryError.make({
180
+ reason: "conflict",
181
+ operation: "insert",
182
+ });
183
+
184
+ return existing;
185
+ }
186
+
187
+ const owned = (yield* all()).filter(
188
+ (record) =>
189
+ record.key.ownerThreadId === input.key.ownerThreadId &&
190
+ isWorkerUpdateDelivery(record) === isWorkerUpdateDelivery(input),
191
+ );
192
+
193
+ const capacity = messageDeliveryCapacity(config, isWorkerUpdateDelivery(input));
194
+
195
+ if (
196
+ owned.length >= capacity.retained ||
197
+ owned.filter(messageDeliveryUsesCapacity).length >= capacity.pending
198
+ ) {
199
+ return yield* MessageDeliveryError.make({
200
+ reason: "capacity",
201
+ operation: "insert",
202
+ });
203
+ }
204
+ yield* commit(input, encoded);
205
+
206
+ return input;
207
+ }),
208
+ ),
209
+ );
210
+
211
+ yield* failpoint.hit("message-delivery:insert:after");
212
+
213
+ return yield* decode(yield* encode(inserted));
214
+ });
215
+
216
+ const get: MessageDeliveryStore["Service"]["get"] = Effect.fn(
217
+ "MemoryMessageDeliveryStore.get",
218
+ )(function* (key) {
219
+ const input = yield* validateMessageDelivery(MessageDeliveryKey, key, "get");
220
+ const text = (yield* Ref.get(state)).records.get(messageDeliveryKeyString(input));
221
+
222
+ return text === undefined ? null : yield* decode(text);
223
+ });
224
+
225
+ const change: MessageDeliveryStore["Service"]["change"] = Effect.fn(
226
+ "MemoryMessageDeliveryStore.change",
227
+ )(function* (key, change) {
228
+ const input = yield* validateMessageDelivery(MessageDeliveryChange, change, "change");
229
+ const decodedKey = yield* validateMessageDelivery(MessageDeliveryKey, key, "change");
230
+ const point = `message-delivery:${input._tag.toLowerCase()}`;
231
+
232
+ yield* failpoint.hit(`${point}:before`);
233
+
234
+ const changed = yield* lock.withPermit(
235
+ Effect.uninterruptible(
236
+ Effect.gen(function* () {
237
+ const existing = yield* get(decodedKey);
238
+
239
+ if (existing === null)
240
+ return yield* MessageDeliveryError.make({
241
+ reason: "not-found",
242
+ operation: "change",
243
+ });
244
+ const next = yield* Effect.fromResult(applyMessageDeliveryChange(existing, input));
245
+ const encoded = yield* encode(next);
246
+
247
+ yield* commit(next, encoded);
248
+
249
+ return next;
250
+ }),
251
+ ),
252
+ );
253
+
254
+ yield* failpoint.hit(`${point}:after`);
255
+
256
+ return yield* decode(yield* encode(changed));
257
+ });
258
+
259
+ return MessageDeliveryStore.of({
260
+ limits: config,
261
+ maxStoredValueBytes,
262
+ insert,
263
+ get,
264
+ change,
265
+ list: Effect.fn("MemoryMessageDeliveryStore.list")(function* (request) {
266
+ const input = yield* validateMessageDelivery(MessageDeliveryPageRequest, request, "list");
267
+
268
+ const current = yield* Ref.get(state);
269
+
270
+ const workerKey =
271
+ input.workerStarts !== undefined
272
+ ? JSON.stringify([
273
+ input.ownerThreadId,
274
+ input.workerStarts.delegationId,
275
+ input.workerStarts.targetAgentId,
276
+ ])
277
+ : input.pendingWorker !== undefined
278
+ ? JSON.stringify([input.ownerThreadId, input.pendingWorker])
279
+ : undefined;
280
+
281
+ const retained =
282
+ workerKey !== undefined || input.pendingOnly
283
+ ? yield* Effect.forEach(
284
+ [
285
+ ...((workerKey === undefined
286
+ ? current.pending.get(input.ownerThreadId)
287
+ : current.workers.get(workerKey)) ?? []),
288
+ ]
289
+ .filter((messageId) => input.after === undefined || messageId > input.after)
290
+ .sort()
291
+ .slice(0, input.limit + 1),
292
+ (messageId) =>
293
+ decode(
294
+ current.records.get(
295
+ messageDeliveryKeyString({ ownerThreadId: input.ownerThreadId, messageId }),
296
+ ) ?? "",
297
+ ),
298
+ )
299
+ : yield* all();
300
+
301
+ const records = retained
302
+ .filter(
303
+ (record) =>
304
+ record.key.ownerThreadId === input.ownerThreadId &&
305
+ (input.after === undefined || record.key.messageId > input.after),
306
+ )
307
+ .sort((left, right) =>
308
+ left.key.messageId < right.key.messageId
309
+ ? -1
310
+ : left.key.messageId > right.key.messageId
311
+ ? 1
312
+ : 0,
313
+ );
314
+
315
+ const items = records.slice(0, input.limit);
316
+
317
+ return {
318
+ items,
319
+ next: records.length > input.limit ? (items.at(-1)?.key.messageId ?? null) : null,
320
+ };
321
+ }),
322
+ due: Effect.fn("MemoryMessageDeliveryStore.due")(
323
+ function* (nowMillis, limit, ownerThreadId) {
324
+ const input = yield* validateMessageDelivery(
325
+ Scan,
326
+ { nowMillis, limit, ...(ownerThreadId === undefined ? {} : { ownerThreadId }) },
327
+ "due",
328
+ );
329
+
330
+ return (yield* all())
331
+ .flatMap((record) => {
332
+ const deadline = messageDeliveryDeadline(record);
333
+
334
+ return deadline !== null &&
335
+ deadline <= input.nowMillis &&
336
+ (input.ownerThreadId === undefined ||
337
+ input.ownerThreadId === record.key.ownerThreadId)
338
+ ? [{ key: record.key, deadline }]
339
+ : [];
340
+ })
341
+ .sort(
342
+ (left, right) =>
343
+ left.deadline - right.deadline ||
344
+ (messageDeliveryKeyString(left.key) < messageDeliveryKeyString(right.key)
345
+ ? -1
346
+ : 1),
347
+ )
348
+ .slice(0, input.limit)
349
+ .map((record) => record.key);
350
+ },
351
+ ),
352
+ nextDeadline: Effect.fn("MemoryMessageDeliveryStore.nextDeadline")(
353
+ function* (ownerThreadId) {
354
+ if (ownerThreadId !== undefined)
355
+ yield* validateMessageDelivery(ThreadId, ownerThreadId, "nextDeadline");
356
+ let next: number | null = null;
357
+
358
+ for (const record of yield* all()) {
359
+ if (ownerThreadId !== undefined && ownerThreadId !== record.key.ownerThreadId)
360
+ continue;
361
+ const deadline = messageDeliveryDeadline(record);
362
+
363
+ if (deadline !== null && (next === null || deadline < next)) next = deadline;
364
+ }
365
+
366
+ return next;
367
+ },
368
+ ),
369
+ });
370
+ }),
371
+ );
372
+
373
+ export const MemoryMessageDeliveryStoreLive = memoryMessageDeliveryStoreLayer();
@@ -0,0 +1,328 @@
1
+ import {
2
+ ScheduleCapacityError,
3
+ ScheduleDueCursor,
4
+ defaultSchedulingLimits,
5
+ ScheduleChange,
6
+ ScheduleConflict,
7
+ ScheduleFailpoint,
8
+ ScheduleKey,
9
+ ScheduleNotFound,
10
+ ScheduleOwner,
11
+ SchedulePageRequest,
12
+ ScheduleRecord,
13
+ ScheduleStorageError,
14
+ ScheduleStore,
15
+ } from "@yielded/agent/schedule";
16
+ import {
17
+ scheduleUsesCapacity,
18
+ applyScheduleChange,
19
+ compareScheduleKeys,
20
+ compareScheduleNames,
21
+ scheduleDeadline,
22
+ scheduleKeyString,
23
+ scheduleKeyOf,
24
+ scheduleOwnerKey,
25
+ } from "@yielded/agent/schedule-transition";
26
+ import { Effect, Layer, Ref, Result, Schema } from "effect";
27
+
28
+ interface MemoryScheduleState {
29
+ readonly records: ReadonlyMap<string, string>;
30
+ }
31
+
32
+ const storageError = (operation: string, reason: "unavailable" | "corrupt") =>
33
+ ScheduleStorageError.make({ operation, reason });
34
+
35
+ const encodeRecord = (operation: string, record: ScheduleRecord) =>
36
+ Effect.try({
37
+ try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(record),
38
+ catch: () => storageError(operation, "corrupt"),
39
+ });
40
+
41
+ const decodeRecord = (operation: string, encoded: string) =>
42
+ Effect.try({
43
+ try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(encoded),
44
+ catch: () => storageError(operation, "corrupt"),
45
+ });
46
+
47
+ const decodeInput = <A, I>(operation: string, schema: Schema.Codec<A, I>, value: unknown) =>
48
+ Effect.try({
49
+ try: () => Schema.decodeUnknownSync(schema)(value),
50
+ catch: () => storageError(operation, "corrupt"),
51
+ });
52
+
53
+ const sameOwner = (record: ScheduleRecord, owner: ScheduleOwner): boolean =>
54
+ scheduleOwnerKey(record.owner) === scheduleOwnerKey(owner);
55
+
56
+ const makeScheduleStore = Effect.gen(function* () {
57
+ const state = yield* Ref.make<MemoryScheduleState>({ records: new Map() });
58
+ const failpoint = yield* ScheduleFailpoint;
59
+
60
+ const insert: ScheduleStore["Service"]["insert"] = Effect.fn("MemoryScheduleStore.insert")(
61
+ (record, ownerLimit) =>
62
+ Effect.gen(function* () {
63
+ const encoded = yield* encodeRecord("insert", record);
64
+
65
+ yield* failpoint.hit("schedule:insert:before");
66
+
67
+ const decision = yield* Effect.uninterruptible(
68
+ Ref.modify(
69
+ state,
70
+ (
71
+ current,
72
+ ): readonly [
73
+ Result.Result<
74
+ ScheduleRecord,
75
+ ScheduleConflict | ScheduleCapacityError | ScheduleStorageError
76
+ >,
77
+ MemoryScheduleState,
78
+ ] => {
79
+ const key = scheduleKeyString(record);
80
+ const existingText = current.records.get(key);
81
+
82
+ if (existingText !== undefined) {
83
+ const decoded = Result.try({
84
+ try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(existingText),
85
+ catch: () => storageError("insert", "corrupt"),
86
+ });
87
+
88
+ if (Result.isFailure(decoded)) {
89
+ return [Result.fail(decoded.failure), current];
90
+ }
91
+ if (decoded.success.creationFingerprint === record.creationFingerprint) {
92
+ return [Result.succeed(decoded.success), current];
93
+ }
94
+
95
+ return [
96
+ Result.fail(
97
+ ScheduleConflict.make({ reason: "creation", key: scheduleKeyOf(record) }),
98
+ ),
99
+ current,
100
+ ];
101
+ }
102
+
103
+ let ownerCount = 0;
104
+
105
+ for (const text of current.records.values()) {
106
+ const decoded = Result.try({
107
+ try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),
108
+ catch: () => storageError("insert", "corrupt"),
109
+ });
110
+
111
+ if (Result.isFailure(decoded)) {
112
+ return [Result.fail(decoded.failure), current];
113
+ }
114
+ if (
115
+ sameOwner(decoded.success, record.owner) &&
116
+ scheduleUsesCapacity(decoded.success)
117
+ )
118
+ ownerCount += 1;
119
+ }
120
+ if (ownerCount >= ownerLimit) {
121
+ return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];
122
+ }
123
+ const records = new Map(current.records);
124
+
125
+ records.set(key, encoded);
126
+ const next = { records };
127
+
128
+ return [Result.succeed(record), next];
129
+ },
130
+ ),
131
+ );
132
+
133
+ const inserted = yield* Effect.fromResult(decision);
134
+
135
+ yield* failpoint.hit("schedule:insert:after");
136
+
137
+ return yield* decodeRecord("insert", yield* encodeRecord("insert", inserted));
138
+ }),
139
+ );
140
+
141
+ const get: ScheduleStore["Service"]["get"] = Effect.fn("MemoryScheduleStore.get")(
142
+ function* (key) {
143
+ const decodedKey = yield* decodeInput("get", ScheduleKey, key);
144
+ const text = (yield* Ref.get(state)).records.get(scheduleKeyString(decodedKey));
145
+
146
+ return text === undefined ? null : yield* decodeRecord("get", text);
147
+ },
148
+ );
149
+
150
+ const list: ScheduleStore["Service"]["list"] = Effect.fn("MemoryScheduleStore.list")(
151
+ function* (request) {
152
+ const decodedRequest = yield* decodeInput("list", SchedulePageRequest, request);
153
+ const records: Array<ScheduleRecord> = [];
154
+
155
+ for (const text of (yield* Ref.get(state)).records.values()) {
156
+ const record = yield* decodeRecord("list", text);
157
+
158
+ if (
159
+ sameOwner(record, decodedRequest.owner) &&
160
+ (decodedRequest.after === undefined ||
161
+ compareScheduleNames(record.scheduleId, decodedRequest.after) > 0)
162
+ ) {
163
+ records.push(record);
164
+ }
165
+ }
166
+ records.sort((left, right) => compareScheduleNames(left.scheduleId, right.scheduleId));
167
+ const hasNext = records.length > decodedRequest.limit;
168
+ const items = records.slice(0, decodedRequest.limit);
169
+
170
+ return {
171
+ items,
172
+ next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null,
173
+ };
174
+ },
175
+ );
176
+
177
+ const change: ScheduleStore["Service"]["change"] = Effect.fn("MemoryScheduleStore.change")(
178
+ (key, command, ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner) =>
179
+ Effect.gen(function* () {
180
+ const decodedKey = yield* decodeInput("change", ScheduleKey, key);
181
+ const decodedCommand = yield* decodeInput("change", ScheduleChange, command);
182
+
183
+ yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:before`);
184
+
185
+ const decision = yield* Effect.uninterruptible(
186
+ Ref.modify(
187
+ state,
188
+ (
189
+ current,
190
+ ): readonly [
191
+ Result.Result<
192
+ ScheduleRecord,
193
+ ScheduleConflict | ScheduleStorageError | ScheduleNotFound | ScheduleCapacityError
194
+ >,
195
+ MemoryScheduleState,
196
+ ] => {
197
+ const storageKey = scheduleKeyString(decodedKey);
198
+ const text = current.records.get(storageKey);
199
+
200
+ if (text === undefined) {
201
+ return [Result.fail(ScheduleNotFound.make({ key: decodedKey })), current];
202
+ }
203
+
204
+ const decoded = Result.try({
205
+ try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),
206
+ catch: () => storageError("change", "corrupt"),
207
+ });
208
+
209
+ if (Result.isFailure(decoded)) {
210
+ return [Result.fail(decoded.failure), current];
211
+ }
212
+ const applied = applyScheduleChange(decoded.success, decodedCommand);
213
+
214
+ if (Result.isFailure(applied)) {
215
+ return [Result.fail(applied.failure), current];
216
+ }
217
+ if (applied.success === decoded.success) {
218
+ return [Result.succeed(decoded.success), current];
219
+ }
220
+ if (!scheduleUsesCapacity(decoded.success) && scheduleUsesCapacity(applied.success)) {
221
+ let count = 0;
222
+
223
+ for (const text of current.records.values()) {
224
+ const candidate = Schema.decodeResult(Schema.fromJsonString(ScheduleRecord))(
225
+ text,
226
+ );
227
+
228
+ if (Result.isFailure(candidate))
229
+ return [Result.fail(storageError("change", "corrupt")), current];
230
+ if (
231
+ sameOwner(candidate.success, decodedKey.owner) &&
232
+ scheduleUsesCapacity(candidate.success)
233
+ )
234
+ count += 1;
235
+ }
236
+ if (count >= ownerLimit)
237
+ return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];
238
+ }
239
+
240
+ const encoded = Result.try({
241
+ try: () =>
242
+ Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(applied.success),
243
+ catch: () => storageError("change", "corrupt"),
244
+ });
245
+
246
+ if (Result.isFailure(encoded)) {
247
+ return [Result.fail(encoded.failure), current];
248
+ }
249
+ const records = new Map(current.records);
250
+
251
+ records.set(storageKey, encoded.success);
252
+ const next = { records };
253
+
254
+ return [Result.succeed(applied.success), next];
255
+ },
256
+ ),
257
+ );
258
+
259
+ const changed = yield* Effect.fromResult(decision);
260
+
261
+ yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:after`);
262
+
263
+ return yield* decodeRecord("change", yield* encodeRecord("change", changed));
264
+ }),
265
+ );
266
+
267
+ const due: ScheduleStore["Service"]["due"] = Effect.fn("MemoryScheduleStore.due")(
268
+ function* (nowMillis, limit, owner, after) {
269
+ const decodedOwner =
270
+ owner === undefined ? undefined : yield* decodeInput("due", ScheduleOwner, owner);
271
+
272
+ const cursor =
273
+ after === undefined ? undefined : yield* decodeInput("due", ScheduleDueCursor, after);
274
+
275
+ const records: Array<ScheduleDueCursor> = [];
276
+
277
+ for (const text of (yield* Ref.get(state)).records.values()) {
278
+ const record = yield* decodeRecord("due", text);
279
+ const deadline = scheduleDeadline(record);
280
+
281
+ if (
282
+ deadline !== null &&
283
+ deadline <= nowMillis &&
284
+ (decodedOwner === undefined || sameOwner(record, decodedOwner)) &&
285
+ (cursor === undefined ||
286
+ deadline > cursor.deadlineAtMillis ||
287
+ (deadline === cursor.deadlineAtMillis && compareScheduleKeys(record, cursor) > 0))
288
+ ) {
289
+ records.push({ ...scheduleKeyOf(record), deadlineAtMillis: deadline });
290
+ }
291
+ }
292
+ records.sort((left, right) => {
293
+ const byDeadline = left.deadlineAtMillis - right.deadlineAtMillis;
294
+
295
+ return byDeadline !== 0 ? byDeadline : compareScheduleKeys(left, right);
296
+ });
297
+
298
+ return records.slice(0, limit);
299
+ },
300
+ );
301
+
302
+ const nextDeadline: ScheduleStore["Service"]["nextDeadline"] = Effect.fn(
303
+ "MemoryScheduleStore.nextDeadline",
304
+ )(function* (owner) {
305
+ const decodedOwner =
306
+ owner === undefined ? undefined : yield* decodeInput("nextDeadline", ScheduleOwner, owner);
307
+
308
+ let earliest: number | null = null;
309
+
310
+ for (const text of (yield* Ref.get(state)).records.values()) {
311
+ const record = yield* decodeRecord("nextDeadline", text);
312
+
313
+ if (decodedOwner !== undefined && !sameOwner(record, decodedOwner)) continue;
314
+ const deadline = scheduleDeadline(record);
315
+
316
+ if (deadline !== null && (earliest === null || deadline < earliest)) earliest = deadline;
317
+ }
318
+
319
+ return earliest;
320
+ });
321
+
322
+ return ScheduleStore.of({ insert, get, list, change, due, nextDeadline });
323
+ });
324
+
325
+ export const memoryScheduleStoreLayer = (): Layer.Layer<ScheduleStore> =>
326
+ Layer.effect(ScheduleStore, makeScheduleStore);
327
+
328
+ export const MemoryScheduleStoreLive: Layer.Layer<ScheduleStore> = memoryScheduleStoreLayer();