@effect-agent/storage-cloudflare 0.1.0-beta.35 → 0.1.0-beta.37
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.
- package/dist/index.d.mts +31 -2
- package/dist/index.mjs +394 -38
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- package/src/do-ledger.ts +5 -4
- package/src/do-schedule-store.ts +530 -0
- package/src/index.ts +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@effect-agent/storage-cloudflare",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.37",
|
|
4
4
|
"exports": {
|
|
5
5
|
".": {
|
|
6
6
|
"types": "./dist/index.d.mts",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
}
|
|
9
9
|
},
|
|
10
10
|
"dependencies": {
|
|
11
|
-
"@effect-agent/session": "0.1.0-beta.
|
|
11
|
+
"@effect-agent/session": "0.1.0-beta.37",
|
|
12
12
|
"@effect/platform-browser": "4.0.0-rc.111",
|
|
13
13
|
"@effect/sql-sqlite-do": "4.0.0-rc.111",
|
|
14
14
|
"effect": "4.0.0-rc.111"
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@cloudflare/vitest-pool-workers": "0.21.3",
|
|
37
37
|
"@cloudflare/workers-types": "5.20260825.1",
|
|
38
|
-
"@effect-agent/testing": "0.1.0-beta.
|
|
38
|
+
"@effect-agent/testing": "0.1.0-beta.35",
|
|
39
39
|
"@effect/vitest": "4.0.0-rc.111",
|
|
40
40
|
"typescript": "7.0.2",
|
|
41
41
|
"vite-plus": "0.2.6",
|
package/src/do-ledger.ts
CHANGED
|
@@ -1210,14 +1210,15 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
1210
1210
|
if (heads.length === 0) return Option.none<Claim>();
|
|
1211
1211
|
const head = heads[0];
|
|
1212
1212
|
|
|
1213
|
-
//
|
|
1214
|
-
//
|
|
1215
|
-
//
|
|
1213
|
+
// Unknown work is claimable only for a durably requested abort: the coordinator
|
|
1214
|
+
// cleans up children and settles without replaying ordinary Tools. Read the intent
|
|
1215
|
+
// in this claim transaction; retain uncertainty evidence and all ownership fencing.
|
|
1216
1216
|
if (
|
|
1217
1217
|
head.state === "joining" ||
|
|
1218
1218
|
head.state === "joined" ||
|
|
1219
1219
|
head.state === "suspended" ||
|
|
1220
|
-
head.state === "unknown"
|
|
1220
|
+
(head.state === "unknown" &&
|
|
1221
|
+
Option.isNone(yield* readAbortIntent(operation, head.submission_id)))
|
|
1221
1222
|
) {
|
|
1222
1223
|
return Option.none<Claim>();
|
|
1223
1224
|
}
|
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
import {
|
|
2
|
+
applyScheduleChange,
|
|
3
|
+
ScheduleCapacityError,
|
|
4
|
+
ScheduleDueCursor,
|
|
5
|
+
defaultSchedulingLimits,
|
|
6
|
+
scheduleUsesCapacity,
|
|
7
|
+
ScheduleChange,
|
|
8
|
+
ScheduleConflict,
|
|
9
|
+
scheduleDeadline,
|
|
10
|
+
ScheduleFailpoint,
|
|
11
|
+
type ScheduleFailpointError,
|
|
12
|
+
ScheduleKey,
|
|
13
|
+
ScheduleId,
|
|
14
|
+
ScheduleInstant,
|
|
15
|
+
ScheduleNotFound,
|
|
16
|
+
ScheduleOwner,
|
|
17
|
+
type SchedulePage,
|
|
18
|
+
SchedulePageRequest,
|
|
19
|
+
ScheduleRecord,
|
|
20
|
+
ScheduleStorageError,
|
|
21
|
+
ScheduleStore,
|
|
22
|
+
} from "@effect-agent/session";
|
|
23
|
+
import { Context, Effect, Layer, Result, Schema } from "effect";
|
|
24
|
+
import * as SqlClientService from "effect/unstable/sql/SqlClient";
|
|
25
|
+
|
|
26
|
+
const CURRENT_SCHEDULE_STORE_VERSION = 1;
|
|
27
|
+
const MAX_STORED_SCHEDULE_BYTES = 1_900_000;
|
|
28
|
+
|
|
29
|
+
const StoredScheduleJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_SCHEDULE_BYTES));
|
|
30
|
+
const StoredDeadline = Schema.NullOr(ScheduleInstant);
|
|
31
|
+
|
|
32
|
+
class ScheduleRow extends Schema.Class<ScheduleRow>("@effect-agent/storage-cloudflare/ScheduleRow")(
|
|
33
|
+
{
|
|
34
|
+
tenant_id: ScheduleOwner.fields.tenantId,
|
|
35
|
+
owner_id: ScheduleOwner.fields.ownerId,
|
|
36
|
+
schedule_id: ScheduleId,
|
|
37
|
+
deadline_at_millis: StoredDeadline,
|
|
38
|
+
record_json: StoredScheduleJson,
|
|
39
|
+
},
|
|
40
|
+
) {}
|
|
41
|
+
|
|
42
|
+
const ScheduleDueRow = Schema.Struct({
|
|
43
|
+
tenant_id: ScheduleOwner.fields.tenantId,
|
|
44
|
+
owner_id: ScheduleOwner.fields.ownerId,
|
|
45
|
+
schedule_id: ScheduleId,
|
|
46
|
+
deadline_at_millis: ScheduleInstant,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
class ScheduleCountRow extends Schema.Class<ScheduleCountRow>(
|
|
50
|
+
"@effect-agent/storage-cloudflare/ScheduleCountRow",
|
|
51
|
+
)({
|
|
52
|
+
schedule_count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
53
|
+
}) {}
|
|
54
|
+
|
|
55
|
+
class ScheduleDeadlineRow extends Schema.Class<ScheduleDeadlineRow>(
|
|
56
|
+
"@effect-agent/storage-cloudflare/ScheduleDeadlineRow",
|
|
57
|
+
)({
|
|
58
|
+
deadline_at_millis: StoredDeadline,
|
|
59
|
+
}) {}
|
|
60
|
+
|
|
61
|
+
class ScheduleStoreStateRow extends Schema.Class<ScheduleStoreStateRow>(
|
|
62
|
+
"@effect-agent/storage-cloudflare/ScheduleStoreStateRow",
|
|
63
|
+
)({
|
|
64
|
+
storage_version: Schema.Int.check(Schema.isGreaterThan(0)),
|
|
65
|
+
alarm_generation: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
66
|
+
}) {}
|
|
67
|
+
|
|
68
|
+
class ScheduleTableNameRow extends Schema.Class<ScheduleTableNameRow>(
|
|
69
|
+
"@effect-agent/storage-cloudflare/ScheduleTableNameRow",
|
|
70
|
+
)({
|
|
71
|
+
name: Schema.String,
|
|
72
|
+
}) {}
|
|
73
|
+
|
|
74
|
+
export interface DoScheduleAlarmReplacement {
|
|
75
|
+
readonly deadlineAtMillis: number | null;
|
|
76
|
+
/** Included in every logical alarm payload so equal-time replacement stays distinguishable. */
|
|
77
|
+
readonly generation: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type DoScheduleReplaceAlarm = (
|
|
81
|
+
replacement: DoScheduleAlarmReplacement,
|
|
82
|
+
) => Effect.Effect<void, ScheduleStorageError>;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Platform-owned transaction boundary for schedule SQL and logical alarm mutation. The callback
|
|
86
|
+
* and its `replaceAlarm` capability belong to one fiber and must not escape or fork.
|
|
87
|
+
*/
|
|
88
|
+
export class DoScheduleTransaction extends Context.Service<
|
|
89
|
+
DoScheduleTransaction,
|
|
90
|
+
{
|
|
91
|
+
readonly run: <A, E, R>(
|
|
92
|
+
body: (replaceAlarm: DoScheduleReplaceAlarm) => Effect.Effect<A, E, R>,
|
|
93
|
+
) => Effect.Effect<A, E | ScheduleStorageError, R>;
|
|
94
|
+
}
|
|
95
|
+
>()("@effect-agent/storage-cloudflare/DoScheduleTransaction") {}
|
|
96
|
+
|
|
97
|
+
/** Platform driver operations that use the same schedule-state and alarm transaction. */
|
|
98
|
+
export class DoScheduleAlarmControl extends Context.Service<
|
|
99
|
+
DoScheduleAlarmControl,
|
|
100
|
+
{
|
|
101
|
+
/** Establish a future recovery wake before cross-Object admission starts. */
|
|
102
|
+
readonly prearm: (
|
|
103
|
+
deadlineAtMillis: number,
|
|
104
|
+
) => Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;
|
|
105
|
+
/** Replace or cancel the wake from the object's authoritative indexed deadline. */
|
|
106
|
+
readonly reconcile: Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;
|
|
107
|
+
}
|
|
108
|
+
>()("@effect-agent/storage-cloudflare/DoScheduleAlarmControl") {}
|
|
109
|
+
|
|
110
|
+
const unavailable = (operation: string): ScheduleStorageError =>
|
|
111
|
+
ScheduleStorageError.make({ operation, reason: "unavailable" });
|
|
112
|
+
|
|
113
|
+
const corrupt = (operation: string): ScheduleStorageError =>
|
|
114
|
+
ScheduleStorageError.make({ operation, reason: "corrupt" });
|
|
115
|
+
|
|
116
|
+
const decodeRows = Effect.fn("DoScheduleStore.decodeRows")(function* <A, I, R>(
|
|
117
|
+
schema: Schema.Codec<A, I, R>,
|
|
118
|
+
rows: ReadonlyArray<unknown>,
|
|
119
|
+
operation: string,
|
|
120
|
+
): Effect.fn.Return<A, ScheduleStorageError, R> {
|
|
121
|
+
return yield* Schema.decodeUnknownEffect(schema)(rows).pipe(
|
|
122
|
+
Effect.mapError(() => corrupt(operation)),
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
const decodeBoundary = <A, I, R>(
|
|
127
|
+
schema: Schema.Codec<A, I, R>,
|
|
128
|
+
value: unknown,
|
|
129
|
+
operation: string,
|
|
130
|
+
): Effect.Effect<A, ScheduleStorageError, R> =>
|
|
131
|
+
Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => corrupt(operation)));
|
|
132
|
+
|
|
133
|
+
const decodeRecord = Effect.fn("DoScheduleStore.decodeRecord")(function* (
|
|
134
|
+
row: ScheduleRow,
|
|
135
|
+
): Effect.fn.Return<ScheduleRecord, ScheduleStorageError> {
|
|
136
|
+
const record = yield* Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(
|
|
137
|
+
row.record_json,
|
|
138
|
+
).pipe(Effect.mapError(() => corrupt("decode schedule")));
|
|
139
|
+
if (
|
|
140
|
+
record.owner.tenantId !== row.tenant_id ||
|
|
141
|
+
record.owner.ownerId !== row.owner_id ||
|
|
142
|
+
record.scheduleId !== row.schedule_id ||
|
|
143
|
+
scheduleDeadline(record) !== row.deadline_at_millis
|
|
144
|
+
) {
|
|
145
|
+
return yield* corrupt("decode schedule index");
|
|
146
|
+
}
|
|
147
|
+
return record;
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const encodeRecord = Effect.fn("DoScheduleStore.encodeRecord")(function* (
|
|
151
|
+
record: ScheduleRecord,
|
|
152
|
+
): Effect.fn.Return<string, ScheduleStorageError> {
|
|
153
|
+
const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(
|
|
154
|
+
Effect.mapError(() => corrupt("encode schedule")),
|
|
155
|
+
);
|
|
156
|
+
return yield* Schema.decodeUnknownEffect(StoredScheduleJson)(encoded).pipe(
|
|
157
|
+
Effect.mapError(() => corrupt("encode schedule bounds")),
|
|
158
|
+
);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const initializeScheduleStore = Effect.fn("DoScheduleStore.initialize")(function* () {
|
|
162
|
+
const sql = yield* SqlClientService.SqlClient;
|
|
163
|
+
const operation = "initialize schedule store";
|
|
164
|
+
const rawTables = yield* sql<Record<string, unknown>>`
|
|
165
|
+
SELECT name
|
|
166
|
+
FROM sqlite_master
|
|
167
|
+
WHERE type = 'table'
|
|
168
|
+
AND name IN (
|
|
169
|
+
'effect_agent_schedule_store_state',
|
|
170
|
+
'effect_agent_schedules'
|
|
171
|
+
)
|
|
172
|
+
ORDER BY name
|
|
173
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
174
|
+
const tables = yield* decodeRows(Schema.Array(ScheduleTableNameRow), rawTables, operation);
|
|
175
|
+
const hasState = tables.some((row) => row.name === "effect_agent_schedule_store_state");
|
|
176
|
+
const hasSchedules = tables.some((row) => row.name === "effect_agent_schedules");
|
|
177
|
+
|
|
178
|
+
if (!hasState) {
|
|
179
|
+
if (hasSchedules) return yield* corrupt(operation);
|
|
180
|
+
yield* sql
|
|
181
|
+
.withTransaction(
|
|
182
|
+
Effect.gen(function* () {
|
|
183
|
+
yield* sql`
|
|
184
|
+
CREATE TABLE effect_agent_schedule_store_state (
|
|
185
|
+
singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),
|
|
186
|
+
storage_version INTEGER NOT NULL,
|
|
187
|
+
alarm_generation INTEGER NOT NULL
|
|
188
|
+
)
|
|
189
|
+
`.withoutTransform;
|
|
190
|
+
yield* sql`
|
|
191
|
+
CREATE TABLE effect_agent_schedules (
|
|
192
|
+
tenant_id TEXT NOT NULL,
|
|
193
|
+
owner_id TEXT NOT NULL,
|
|
194
|
+
schedule_id TEXT NOT NULL,
|
|
195
|
+
deadline_at_millis INTEGER,
|
|
196
|
+
record_json TEXT NOT NULL,
|
|
197
|
+
PRIMARY KEY (tenant_id, owner_id, schedule_id)
|
|
198
|
+
)
|
|
199
|
+
`.withoutTransform;
|
|
200
|
+
yield* sql`
|
|
201
|
+
CREATE INDEX effect_agent_schedules_deadline
|
|
202
|
+
ON effect_agent_schedules (deadline_at_millis, tenant_id, owner_id, schedule_id)
|
|
203
|
+
WHERE deadline_at_millis IS NOT NULL
|
|
204
|
+
`.withoutTransform;
|
|
205
|
+
yield* sql`
|
|
206
|
+
CREATE INDEX effect_agent_schedules_owner_deadline
|
|
207
|
+
ON effect_agent_schedules (tenant_id, owner_id, deadline_at_millis, schedule_id)
|
|
208
|
+
WHERE deadline_at_millis IS NOT NULL
|
|
209
|
+
`.withoutTransform;
|
|
210
|
+
yield* sql`
|
|
211
|
+
INSERT INTO effect_agent_schedule_store_state (
|
|
212
|
+
singleton, storage_version, alarm_generation
|
|
213
|
+
) VALUES (1, ${CURRENT_SCHEDULE_STORE_VERSION}, 0)
|
|
214
|
+
`.withoutTransform;
|
|
215
|
+
}),
|
|
216
|
+
)
|
|
217
|
+
.pipe(Effect.mapError(() => unavailable(operation)));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (!hasSchedules) return yield* corrupt(operation);
|
|
222
|
+
const rawState = yield* sql<Record<string, unknown>>`
|
|
223
|
+
SELECT storage_version, alarm_generation
|
|
224
|
+
FROM effect_agent_schedule_store_state
|
|
225
|
+
WHERE singleton = 1
|
|
226
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
227
|
+
const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);
|
|
228
|
+
if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {
|
|
229
|
+
return yield* corrupt(operation);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
const makeServices = Effect.gen(function* () {
|
|
234
|
+
const sql = yield* SqlClientService.SqlClient;
|
|
235
|
+
const transactions = yield* DoScheduleTransaction;
|
|
236
|
+
const scheduleFailpoint = yield* ScheduleFailpoint;
|
|
237
|
+
|
|
238
|
+
yield* initializeScheduleStore();
|
|
239
|
+
|
|
240
|
+
const readRows = Effect.fn("DoScheduleStore.readRows")(function* (
|
|
241
|
+
key: ScheduleKey,
|
|
242
|
+
operation: string,
|
|
243
|
+
): Effect.fn.Return<ReadonlyArray<ScheduleRow>, ScheduleStorageError> {
|
|
244
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
245
|
+
SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json
|
|
246
|
+
FROM effect_agent_schedules
|
|
247
|
+
WHERE tenant_id = ${key.owner.tenantId}
|
|
248
|
+
AND owner_id = ${key.owner.ownerId}
|
|
249
|
+
AND schedule_id = ${key.scheduleId}
|
|
250
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
251
|
+
return yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
const readOne = Effect.fn("DoScheduleStore.readOne")(function* (
|
|
255
|
+
key: ScheduleKey,
|
|
256
|
+
operation: string,
|
|
257
|
+
): Effect.fn.Return<ScheduleRecord | null, ScheduleStorageError> {
|
|
258
|
+
const rows = yield* readRows(key, operation);
|
|
259
|
+
if (rows.length === 0) return null;
|
|
260
|
+
if (rows.length !== 1) return yield* corrupt(operation);
|
|
261
|
+
return yield* decodeRecord(rows[0]);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
const readNextDeadline = Effect.fn("DoScheduleStore.readNextDeadline")(function* (
|
|
265
|
+
owner: ScheduleOwner | undefined,
|
|
266
|
+
operation: string,
|
|
267
|
+
): Effect.fn.Return<number | null, ScheduleStorageError> {
|
|
268
|
+
const rows =
|
|
269
|
+
owner === undefined
|
|
270
|
+
? yield* sql<Record<string, unknown>>`
|
|
271
|
+
SELECT MIN(deadline_at_millis) AS deadline_at_millis
|
|
272
|
+
FROM effect_agent_schedules
|
|
273
|
+
WHERE deadline_at_millis IS NOT NULL
|
|
274
|
+
`.pipe(Effect.mapError(() => unavailable(operation)))
|
|
275
|
+
: yield* sql<Record<string, unknown>>`
|
|
276
|
+
SELECT MIN(deadline_at_millis) AS deadline_at_millis
|
|
277
|
+
FROM effect_agent_schedules
|
|
278
|
+
WHERE tenant_id = ${owner.tenantId}
|
|
279
|
+
AND owner_id = ${owner.ownerId}
|
|
280
|
+
AND deadline_at_millis IS NOT NULL
|
|
281
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
282
|
+
const decoded = yield* decodeRows(Schema.Array(ScheduleDeadlineRow), rows, operation);
|
|
283
|
+
if (decoded.length !== 1) return yield* corrupt(operation);
|
|
284
|
+
return decoded[0].deadline_at_millis;
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
const replaceAlarm = Effect.fn("DoScheduleStore.replaceAlarm")(function* (
|
|
288
|
+
replace: DoScheduleReplaceAlarm,
|
|
289
|
+
deadlineAtMillis: number | null,
|
|
290
|
+
operation: string,
|
|
291
|
+
) {
|
|
292
|
+
const rawState = yield* sql<Record<string, unknown>>`
|
|
293
|
+
UPDATE effect_agent_schedule_store_state
|
|
294
|
+
SET alarm_generation = alarm_generation + 1
|
|
295
|
+
WHERE singleton = 1
|
|
296
|
+
RETURNING storage_version, alarm_generation
|
|
297
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
298
|
+
const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);
|
|
299
|
+
if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {
|
|
300
|
+
return yield* corrupt(operation);
|
|
301
|
+
}
|
|
302
|
+
yield* scheduleFailpoint.hit("schedule:alarm:before");
|
|
303
|
+
yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation });
|
|
304
|
+
yield* scheduleFailpoint.hit("schedule:alarm:after");
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
const insert: ScheduleStore["Service"]["insert"] = Effect.fn("DoScheduleStore.insert")(
|
|
308
|
+
function* (record, ownerLimit) {
|
|
309
|
+
const operation = "insert schedule";
|
|
310
|
+
const canonical = yield* decodeBoundary(ScheduleRecord, record, operation);
|
|
311
|
+
const recordJson = yield* encodeRecord(canonical);
|
|
312
|
+
const result = yield* transactions.run((replace) =>
|
|
313
|
+
Effect.gen(function* () {
|
|
314
|
+
const existing = yield* readOne(canonical, operation);
|
|
315
|
+
if (existing !== null) {
|
|
316
|
+
if (existing.creationFingerprint === canonical.creationFingerprint) {
|
|
317
|
+
return { record: existing, inserted: false } as const;
|
|
318
|
+
}
|
|
319
|
+
return yield* ScheduleConflict.make({ reason: "creation", key: canonical });
|
|
320
|
+
}
|
|
321
|
+
const rawCounts = yield* sql<Record<string, unknown>>`
|
|
322
|
+
SELECT COUNT(*) AS schedule_count
|
|
323
|
+
FROM effect_agent_schedules
|
|
324
|
+
WHERE tenant_id = ${canonical.owner.tenantId}
|
|
325
|
+
AND owner_id = ${canonical.owner.ownerId}
|
|
326
|
+
AND (json_extract(record_json, '$.pending') IS NOT NULL OR
|
|
327
|
+
(json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))
|
|
328
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
329
|
+
const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);
|
|
330
|
+
if (counts.length !== 1) return yield* corrupt(operation);
|
|
331
|
+
if (counts[0].schedule_count >= ownerLimit) {
|
|
332
|
+
return yield* ScheduleCapacityError.make({ limit: ownerLimit });
|
|
333
|
+
}
|
|
334
|
+
yield* scheduleFailpoint.hit("schedule:insert:before");
|
|
335
|
+
yield* sql`
|
|
336
|
+
INSERT INTO effect_agent_schedules (
|
|
337
|
+
tenant_id, owner_id, schedule_id, deadline_at_millis, record_json
|
|
338
|
+
) VALUES (
|
|
339
|
+
${canonical.owner.tenantId},
|
|
340
|
+
${canonical.owner.ownerId},
|
|
341
|
+
${canonical.scheduleId},
|
|
342
|
+
${scheduleDeadline(canonical)},
|
|
343
|
+
${recordJson}
|
|
344
|
+
)
|
|
345
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
346
|
+
const deadline = yield* readNextDeadline(undefined, operation);
|
|
347
|
+
yield* replaceAlarm(replace, deadline, operation);
|
|
348
|
+
return { record: canonical, inserted: true } as const;
|
|
349
|
+
}),
|
|
350
|
+
);
|
|
351
|
+
if (result.inserted) yield* scheduleFailpoint.hit("schedule:insert:after");
|
|
352
|
+
return result.record;
|
|
353
|
+
},
|
|
354
|
+
);
|
|
355
|
+
|
|
356
|
+
const get: ScheduleStore["Service"]["get"] = Effect.fn("DoScheduleStore.get")(function* (key) {
|
|
357
|
+
const canonical = yield* decodeBoundary(ScheduleKey, key, "get schedule");
|
|
358
|
+
return yield* readOne(canonical, "get schedule");
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
const list: ScheduleStore["Service"]["list"] = Effect.fn("DoScheduleStore.list")(function* (
|
|
362
|
+
requestValue: SchedulePageRequest,
|
|
363
|
+
): Effect.fn.Return<SchedulePage, ScheduleStorageError> {
|
|
364
|
+
const operation = "list schedules";
|
|
365
|
+
const request = yield* decodeBoundary(SchedulePageRequest, requestValue, operation);
|
|
366
|
+
const rows =
|
|
367
|
+
request.after === undefined
|
|
368
|
+
? yield* sql<Record<string, unknown>>`
|
|
369
|
+
SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json
|
|
370
|
+
FROM effect_agent_schedules
|
|
371
|
+
WHERE tenant_id = ${request.owner.tenantId}
|
|
372
|
+
AND owner_id = ${request.owner.ownerId}
|
|
373
|
+
ORDER BY schedule_id
|
|
374
|
+
LIMIT ${request.limit + 1}
|
|
375
|
+
`.pipe(Effect.mapError(() => unavailable(operation)))
|
|
376
|
+
: yield* sql<Record<string, unknown>>`
|
|
377
|
+
SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json
|
|
378
|
+
FROM effect_agent_schedules
|
|
379
|
+
WHERE tenant_id = ${request.owner.tenantId}
|
|
380
|
+
AND owner_id = ${request.owner.ownerId}
|
|
381
|
+
AND schedule_id > ${request.after}
|
|
382
|
+
ORDER BY schedule_id
|
|
383
|
+
LIMIT ${request.limit + 1}
|
|
384
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
385
|
+
const decoded = yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);
|
|
386
|
+
const records = yield* Effect.forEach(decoded, decodeRecord);
|
|
387
|
+
const hasNext = records.length > request.limit;
|
|
388
|
+
const items = hasNext ? records.slice(0, request.limit) : records;
|
|
389
|
+
return { items, next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null };
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
const change: ScheduleStore["Service"]["change"] = Effect.fn("DoScheduleStore.change")(function* (
|
|
393
|
+
key,
|
|
394
|
+
change,
|
|
395
|
+
ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,
|
|
396
|
+
) {
|
|
397
|
+
const operation = "change schedule";
|
|
398
|
+
const canonicalKey = yield* decodeBoundary(ScheduleKey, key, operation);
|
|
399
|
+
const canonicalChange = yield* decodeBoundary(ScheduleChange, change, operation);
|
|
400
|
+
const result = yield* transactions.run((replace) =>
|
|
401
|
+
Effect.gen(function* () {
|
|
402
|
+
const current = yield* readOne(canonicalKey, operation);
|
|
403
|
+
if (current === null) return yield* ScheduleNotFound.make({ key: canonicalKey });
|
|
404
|
+
const transition = applyScheduleChange(current, canonicalChange);
|
|
405
|
+
if (Result.isFailure(transition)) return yield* transition.failure;
|
|
406
|
+
const next = transition.success;
|
|
407
|
+
if (!scheduleUsesCapacity(current) && scheduleUsesCapacity(next)) {
|
|
408
|
+
const rawCounts = yield* sql<Record<string, unknown>>`
|
|
409
|
+
SELECT COUNT(*) AS schedule_count FROM effect_agent_schedules
|
|
410
|
+
WHERE tenant_id = ${key.owner.tenantId} AND owner_id = ${key.owner.ownerId}
|
|
411
|
+
AND (json_extract(record_json, '$.pending') IS NOT NULL OR
|
|
412
|
+
(json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))
|
|
413
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
414
|
+
const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);
|
|
415
|
+
if (counts.length !== 1) return yield* corrupt(operation);
|
|
416
|
+
if (counts[0].schedule_count >= ownerLimit)
|
|
417
|
+
return yield* ScheduleCapacityError.make({ limit: ownerLimit });
|
|
418
|
+
}
|
|
419
|
+
if (next === current) return { record: current, changed: false } as const;
|
|
420
|
+
const recordJson = yield* encodeRecord(next);
|
|
421
|
+
yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:before`);
|
|
422
|
+
yield* sql`
|
|
423
|
+
UPDATE effect_agent_schedules
|
|
424
|
+
SET deadline_at_millis = ${scheduleDeadline(next)}, record_json = ${recordJson}
|
|
425
|
+
WHERE tenant_id = ${canonicalKey.owner.tenantId}
|
|
426
|
+
AND owner_id = ${canonicalKey.owner.ownerId}
|
|
427
|
+
AND schedule_id = ${canonicalKey.scheduleId}
|
|
428
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
429
|
+
const deadline = yield* readNextDeadline(undefined, operation);
|
|
430
|
+
yield* replaceAlarm(replace, deadline, operation);
|
|
431
|
+
return { record: next, changed: true } as const;
|
|
432
|
+
}),
|
|
433
|
+
);
|
|
434
|
+
if (result.changed) {
|
|
435
|
+
yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:after`);
|
|
436
|
+
}
|
|
437
|
+
return result.record;
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
const due: ScheduleStore["Service"]["due"] = Effect.fn("DoScheduleStore.due")(function* (
|
|
441
|
+
nowMillis,
|
|
442
|
+
limit,
|
|
443
|
+
owner?: ScheduleOwner,
|
|
444
|
+
after?: ScheduleDueCursor,
|
|
445
|
+
) {
|
|
446
|
+
const operation = "query due schedules";
|
|
447
|
+
const cursor =
|
|
448
|
+
after === undefined
|
|
449
|
+
? undefined
|
|
450
|
+
: yield* Schema.decodeUnknownEffect(ScheduleDueCursor)(after).pipe(
|
|
451
|
+
Effect.mapError(() => corrupt(operation)),
|
|
452
|
+
);
|
|
453
|
+
const continuation =
|
|
454
|
+
cursor === undefined
|
|
455
|
+
? sql`1 = 1`
|
|
456
|
+
: sql`
|
|
457
|
+
(deadline_at_millis, tenant_id, owner_id, schedule_id) >
|
|
458
|
+
(${cursor.deadlineAtMillis}, ${cursor.owner.tenantId}, ${cursor.owner.ownerId}, ${cursor.scheduleId})`;
|
|
459
|
+
const rows =
|
|
460
|
+
owner === undefined
|
|
461
|
+
? yield* sql<Record<string, unknown>>`
|
|
462
|
+
SELECT tenant_id, owner_id, schedule_id, deadline_at_millis
|
|
463
|
+
FROM effect_agent_schedules
|
|
464
|
+
WHERE deadline_at_millis <= ${nowMillis} AND ${continuation}
|
|
465
|
+
ORDER BY deadline_at_millis, tenant_id, owner_id, schedule_id
|
|
466
|
+
LIMIT ${limit}
|
|
467
|
+
`.pipe(Effect.mapError(() => unavailable(operation)))
|
|
468
|
+
: yield* sql<Record<string, unknown>>`
|
|
469
|
+
SELECT tenant_id, owner_id, schedule_id, deadline_at_millis
|
|
470
|
+
FROM effect_agent_schedules
|
|
471
|
+
WHERE tenant_id = ${owner.tenantId}
|
|
472
|
+
AND owner_id = ${owner.ownerId}
|
|
473
|
+
AND deadline_at_millis <= ${nowMillis} AND ${continuation}
|
|
474
|
+
ORDER BY deadline_at_millis, schedule_id
|
|
475
|
+
LIMIT ${limit}
|
|
476
|
+
`.pipe(Effect.mapError(() => unavailable(operation)));
|
|
477
|
+
const decoded = yield* decodeRows(Schema.Array(ScheduleDueRow), rows, operation);
|
|
478
|
+
return decoded.map((row) => ({
|
|
479
|
+
owner: { tenantId: row.tenant_id, ownerId: row.owner_id },
|
|
480
|
+
scheduleId: row.schedule_id,
|
|
481
|
+
deadlineAtMillis: row.deadline_at_millis,
|
|
482
|
+
}));
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
const nextDeadline: ScheduleStore["Service"]["nextDeadline"] = Effect.fn(
|
|
486
|
+
"DoScheduleStore.nextDeadline",
|
|
487
|
+
)(function* (owner?: ScheduleOwner) {
|
|
488
|
+
const operation = "query next schedule deadline";
|
|
489
|
+
return yield* readNextDeadline(owner, operation);
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
const prearm = Effect.fn("DoScheduleStore.prearm")(function* (
|
|
493
|
+
deadlineAtMillis: number,
|
|
494
|
+
): Effect.fn.Return<void, ScheduleStorageError | ScheduleFailpointError> {
|
|
495
|
+
yield* decodeBoundary(ScheduleInstant, deadlineAtMillis, "pre-arm schedule recovery");
|
|
496
|
+
yield* transactions.run((replace) =>
|
|
497
|
+
replaceAlarm(replace, deadlineAtMillis, "pre-arm schedule recovery"),
|
|
498
|
+
);
|
|
499
|
+
yield* scheduleFailpoint.hit("schedule:prearm:after");
|
|
500
|
+
});
|
|
501
|
+
|
|
502
|
+
const reconcile = Effect.gen(function* () {
|
|
503
|
+
yield* transactions.run((replace) =>
|
|
504
|
+
Effect.gen(function* () {
|
|
505
|
+
const deadline = yield* readNextDeadline(undefined, "reconcile schedule alarm");
|
|
506
|
+
yield* replaceAlarm(replace, deadline, "reconcile schedule alarm");
|
|
507
|
+
}),
|
|
508
|
+
);
|
|
509
|
+
yield* scheduleFailpoint.hit("schedule:reconcile:after");
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
return Context.make(ScheduleStore, {
|
|
513
|
+
insert,
|
|
514
|
+
get,
|
|
515
|
+
list,
|
|
516
|
+
change,
|
|
517
|
+
due,
|
|
518
|
+
nextDeadline,
|
|
519
|
+
}).pipe(Context.add(DoScheduleAlarmControl, { prearm, reconcile }));
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Durable Object SQLite ScheduleStore. Platform code supplies the one transaction owner that
|
|
524
|
+
* combines these SQL mutations with its logical and native alarm lifecycle.
|
|
525
|
+
*/
|
|
526
|
+
export const scheduleStoreLayer: Layer.Layer<
|
|
527
|
+
ScheduleStore | DoScheduleAlarmControl,
|
|
528
|
+
ScheduleStorageError,
|
|
529
|
+
SqlClientService.SqlClient | DoScheduleTransaction
|
|
530
|
+
> = Layer.effectContext(makeServices);
|
package/src/index.ts
CHANGED
|
@@ -26,6 +26,7 @@ export * from "./errors.ts";
|
|
|
26
26
|
export * from "./migrations.ts";
|
|
27
27
|
export * from "./do-conversation-store.ts";
|
|
28
28
|
export * from "./do-ledger.ts";
|
|
29
|
+
export * from "./do-schedule-store.ts";
|
|
29
30
|
export * from "./do-storage-config.ts";
|
|
30
31
|
export * from "./do-storage-failpoint.ts";
|
|
31
32
|
export * from "./port-protocol.ts";
|