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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore.d.mts +30 -0
  3. package/dist/DoMemoryStore.mjs +66 -0
  4. package/dist/DoMemoryStore.mjs.map +1 -0
  5. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  6. package/dist/DoMessageDeliveryStore.mjs +30 -0
  7. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  8. package/dist/DoScheduleStore.d.mts +36 -0
  9. package/dist/DoScheduleStore.mjs +388 -0
  10. package/dist/DoScheduleStore.mjs.map +1 -0
  11. package/dist/DoStorageConfig.d.mts +45 -0
  12. package/dist/DoStorageConfig.mjs +52 -0
  13. package/dist/DoStorageConfig.mjs.map +1 -0
  14. package/dist/DoStorageError-CGuAfSwF.d.mts +101 -0
  15. package/dist/DoStorageError.d.mts +2 -0
  16. package/dist/DoStorageError.mjs +167 -0
  17. package/dist/DoStorageError.mjs.map +1 -0
  18. package/dist/DoStorageFailpoint.d.mts +17 -0
  19. package/dist/DoStorageFailpoint.mjs +14 -0
  20. package/dist/DoStorageFailpoint.mjs.map +1 -0
  21. package/dist/DoStorageFailpointTesting.d.mts +24 -0
  22. package/dist/DoStorageFailpointTesting.mjs +22 -0
  23. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  24. package/dist/DoStorageVersion-iNSyi3cJ.d.mts +12 -0
  25. package/dist/DoStorageVersion.d.mts +2 -0
  26. package/dist/DoStorageVersion.mjs +8 -0
  27. package/dist/DoStorageVersion.mjs.map +1 -0
  28. package/dist/DoSubmissionLedger.d.mts +23 -0
  29. package/dist/DoSubmissionLedger.mjs +1979 -0
  30. package/dist/DoSubmissionLedger.mjs.map +1 -0
  31. package/dist/DoSubscriptionStore.d.mts +25 -0
  32. package/dist/DoSubscriptionStore.mjs +186 -0
  33. package/dist/DoSubscriptionStore.mjs.map +1 -0
  34. package/dist/DoThreadStore-D_83OjCH.d.mts +72 -0
  35. package/dist/DoThreadStore.d.mts +2 -0
  36. package/dist/DoThreadStore.mjs +529 -0
  37. package/dist/DoThreadStore.mjs.map +1 -0
  38. package/dist/MemoryProtocol.d.mts +38160 -0
  39. package/dist/MemoryProtocol.mjs +219 -0
  40. package/dist/MemoryProtocol.mjs.map +1 -0
  41. package/dist/PortProtocol.d.mts +7726 -0
  42. package/dist/PortProtocol.mjs +234 -0
  43. package/dist/PortProtocol.mjs.map +1 -0
  44. package/dist/PortRouting.d.mts +97 -0
  45. package/dist/PortRouting.mjs +544 -0
  46. package/dist/PortRouting.mjs.map +1 -0
  47. package/dist/do-journal-DUhjZkOf.mjs +1352 -0
  48. package/dist/do-journal-DUhjZkOf.mjs.map +1 -0
  49. package/dist/index.d.mts +14 -0
  50. package/dist/index.mjs +14 -0
  51. package/dist/migrations-DtKz_Gxr.mjs +306 -0
  52. package/dist/migrations-DtKz_Gxr.mjs.map +1 -0
  53. package/dist/owned-state-DHm2aRXx.mjs +119 -0
  54. package/dist/owned-state-DHm2aRXx.mjs.map +1 -0
  55. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  56. package/package.json +1 -0
  57. package/src/DoMemoryStore.ts +73 -0
  58. package/src/DoMessageDeliveryStore.ts +39 -0
  59. package/src/DoScheduleStore.ts +622 -0
  60. package/src/DoStorageConfig.ts +53 -0
  61. package/src/DoStorageError.ts +180 -0
  62. package/src/DoStorageFailpoint.ts +20 -0
  63. package/src/DoStorageFailpointTesting.ts +41 -0
  64. package/src/DoStorageVersion.ts +2 -0
  65. package/src/DoSubmissionLedger.ts +4027 -0
  66. package/src/DoSubscriptionStore.ts +327 -0
  67. package/src/DoThreadStore.ts +1121 -0
  68. package/src/MemoryProtocol.ts +355 -0
  69. package/src/PortProtocol.ts +436 -0
  70. package/src/PortRouting.ts +1464 -0
  71. package/src/index.ts +13 -0
  72. package/src/internal/do-journal.ts +2282 -0
  73. package/src/internal/message-delivery-schema.ts +24 -0
  74. package/src/internal/migrations.ts +304 -0
  75. package/src/internal/owned-state.ts +228 -0
  76. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  77. package/src/internal/storage-span.ts +44 -0
