@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.0-beta.192

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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
  3. package/dist/DoMemoryStore-DVun329p.mjs +67 -0
  4. package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
  5. package/dist/DoMemoryStore.d.mts +2 -0
  6. package/dist/DoMemoryStore.mjs +1 -0
  7. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
  8. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
  9. package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
  10. package/dist/DoMessageDeliveryStore.d.mts +2 -0
  11. package/dist/DoMessageDeliveryStore.mjs +1 -0
  12. package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
  13. package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
  14. package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
  15. package/dist/DoScheduleStore.d.mts +2 -0
  16. package/dist/DoScheduleStore.mjs +1 -0
  17. package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
  18. package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
  19. package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
  20. package/dist/DoStorageConfig.d.mts +2 -0
  21. package/dist/DoStorageConfig.mjs +1 -0
  22. package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
  23. package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
  24. package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
  25. package/dist/DoStorageError.d.mts +2 -0
  26. package/dist/DoStorageError.mjs +1 -0
  27. package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
  28. package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
  29. package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
  30. package/dist/DoStorageFailpoint.d.mts +2 -0
  31. package/dist/DoStorageFailpoint.mjs +1 -0
  32. package/dist/DoStorageFailpointTesting.d.mts +21 -0
  33. package/dist/DoStorageFailpointTesting.mjs +18 -0
  34. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  35. package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
  36. package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
  37. package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
  38. package/dist/DoStorageVersion.d.mts +3 -0
  39. package/dist/DoStorageVersion.mjs +2 -0
  40. package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
  41. package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
  42. package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
  43. package/dist/DoSubmissionLedger.d.mts +2 -0
  44. package/dist/DoSubmissionLedger.mjs +1 -0
  45. package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
  46. package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
  47. package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
  48. package/dist/DoSubscriptionStore.d.mts +2 -0
  49. package/dist/DoSubscriptionStore.mjs +1 -0
  50. package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
  51. package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
  52. package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
  53. package/dist/DoThreadStore.d.mts +2 -0
  54. package/dist/DoThreadStore.mjs +5 -0
  55. package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
  56. package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
  57. package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
  58. package/dist/MemoryProtocol.d.mts +2 -0
  59. package/dist/MemoryProtocol.mjs +1 -0
  60. package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
  61. package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
  62. package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
  63. package/dist/PortProtocol.d.mts +2 -0
  64. package/dist/PortProtocol.mjs +1 -0
  65. package/dist/PortRouting-B9302ouX.mjs +683 -0
  66. package/dist/PortRouting-B9302ouX.mjs.map +1 -0
  67. package/dist/PortRouting-DsoI6soW.d.mts +105 -0
  68. package/dist/PortRouting.d.mts +2 -0
  69. package/dist/PortRouting.mjs +1 -0
  70. package/dist/do-journal-nPNEAjV5.mjs +769 -0
  71. package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
  72. package/dist/index.d.mts +14 -0
  73. package/dist/index.mjs +14 -0
  74. package/dist/migrations-BRTvj8Ue.mjs +233 -0
  75. package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
  76. package/dist/owned-state-DrOD9s0c.mjs +157 -0
  77. package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
  78. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  79. package/package.json +106 -3
  80. package/src/DoMemoryStore.ts +71 -0
  81. package/src/DoMessageDeliveryStore.ts +46 -0
  82. package/src/DoScheduleStore.ts +276 -0
  83. package/src/DoStorageConfig.ts +45 -0
  84. package/src/DoStorageError.ts +146 -0
  85. package/src/DoStorageFailpoint.ts +25 -0
  86. package/src/DoStorageFailpointTesting.ts +42 -0
  87. package/src/DoStorageVersion.ts +2 -0
  88. package/src/DoSubmissionLedger.ts +3980 -0
  89. package/src/DoSubscriptionStore.ts +331 -0
  90. package/src/DoThreadStore.ts +602 -0
  91. package/src/MemoryProtocol.ts +357 -0
  92. package/src/PortProtocol.ts +626 -0
  93. package/src/PortRouting.ts +1888 -0
  94. package/src/index.ts +13 -0
  95. package/src/internal/canonical-append.ts +15 -0
  96. package/src/internal/do-journal.ts +1449 -0
  97. package/src/internal/migrations.ts +395 -0
  98. package/src/internal/owned-state.ts +300 -0
  99. package/src/internal/prompt-checkpoint.ts +170 -0
  100. package/src/internal/storage-span.ts +54 -0
  101. package/README.md +0 -3
