@effect-agent/storage-sqlite 0.1.0-beta.48 → 0.1.0-beta.50

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