@effect-agent/storage-cloudflare 0.1.0-beta.8 → 0.1.0-beta.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/DoMemoryStore.d.mts +29 -0
  2. package/dist/DoMemoryStore.mjs +55 -0
  3. package/dist/DoMemoryStore.mjs.map +1 -0
  4. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  5. package/dist/DoMessageDeliveryStore.mjs +32 -0
  6. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/DoScheduleStore.d.mts +36 -0
  8. package/dist/DoScheduleStore.mjs +388 -0
  9. package/dist/DoScheduleStore.mjs.map +1 -0
  10. package/dist/DoStorageConfig.d.mts +45 -0
  11. package/dist/DoStorageConfig.mjs +52 -0
  12. package/dist/DoStorageConfig.mjs.map +1 -0
  13. package/dist/DoStorageError-Cmhvl4TQ.d.mts +98 -0
  14. package/dist/DoStorageError.d.mts +2 -0
  15. package/dist/DoStorageError.mjs +164 -0
  16. package/dist/DoStorageError.mjs.map +1 -0
  17. package/dist/DoStorageFailpoint.d.mts +17 -0
  18. package/dist/DoStorageFailpoint.mjs +14 -0
  19. package/dist/DoStorageFailpoint.mjs.map +1 -0
  20. package/dist/DoStorageFailpointTesting.d.mts +34 -0
  21. package/dist/DoStorageFailpointTesting.mjs +35 -0
  22. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/DoStorageVersion-x5OOurvZ.d.mts +12 -0
  24. package/dist/DoStorageVersion.d.mts +2 -0
  25. package/dist/DoStorageVersion.mjs +8 -0
  26. package/dist/DoStorageVersion.mjs.map +1 -0
  27. package/dist/DoSubmissionLedger.d.mts +23 -0
  28. package/dist/DoSubmissionLedger.mjs +1849 -0
  29. package/dist/DoSubmissionLedger.mjs.map +1 -0
  30. package/dist/DoSubscriptionStore.d.mts +25 -0
  31. package/dist/DoSubscriptionStore.mjs +183 -0
  32. package/dist/DoSubscriptionStore.mjs.map +1 -0
  33. package/dist/DoThreadStore.d.mts +59 -0
  34. package/dist/DoThreadStore.mjs +465 -0
  35. package/dist/DoThreadStore.mjs.map +1 -0
  36. package/dist/MemoryProtocol.d.mts +38160 -0
  37. package/dist/MemoryProtocol.mjs +219 -0
  38. package/dist/MemoryProtocol.mjs.map +1 -0
  39. package/dist/PortProtocol.d.mts +3207 -0
  40. package/dist/PortProtocol.mjs +176 -0
  41. package/dist/PortProtocol.mjs.map +1 -0
  42. package/dist/PortRouting.d.mts +83 -0
  43. package/dist/PortRouting.mjs +410 -0
  44. package/dist/PortRouting.mjs.map +1 -0
  45. package/dist/do-journal-DHqCQeBU.mjs +991 -0
  46. package/dist/do-journal-DHqCQeBU.mjs.map +1 -0
  47. package/dist/index.d.mts +14 -1521
  48. package/dist/index.mjs +14 -3695
  49. package/dist/migrations-Ba_kOrSx.mjs +287 -0
  50. package/dist/migrations-Ba_kOrSx.mjs.map +1 -0
  51. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  52. package/package.json +1 -45
  53. package/src/DoMemoryStore.ts +59 -0
  54. package/src/DoMessageDeliveryStore.ts +53 -0
  55. package/src/DoScheduleStore.ts +622 -0
  56. package/src/{errors.ts → DoStorageError.ts} +10 -3
  57. package/src/DoStorageFailpoint.ts +20 -0
  58. package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
  59. package/src/DoStorageVersion.ts +2 -0
  60. package/src/{do-ledger.ts → DoSubmissionLedger.ts} +862 -163
  61. package/src/DoSubscriptionStore.ts +329 -0
  62. package/src/DoThreadStore.ts +1014 -0
  63. package/src/MemoryProtocol.ts +355 -0
  64. package/src/{port-protocol.ts → PortProtocol.ts} +44 -37
  65. package/src/{routing.ts → PortRouting.ts} +292 -264
  66. package/src/index.ts +13 -32
  67. package/src/{do-journal.ts → internal/do-journal.ts} +716 -232
  68. package/src/internal/message-delivery-schema.ts +24 -0
  69. package/src/{migrations.ts → internal/migrations.ts} +51 -35
  70. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  71. package/dist/index.mjs.map +0 -1
  72. package/src/do-conversation-store.ts +0 -850
  73. /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