@@ -0,0 +1,276 @@
1
+ import {
2
+ makeSqlScheduleStore,
3
+ SqlScheduleWriteTransaction,
4
+ } from '@systemfsoftware/agent-storage-sql/sql-schedule-store'
5
+ import {
6
+ ScheduleFailpoint,
7
+ type ScheduleFailpointError,
8
+ ScheduleInstant,
9
+ ScheduleStorageError,
10
+ ScheduleStore,
11
+ } from '@systemfsoftware/agent/schedule'
12
+ import * as Context from 'effect/Context'
13
+ import * as Effect from 'effect/Effect'
14
+ import * as Layer from 'effect/Layer'
15
+ import * as Schema from 'effect/Schema'
16
+ import * as SqlClientService from 'effect/sql/SqlClient'
17
+
18
+ const CURRENT_SCHEDULE_STORE_VERSION = 3
19
+ const MAX_STORED_SCHEDULE_LENGTH = 1_900_000
20
+
21
+ class ScheduleDeadlineRow extends Schema.Class<ScheduleDeadlineRow>(
22
+ '@effect-agent/storage-cloudflare/ScheduleDeadlineRow',
23
+ )({
24
+ deadline_at_millis: Schema.NullOr(ScheduleInstant),
25
+ }) {}
26
+
27
+ class ScheduleStoreStateRow extends Schema.Class<ScheduleStoreStateRow>(
28
+ '@effect-agent/storage-cloudflare/ScheduleStoreStateRow',
29
+ )({
30
+ storage_version: Schema.Int.check(Schema.isGreaterThan(0)),
31
+ alarm_generation: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
32
+ }) {}
33
+
34
+ class ScheduleTableNameRow extends Schema.Class<ScheduleTableNameRow>(
35
+ '@effect-agent/storage-cloudflare/ScheduleTableNameRow',
36
+ )({
37
+ name: Schema.String,
38
+ }) {}
39
+
40
+ export interface DoScheduleAlarmReplacement {
41
+ readonly deadlineAtMillis: number | null
42
+ /** Included in every logical alarm payload so equal-time replacement stays distinguishable. */
43
+ readonly generation: number
44
+ }
45
+
46
+ export type DoScheduleReplaceAlarm = (
47
+ replacement: DoScheduleAlarmReplacement,
48
+ ) => Effect.Effect<void, ScheduleStorageError>
49
+
50
+ /**
51
+ * Platform-owned transaction boundary for schedule SQL and logical alarm mutation. The callback
52
+ * and its `replaceAlarm` capability belong to one fiber and must not escape or fork.
53
+ */
54
+ export class DoScheduleTransaction extends Context.Service<
55
+ DoScheduleTransaction,
56
+ {
57
+ readonly run: <A, E, R>(
58
+ body: (replaceAlarm: DoScheduleReplaceAlarm) => Effect.Effect<A, E, R>,
59
+ ) => Effect.Effect<A, E | ScheduleStorageError, R>
60
+ }
61
+ >()('@effect-agent/storage-cloudflare/DoScheduleTransaction') {}
62
+
63
+ /** Platform driver operations that use the same schedule-state and alarm transaction. */
64
+ export class DoScheduleAlarmControl extends Context.Service<
65
+ DoScheduleAlarmControl,
66
+ {
67
+ /** Establish a future recovery wake before cross-Object admission starts. */
68
+ readonly prearm: (
69
+ deadlineAtMillis: number,
70
+ ) => Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>
71
+ /** Replace or cancel the wake from the object's authoritative indexed deadline. */
72
+ readonly reconcile: Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>
73
+ }
74
+ >()('@effect-agent/storage-cloudflare/DoScheduleAlarmControl') {}
75
+
76
+ const unavailable = (operation: string): ScheduleStorageError =>
77
+ ScheduleStorageError.make({ operation, reason: 'unavailable' })
78
+
79
+ const corrupt = (operation: string): ScheduleStorageError => ScheduleStorageError.make({ operation, reason: 'corrupt' })
80
+
81
+ const decodeRows = <A, I, R>(
82
+ schema: Schema.Codec<A, I, R>,
83
+ rows: ReadonlyArray<unknown>,
84
+ operation: string,
85
+ ): Effect.Effect<A, ScheduleStorageError, R> =>
86
+ Schema.decodeUnknownEffect(schema)(rows).pipe(Effect.mapError(() => corrupt(operation)))
87
+
88
+ const decodeBoundary = <A, I, R>(
89
+ schema: Schema.Codec<A, I, R>,
90
+ value: unknown,
91
+ operation: string,
92
+ ): Effect.Effect<A, ScheduleStorageError, R> =>
93
+ Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => corrupt(operation)))
94
+
95
+ const initializeScheduleStore = Effect.fnUntraced(function*() {
96
+ const sql = yield* SqlClientService.SqlClient
97
+ const operation = 'initialize schedule store'
98
+
99
+ const rawTables = yield* sql<Record<string, unknown>>`
100
+ SELECT name
101
+ FROM sqlite_master
102
+ WHERE type = 'table'
103
+ AND name IN (
104
+ 'effect_agent_schedule_store_state',
105
+ 'effect_agent_schedules'
106
+ )
107
+ ORDER BY name
108
+ `.pipe(Effect.mapError(() => unavailable(operation)))
109
+
110
+ const tables = yield* decodeRows(Schema.Array(ScheduleTableNameRow), rawTables, operation)
111
+ const hasState = tables.some((row) => row.name === 'effect_agent_schedule_store_state')
112
+ const hasSchedules = tables.some((row) => row.name === 'effect_agent_schedules')
113
+
114
+ if (!hasState) {
115
+ if (hasSchedules) return yield* corrupt(operation)
116
+ yield* sql
117
+ .withTransaction(
118
+ Effect.gen(function*() {
119
+ yield* sql`
120
+ CREATE TABLE effect_agent_schedule_store_state (
121
+ singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),
122
+ storage_version INTEGER NOT NULL,
123
+ alarm_generation INTEGER NOT NULL
124
+ )
125
+ `.withoutTransform
126
+ yield* sql`
127
+ CREATE TABLE effect_agent_schedules (
128
+ tenant_id TEXT NOT NULL,
129
+ owner_id TEXT NOT NULL,
130
+ schedule_id TEXT NOT NULL,
131
+ deadline_at_millis INTEGER,
132
+ record_json TEXT NOT NULL,
133
+ PRIMARY KEY (tenant_id, owner_id, schedule_id)
134
+ )
135
+ `.withoutTransform
136
+ yield* sql`
137
+ CREATE INDEX effect_agent_schedules_deadline
138
+ ON effect_agent_schedules (deadline_at_millis, tenant_id, owner_id, schedule_id)
139
+ WHERE deadline_at_millis IS NOT NULL
140
+ `.withoutTransform
141
+ yield* sql`
142
+ CREATE INDEX effect_agent_schedules_owner_deadline
143
+ ON effect_agent_schedules (tenant_id, owner_id, deadline_at_millis, schedule_id)
144
+ WHERE deadline_at_millis IS NOT NULL
145
+ `.withoutTransform
146
+ yield* sql`
147
+ INSERT INTO effect_agent_schedule_store_state (
148
+ singleton, storage_version, alarm_generation
149
+ ) VALUES (1, ${CURRENT_SCHEDULE_STORE_VERSION}, 0)
150
+ `.withoutTransform
151
+ }),
152
+ )
153
+ .pipe(Effect.mapError(() => unavailable(operation)))
154
+
155
+ return
156
+ }
157
+
158
+ if (!hasSchedules) return yield* corrupt(operation)
159
+
160
+ const rawState = yield* sql<Record<string, unknown>>`
161
+ SELECT storage_version, alarm_generation
162
+ FROM effect_agent_schedule_store_state
163
+ WHERE singleton = 1
164
+ `.pipe(Effect.mapError(() => unavailable(operation)))
165
+
166
+ const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation)
167
+
168
+ if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {
169
+ return yield* corrupt(
170
+ state.length === 1
171
+ ? `${operation}: incompatible storage version ${
172
+ state[0].storage_version
173
+ }; expected ${CURRENT_SCHEDULE_STORE_VERSION}`
174
+ : `${operation}: invalid storage version row`,
175
+ )
176
+ }
177
+ })
178
+
179
+ const makeServices = Effect.gen(function*() {
180
+ const sql = yield* SqlClientService.SqlClient
181
+ const transactions = yield* DoScheduleTransaction
182
+ const scheduleFailpoint = yield* ScheduleFailpoint
183
+
184
+ yield* initializeScheduleStore()
185
+
186
+ const readNextDeadline = Effect.fnUntraced(function*(
187
+ operation: string,
188
+ ): Effect.fn.Return<number | null, ScheduleStorageError> {
189
+ const rows = yield* sql<Record<string, unknown>>`
190
+ SELECT MIN(deadline_at_millis) AS deadline_at_millis
191
+ FROM effect_agent_schedules
192
+ WHERE deadline_at_millis IS NOT NULL
193
+ `.pipe(Effect.mapError(() => unavailable(operation)))
194
+
195
+ const decoded = yield* decodeRows(Schema.Array(ScheduleDeadlineRow), rows, operation)
196
+
197
+ if (decoded.length !== 1) return yield* corrupt(operation)
198
+
199
+ return decoded[0].deadline_at_millis
200
+ })
201
+
202
+ const replaceAlarm = Effect.fnUntraced(function*(
203
+ replace: DoScheduleReplaceAlarm,
204
+ deadlineAtMillis: number | null,
205
+ operation: string,
206
+ ) {
207
+ const rawState = yield* sql<Record<string, unknown>>`
208
+ UPDATE effect_agent_schedule_store_state
209
+ SET alarm_generation = alarm_generation + 1
210
+ WHERE singleton = 1
211
+ RETURNING storage_version, alarm_generation
212
+ `.pipe(Effect.mapError(() => unavailable(operation)))
213
+
214
+ const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation)
215
+
216
+ if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {
217
+ return yield* corrupt(operation)
218
+ }
219
+ yield* scheduleFailpoint.hit('schedule:alarm:before')
220
+ yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation })
221
+ yield* scheduleFailpoint.hit('schedule:alarm:after')
222
+ })
223
+
224
+ const run: SqlScheduleWriteTransaction['Service']['run'] = (body, operation) =>
225
+ transactions.run((replace) =>
226
+ Effect.gen(function*() {
227
+ const result = yield* body
228
+
229
+ if (result.changed) {
230
+ yield* replaceAlarm(replace, yield* readNextDeadline(operation), operation)
231
+ }
232
+
233
+ return result
234
+ })
235
+ )
236
+
237
+ const prearm = Effect.fnUntraced(function*(
238
+ deadlineAtMillis: number,
239
+ ): Effect.fn.Return<void, ScheduleStorageError | ScheduleFailpointError> {
240
+ yield* decodeBoundary(ScheduleInstant, deadlineAtMillis, 'pre-arm schedule recovery')
241
+ yield* transactions.run((replace) => replaceAlarm(replace, deadlineAtMillis, 'pre-arm schedule recovery'))
242
+ yield* scheduleFailpoint.hit('schedule:prearm:after')
243
+ })
244
+
245
+ const reconcile = Effect.gen(function*() {
246
+ yield* transactions.run((replace) =>
247
+ Effect.gen(function*() {
248
+ const deadline = yield* readNextDeadline('reconcile schedule alarm')
249
+
250
+ yield* replaceAlarm(replace, deadline, 'reconcile schedule alarm')
251
+ })
252
+ )
253
+ yield* scheduleFailpoint.hit('schedule:reconcile:after')
254
+ })
255
+
256
+ return Context.make(SqlScheduleWriteTransaction, { run }).pipe(
257
+ Context.add(DoScheduleAlarmControl, { prearm, reconcile }),
258
+ )
259
+ })
260
+
261
+ /**
262
+ * Durable Object SQLite ScheduleStore. Platform code supplies the one transaction owner that
263
+ * combines these SQL mutations with its logical and native alarm lifecycle.
264
+ */
265
+ export const scheduleStoreLayer: Layer.Layer<
266
+ ScheduleStore | DoScheduleAlarmControl,
267
+ ScheduleStorageError,
268
+ SqlClientService.SqlClient | DoScheduleTransaction
269
+ > = Layer.effectContext(
270
+ Effect.gen(function*() {
271
+ const store = yield* makeSqlScheduleStore(undefined, MAX_STORED_SCHEDULE_LENGTH)
272
+ const alarms = yield* DoScheduleAlarmControl
273
+
274
+ return Context.make(ScheduleStore, store).pipe(Context.add(DoScheduleAlarmControl, alarms))
275
+ }),
276
+ ).pipe(Layer.provide(Layer.effectContext(makeServices)))
@@ -0,0 +1,45 @@
1
+ import * as Context from 'effect/Context'
2
+ import * as Schema from 'effect/Schema'
3
+
4
+ const ObservationPollInterval = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
5
+
6
+ /**
7
+ * Default per-value byte bound, kept under the Durable Object platform's 2 MB SQLite value
8
+ * limit with a safety margin. This is the DC analogue of Node's 16 MB `BoundedStoredText`
9
+ * bound: both fail typed before mutating, only the threshold differs (a documented DN/DC
10
+ * behavioral difference; Travel Planner payloads sit orders of magnitude below both).
11
+ */
12
+ export const DEFAULT_MAX_STORED_VALUE_BYTES = 1_900_000
13
+
14
+ /** The hard schema ceiling for the configurable bound: never at or above the platform limit. */
15
+ const MaxStoredValueBytes = Schema.Int.check(
16
+ Schema.isGreaterThan(0),
17
+ Schema.isLessThanOrEqualTo(2_000_000),
18
+ )
19
+
20
+ /**
21
+ * Validated construction configuration consumed by the Durable Object storage Layers. The
22
+ * storage identity itself belongs to the SqlClient Layer (built from `ctx.storage`);
23
+ * duplicating it here could silently diverge from the handle actually in use.
24
+ */
25
+ export class DoStorageConfigValue extends Schema.Class<DoStorageConfigValue>(
26
+ '@effect-agent/storage-cloudflare/DoStorageConfigValue',
27
+ )({
28
+ observationPollInterval: ObservationPollInterval,
29
+ /**
30
+ * Maximum bytes for any single stored text value (canonical batch/record JSON, admission
31
+ * input payload, checkpoint JSON). Enforced typed BEFORE any write; must stay under the
32
+ * platform's 2 MB per-value limit.
33
+ */
34
+ maxStoredValueBytes: MaxStoredValueBytes,
35
+ /**
36
+ * Audit stored payload schemas, identities, and batch coverage while opening the store.
37
+ * Per-operation Schema decoding remains enabled; this complete scan is an explicit opt-in.
38
+ */
39
+ verifyOnOpen: Schema.Boolean,
40
+ }) {}
41
+
42
+ /** Explicit Durable Object storage configuration authority. */
43
+ export class DoStorageConfig extends Context.Service<DoStorageConfig, DoStorageConfigValue>()(
44
+ '@effect-agent/storage-cloudflare/DoStorageConfig',
45
+ ) {}
@@ -0,0 +1,146 @@
1
+ import { CanonicalSequence } from '@systemfsoftware/agent/records'
2
+ import { ThreadStoreDiagnostic } from '@systemfsoftware/agent/thread-store'
3
+ import * as Schema from 'effect/Schema'
4
+
5
+ /** The Durable Object's SQLite storage uses a private-development format this adapter cannot read. */
6
+ export class DoStorageCompatibilityError extends Schema.TaggedError<DoStorageCompatibilityError>()(
7
+ 'DoStorageCompatibilityError',
8
+ {
9
+ actualVersion: Schema.Int,
10
+ message: Schema.String,
11
+ supportedVersion: Schema.Int,
12
+ },
13
+ ) {}
14
+
15
+ /** Stored bytes failed the current Schema and cannot be used as recovery truth. */
16
+ export class DoStorageCorruptionError extends Schema.TaggedError<DoStorageCorruptionError>()(
17
+ 'DoStorageCorruptionError',
18
+ {
19
+ message: Schema.String,
20
+ rowKey: Schema.String,
21
+ table: Schema.String,
22
+ diagnostic: Schema.optionalKey(ThreadStoreDiagnostic),
23
+ },
24
+ ) {}
25
+
26
+ /** Durable Object SQLite infrastructure failed while opening or operating the store. */
27
+ export class DoStorageError extends Schema.TaggedError<DoStorageError>()('DoStorageError', {
28
+ cause: Schema.optionalKey(Schema.Defect()),
29
+ message: Schema.String,
30
+ operation: Schema.String,
31
+ diagnostic: Schema.optionalKey(ThreadStoreDiagnostic),
32
+ }) {}
33
+
34
+ /**
35
+ * Durable Object SQLite infrastructure failed while operating the Submission Ledger. Surfaces
36
+ * at the SubmissionLedger port as the typed `LedgerError` with this error preserved as its
37
+ * cause, so the adapter-level tag is never erased.
38
+ */
39
+ export class DoLedgerError extends Schema.TaggedError<DoLedgerError>()('DoLedgerError', {
40
+ cause: Schema.optionalKey(Schema.Defect()),
41
+ message: Schema.String,
42
+ operation: Schema.String,
43
+ }) {}
44
+
45
+ /**
46
+ * A value to be stored exceeds the configured Durable Object per-value bound
47
+ * (`DoStorageConfigValue.maxStoredValueBytes`, kept under the platform's 2 MB SQLite value
48
+ * limit). The refusal happens typed BEFORE any durable mutation; no partial state is written.
49
+ * Payloads of this size are the designed overflow case for a future R2-backed AttachmentStore
50
+ * (deployment spec §3.1, deferred until a real attachment requirement exists).
51
+ */
52
+ export class DoValueBoundExceeded extends Schema.TaggedError<DoValueBoundExceeded>()(
53
+ 'DoValueBoundExceeded',
54
+ {
55
+ actualBytes: Schema.Int,
56
+ maxBytes: Schema.Int,
57
+ operation: Schema.String,
58
+ },
59
+ ) {
60
+ override get message() {
61
+ return (
62
+ `A stored value of ${this.actualBytes} bytes exceeds the Durable Object per-value bound ` +
63
+ `of ${this.maxBytes} bytes during ${this.operation}. Nothing was written. Values of this ` +
64
+ 'size are the designed R2 AttachmentStore overflow path (deferred, deployment spec §3.1).'
65
+ )
66
+ }
67
+ }
68
+
69
+ /**
70
+ * A canonical batch retry conflicts with existing append state. Tail conflicts carry the
71
+ * actual committed tail as a diagnostic resume hint.
72
+ */
73
+ export class DoAppendConflict extends Schema.TaggedError<DoAppendConflict>()('DoAppendConflict', {
74
+ message: Schema.String,
75
+ reason: Schema.Literals(['batch-content', 'record-identity', 'tail', 'stale-command']),
76
+ actualTailSequence: Schema.optionalKey(CanonicalSequence),
77
+ }) {}
78
+
79
+ /**
80
+ * Deterministic fault-injection locations at Durable Object storage operation boundaries.
81
+ *
82
+ * The string list is copied VERBATIM from `SqliteStorageFailpointLocation`
83
+ * (`packages/storage-sqlite/src/errors.ts`) so every crash-matrix row keeps the same name on
84
+ * both platforms — the DN process-kill evidence and the DC eviction evidence address identical
85
+ * locations. There is intentionally no Cloudflare-only location.
86
+ */
87
+ export const DoStorageFailpointLocation = Schema.Literals([
88
+ 'materialize:before',
89
+ 'materialize:after',
90
+ 'append:before',
91
+ 'append:after-batch-insert',
92
+ 'append:after-record-insert',
93
+ 'append:after-tail-update',
94
+ 'append:after',
95
+ 'export:after-thread-read',
96
+ 'ledger:admit:before',
97
+ 'ledger:admit:after',
98
+ 'ledger:mark-ready:before',
99
+ 'ledger:mark-ready:after',
100
+ 'ledger:claim:before',
101
+ 'ledger:claim:after',
102
+ 'ledger:mark-input-applied:before',
103
+ 'ledger:mark-input-applied:after',
104
+ 'ledger:finalize-settlement:before',
105
+ 'ledger:finalize-settlement:after',
106
+ 'ledger:request-abort:before',
107
+ 'ledger:request-abort:after',
108
+ 'ledger:claim-joining:before',
109
+ 'ledger:claim-joining:after',
110
+ 'ledger:mark-joined:before',
111
+ 'ledger:mark-joined:after',
112
+ 'ledger:revert-joining:before',
113
+ 'ledger:revert-joining:after',
114
+ 'ledger:suspend:before',
115
+ 'ledger:suspend:after',
116
+ 'ledger:approval-decision:before',
117
+ 'ledger:approval-decision:after',
118
+ 'ledger:mark-unknown:before',
119
+ 'ledger:mark-unknown:after',
120
+ 'ledger:unknown-resolution:before',
121
+ 'ledger:unknown-resolution:after',
122
+ 'ledger:child-reservation:before',
123
+ 'ledger:child-reservation:after',
124
+ 'ledger:child-attach:before',
125
+ 'ledger:child-attach:after',
126
+ 'ledger:child-release-pending:before',
127
+ 'ledger:child-release-pending:after',
128
+ 'ledger:child-release:before',
129
+ 'ledger:child-release:after',
130
+ 'ledger:child-settled:before',
131
+ 'ledger:child-settled:after',
132
+ ])
133
+
134
+ export type DoStorageFailpointLocation = typeof DoStorageFailpointLocation.Type
135
+
136
+ /** Deterministic test-only fault or pause injected at a Durable Object storage boundary. */
137
+ export class DoStorageFailpointError extends Schema.TaggedError<DoStorageFailpointError>()(
138
+ 'DoStorageFailpointError',
139
+ {
140
+ location: DoStorageFailpointLocation,
141
+ },
142
+ ) {
143
+ override get message() {
144
+ return `Injected Durable Object storage failure at ${this.location}.`
145
+ }
146
+ }
@@ -0,0 +1,25 @@
1
+ import * as Context from 'effect/Context'
2
+ import * as Effect from 'effect/Effect'
3
+ import * as Layer from 'effect/Layer'
4
+
5
+ import type { DoStorageFailpointError, DoStorageFailpointLocation } from './DoStorageError'
6
+
7
+ export type DoStorageFailpointHandler = (
8
+ location: DoStorageFailpointLocation,
9
+ ) => Effect.Effect<void, DoStorageFailpointError>
10
+
11
+ const noFailpoint: DoStorageFailpointHandler = () => Effect.void
12
+
13
+ /** @internal Select a plain native body only for the library's no-op handler. */
14
+ export const isDefaultDoStorageFailpoint = (handler: DoStorageFailpointHandler): boolean => handler === noFailpoint
15
+
16
+ /** Explicit fault-injection authority used at Durable Object storage operation boundaries. */
17
+ export class DoStorageFailpoint extends Context.Service<
18
+ DoStorageFailpoint,
19
+ {
20
+ readonly hit: DoStorageFailpointHandler
21
+ }
22
+ >()('@effect-agent/storage-cloudflare/DoStorageFailpoint') {
23
+ /** Production default: no fault injection. */
24
+ static readonly layer = Layer.succeed(this)({ hit: noFailpoint })
25
+ }
@@ -0,0 +1,42 @@
1
+ import * as Effect from 'effect/Effect'
2
+
3
+ import type { DoStorageFailpointLocation } from './DoStorageError'
4
+ import type { DoStorageFailpointHandler } from './DoStorageFailpoint'
5
+
6
+ /**
7
+ * The DC-specific eviction failpoint mode: instead of failing typed, an armed hit evicts the
8
+ * Durable Object through an injected `evict` thunk — in production-shaped harnesses that thunk
9
+ * is `() => ctx.abort()`, the platform's real failure mode. `ctx.abort()` never returns (it
10
+ * throws while destroying the in-memory instance and every in-flight implicit or explicit
11
+ * storage transaction rolls back), so an armed hit ends the current Attempt exactly like an
12
+ * unannounced platform eviction; DO storage — the only correctness-critical state — survives
13
+ * for the next incarnation, which the persisted alarm wakes without any incoming request.
14
+ *
15
+ * The handles stay injected: this package never imports `cloudflare:workers`, so the harness
16
+ * that owns a `DurableObjectState` supplies the thunk.
17
+ */
18
+ export const evictionFailpointHandler = (options: {
19
+ readonly isArmed: (location: DoStorageFailpointLocation) => Effect.Effect<boolean>
20
+ /** Kills the incarnation — e.g. `() => ctx.abort()`. Typed `void` because the platform
21
+ * declares `abort` as returning, but it throws while destroying the instance. */
22
+ readonly evict: (location: DoStorageFailpointLocation) => void
23
+ }): DoStorageFailpointHandler =>
24
+ (location) =>
25
+ options.isArmed(location).pipe(
26
+ Effect.flatMap((armed) =>
27
+ armed
28
+ // `ctx.abort()` throws while destroying the instance; that throw surfaces as a
29
+ // defect in the (already dying) incarnation. The defensive defect below keeps the
30
+ // guarantee — nothing after an armed hit may observe in-memory state — even if a
31
+ // harness supplies an evict thunk that returns.
32
+ ? Effect.sync(() => options.evict(location)).pipe(
33
+ Effect.andThen(
34
+ Effect.die(
35
+ // oxlint-disable-next-line effect/no-native-error -- A returning native eviction callback violates the host contract and must remain a defect.
36
+ new Error(`Durable Object eviction did not interrupt execution at ${location}.`),
37
+ ),
38
+ ),
39
+ )
40
+ : Effect.void
41
+ ),
42
+ )
@@ -0,0 +1,2 @@
1
+ /** Current adapter layout version; record encoding is versioned independently. */
2
+ export { CurrentDoStorageVersion } from './internal/migrations'