@@ -0,0 +1,1121 @@
1
+ import { BrowserCrypto } from "@effect/platform-browser";
2
+ import { SqliteClient } from "@effect/sql-sqlite-do";
3
+ import {
4
+ makeSelectedReads,
5
+ SelectedReadOwner,
6
+ } from "@yielded/agent-storage-sql/sql-thread-native-reads";
7
+ import { digestCanonicalBatch, EMPTY_TAIL_DIGEST } from "@yielded/agent/digest";
8
+ import {
9
+ CanonicalBatch,
10
+ CanonicalRecord,
11
+ CanonicalRecordEnvelope,
12
+ CanonicalSequence,
13
+ Digest,
14
+ ObservationOffset,
15
+ } from "@yielded/agent/records";
16
+ import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
17
+ import { DEFAULT_OWNERSHIP_LEASE_DURATION } from "@yielded/agent/submission-ledger";
18
+ import {
19
+ AppendConflict,
20
+ AppendResult,
21
+ CheckpointRejected,
22
+ ThreadCheckpoint,
23
+ ThreadExport,
24
+ ThreadExportRequest,
25
+ ThreadMaterialization,
26
+ ThreadNotMaterialized,
27
+ ThreadObservation,
28
+ ThreadReadRequest,
29
+ ThreadStore,
30
+ type ThreadCheckpoints,
31
+ ThreadStoreError,
32
+ ThreadStoreDiagnostic,
33
+ ThreadTail,
34
+ ThreadTailRequest,
35
+ FenceRejected,
36
+ FencedAppendRequest,
37
+ LoadCheckpointRequest,
38
+ SaveCheckpointRequest,
39
+ SaveRecoveryCheckpointRequest,
40
+ MAX_THREAD_EXPORT_RECORDS,
41
+ type ThreadRecoveryCheckpoints,
42
+ } from "@yielded/agent/thread-store";
43
+ import {
44
+ Clock,
45
+ Context,
46
+ Crypto,
47
+ Duration,
48
+ Effect,
49
+ Layer,
50
+ Option,
51
+ Ref,
52
+ Schema,
53
+ Stream,
54
+ } from "effect";
55
+ import * as SqlClientService from "effect/sql/SqlClient";
56
+
57
+ import {
58
+ DEFAULT_MAX_STORED_VALUE_BYTES,
59
+ DoStorageConfig,
60
+ DoStorageConfigValue,
61
+ } from "./DoStorageConfig.ts";
62
+ import {
63
+ type DoStorageCompatibilityError,
64
+ DoAppendConflict,
65
+ DoCheckpointConflict,
66
+ DoFenceRejected,
67
+ type DoStorageFailpointLocation,
68
+ DoStorageCorruptionError,
69
+ DoStorageError,
70
+ } from "./DoStorageError.ts";
71
+ import { DoStorageFailpoint, type DoStorageFailpointHandler } from "./DoStorageFailpoint.ts";
72
+ import {
73
+ initializeDoJournal,
74
+ RawAppendRequest,
75
+ RawCheckpoint,
76
+ RawReadRequest,
77
+ type DoJournal,
78
+ } from "./internal/do-journal.ts";
79
+ import { invalidateOwnedState, ownedState } from "./internal/owned-state.ts";
80
+ import { isAppendContention, withStorageSpan } from "./internal/storage-span.ts";
81
+
82
+ /**
83
+ * Convenience-layer construction options. `storage` is the Durable Object's own
84
+ * `ctx.storage` handle, injected as a value (DEPLOY-010: platform bindings enter only
85
+ * through Layers; this package never imports `cloudflare:workers`).
86
+ */
87
+ export interface DoStorageOptions {
88
+ readonly storage: DurableObjectStorage;
89
+ readonly observationPollInterval?: number | undefined;
90
+ /**
91
+ * Submission ownership lease duration in milliseconds (D5). Defaults to
92
+ * `DEFAULT_OWNERSHIP_LEASE_DURATION` from `@yielded/agent/submission-ledger`.
93
+ */
94
+ readonly ownershipLeaseDuration?: number | undefined;
95
+ /**
96
+ * Maximum bytes for any single stored value; must stay under the platform's 2 MB
97
+ * per-value limit. Defaults to `DEFAULT_MAX_STORED_VALUE_BYTES`.
98
+ */
99
+ readonly maxStoredValueBytes?: number | undefined;
100
+ /**
101
+ * Re-verify every stored payload and digest chain while opening the store. Defaults to
102
+ * off: per-operation Schema decoding and the digest chain already fail clearly on corrupt
103
+ * rows without scanning the whole database on every open.
104
+ */
105
+ readonly verifyOnOpen?: boolean | undefined;
106
+ readonly failpoint?: DoStorageFailpointHandler | undefined;
107
+ }
108
+
109
+ export type DoStorageInitializationError =
110
+ | DoStorageCompatibilityError
111
+ | DoStorageCorruptionError
112
+ | DoStorageError;
113
+
114
+ const OffsetText = Schema.String.check(Schema.isMaxLength(4 * 1024));
115
+ const DO_OFFSET_PREFIX = "effect-agent-do@1:";
116
+ const ZERO_CANONICAL_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
117
+ const isDigest = Schema.is(Digest);
118
+ const isDoFenceRejected = Schema.is(DoFenceRejected);
119
+ const isDoAppendConflict = Schema.is(DoAppendConflict);
120
+ const isDoCheckpointConflict = Schema.is(DoCheckpointConflict);
121
+ // Reuse the same AST/parser across reads. Reconstructing a JSON codec per row
122
+ // defeats Schema's parser cache and repeatedly walks the canonical union.
123
+ const CanonicalRecordJson = Schema.fromJsonString(CanonicalRecord);
124
+ const CanonicalBatchJson = Schema.fromJsonString(CanonicalBatch);
125
+ const ThreadCheckpointJson = Schema.fromJsonString(ThreadCheckpoint);
126
+ const decodeCanonicalRecord = Schema.decodeEffect(CanonicalRecordJson);
127
+
128
+ const storeError = (
129
+ operation: string,
130
+ error: { readonly message: string; readonly diagnostic?: ThreadStoreDiagnostic },
131
+ ) =>
132
+ ThreadStoreError.make({
133
+ cause: error,
134
+ operation,
135
+ message: error.message,
136
+ ...(error.diagnostic === undefined ? {} : { diagnostic: error.diagnostic }),
137
+ });
138
+
139
+ const schemaStoreError = (operation: string, error: Schema.SchemaError) =>
140
+ ThreadStoreError.make({
141
+ operation,
142
+ message: "A Thread storage value does not satisfy its schema",
143
+ diagnostic: ThreadStoreDiagnostic.make({
144
+ causeTag: error._tag,
145
+ operation,
146
+ issueTag: error.issue._tag,
147
+ }),
148
+ });
149
+
150
+ const makeOffset = Effect.fn(function* (
151
+ threadId: ThreadMaterialization["threadId"],
152
+ sequence: number,
153
+ ): Effect.fn.Return<ObservationOffset, ThreadStoreError> {
154
+ return yield* Schema.decodeEffect(CanonicalSequence)(sequence).pipe(
155
+ Effect.flatMap((validatedSequence) =>
156
+ Schema.decodeEffect(ObservationOffset)(
157
+ `${DO_OFFSET_PREFIX}${encodeURIComponent(threadId)}:${validatedSequence}`,
158
+ ),
159
+ ),
160
+ Effect.mapError((error) => schemaStoreError("encode observation offset", error)),
161
+ );
162
+ });
163
+
164
+ const parseOffset = Effect.fn(function* (
165
+ threadId: ThreadMaterialization["threadId"],
166
+ offset: ObservationOffset | undefined,
167
+ ): Effect.fn.Return<CanonicalSequence, ThreadStoreError> {
168
+ if (offset === undefined) return ZERO_CANONICAL_SEQUENCE;
169
+
170
+ const text = yield* Schema.decodeEffect(OffsetText)(offset).pipe(
171
+ Effect.mapError((error) => schemaStoreError("decode observation offset", error)),
172
+ );
173
+
174
+ const threadPrefix = `${DO_OFFSET_PREFIX}${encodeURIComponent(threadId)}:`;
175
+
176
+ if (!text.startsWith(threadPrefix)) {
177
+ return yield* ThreadStoreError.make({
178
+ operation: "decode observation offset",
179
+ message: "The observation offset belongs to a different adapter, storage version, or Thread.",
180
+ });
181
+ }
182
+ const sequenceText = text.slice(threadPrefix.length);
183
+
184
+ if (!/^(0|[1-9][0-9]*)$/.test(sequenceText)) {
185
+ return yield* ThreadStoreError.make({
186
+ operation: "decode observation offset",
187
+ message: "The observation offset is malformed.",
188
+ });
189
+ }
190
+
191
+ return yield* Schema.decodeEffect(CanonicalSequence)(Number(sequenceText)).pipe(
192
+ Effect.mapError((error) => schemaStoreError("decode observation offset", error)),
193
+ );
194
+ });
195
+
196
+ const mapFence = (threadId: ThreadMaterialization["threadId"], error: DoFenceRejected) =>
197
+ FenceRejected.make({
198
+ threadId,
199
+ actualEpoch: error.actualEpoch,
200
+ attemptedEpoch: error.producerEpoch,
201
+ });
202
+
203
+ const encodeCanonicalRecord = Effect.fn(function* (
204
+ record: CanonicalRecord,
205
+ ): Effect.fn.Return<string, ThreadStoreError> {
206
+ return yield* Schema.encodeEffect(CanonicalRecordJson)(record).pipe(
207
+ Effect.mapError((error) => schemaStoreError("encode canonical record", error)),
208
+ );
209
+ });
210
+
211
+ const encodeCanonicalBatch = Effect.fn(function* (
212
+ batch: CanonicalBatch,
213
+ ): Effect.fn.Return<string, ThreadStoreError> {
214
+ return yield* Schema.encodeEffect(CanonicalBatchJson)(batch).pipe(
215
+ Effect.mapError((error) => schemaStoreError("encode canonical batch", error)),
216
+ );
217
+ });
218
+
219
+ const encodeCheckpoint = Effect.fn(function* (
220
+ checkpoint: ThreadCheckpoint,
221
+ ): Effect.fn.Return<string, ThreadStoreError> {
222
+ return yield* Schema.encodeEffect(ThreadCheckpointJson)(checkpoint).pipe(
223
+ Effect.mapError((error) => schemaStoreError("encode checkpoint", error)),
224
+ );
225
+ });
226
+
227
+ const envelopes = new WeakMap<object, CanonicalRecordEnvelope>();
228
+
229
+ const decodeEnvelope = Effect.fnUntraced(function* (row: {
230
+ readonly batch_id: string;
231
+ readonly thread_id: string;
232
+ readonly record_json: string;
233
+ readonly sequence: CanonicalSequence;
234
+ }) {
235
+ const cached = envelopes.get(row);
236
+
237
+ if (cached !== undefined) return cached;
238
+
239
+ const record = yield* decodeCanonicalRecord(row.record_json).pipe(
240
+ Effect.mapError((error) =>
241
+ ThreadStoreError.make({
242
+ operation: "decode canonical record",
243
+ message: "The canonical record does not satisfy its schema",
244
+ diagnostic: ThreadStoreDiagnostic.make({
245
+ causeTag: error._tag,
246
+ operation: "decode canonical record",
247
+ decoder: "CanonicalRecord",
248
+ sequence: row.sequence,
249
+ issueTag: error.issue._tag,
250
+ }),
251
+ }),
252
+ ),
253
+ Effect.tapError((error) =>
254
+ Effect.annotateCurrentSpan({
255
+ "storage.failure.operation": error.diagnostic?.operation,
256
+ "storage.failure.cause": error.diagnostic?.causeTag,
257
+ "storage.failure.decoder": error.diagnostic?.decoder,
258
+ "storage.failure.sequence": row.sequence,
259
+ "storage.failure.issue": error.diagnostic?.issueTag,
260
+ }),
261
+ ),
262
+ );
263
+
264
+ const threadId = yield* Schema.decodeEffect(CanonicalRecordEnvelope.fields.threadId)(
265
+ row.thread_id,
266
+ ).pipe(Effect.mapError((error) => schemaStoreError("decode thread identity", error)));
267
+
268
+ const offset = yield* makeOffset(threadId, row.sequence);
269
+
270
+ const batchId = yield* Schema.decodeEffect(CanonicalRecordEnvelope.fields.batchId)(
271
+ row.batch_id,
272
+ ).pipe(Effect.mapError((error) => schemaStoreError("decode batch identity", error)));
273
+
274
+ const envelope = CanonicalRecordEnvelope.make({
275
+ threadId,
276
+ batchId,
277
+ sequence: row.sequence,
278
+ offset,
279
+ record,
280
+ });
281
+
282
+ envelopes.set(row, envelope);
283
+
284
+ return envelope;
285
+ });
286
+
287
+ const decodeCheckpoint = Effect.fn(function* (
288
+ checkpointJson: string,
289
+ ): Effect.fn.Return<ThreadCheckpoint, ThreadStoreError> {
290
+ return yield* Schema.decodeEffect(Schema.fromJsonString(ThreadCheckpoint))(checkpointJson).pipe(
291
+ Effect.mapError((error) => schemaStoreError("decode checkpoint", error)),
292
+ );
293
+ });
294
+
295
+ const requireThread = Effect.fn("DoThreadStore.requireThread")(function* (
296
+ journal: DoJournal,
297
+ threadId: ThreadMaterialization["threadId"],
298
+ ) {
299
+ const rows = yield* journal
300
+ .getThread(threadId)
301
+ .pipe(Effect.mapError((error) => storeError("read thread", error)));
302
+
303
+ if (rows.length === 0) {
304
+ return yield* ThreadNotMaterialized.make({ threadId });
305
+ }
306
+
307
+ return rows[0];
308
+ });
309
+
310
+ const tailDigestAt = Effect.fn("DoThreadStore.tailDigestAt")(function* (
311
+ journal: DoJournal,
312
+ threadId: ThreadMaterialization["threadId"],
313
+ sequence: CanonicalSequence,
314
+ ) {
315
+ if (sequence === 0) return EMPTY_TAIL_DIGEST;
316
+
317
+ const digests = yield* journal
318
+ .getTailDigestAt(threadId, sequence)
319
+ .pipe(Effect.mapError((error) => storeError("read checkpoint digest", error)));
320
+
321
+ if (digests.length !== 1) {
322
+ return yield* CheckpointRejected.make({
323
+ threadId,
324
+ reason: "digest-mismatch",
325
+ });
326
+ }
327
+
328
+ return yield* Schema.decodeEffect(Digest)(digests[0]).pipe(
329
+ Effect.mapError((error) => schemaStoreError("decode checkpoint digest", error)),
330
+ );
331
+ });
332
+
333
+ const groupByKey = <A>(
334
+ rows: ReadonlyArray<A>,
335
+ key: (row: A) => string,
336
+ ): ReadonlyMap<string, ReadonlyArray<A>> => {
337
+ const grouped = new Map<string, Array<A>>();
338
+
339
+ for (const row of rows) {
340
+ const existing = grouped.get(key(row));
341
+
342
+ if (existing === undefined) {
343
+ grouped.set(key(row), [row]);
344
+ } else {
345
+ existing.push(row);
346
+ }
347
+ }
348
+
349
+ return grouped;
350
+ };
351
+
352
+ /**
353
+ * Opt-in integrity audit (`verifyOnOpen`) of canonical payloads, their digest chains and generic
354
+ * projection checkpoints. Disposable recovery checkpoints are validated when loaded. Routine opens
355
+ * skip this scan: per-operation Schema decoding fails clearly on corrupt canonical rows.
356
+ */
357
+ const decodeStartupPayloads = Effect.fn("DoThreadStore.decodeStartupPayloads")(function* (
358
+ journal: DoJournal,
359
+ crypto: Crypto.Crypto,
360
+ ) {
361
+ const stored = yield* journal.scanStoredPayloads();
362
+
363
+ const batches = yield* Effect.forEach(stored.batches, (batch) =>
364
+ Schema.decodeEffect(Schema.fromJsonString(CanonicalBatch))(batch.batch_json).pipe(
365
+ Effect.map((decoded) => ({ decoded, row: batch })),
366
+ Effect.mapError((error) =>
367
+ DoStorageCorruptionError.make({
368
+ table: "effect_agent_canonical_batches",
369
+ rowKey: `${batch.thread_id}/${batch.batch_id}`,
370
+ message: error.message,
371
+ }),
372
+ ),
373
+ ),
374
+ );
375
+
376
+ const records = yield* Effect.forEach(stored.records, (record) =>
377
+ Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(record.record_json).pipe(
378
+ Effect.map((decoded) => ({ decoded, row: record })),
379
+ Effect.mapError((error) =>
380
+ DoStorageCorruptionError.make({
381
+ table: "effect_agent_canonical_records",
382
+ rowKey: `${record.thread_id}/${record.sequence}`,
383
+ message: error.message,
384
+ }),
385
+ ),
386
+ ),
387
+ );
388
+
389
+ const checkpoints = yield* Effect.forEach(stored.checkpoints, (checkpoint) =>
390
+ Schema.decodeEffect(Schema.fromJsonString(ThreadCheckpoint))(checkpoint.checkpoint_json).pipe(
391
+ Effect.map((decoded) => ({ decoded, row: checkpoint })),
392
+ Effect.mapError((error) =>
393
+ DoStorageCorruptionError.make({
394
+ table: "effect_agent_checkpoints",
395
+ rowKey: `${checkpoint.thread_id}/${checkpoint.through_sequence}`,
396
+ message: error.message,
397
+ }),
398
+ ),
399
+ ),
400
+ );
401
+
402
+ const batchesByThread = groupByKey(batches, ({ row }) => row.thread_id);
403
+ const recordsByThread = groupByKey(records, ({ row }) => row.thread_id);
404
+ const checkpointsByThread = groupByKey(checkpoints, ({ row }) => row.thread_id);
405
+ const materializedIds = new Set(stored.threads.map((thread) => thread.thread_id));
406
+
407
+ for (const thread of stored.threads) {
408
+ const threadBatches = batchesByThread.get(thread.thread_id) ?? [];
409
+ const threadRecords = recordsByThread.get(thread.thread_id) ?? [];
410
+ const threadCheckpoints = checkpointsByThread.get(thread.thread_id) ?? [];
411
+ const recordsByBatch = groupByKey(threadRecords, ({ row }) => row.batch_id);
412
+ let previousDigest = EMPTY_TAIL_DIGEST;
413
+ let expectedSequence = 1;
414
+ const tailDigests = new Map<number, string>([[0, EMPTY_TAIL_DIGEST]]);
415
+
416
+ for (const { decoded: canonicalBatch, row: batchRow } of threadBatches) {
417
+ const key = `${batchRow.thread_id}/${batchRow.batch_id}`;
418
+
419
+ if (
420
+ canonicalBatch.batchId !== batchRow.batch_id ||
421
+ batchRow.first_sequence !== expectedSequence ||
422
+ batchRow.last_sequence !== batchRow.first_sequence + canonicalBatch.records.length - 1
423
+ ) {
424
+ return yield* DoStorageCorruptionError.make({
425
+ table: "effect_agent_canonical_batches",
426
+ rowKey: key,
427
+ message: "Canonical batch identity, sequence, or record count is inconsistent.",
428
+ });
429
+ }
430
+
431
+ const digest = yield* digestCanonicalBatch(previousDigest, canonicalBatch).pipe(
432
+ Effect.provideService(Crypto.Crypto, crypto),
433
+ Effect.mapError((error) =>
434
+ DoStorageCorruptionError.make({
435
+ table: "effect_agent_canonical_batches",
436
+ rowKey: key,
437
+ message: error.message,
438
+ }),
439
+ ),
440
+ );
441
+
442
+ if (batchRow.batch_digest !== digest || batchRow.tail_digest !== digest) {
443
+ return yield* DoStorageCorruptionError.make({
444
+ table: "effect_agent_canonical_batches",
445
+ rowKey: key,
446
+ message: "Canonical batch digest does not match its decoded content and prior tail.",
447
+ });
448
+ }
449
+
450
+ const batchRecords = recordsByBatch.get(batchRow.batch_id) ?? [];
451
+
452
+ if (batchRecords.length !== canonicalBatch.records.length) {
453
+ return yield* DoStorageCorruptionError.make({
454
+ table: "effect_agent_canonical_records",
455
+ rowKey: key,
456
+ message: "Canonical batch and record-table counts differ.",
457
+ });
458
+ }
459
+ for (let index = 0; index < canonicalBatch.records.length; index++) {
460
+ const expectedRecord = canonicalBatch.records[index];
461
+ const storedRecord = batchRecords[index];
462
+
463
+ const expectedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(
464
+ expectedRecord,
465
+ ).pipe(
466
+ Effect.mapError((error) =>
467
+ DoStorageCorruptionError.make({
468
+ table: "effect_agent_canonical_batches",
469
+ rowKey: key,
470
+ message: error.message,
471
+ }),
472
+ ),
473
+ );
474
+
475
+ const storedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(
476
+ storedRecord.decoded,
477
+ ).pipe(
478
+ Effect.mapError((error) =>
479
+ DoStorageCorruptionError.make({
480
+ table: "effect_agent_canonical_records",
481
+ rowKey: `${key}/${storedRecord.row.sequence}`,
482
+ message: error.message,
483
+ }),
484
+ ),
485
+ );
486
+
487
+ if (
488
+ storedRecord.row.sequence !== batchRow.first_sequence + index ||
489
+ storedRecord.row.record_id !== expectedRecord.recordId ||
490
+ expectedJson !== storedJson
491
+ ) {
492
+ return yield* DoStorageCorruptionError.make({
493
+ table: "effect_agent_canonical_records",
494
+ rowKey: `${key}/${storedRecord.row.sequence}`,
495
+ message: "Canonical record identity, sequence, or payload differs from its batch.",
496
+ });
497
+ }
498
+ }
499
+
500
+ previousDigest = digest;
501
+ expectedSequence = batchRow.last_sequence + 1;
502
+ tailDigests.set(batchRow.last_sequence, digest);
503
+ }
504
+
505
+ if (
506
+ threadRecords.length !== thread.tail_sequence ||
507
+ thread.tail_sequence !== expectedSequence - 1 ||
508
+ thread.tail_digest !== previousDigest
509
+ ) {
510
+ return yield* DoStorageCorruptionError.make({
511
+ table: "effect_agent_threads",
512
+ rowKey: thread.thread_id,
513
+ message: "Thread tail does not match its canonical batch chain.",
514
+ });
515
+ }
516
+
517
+ for (const checkpoint of threadCheckpoints) {
518
+ if (
519
+ checkpoint.decoded.threadId !== thread.thread_id ||
520
+ checkpoint.decoded.throughSequence !== checkpoint.row.through_sequence ||
521
+ checkpoint.decoded.tailDigest !== checkpoint.row.tail_digest ||
522
+ tailDigests.get(checkpoint.row.through_sequence) !== checkpoint.row.tail_digest
523
+ ) {
524
+ return yield* DoStorageCorruptionError.make({
525
+ table: "effect_agent_checkpoints",
526
+ rowKey: `${thread.thread_id}/${checkpoint.row.through_sequence}`,
527
+ message: "Checkpoint identity or digest is not bound to a canonical batch tail.",
528
+ });
529
+ }
530
+ }
531
+ }
532
+
533
+ if (
534
+ batches.some(({ row }) => !materializedIds.has(row.thread_id)) ||
535
+ records.some(({ row }) => !materializedIds.has(row.thread_id)) ||
536
+ checkpoints.some(({ row }) => !materializedIds.has(row.thread_id))
537
+ ) {
538
+ return yield* DoStorageCorruptionError.make({
539
+ table: "effect_agent_threads",
540
+ rowKey: "startup_scan",
541
+ message: "Canonical rows exist without a materialized Thread.",
542
+ });
543
+ }
544
+ });
545
+
546
+ const makeServices = Effect.fn("DoThreadStore.makeServices")(function* () {
547
+ const config = yield* DoStorageConfig;
548
+ const failpoint = yield* DoStorageFailpoint;
549
+ const sql = yield* SqlClientService.SqlClient;
550
+ const crypto = yield* Crypto.Crypto;
551
+ const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes);
552
+
553
+ if (config.verifyOnOpen) {
554
+ yield* decodeStartupPayloads(journal, crypto);
555
+ }
556
+
557
+ const provideCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>
558
+ Effect.provideService(effect, Crypto.Crypto, crypto);
559
+
560
+ const hitFailpoint = Effect.fn(
561
+ (location: DoStorageFailpointLocation): Effect.Effect<void, ThreadStoreError> =>
562
+ failpoint
563
+ .hit(location)
564
+ .pipe(Effect.mapError((error) => storeError(`storage failpoint ${location}`, error))),
565
+ );
566
+
567
+ const materialize: ThreadStore["Service"]["materialize"] = Effect.fnUntraced(
568
+ function* (request: ThreadMaterialization) {
569
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadMaterialization))(
570
+ request,
571
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate materialization", error)));
572
+
573
+ const now = yield* Clock.currentTimeMillis;
574
+
575
+ yield* hitFailpoint("materialize:before");
576
+ yield* journal
577
+ .materialize(
578
+ validated.threadId,
579
+ new Date(now).toISOString(),
580
+ EMPTY_TAIL_DIGEST,
581
+ validated.producerEpoch,
582
+ )
583
+ .pipe(
584
+ Effect.mapError((error) =>
585
+ error._tag === "DoFenceRejected"
586
+ ? mapFence(validated.threadId, error)
587
+ : storeError("materialize thread", error),
588
+ ),
589
+ );
590
+ yield* hitFailpoint("materialize:after");
591
+ },
592
+ withStorageSpan("DoThreadStore.materialize", (error) => error._tag === "FenceRejected"),
593
+ );
594
+
595
+ const append: ThreadStore["Service"]["append"] = Effect.fnUntraced(
596
+ function* (request: FencedAppendRequest) {
597
+ const validated = yield* Schema.decodeEffect(Schema.toType(FencedAppendRequest))(
598
+ request,
599
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate canonical append", error)));
600
+
601
+ const observed = yield* requireThread(journal, validated.threadId);
602
+
603
+ const tailDigest = yield* provideCrypto(
604
+ digestCanonicalBatch(validated.expectedTailDigest, validated.batch),
605
+ ).pipe(Effect.mapError((error) => storeError("digest canonical append", error)));
606
+
607
+ const batchJson = yield* encodeCanonicalBatch(validated.batch);
608
+
609
+ const rawRecords = yield* Effect.forEach(validated.batch.records, (record) =>
610
+ encodeCanonicalRecord(record).pipe(
611
+ Effect.map((recordJson) => ({
612
+ recordId: record.recordId,
613
+ recordJson,
614
+ })),
615
+ ),
616
+ );
617
+
618
+ const rawRequest = yield* Schema.decodeEffect(RawAppendRequest)({
619
+ threadId: validated.threadId,
620
+ batchId: validated.batch.batchId,
621
+ batchDigest: tailDigest,
622
+ batchJson,
623
+ expectedTailSequence: validated.expectedTailSequence,
624
+ expectedTailDigest: validated.expectedTailDigest,
625
+ producerEpoch: validated.producerEpoch,
626
+ records: rawRecords,
627
+ tailDigest,
628
+ }).pipe(Effect.mapError((error) => schemaStoreError("encode canonical append", error)));
629
+
630
+ yield* hitFailpoint("append:before");
631
+
632
+ const result = yield* journal.append(rawRequest, observed).pipe(
633
+ Effect.mapError((error) => {
634
+ if (isDoFenceRejected(error)) {
635
+ return mapFence(validated.threadId, error);
636
+ }
637
+ if (isDoAppendConflict(error)) {
638
+ return error.actualTailSequence !== undefined && isDigest(error.actualTailDigest)
639
+ ? AppendConflict.make({
640
+ threadId: validated.threadId,
641
+ batchId: validated.batch.batchId,
642
+ reason: error.reason,
643
+ actualTailSequence: error.actualTailSequence,
644
+ actualTailDigest: error.actualTailDigest,
645
+ })
646
+ : AppendConflict.make({
647
+ threadId: validated.threadId,
648
+ batchId: validated.batch.batchId,
649
+ reason: error.reason,
650
+ });
651
+ }
652
+
653
+ return storeError("append canonical batch", error);
654
+ }),
655
+ Effect.flatMap((result) =>
656
+ Schema.decodeEffect(AppendResult)(result).pipe(
657
+ Effect.mapError((error) => schemaStoreError("decode append result", error)),
658
+ ),
659
+ ),
660
+ );
661
+
662
+ yield* hitFailpoint("append:after");
663
+
664
+ return result;
665
+ },
666
+ withStorageSpan("DoThreadStore.append", isAppendContention),
667
+ );
668
+
669
+ const loadRecords = Effect.fnUntraced(function* (request: RawReadRequest) {
670
+ const result = yield* journal
671
+ .read(request)
672
+ .pipe(Effect.mapError((error) => storeError("read canonical records", error)));
673
+
674
+ return {
675
+ count: result.count,
676
+ records: result.records.pipe(
677
+ Stream.mapError((error) => storeError("read canonical records", error)),
678
+ Stream.mapEffect(decodeEnvelope),
679
+ ),
680
+ };
681
+ });
682
+
683
+ const readEffect = Effect.fn("DoThreadStore.read")(function* (request: ThreadReadRequest) {
684
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadReadRequest))(request).pipe(
685
+ Effect.mapError((error) => schemaStoreError("validate thread read", error)),
686
+ );
687
+
688
+ if ("selection" in validated) return Stream.fromIterable(yield* selectedReads.read(validated));
689
+ yield* requireThread(journal, validated.threadId);
690
+
691
+ const result = yield* loadRecords(
692
+ RawReadRequest.make({
693
+ threadId: validated.threadId,
694
+ fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,
695
+ limit: validated.limit,
696
+ }),
697
+ );
698
+
699
+ return result.records;
700
+ });
701
+
702
+ const read: ThreadStore["Service"]["read"] = (request) => Stream.unwrap(readEffect(request));
703
+
704
+ const observeEffect = Effect.fnUntraced(function* (request: ThreadObservation) {
705
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadObservation))(request).pipe(
706
+ Effect.mapError((error) => schemaStoreError("validate thread observation", error)),
707
+ );
708
+
709
+ yield* requireThread(journal, validated.threadId);
710
+ const initialSequence = yield* parseOffset(validated.threadId, validated.afterOffset);
711
+ const cursor = yield* Ref.make(initialSequence);
712
+ let polls = 0;
713
+ let emptyPolls = 0;
714
+ let deliveredRecords = 0;
715
+
716
+ const poll = Effect.fnUntraced(function* () {
717
+ polls++;
718
+ const fromSequenceExclusive = yield* Ref.get(cursor);
719
+
720
+ const result = yield* loadRecords(
721
+ RawReadRequest.make({
722
+ threadId: validated.threadId,
723
+ fromSequenceExclusive,
724
+ limit: 1_024,
725
+ }),
726
+ );
727
+
728
+ if (result.count === 0) {
729
+ emptyPolls++;
730
+ yield* Effect.sleep(config.observationPollInterval);
731
+
732
+ return Stream.empty;
733
+ }
734
+
735
+ return result.records.pipe(
736
+ Stream.tap((record) => {
737
+ deliveredRecords++;
738
+
739
+ return Ref.set(cursor, record.sequence);
740
+ }),
741
+ );
742
+ });
743
+
744
+ return Stream.fromEffectRepeat(poll()).pipe(
745
+ Stream.flatten,
746
+ Stream.ensuring(
747
+ Effect.suspend(() =>
748
+ Effect.annotateCurrentSpan({
749
+ "effect_agent.observation.polls": polls,
750
+ "effect_agent.observation.empty_polls": emptyPolls,
751
+ "effect_agent.observation.records": deliveredRecords,
752
+ }),
753
+ ),
754
+ ),
755
+ );
756
+ });
757
+
758
+ const observe: ThreadStore["Service"]["observe"] = (request) =>
759
+ Stream.unwrap(observeEffect(request)).pipe(Stream.withSpan("DoThreadStore.observe"));
760
+
761
+ const exportThread: ThreadStore["Service"]["export"] = Effect.fn("DoThreadStore.export")(
762
+ function* (request: ThreadExportRequest) {
763
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadExportRequest))(
764
+ request,
765
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate thread export", error)));
766
+
767
+ yield* requireThread(journal, validated.threadId);
768
+
769
+ const exported = yield* journal
770
+ .exportThread(validated.threadId)
771
+ .pipe(Effect.mapError((error) => storeError("export thread", error)));
772
+
773
+ const records = yield* Effect.forEach(exported.records, decodeEnvelope);
774
+
775
+ if (records.length > MAX_THREAD_EXPORT_RECORDS) {
776
+ return yield* ThreadStoreError.make({
777
+ operation: "decode thread export",
778
+ message: "The thread exceeds the current export record limit.",
779
+ });
780
+ }
781
+
782
+ const tailDigest = yield* Schema.decodeEffect(Digest)(exported.thread.tail_digest).pipe(
783
+ Effect.mapError((error) => schemaStoreError("decode export tail digest", error)),
784
+ );
785
+
786
+ return ThreadExport.make({
787
+ format: "effect-agent/thread@1",
788
+ threadId: validated.threadId,
789
+ tailSequence: exported.thread.tail_sequence,
790
+ tailDigest,
791
+ records,
792
+ });
793
+ },
794
+ );
795
+
796
+ const inspectTail: ThreadStore["Service"]["inspectTail"] = Effect.fn("DoThreadStore.inspectTail")(
797
+ function* (request: ThreadTailRequest) {
798
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadTailRequest))(request).pipe(
799
+ Effect.mapError((error) => schemaStoreError("validate tail inspection", error)),
800
+ );
801
+
802
+ const thread = yield* requireThread(journal, validated.threadId);
803
+
804
+ const tailDigest = yield* Schema.decodeEffect(Digest)(thread.tail_digest).pipe(
805
+ Effect.mapError((error) => schemaStoreError("decode tail digest", error)),
806
+ );
807
+
808
+ return ThreadTail.make({
809
+ threadId: validated.threadId,
810
+ tailSequence: thread.tail_sequence,
811
+ tailDigest,
812
+ producerEpoch: thread.producer_epoch,
813
+ });
814
+ },
815
+ );
816
+
817
+ const saveCheckpoint: ThreadCheckpoints["save"] = Effect.fn("DoThreadStore.saveCheckpoint")(
818
+ function* (request: SaveCheckpointRequest) {
819
+ const validated = yield* Schema.decodeEffect(Schema.toType(SaveCheckpointRequest))(
820
+ request,
821
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint", error)));
822
+
823
+ const thread = yield* requireThread(journal, validated.checkpoint.threadId);
824
+
825
+ if (validated.checkpoint.throughSequence > thread.tail_sequence) {
826
+ return yield* CheckpointRejected.make({
827
+ threadId: validated.checkpoint.threadId,
828
+ reason: "ahead-of-tail",
829
+ });
830
+ }
831
+
832
+ const canonicalDigest = yield* tailDigestAt(
833
+ journal,
834
+ validated.checkpoint.threadId,
835
+ validated.checkpoint.throughSequence,
836
+ );
837
+
838
+ if (canonicalDigest !== validated.checkpoint.tailDigest) {
839
+ return yield* CheckpointRejected.make({
840
+ threadId: validated.checkpoint.threadId,
841
+ reason: "digest-mismatch",
842
+ });
843
+ }
844
+ const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);
845
+
846
+ const raw = RawCheckpoint.make({
847
+ threadId: validated.checkpoint.threadId,
848
+ throughSequence: validated.checkpoint.throughSequence,
849
+ tailDigest: validated.checkpoint.tailDigest,
850
+ checkpointJson,
851
+ });
852
+
853
+ yield* hitFailpoint("save-checkpoint:before");
854
+ yield* journal.saveCheckpoint(raw).pipe(
855
+ Effect.mapError((error) =>
856
+ isDoCheckpointConflict(error)
857
+ ? CheckpointRejected.make({
858
+ threadId: validated.checkpoint.threadId,
859
+ reason: "digest-mismatch",
860
+ })
861
+ : storeError("save checkpoint", error),
862
+ ),
863
+ );
864
+ yield* hitFailpoint("save-checkpoint:after");
865
+ },
866
+ );
867
+
868
+ const loadCheckpoint: ThreadCheckpoints["load"] = Effect.fn("DoThreadStore.loadCheckpoint")(
869
+ function* (request: LoadCheckpointRequest) {
870
+ const validated = yield* Schema.decodeEffect(Schema.toType(LoadCheckpointRequest))(
871
+ request,
872
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint lookup", error)));
873
+
874
+ const thread = yield* requireThread(journal, validated.threadId);
875
+
876
+ const rows = yield* journal
877
+ .loadCheckpoint(validated.threadId, validated.atOrBeforeSequence ?? thread.tail_sequence)
878
+ .pipe(Effect.mapError((error) => storeError("load checkpoint", error)));
879
+
880
+ if (rows.length === 0) return Option.none();
881
+ if (rows.length !== 1) {
882
+ return yield* ThreadStoreError.make({
883
+ operation: "load checkpoint",
884
+ message: `Expected at most one checkpoint row but found ${rows.length}.`,
885
+ });
886
+ }
887
+ const row = rows[0];
888
+ const checkpoint = yield* decodeCheckpoint(row.checkpoint_json);
889
+
890
+ if (
891
+ row.thread_id !== validated.threadId ||
892
+ checkpoint.threadId !== row.thread_id ||
893
+ checkpoint.throughSequence !== row.through_sequence ||
894
+ checkpoint.tailDigest !== row.tail_digest
895
+ ) {
896
+ return yield* ThreadStoreError.make({
897
+ operation: "load checkpoint",
898
+ message: "Stored checkpoint metadata does not match its canonical row.",
899
+ });
900
+ }
901
+
902
+ const canonicalDigest = yield* tailDigestAt(
903
+ journal,
904
+ checkpoint.threadId,
905
+ checkpoint.throughSequence,
906
+ );
907
+
908
+ if (canonicalDigest !== checkpoint.tailDigest) {
909
+ return yield* CheckpointRejected.make({
910
+ threadId: checkpoint.threadId,
911
+ reason: "digest-mismatch",
912
+ });
913
+ }
914
+
915
+ return Option.some(checkpoint);
916
+ },
917
+ );
918
+
919
+ const saveRecoveryCheckpoint: ThreadRecoveryCheckpoints["save"] = Effect.fn(
920
+ "DoThreadStore.saveRecoveryCheckpoint",
921
+ )(function* (request) {
922
+ const validated = yield* Schema.decodeEffect(Schema.toType(SaveRecoveryCheckpointRequest))(
923
+ request,
924
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate recovery checkpoint", error)));
925
+
926
+ const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);
927
+
928
+ yield* journal
929
+ .saveRecoveryCheckpoint(validated, checkpointJson)
930
+ .pipe(
931
+ Effect.mapError((error) =>
932
+ error._tag === "CheckpointRejected" ||
933
+ error._tag === "FenceRejected" ||
934
+ error._tag === "ThreadNotMaterialized"
935
+ ? error
936
+ : storeError("save recovery checkpoint", error),
937
+ ),
938
+ );
939
+ });
940
+
941
+ const loadRecoveryCheckpoint: ThreadRecoveryCheckpoints["load"] = Effect.fn(
942
+ "DoThreadStore.loadRecoveryCheckpoint",
943
+ )(function* (request) {
944
+ const validated = yield* Schema.decodeEffect(Schema.toType(LoadCheckpointRequest))(
945
+ request,
946
+ ).pipe(
947
+ Effect.mapError((error) => schemaStoreError("validate recovery checkpoint lookup", error)),
948
+ );
949
+
950
+ const thread = yield* requireThread(journal, validated.threadId);
951
+
952
+ const corrupt = () =>
953
+ CheckpointRejected.make({ threadId: validated.threadId, reason: "corrupt" });
954
+
955
+ const rows = yield* journal
956
+ .loadRecoveryCheckpoint(validated.threadId)
957
+ .pipe(
958
+ Effect.mapError((error) =>
959
+ error._tag === "DoStorageCorruptionError"
960
+ ? corrupt()
961
+ : storeError("load recovery checkpoint", error),
962
+ ),
963
+ );
964
+
965
+ if (rows.length === 0) return Option.none();
966
+ if (rows.length !== 1) return yield* corrupt();
967
+ const row = rows[0];
968
+
969
+ const checkpoint = yield* Schema.decodeEffect(Schema.fromJsonString(ThreadCheckpoint))(
970
+ row.checkpoint_json,
971
+ ).pipe(Effect.mapError(corrupt));
972
+
973
+ if (
974
+ row.thread_id !== validated.threadId ||
975
+ checkpoint.threadId !== row.thread_id ||
976
+ checkpoint.throughSequence !== row.through_sequence ||
977
+ checkpoint.tailDigest !== row.tail_digest
978
+ )
979
+ return yield* corrupt();
980
+ if (checkpoint.throughSequence > thread.tail_sequence)
981
+ return yield* CheckpointRejected.make({
982
+ threadId: validated.threadId,
983
+ reason: "ahead-of-tail",
984
+ });
985
+ if (checkpoint.throughSequence > (validated.atOrBeforeSequence ?? thread.tail_sequence))
986
+ return Option.none();
987
+
988
+ const canonicalDigest = yield* tailDigestAt(
989
+ journal,
990
+ checkpoint.threadId,
991
+ checkpoint.throughSequence,
992
+ );
993
+
994
+ if (canonicalDigest !== checkpoint.tailDigest)
995
+ return yield* CheckpointRejected.make({
996
+ threadId: validated.threadId,
997
+ reason: "digest-mismatch",
998
+ });
999
+
1000
+ return Option.some(checkpoint);
1001
+ });
1002
+
1003
+ const selectedReads = yield* makeSelectedReads(decodeEnvelope).pipe(
1004
+ Effect.provideService(SelectedReadOwner, {
1005
+ snapshot: journal.state.read,
1006
+ tail: (threadId) =>
1007
+ journal.getThread(threadId).pipe(
1008
+ Effect.flatMap((rows) =>
1009
+ Schema.decodeEffect(
1010
+ Schema.UndefinedOr(
1011
+ Schema.Struct({
1012
+ tail_sequence: CanonicalSequence,
1013
+ tail_digest: Digest,
1014
+ producer_epoch: ThreadMaterialization.fields.producerEpoch,
1015
+ }),
1016
+ ),
1017
+ )(rows[0]),
1018
+ ),
1019
+ Effect.mapError((error) => storeError("native thread tail", error)),
1020
+ ),
1021
+ }),
1022
+ );
1023
+
1024
+ const threadStore = ThreadStore.of({
1025
+ ...(journal.lifecycle === undefined
1026
+ ? {}
1027
+ : { lifecyclePublications: journal.lifecycle.storage }),
1028
+ readIdentity: selectedReads.readIdentity,
1029
+ countPeerMessages: selectedReads.countPeerMessages,
1030
+ append,
1031
+ export: exportThread,
1032
+ inspectTail,
1033
+ materialize,
1034
+ observe,
1035
+ read,
1036
+ checkpoints: { save: saveCheckpoint, load: loadCheckpoint },
1037
+ recoveryCheckpoints: { save: saveRecoveryCheckpoint, load: loadRecoveryCheckpoint },
1038
+ });
1039
+
1040
+ return Context.make(ThreadStore, threadStore);
1041
+ });
1042
+
1043
+ /**
1044
+ * Durable Object Thread Store implementation with configuration, failpoint, SQL, and
1045
+ * Crypto authority kept visible in its input channel.
1046
+ */
1047
+ export const threadStoreLayer: Layer.Layer<
1048
+ ThreadStore,
1049
+ DoStorageInitializationError,
1050
+ DoStorageConfig | DoStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto
1051
+ > = Layer.effectContext(makeServices());
1052
+
1053
+ /**
1054
+ * Validated Durable Object storage configuration Layer with the documented defaults applied.
1055
+ * Shared by the ThreadStore and SubmissionLedger convenience layers so their defaults
1056
+ * cannot drift.
1057
+ */
1058
+ export const storageConfigLayer = (
1059
+ options: DoStorageOptions,
1060
+ ): Layer.Layer<DoStorageConfig, DoStorageError> =>
1061
+ Layer.effect(DoStorageConfig)(
1062
+ Schema.decodeEffect(DoStorageConfigValue)({
1063
+ observationPollInterval: options.observationPollInterval ?? 25,
1064
+ ownershipLeaseDuration:
1065
+ options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),
1066
+ maxStoredValueBytes: options.maxStoredValueBytes ?? DEFAULT_MAX_STORED_VALUE_BYTES,
1067
+ verifyOnOpen: options.verifyOnOpen ?? false,
1068
+ }).pipe(
1069
+ Effect.mapError((error) =>
1070
+ DoStorageError.make({
1071
+ cause: error,
1072
+ operation: "configure Durable Object storage",
1073
+ message: error.message,
1074
+ }),
1075
+ ),
1076
+ ),
1077
+ );
1078
+
1079
+ /** The failpoint Layer selected by convenience options: explicit handler or the no-op default. */
1080
+ export const storageFailpointLayer = (
1081
+ options: DoStorageOptions,
1082
+ ): Layer.Layer<DoStorageFailpoint> =>
1083
+ options.failpoint === undefined
1084
+ ? DoStorageFailpoint.layer
1085
+ : Layer.succeed(DoStorageFailpoint)({ hit: options.failpoint });
1086
+
1087
+ /**
1088
+ * A composition-root convenience Layer for canonical Threads inside one Durable Object,
1089
+ * built over `ctx.storage`. Durable accepted work is served by the separate SubmissionLedger
1090
+ * port; point both at the SAME `ctx.storage` so claims fence the same producer epochs
1091
+ * (ADR-0011 D7's "same file" rule, transposed to one object's private database).
1092
+ */
1093
+ export const layer = (
1094
+ options: DoStorageOptions,
1095
+ ): Layer.Layer<ThreadStore, DoStorageInitializationError> =>
1096
+ Layer.unwrap(
1097
+ Effect.map(DoStorageConfig, (config) =>
1098
+ threadStoreLayer.pipe(
1099
+ Layer.provide(
1100
+ Layer.mergeAll(
1101
+ Layer.succeed(DoStorageConfig)(config),
1102
+ storageFailpointLayer(options),
1103
+ SqliteClient.layer({ storage: options.storage }),
1104
+ BrowserCrypto.layer,
1105
+ ),
1106
+ ),
1107
+ ),
1108
+ ),
1109
+ ).pipe(Layer.provide(storageConfigLayer(options)));
1110
+
1111
+ /**
1112
+ * Discard the Object's derived thread and ledger state after direct SQL maintenance.
1113
+ * Quiesce port operations during the raw write and invalidation, and enroll the write with
1114
+ * the host mutation gate. Ordinary ThreadStore/SubmissionLedger writes maintain this view.
1115
+ */
1116
+ export const invalidate = invalidateOwnedState;
1117
+
1118
+ /** Share the Object's transaction gate with owner-local SQL Memory compositions. */
1119
+ export const sqlOwnerLayer = Layer.effect(SqlStorageOwner)(
1120
+ Effect.flatMap(SqlClientService.SqlClient, ownedState),
1121
+ );