@effect-agent/storage-sqlite 0.1.0-beta.37 → 0.1.0-beta.39

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