@@ -1,850 +0,0 @@
1
- import {
2
- AppendConflict,
3
- AppendResult,
4
- CanonicalBatch,
5
- CanonicalRecord,
6
- CanonicalRecordEnvelope,
7
- CanonicalSequence,
8
- CheckpointRejected,
9
- ConversationCheckpoint,
10
- ConversationExport,
11
- ConversationExportRequest,
12
- ConversationMaterialization,
13
- ConversationNotMaterialized,
14
- ConversationObservation,
15
- ConversationRead,
16
- ConversationStore,
17
- ConversationStoreError,
18
- ConversationTail,
19
- ConversationTailRequest,
20
- DEFAULT_OWNERSHIP_LEASE_DURATION,
21
- digestCanonicalBatch,
22
- Digest,
23
- EMPTY_TAIL_DIGEST,
24
- FenceRejected,
25
- FencedAppendRequest,
26
- LoadCheckpointRequest,
27
- ObservationOffset,
28
- SaveCheckpointRequest,
29
- } from "@effect-agent/session";
30
- import { BrowserCrypto } from "@effect/platform-browser";
31
- import { SqliteClient } from "@effect/sql-sqlite-do";
32
- import {
33
- Clock,
34
- Context,
35
- Crypto,
36
- Duration,
37
- Effect,
38
- Layer,
39
- Option,
40
- Ref,
41
- Schema,
42
- Stream,
43
- } from "effect";
44
- import * as SqlClientService from "effect/unstable/sql/SqlClient";
45
-
46
- import {
47
- initializeDoJournal,
48
- RawAppendRequest,
49
- RawCheckpoint,
50
- RawReadRequest,
51
- type DoJournal,
52
- } from "./do-journal.ts";
53
- import {
54
- DEFAULT_MAX_STORED_VALUE_BYTES,
55
- DoStorageConfig,
56
- DoStorageConfigValue,
57
- } from "./do-storage-config.ts";
58
- import { DoStorageFailpoint, type DoStorageFailpointHandler } from "./do-storage-failpoint.ts";
59
- import {
60
- DoAppendConflict,
61
- DoCheckpointConflict,
62
- DoFenceRejected,
63
- type DoStorageFailpointLocation,
64
- DoStorageCompatibilityError,
65
- DoStorageCorruptionError,
66
- DoStorageError,
67
- } from "./errors.ts";
68
-
69
- /**
70
- * Convenience-layer construction options. `storage` is the Durable Object's own
71
- * `ctx.storage` handle, injected as a value (DEPLOY-010: platform bindings enter only
72
- * through Layers; this package never imports `cloudflare:workers`).
73
- */
74
- export interface DoStorageOptions {
75
- readonly storage: DurableObjectStorage;
76
- readonly observationPollInterval?: number | undefined;
77
- /**
78
- * Submission ownership lease duration in milliseconds (D5). Defaults to
79
- * `DEFAULT_OWNERSHIP_LEASE_DURATION` from `@effect-agent/session`.
80
- */
81
- readonly ownershipLeaseDuration?: number | undefined;
82
- /**
83
- * Maximum bytes for any single stored value; must stay under the platform's 2 MB
84
- * per-value limit. Defaults to `DEFAULT_MAX_STORED_VALUE_BYTES`.
85
- */
86
- readonly maxStoredValueBytes?: number | undefined;
87
- /**
88
- * Re-verify every stored payload and digest chain while opening the store. Defaults to
89
- * off: per-operation Schema decoding and the digest chain already fail clearly on corrupt
90
- * rows without scanning the whole database on every open.
91
- */
92
- readonly verifyOnOpen?: boolean | undefined;
93
- readonly failpoint?: DoStorageFailpointHandler | undefined;
94
- }
95
-
96
- export type DoStorageInitializationError =
97
- | DoStorageCompatibilityError
98
- | DoStorageCorruptionError
99
- | DoStorageError;
100
-
101
- const OffsetText = Schema.String.check(Schema.isMaxLength(4 * 1024));
102
- const DO_OFFSET_PREFIX = "effect-agent-do@1:";
103
- const ZERO_CANONICAL_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
104
- const isDigest = Schema.is(Digest);
105
-
106
- const storeError = (operation: string, error: { readonly message: string }) =>
107
- ConversationStoreError.make({
108
- cause: error,
109
- operation,
110
- message: error.message,
111
- });
112
-
113
- const schemaStoreError = (operation: string, error: { readonly message: string }) =>
114
- ConversationStoreError.make({
115
- cause: error,
116
- operation,
117
- message: error.message,
118
- });
119
-
120
- const makeOffset = Effect.fn("DoConversationStore.makeOffset")(function* (
121
- conversationId: ConversationMaterialization["conversationId"],
122
- sequence: number,
123
- ): Effect.fn.Return<ObservationOffset, ConversationStoreError> {
124
- return yield* Schema.decodeUnknownEffect(CanonicalSequence)(sequence).pipe(
125
- Effect.flatMap((validatedSequence) =>
126
- Schema.decodeUnknownEffect(ObservationOffset)(
127
- `${DO_OFFSET_PREFIX}${encodeURIComponent(conversationId)}:${validatedSequence}`,
128
- ),
129
- ),
130
- Effect.mapError((error) => schemaStoreError("encode observation offset", error)),
131
- );
132
- });
133
-
134
- const parseOffset = Effect.fn("DoConversationStore.parseOffset")(function* (
135
- conversationId: ConversationMaterialization["conversationId"],
136
- offset: ObservationOffset | undefined,
137
- ): Effect.fn.Return<CanonicalSequence, ConversationStoreError> {
138
- if (offset === undefined) return ZERO_CANONICAL_SEQUENCE;
139
- const text = yield* Schema.decodeUnknownEffect(OffsetText)(offset).pipe(
140
- Effect.mapError((error) => schemaStoreError("decode observation offset", error)),
141
- );
142
- const conversationPrefix = `${DO_OFFSET_PREFIX}${encodeURIComponent(conversationId)}:`;
143
- if (!text.startsWith(conversationPrefix)) {
144
- return yield* ConversationStoreError.make({
145
- operation: "decode observation offset",
146
- message:
147
- "The observation offset belongs to a different adapter, storage version, or Conversation.",
148
- });
149
- }
150
- const sequenceText = text.slice(conversationPrefix.length);
151
- if (!/^(0|[1-9][0-9]*)$/.test(sequenceText)) {
152
- return yield* ConversationStoreError.make({
153
- operation: "decode observation offset",
154
- message: "The observation offset is malformed.",
155
- });
156
- }
157
- return yield* Schema.decodeUnknownEffect(CanonicalSequence)(Number(sequenceText)).pipe(
158
- Effect.mapError((error) => schemaStoreError("decode observation offset", error)),
159
- );
160
- });
161
-
162
- const mapFence = (
163
- conversationId: ConversationMaterialization["conversationId"],
164
- error: DoFenceRejected,
165
- ) =>
166
- FenceRejected.make({
167
- conversationId,
168
- actualEpoch: error.actualEpoch,
169
- attemptedEpoch: error.producerEpoch,
170
- });
171
-
172
- const encodeCanonicalRecord = Effect.fn("DoConversationStore.encodeCanonicalRecord")(function* (
173
- record: CanonicalRecord,
174
- ): Effect.fn.Return<string, ConversationStoreError> {
175
- return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(record).pipe(
176
- Effect.mapError((error) => schemaStoreError("encode canonical record", error)),
177
- );
178
- });
179
-
180
- const encodeCanonicalBatch = Effect.fn("DoConversationStore.encodeCanonicalBatch")(function* (
181
- batch: CanonicalBatch,
182
- ): Effect.fn.Return<string, ConversationStoreError> {
183
- return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalBatch))(batch).pipe(
184
- Effect.mapError((error) => schemaStoreError("encode canonical batch", error)),
185
- );
186
- });
187
-
188
- const encodeCheckpoint = Effect.fn("DoConversationStore.encodeCheckpoint")(function* (
189
- checkpoint: ConversationCheckpoint,
190
- ): Effect.fn.Return<string, ConversationStoreError> {
191
- return yield* Schema.encodeEffect(Schema.fromJsonString(ConversationCheckpoint))(checkpoint).pipe(
192
- Effect.mapError((error) => schemaStoreError("encode checkpoint", error)),
193
- );
194
- });
195
-
196
- const decodeEnvelope = Effect.fn("DoConversationStore.decodeEnvelope")(function* (row: {
197
- readonly batch_id: string;
198
- readonly conversation_id: string;
199
- readonly record_json: string;
200
- readonly sequence: CanonicalSequence;
201
- }) {
202
- const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(
203
- row.record_json,
204
- ).pipe(
205
- Effect.mapError((error) =>
206
- ConversationStoreError.make({
207
- operation: "decode canonical record",
208
- message: error.message,
209
- }),
210
- ),
211
- );
212
- const conversationId = yield* Schema.decodeUnknownEffect(
213
- CanonicalRecordEnvelope.fields.conversationId,
214
- )(row.conversation_id).pipe(
215
- Effect.mapError((error) => schemaStoreError("decode conversation identity", error)),
216
- );
217
- const offset = yield* makeOffset(conversationId, row.sequence);
218
- const batchId = yield* Schema.decodeUnknownEffect(CanonicalRecordEnvelope.fields.batchId)(
219
- row.batch_id,
220
- ).pipe(Effect.mapError((error) => schemaStoreError("decode batch identity", error)));
221
- return CanonicalRecordEnvelope.make({
222
- conversationId,
223
- batchId,
224
- sequence: row.sequence,
225
- offset,
226
- record,
227
- });
228
- });
229
-
230
- const decodeCheckpoint = Effect.fn("DoConversationStore.decodeCheckpoint")(function* (
231
- checkpointJson: string,
232
- ): Effect.fn.Return<ConversationCheckpoint, ConversationStoreError> {
233
- return yield* Schema.decodeEffect(Schema.fromJsonString(ConversationCheckpoint))(
234
- checkpointJson,
235
- ).pipe(Effect.mapError((error) => schemaStoreError("decode checkpoint", error)));
236
- });
237
-
238
- const requireConversation = Effect.fn("DoConversationStore.requireConversation")(function* (
239
- journal: DoJournal,
240
- conversationId: ConversationMaterialization["conversationId"],
241
- ) {
242
- const rows = yield* journal
243
- .getConversation(conversationId)
244
- .pipe(Effect.mapError((error) => storeError("read conversation", error)));
245
- if (rows.length === 0) {
246
- return yield* ConversationNotMaterialized.make({ conversationId });
247
- }
248
- return rows[0];
249
- });
250
-
251
- const tailDigestAt = Effect.fn("DoConversationStore.tailDigestAt")(function* (
252
- journal: DoJournal,
253
- conversationId: ConversationMaterialization["conversationId"],
254
- sequence: CanonicalSequence,
255
- ) {
256
- if (sequence === 0) return EMPTY_TAIL_DIGEST;
257
- const digests = yield* journal
258
- .getTailDigestAt(conversationId, sequence)
259
- .pipe(Effect.mapError((error) => storeError("read checkpoint digest", error)));
260
- if (digests.length !== 1) {
261
- return yield* CheckpointRejected.make({
262
- conversationId,
263
- reason: "digest-mismatch",
264
- });
265
- }
266
- return yield* Schema.decodeUnknownEffect(Digest)(digests[0]).pipe(
267
- Effect.mapError((error) => schemaStoreError("decode checkpoint digest", error)),
268
- );
269
- });
270
-
271
- const groupByKey = <A>(
272
- rows: ReadonlyArray<A>,
273
- key: (row: A) => string,
274
- ): ReadonlyMap<string, ReadonlyArray<A>> => {
275
- const grouped = new Map<string, Array<A>>();
276
- for (const row of rows) {
277
- const existing = grouped.get(key(row));
278
- if (existing === undefined) {
279
- grouped.set(key(row), [row]);
280
- } else {
281
- existing.push(row);
282
- }
283
- }
284
- return grouped;
285
- };
286
-
287
- /**
288
- * Opt-in full integrity audit (`verifyOnOpen`). Every stored payload is decoded, re-encoded,
289
- * and re-digested against the canonical chain. Routine opens skip this scan: per-operation
290
- * Schema decoding plus the digest chain already fail clearly on corrupt rows.
291
- */
292
- const decodeStartupPayloads = Effect.fn("DoConversationStore.decodeStartupPayloads")(function* (
293
- journal: DoJournal,
294
- crypto: Crypto.Crypto,
295
- ) {
296
- const stored = yield* journal.scanStoredPayloads();
297
- const batches = yield* Effect.forEach(stored.batches, (batch) =>
298
- Schema.decodeEffect(Schema.fromJsonString(CanonicalBatch))(batch.batch_json).pipe(
299
- Effect.map((decoded) => ({ decoded, row: batch })),
300
- Effect.mapError((error) =>
301
- DoStorageCorruptionError.make({
302
- table: "effect_agent_canonical_batches",
303
- rowKey: `${batch.conversation_id}/${batch.batch_id}`,
304
- message: error.message,
305
- }),
306
- ),
307
- ),
308
- );
309
- const records = yield* Effect.forEach(stored.records, (record) =>
310
- Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(record.record_json).pipe(
311
- Effect.map((decoded) => ({ decoded, row: record })),
312
- Effect.mapError((error) =>
313
- DoStorageCorruptionError.make({
314
- table: "effect_agent_canonical_records",
315
- rowKey: `${record.conversation_id}/${record.sequence}`,
316
- message: error.message,
317
- }),
318
- ),
319
- ),
320
- );
321
- const checkpoints = yield* Effect.forEach(stored.checkpoints, (checkpoint) =>
322
- Schema.decodeEffect(Schema.fromJsonString(ConversationCheckpoint))(
323
- checkpoint.checkpoint_json,
324
- ).pipe(
325
- Effect.map((decoded) => ({ decoded, row: checkpoint })),
326
- Effect.mapError((error) =>
327
- DoStorageCorruptionError.make({
328
- table: "effect_agent_checkpoints",
329
- rowKey: `${checkpoint.conversation_id}/${checkpoint.through_sequence}`,
330
- message: error.message,
331
- }),
332
- ),
333
- ),
334
- );
335
-
336
- const batchesByConversation = groupByKey(batches, ({ row }) => row.conversation_id);
337
- const recordsByConversation = groupByKey(records, ({ row }) => row.conversation_id);
338
- const checkpointsByConversation = groupByKey(checkpoints, ({ row }) => row.conversation_id);
339
- const materializedIds = new Set(
340
- stored.conversations.map((conversation) => conversation.conversation_id),
341
- );
342
-
343
- for (const conversation of stored.conversations) {
344
- const conversationBatches = batchesByConversation.get(conversation.conversation_id) ?? [];
345
- const conversationRecords = recordsByConversation.get(conversation.conversation_id) ?? [];
346
- const conversationCheckpoints =
347
- checkpointsByConversation.get(conversation.conversation_id) ?? [];
348
- const recordsByBatch = groupByKey(conversationRecords, ({ row }) => row.batch_id);
349
- let previousDigest = EMPTY_TAIL_DIGEST;
350
- let expectedSequence = 1;
351
- const tailDigests = new Map<number, string>([[0, EMPTY_TAIL_DIGEST]]);
352
-
353
- for (const { decoded: canonicalBatch, row: batchRow } of conversationBatches) {
354
- const key = `${batchRow.conversation_id}/${batchRow.batch_id}`;
355
- if (
356
- canonicalBatch.batchId !== batchRow.batch_id ||
357
- batchRow.first_sequence !== expectedSequence ||
358
- batchRow.last_sequence !== batchRow.first_sequence + canonicalBatch.records.length - 1
359
- ) {
360
- return yield* DoStorageCorruptionError.make({
361
- table: "effect_agent_canonical_batches",
362
- rowKey: key,
363
- message: "Canonical batch identity, sequence, or record count is inconsistent.",
364
- });
365
- }
366
-
367
- const digest = yield* digestCanonicalBatch(previousDigest, canonicalBatch).pipe(
368
- Effect.provideService(Crypto.Crypto, crypto),
369
- Effect.mapError((error) =>
370
- DoStorageCorruptionError.make({
371
- table: "effect_agent_canonical_batches",
372
- rowKey: key,
373
- message: error.message,
374
- }),
375
- ),
376
- );
377
- if (batchRow.batch_digest !== digest || batchRow.tail_digest !== digest) {
378
- return yield* DoStorageCorruptionError.make({
379
- table: "effect_agent_canonical_batches",
380
- rowKey: key,
381
- message: "Canonical batch digest does not match its decoded content and prior tail.",
382
- });
383
- }
384
-
385
- const batchRecords = recordsByBatch.get(batchRow.batch_id) ?? [];
386
- if (batchRecords.length !== canonicalBatch.records.length) {
387
- return yield* DoStorageCorruptionError.make({
388
- table: "effect_agent_canonical_records",
389
- rowKey: key,
390
- message: "Canonical batch and record-table counts differ.",
391
- });
392
- }
393
- for (let index = 0; index < canonicalBatch.records.length; index++) {
394
- const expectedRecord = canonicalBatch.records[index];
395
- const storedRecord = batchRecords[index];
396
- const expectedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(
397
- expectedRecord,
398
- ).pipe(
399
- Effect.mapError((error) =>
400
- DoStorageCorruptionError.make({
401
- table: "effect_agent_canonical_batches",
402
- rowKey: key,
403
- message: error.message,
404
- }),
405
- ),
406
- );
407
- const storedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(
408
- storedRecord.decoded,
409
- ).pipe(
410
- Effect.mapError((error) =>
411
- DoStorageCorruptionError.make({
412
- table: "effect_agent_canonical_records",
413
- rowKey: `${key}/${storedRecord.row.sequence}`,
414
- message: error.message,
415
- }),
416
- ),
417
- );
418
- if (
419
- storedRecord.row.sequence !== batchRow.first_sequence + index ||
420
- storedRecord.row.record_id !== expectedRecord.recordId ||
421
- expectedJson !== storedJson
422
- ) {
423
- return yield* DoStorageCorruptionError.make({
424
- table: "effect_agent_canonical_records",
425
- rowKey: `${key}/${storedRecord.row.sequence}`,
426
- message: "Canonical record identity, sequence, or payload differs from its batch.",
427
- });
428
- }
429
- }
430
-
431
- previousDigest = digest;
432
- expectedSequence = batchRow.last_sequence + 1;
433
- tailDigests.set(batchRow.last_sequence, digest);
434
- }
435
-
436
- if (
437
- conversationRecords.length !== conversation.tail_sequence ||
438
- conversation.tail_sequence !== expectedSequence - 1 ||
439
- conversation.tail_digest !== previousDigest
440
- ) {
441
- return yield* DoStorageCorruptionError.make({
442
- table: "effect_agent_conversations",
443
- rowKey: conversation.conversation_id,
444
- message: "Conversation tail does not match its canonical batch chain.",
445
- });
446
- }
447
-
448
- for (const checkpoint of conversationCheckpoints) {
449
- if (
450
- checkpoint.decoded.conversationId !== conversation.conversation_id ||
451
- checkpoint.decoded.throughSequence !== checkpoint.row.through_sequence ||
452
- checkpoint.decoded.tailDigest !== checkpoint.row.tail_digest ||
453
- tailDigests.get(checkpoint.row.through_sequence) !== checkpoint.row.tail_digest
454
- ) {
455
- return yield* DoStorageCorruptionError.make({
456
- table: "effect_agent_checkpoints",
457
- rowKey: `${conversation.conversation_id}/${checkpoint.row.through_sequence}`,
458
- message: "Checkpoint identity or digest is not bound to a canonical batch tail.",
459
- });
460
- }
461
- }
462
- }
463
-
464
- if (
465
- batches.some(({ row }) => !materializedIds.has(row.conversation_id)) ||
466
- records.some(({ row }) => !materializedIds.has(row.conversation_id)) ||
467
- checkpoints.some(({ row }) => !materializedIds.has(row.conversation_id))
468
- ) {
469
- return yield* DoStorageCorruptionError.make({
470
- table: "effect_agent_conversations",
471
- rowKey: "startup_scan",
472
- message: "Canonical rows exist without a materialized Conversation.",
473
- });
474
- }
475
- });
476
-
477
- const makeServices = Effect.fn("DoConversationStore.makeServices")(function* () {
478
- const config = yield* DoStorageConfig;
479
- const failpoint = yield* DoStorageFailpoint;
480
- const sql = yield* SqlClientService.SqlClient;
481
- const crypto = yield* Crypto.Crypto;
482
- const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes);
483
- if (config.verifyOnOpen) {
484
- yield* decodeStartupPayloads(journal, crypto);
485
- }
486
-
487
- const provideCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>
488
- Effect.provideService(effect, Crypto.Crypto, crypto);
489
- const hitFailpoint = Effect.fn("DoConversationStore.hitFailpoint")(
490
- (location: DoStorageFailpointLocation): Effect.Effect<void, ConversationStoreError> =>
491
- failpoint
492
- .hit(location)
493
- .pipe(Effect.mapError((error) => storeError(`storage failpoint ${location}`, error))),
494
- );
495
-
496
- const materialize: ConversationStore["Service"]["materialize"] = Effect.fn(
497
- "DoConversationStore.materialize",
498
- )(function* (request: ConversationMaterialization) {
499
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationMaterialization))(
500
- request,
501
- ).pipe(Effect.mapError((error) => schemaStoreError("validate materialization", error)));
502
- const now = yield* Clock.currentTimeMillis;
503
- yield* hitFailpoint("materialize:before");
504
- yield* journal
505
- .materialize(
506
- validated.conversationId,
507
- new Date(now).toISOString(),
508
- EMPTY_TAIL_DIGEST,
509
- validated.producerEpoch,
510
- )
511
- .pipe(
512
- Effect.mapError((error) =>
513
- error._tag === "DoFenceRejected"
514
- ? mapFence(validated.conversationId, error)
515
- : storeError("materialize conversation", error),
516
- ),
517
- );
518
- yield* hitFailpoint("materialize:after");
519
- });
520
-
521
- const append: ConversationStore["Service"]["append"] = Effect.fn("DoConversationStore.append")(
522
- function* (request: FencedAppendRequest) {
523
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(FencedAppendRequest))(
524
- request,
525
- ).pipe(Effect.mapError((error) => schemaStoreError("validate canonical append", error)));
526
- yield* requireConversation(journal, validated.conversationId);
527
- const tailDigest = yield* provideCrypto(
528
- digestCanonicalBatch(validated.expectedTailDigest, validated.batch),
529
- ).pipe(Effect.mapError((error) => storeError("digest canonical append", error)));
530
- const batchJson = yield* encodeCanonicalBatch(validated.batch);
531
- const rawRecords = yield* Effect.forEach(validated.batch.records, (record) =>
532
- encodeCanonicalRecord(record).pipe(
533
- Effect.map((recordJson) => ({
534
- recordId: record.recordId,
535
- recordJson,
536
- })),
537
- ),
538
- );
539
- const rawRequest = yield* Schema.decodeUnknownEffect(RawAppendRequest)({
540
- conversationId: validated.conversationId,
541
- batchId: validated.batch.batchId,
542
- batchDigest: tailDigest,
543
- batchJson,
544
- expectedTailSequence: validated.expectedTailSequence,
545
- expectedTailDigest: validated.expectedTailDigest,
546
- producerEpoch: validated.producerEpoch,
547
- records: rawRecords,
548
- tailDigest,
549
- }).pipe(Effect.mapError((error) => schemaStoreError("encode canonical append", error)));
550
- yield* hitFailpoint("append:before");
551
- const result = yield* journal.append(rawRequest).pipe(
552
- Effect.mapError((error) => {
553
- if (error instanceof DoFenceRejected) {
554
- return mapFence(validated.conversationId, error);
555
- }
556
- if (error instanceof DoAppendConflict) {
557
- return error.actualTailSequence !== undefined && isDigest(error.actualTailDigest)
558
- ? AppendConflict.make({
559
- conversationId: validated.conversationId,
560
- batchId: validated.batch.batchId,
561
- reason: error.reason,
562
- actualTailSequence: error.actualTailSequence,
563
- actualTailDigest: error.actualTailDigest,
564
- })
565
- : AppendConflict.make({
566
- conversationId: validated.conversationId,
567
- batchId: validated.batch.batchId,
568
- reason: error.reason,
569
- });
570
- }
571
- return storeError("append canonical batch", error);
572
- }),
573
- Effect.flatMap((result) =>
574
- Schema.decodeUnknownEffect(AppendResult)(result).pipe(
575
- Effect.mapError((error) => schemaStoreError("decode append result", error)),
576
- ),
577
- ),
578
- );
579
- yield* hitFailpoint("append:after");
580
- return result;
581
- },
582
- );
583
-
584
- const loadRecords = Effect.fn("DoConversationStore.loadRecords")(function* (
585
- request: RawReadRequest,
586
- ) {
587
- const rows = yield* journal
588
- .read(request)
589
- .pipe(Effect.mapError((error) => storeError("read canonical records", error)));
590
- return yield* Effect.forEach(rows, decodeEnvelope);
591
- });
592
-
593
- const readEffect = Effect.fn("DoConversationStore.read")(function* (request: ConversationRead) {
594
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationRead))(
595
- request,
596
- ).pipe(Effect.mapError((error) => schemaStoreError("validate conversation read", error)));
597
- yield* requireConversation(journal, validated.conversationId);
598
- const records = yield* loadRecords(
599
- RawReadRequest.make({
600
- conversationId: validated.conversationId,
601
- fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,
602
- limit: validated.limit,
603
- }),
604
- );
605
- return Stream.fromIterable(records);
606
- });
607
- const read: ConversationStore["Service"]["read"] = (request) =>
608
- Stream.unwrap(readEffect(request));
609
-
610
- const observeEffect = Effect.fn("DoConversationStore.observe")(function* (
611
- request: ConversationObservation,
612
- ) {
613
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationObservation))(
614
- request,
615
- ).pipe(
616
- Effect.mapError((error) => schemaStoreError("validate conversation observation", error)),
617
- );
618
- yield* requireConversation(journal, validated.conversationId);
619
- const initialSequence = yield* parseOffset(validated.conversationId, validated.afterOffset);
620
- const cursor = yield* Ref.make(initialSequence);
621
- const poll = Effect.fn("DoConversationStore.observePoll")(function* () {
622
- const fromSequenceExclusive = yield* Ref.get(cursor);
623
- const records = yield* loadRecords(
624
- RawReadRequest.make({
625
- conversationId: validated.conversationId,
626
- fromSequenceExclusive,
627
- limit: 1_024,
628
- }),
629
- );
630
- if (records.length === 0) {
631
- yield* Effect.sleep(config.observationPollInterval);
632
- return [];
633
- }
634
- yield* Ref.set(cursor, records[records.length - 1].sequence);
635
- return records;
636
- });
637
- return Stream.fromIterableEffectRepeat(poll());
638
- });
639
- const observe: ConversationStore["Service"]["observe"] = (request) =>
640
- Stream.unwrap(observeEffect(request));
641
-
642
- const exportConversation: ConversationStore["Service"]["export"] = Effect.fn(
643
- "DoConversationStore.export",
644
- )(function* (request: ConversationExportRequest) {
645
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationExportRequest))(
646
- request,
647
- ).pipe(Effect.mapError((error) => schemaStoreError("validate conversation export", error)));
648
- yield* requireConversation(journal, validated.conversationId);
649
- const exported = yield* journal
650
- .exportConversation(validated.conversationId)
651
- .pipe(Effect.mapError((error) => storeError("export conversation", error)));
652
- const records = yield* Effect.forEach(exported.records, decodeEnvelope);
653
- if (records.length > 65_536) {
654
- return yield* ConversationStoreError.make({
655
- operation: "decode conversation export",
656
- message: "The conversation exceeds the current export record limit.",
657
- });
658
- }
659
- const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(
660
- exported.conversation.tail_digest,
661
- ).pipe(Effect.mapError((error) => schemaStoreError("decode export tail digest", error)));
662
- return ConversationExport.make({
663
- format: "effect-agent/conversation@1",
664
- conversationId: validated.conversationId,
665
- tailSequence: exported.conversation.tail_sequence,
666
- tailDigest,
667
- records,
668
- });
669
- });
670
-
671
- const inspectTail: ConversationStore["Service"]["inspectTail"] = Effect.fn(
672
- "DoConversationStore.inspectTail",
673
- )(function* (request: ConversationTailRequest) {
674
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationTailRequest))(
675
- request,
676
- ).pipe(Effect.mapError((error) => schemaStoreError("validate tail inspection", error)));
677
- const conversation = yield* requireConversation(journal, validated.conversationId);
678
- const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(conversation.tail_digest).pipe(
679
- Effect.mapError((error) => schemaStoreError("decode tail digest", error)),
680
- );
681
- return ConversationTail.make({
682
- conversationId: validated.conversationId,
683
- tailSequence: conversation.tail_sequence,
684
- tailDigest,
685
- producerEpoch: conversation.producer_epoch,
686
- });
687
- });
688
-
689
- const saveCheckpoint: ConversationStore["Service"]["saveCheckpoint"] = Effect.fn(
690
- "DoConversationStore.saveCheckpoint",
691
- )(function* (request: SaveCheckpointRequest) {
692
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SaveCheckpointRequest))(
693
- request,
694
- ).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint", error)));
695
- const conversation = yield* requireConversation(journal, validated.checkpoint.conversationId);
696
- if (validated.checkpoint.throughSequence > conversation.tail_sequence) {
697
- return yield* CheckpointRejected.make({
698
- conversationId: validated.checkpoint.conversationId,
699
- reason: "ahead-of-tail",
700
- });
701
- }
702
- const canonicalDigest = yield* tailDigestAt(
703
- journal,
704
- validated.checkpoint.conversationId,
705
- validated.checkpoint.throughSequence,
706
- );
707
- if (canonicalDigest !== validated.checkpoint.tailDigest) {
708
- return yield* CheckpointRejected.make({
709
- conversationId: validated.checkpoint.conversationId,
710
- reason: "digest-mismatch",
711
- });
712
- }
713
- const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);
714
- const raw = RawCheckpoint.make({
715
- conversationId: validated.checkpoint.conversationId,
716
- throughSequence: validated.checkpoint.throughSequence,
717
- tailDigest: validated.checkpoint.tailDigest,
718
- checkpointJson,
719
- });
720
- yield* hitFailpoint("save-checkpoint:before");
721
- yield* journal.saveCheckpoint(raw).pipe(
722
- Effect.mapError((error) =>
723
- error instanceof DoCheckpointConflict
724
- ? CheckpointRejected.make({
725
- conversationId: validated.checkpoint.conversationId,
726
- reason: "digest-mismatch",
727
- })
728
- : storeError("save checkpoint", error),
729
- ),
730
- );
731
- yield* hitFailpoint("save-checkpoint:after");
732
- });
733
-
734
- const loadCheckpoint: ConversationStore["Service"]["loadCheckpoint"] = Effect.fn(
735
- "DoConversationStore.loadCheckpoint",
736
- )(function* (request: LoadCheckpointRequest) {
737
- const validated = yield* Schema.decodeUnknownEffect(Schema.toType(LoadCheckpointRequest))(
738
- request,
739
- ).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint lookup", error)));
740
- const conversation = yield* requireConversation(journal, validated.conversationId);
741
- const rows = yield* journal
742
- .loadCheckpoint(
743
- validated.conversationId,
744
- validated.atOrBeforeSequence ?? conversation.tail_sequence,
745
- )
746
- .pipe(Effect.mapError((error) => storeError("load checkpoint", error)));
747
- if (rows.length === 0) return Option.none();
748
- if (rows.length !== 1) {
749
- return yield* ConversationStoreError.make({
750
- operation: "load checkpoint",
751
- message: `Expected at most one checkpoint row but found ${rows.length}.`,
752
- });
753
- }
754
- const checkpoint = yield* decodeCheckpoint(rows[0].checkpoint_json);
755
- const canonicalDigest = yield* tailDigestAt(
756
- journal,
757
- checkpoint.conversationId,
758
- checkpoint.throughSequence,
759
- );
760
- if (canonicalDigest !== checkpoint.tailDigest) {
761
- return yield* CheckpointRejected.make({
762
- conversationId: checkpoint.conversationId,
763
- reason: "digest-mismatch",
764
- });
765
- }
766
- return Option.some(checkpoint);
767
- });
768
-
769
- const conversationStore = ConversationStore.of({
770
- append,
771
- export: exportConversation,
772
- inspectTail,
773
- loadCheckpoint,
774
- materialize,
775
- observe,
776
- read,
777
- saveCheckpoint,
778
- });
779
-
780
- return Context.make(ConversationStore, conversationStore);
781
- });
782
-
783
- /**
784
- * Durable Object Conversation Store implementation with configuration, failpoint, SQL, and
785
- * Crypto authority kept visible in its input channel.
786
- */
787
- export const conversationStoreLayer: Layer.Layer<
788
- ConversationStore,
789
- DoStorageInitializationError,
790
- DoStorageConfig | DoStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto
791
- > = Layer.effectContext(makeServices());
792
-
793
- /**
794
- * Validated Durable Object storage configuration Layer with the documented defaults applied.
795
- * Shared by the ConversationStore and SubmissionLedger convenience layers so their defaults
796
- * cannot drift.
797
- */
798
- export const storageConfigLayer = (
799
- options: DoStorageOptions,
800
- ): Layer.Layer<DoStorageConfig, DoStorageError> =>
801
- Layer.effect(DoStorageConfig)(
802
- Schema.decodeUnknownEffect(DoStorageConfigValue)({
803
- observationPollInterval: options.observationPollInterval ?? 25,
804
- ownershipLeaseDuration:
805
- options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),
806
- maxStoredValueBytes: options.maxStoredValueBytes ?? DEFAULT_MAX_STORED_VALUE_BYTES,
807
- verifyOnOpen: options.verifyOnOpen ?? false,
808
- }).pipe(
809
- Effect.mapError((error) =>
810
- DoStorageError.make({
811
- cause: error,
812
- operation: "configure Durable Object storage",
813
- message: error.message,
814
- }),
815
- ),
816
- ),
817
- );
818
-
819
- /** The failpoint Layer selected by convenience options: explicit handler or the no-op default. */
820
- export const storageFailpointLayer = (
821
- options: DoStorageOptions,
822
- ): Layer.Layer<DoStorageFailpoint> =>
823
- options.failpoint === undefined
824
- ? DoStorageFailpoint.layer
825
- : Layer.succeed(DoStorageFailpoint)({ hit: options.failpoint });
826
-
827
- /**
828
- * A composition-root convenience Layer for canonical Conversations inside one Durable Object,
829
- * built over `ctx.storage`. Durable accepted work is served by the separate SubmissionLedger
830
- * port; point both at the SAME `ctx.storage` so claims fence the same producer epochs
831
- * (ADR-0011 D7's "same file" rule, transposed to one object's private database).
832
- */
833
- export const layer = (
834
- options: DoStorageOptions,
835
- ): Layer.Layer<ConversationStore, DoStorageInitializationError> => {
836
- const sqlLayer = SqliteClient.layer({ storage: options.storage });
837
- return conversationStoreLayer.pipe(
838
- Layer.provide(
839
- Layer.mergeAll(
840
- storageConfigLayer(options),
841
- storageFailpointLayer(options),
842
- sqlLayer,
843
- BrowserCrypto.layer,
844
- ),
845
- ),
846
- );
847
- };
848
-
849
- /** Create an adapter-owned resumable observation offset for a known canonical sequence. */
850
- export const observationOffsetAt = makeOffset;