@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.
- package/LICENSE +21 -0
- package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
- package/dist/DoMemoryStore-DVun329p.mjs +67 -0
- package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
- package/dist/DoMemoryStore.d.mts +2 -0
- package/dist/DoMemoryStore.mjs +1 -0
- package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
- package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
- package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
- package/dist/DoMessageDeliveryStore.d.mts +2 -0
- package/dist/DoMessageDeliveryStore.mjs +1 -0
- package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
- package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
- package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
- package/dist/DoScheduleStore.d.mts +2 -0
- package/dist/DoScheduleStore.mjs +1 -0
- package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
- package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
- package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
- package/dist/DoStorageConfig.d.mts +2 -0
- package/dist/DoStorageConfig.mjs +1 -0
- package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
- package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
- package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
- package/dist/DoStorageError.d.mts +2 -0
- package/dist/DoStorageError.mjs +1 -0
- package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
- package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
- package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
- package/dist/DoStorageFailpoint.d.mts +2 -0
- package/dist/DoStorageFailpoint.mjs +1 -0
- package/dist/DoStorageFailpointTesting.d.mts +21 -0
- package/dist/DoStorageFailpointTesting.mjs +18 -0
- package/dist/DoStorageFailpointTesting.mjs.map +1 -0
- package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
- package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
- package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
- package/dist/DoStorageVersion.d.mts +3 -0
- package/dist/DoStorageVersion.mjs +2 -0
- package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
- package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
- package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
- package/dist/DoSubmissionLedger.d.mts +2 -0
- package/dist/DoSubmissionLedger.mjs +1 -0
- package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
- package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
- package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
- package/dist/DoSubscriptionStore.d.mts +2 -0
- package/dist/DoSubscriptionStore.mjs +1 -0
- package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
- package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
- package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
- package/dist/DoThreadStore.d.mts +2 -0
- package/dist/DoThreadStore.mjs +5 -0
- package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
- package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
- package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
- package/dist/MemoryProtocol.d.mts +2 -0
- package/dist/MemoryProtocol.mjs +1 -0
- package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
- package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
- package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
- package/dist/PortProtocol.d.mts +2 -0
- package/dist/PortProtocol.mjs +1 -0
- package/dist/PortRouting-B9302ouX.mjs +683 -0
- package/dist/PortRouting-B9302ouX.mjs.map +1 -0
- package/dist/PortRouting-DsoI6soW.d.mts +105 -0
- package/dist/PortRouting.d.mts +2 -0
- package/dist/PortRouting.mjs +1 -0
- package/dist/do-journal-nPNEAjV5.mjs +769 -0
- package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
- package/dist/index.d.mts +14 -0
- package/dist/index.mjs +14 -0
- package/dist/migrations-BRTvj8Ue.mjs +233 -0
- package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
- package/dist/owned-state-DrOD9s0c.mjs +157 -0
- package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +106 -3
- package/src/DoMemoryStore.ts +71 -0
- package/src/DoMessageDeliveryStore.ts +46 -0
- package/src/DoScheduleStore.ts +276 -0
- package/src/DoStorageConfig.ts +45 -0
- package/src/DoStorageError.ts +146 -0
- package/src/DoStorageFailpoint.ts +25 -0
- package/src/DoStorageFailpointTesting.ts +42 -0
- package/src/DoStorageVersion.ts +2 -0
- package/src/DoSubmissionLedger.ts +3980 -0
- package/src/DoSubscriptionStore.ts +331 -0
- package/src/DoThreadStore.ts +602 -0
- package/src/MemoryProtocol.ts +357 -0
- package/src/PortProtocol.ts +626 -0
- package/src/PortRouting.ts +1888 -0
- package/src/index.ts +13 -0
- package/src/internal/canonical-append.ts +15 -0
- package/src/internal/do-journal.ts +1449 -0
- package/src/internal/migrations.ts +395 -0
- package/src/internal/owned-state.ts +300 -0
- package/src/internal/prompt-checkpoint.ts +170 -0
- package/src/internal/storage-span.ts +54 -0
- package/README.md +0 -3
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
import * as BrowserCrypto from '@effect/platform-browser/BrowserCrypto'
|
|
2
|
+
import * as SqliteClient from '@effect/sql-sqlite-do/SqliteClient'
|
|
3
|
+
import {
|
|
4
|
+
formatObservationOffset,
|
|
5
|
+
makeObservationOffsetParser,
|
|
6
|
+
} from '@systemfsoftware/agent-storage-sql/sql-observation-offset'
|
|
7
|
+
import { makeSqlThreadImport } from '@systemfsoftware/agent-storage-sql/sql-thread-import'
|
|
8
|
+
import { makeSelectedReads, SelectedReadOwner } from '@systemfsoftware/agent-storage-sql/sql-thread-native-reads'
|
|
9
|
+
import { decodeExportRecordJson } from '@systemfsoftware/agent/record-format'
|
|
10
|
+
import { CanonicalRecordEnvelope, CanonicalSequence, ObservationOffset } from '@systemfsoftware/agent/records'
|
|
11
|
+
import { StorageOwner } from '@systemfsoftware/agent/run-storage'
|
|
12
|
+
import { SqlStorageOwner } from '@systemfsoftware/agent/sql-storage-owner'
|
|
13
|
+
import { MAX_ARCHIVE_RANGE_PAGE } from '@systemfsoftware/agent/thread-archive-range'
|
|
14
|
+
import { ThreadImport } from '@systemfsoftware/agent/thread-import'
|
|
15
|
+
import {
|
|
16
|
+
AppendConflict,
|
|
17
|
+
type AppendRequest,
|
|
18
|
+
PreparedAppend,
|
|
19
|
+
type ThreadExportRequest,
|
|
20
|
+
ThreadMaterialization,
|
|
21
|
+
ThreadNotMaterialized,
|
|
22
|
+
ThreadObservation,
|
|
23
|
+
ThreadReader,
|
|
24
|
+
ThreadReadRequest,
|
|
25
|
+
ThreadStore,
|
|
26
|
+
ThreadStoreDiagnostic,
|
|
27
|
+
ThreadStoreError,
|
|
28
|
+
ThreadTail,
|
|
29
|
+
ThreadTailRequest,
|
|
30
|
+
} from '@systemfsoftware/agent/thread-store'
|
|
31
|
+
import { checkExportSource } from '@systemfsoftware/agent/thread-transfer'
|
|
32
|
+
import * as Clock from 'effect/Clock'
|
|
33
|
+
import * as Context from 'effect/Context'
|
|
34
|
+
import * as CryptoDigest from 'effect/crypto/Digest'
|
|
35
|
+
import * as Effect from 'effect/Effect'
|
|
36
|
+
import * as Layer from 'effect/Layer'
|
|
37
|
+
import * as Ref from 'effect/Ref'
|
|
38
|
+
import * as Schema from 'effect/Schema'
|
|
39
|
+
import * as SqlClientService from 'effect/sql/SqlClient'
|
|
40
|
+
import * as SqlError from 'effect/sql/SqlError'
|
|
41
|
+
import * as Stream from 'effect/Stream'
|
|
42
|
+
|
|
43
|
+
import { DEFAULT_MAX_STORED_VALUE_BYTES, DoStorageConfig, DoStorageConfigValue } from './DoStorageConfig'
|
|
44
|
+
import {
|
|
45
|
+
DoAppendConflict,
|
|
46
|
+
type DoStorageCompatibilityError,
|
|
47
|
+
DoStorageCorruptionError,
|
|
48
|
+
DoStorageError,
|
|
49
|
+
type DoStorageFailpointLocation,
|
|
50
|
+
} from './DoStorageError'
|
|
51
|
+
import { DoStorageFailpoint, type DoStorageFailpointHandler } from './DoStorageFailpoint'
|
|
52
|
+
import { DO_OFFSET_PREFIX, prepareCanonicalAppend } from './internal/canonical-append'
|
|
53
|
+
import { type DoJournal, initializeDoJournal, RawReadRequest } from './internal/do-journal'
|
|
54
|
+
import { readDoStorageHeader } from './internal/migrations'
|
|
55
|
+
import { invalidateOwnedState, ownedState } from './internal/owned-state'
|
|
56
|
+
import { makePromptCheckpoints, promptCheckpointPrefix } from './internal/prompt-checkpoint'
|
|
57
|
+
import { isAppendContention, withStorageSpan } from './internal/storage-span'
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Convenience-layer construction options. `storage` is the Durable Object's own
|
|
61
|
+
* `ctx.storage` handle, injected as a value (DEPLOY-010: platform bindings enter only
|
|
62
|
+
* through Layers; this package never imports `cloudflare:workers`).
|
|
63
|
+
*/
|
|
64
|
+
export interface DoStorageOptions {
|
|
65
|
+
readonly storage: DurableObjectStorage
|
|
66
|
+
readonly observationPollInterval?: number | undefined
|
|
67
|
+
/**
|
|
68
|
+
* Maximum bytes for any single stored value; must stay under the platform's 2 MB
|
|
69
|
+
* per-value limit. Defaults to `DEFAULT_MAX_STORED_VALUE_BYTES`.
|
|
70
|
+
*/
|
|
71
|
+
readonly maxStoredValueBytes?: number | undefined
|
|
72
|
+
/**
|
|
73
|
+
* Audit journal payloads, ownership, and batch coverage in bounded pages on open, including
|
|
74
|
+
* orphan rows and rows outside declared ranges. Defaults to false. Full reads validate
|
|
75
|
+
* canonical records; readPrompt trusts write-time validation of the omitted fields.
|
|
76
|
+
*/
|
|
77
|
+
readonly verifyOnOpen?: boolean | undefined
|
|
78
|
+
readonly failpoint?: DoStorageFailpointHandler | undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type DoStorageInitializationError =
|
|
82
|
+
| DoStorageCompatibilityError
|
|
83
|
+
| DoStorageCorruptionError
|
|
84
|
+
| DoStorageError
|
|
85
|
+
|
|
86
|
+
const ZERO_CANONICAL_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0)
|
|
87
|
+
const isDoAppendConflict = Schema.is(DoAppendConflict)
|
|
88
|
+
// Reuse the same AST/parser across reads. Reconstructing a JSON codec per row
|
|
89
|
+
// defeats Schema's parser cache and repeatedly walks the canonical union.
|
|
90
|
+
const decodeCanonicalRecord = decodeExportRecordJson
|
|
91
|
+
|
|
92
|
+
const decodeThreadMaterializationType = Schema.decodeEffect(Schema.toType(ThreadMaterialization))
|
|
93
|
+
const decodeThreadReadRequestType = Schema.decodeEffect(Schema.toType(ThreadReadRequest))
|
|
94
|
+
const decodeThreadTailRequestType = Schema.decodeEffect(Schema.toType(ThreadTailRequest))
|
|
95
|
+
const decodeStorageConfig = Schema.decodeEffect(DoStorageConfigValue)
|
|
96
|
+
|
|
97
|
+
const storeError = (
|
|
98
|
+
operation: string,
|
|
99
|
+
error: { readonly message: string; readonly diagnostic?: ThreadStoreDiagnostic },
|
|
100
|
+
) =>
|
|
101
|
+
ThreadStoreError.make({
|
|
102
|
+
cause: error,
|
|
103
|
+
operation,
|
|
104
|
+
message: error.message,
|
|
105
|
+
...(error.diagnostic === undefined ? {} : { diagnostic: error.diagnostic }),
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
const schemaStoreError = (operation: string, error: Schema.SchemaError) =>
|
|
109
|
+
ThreadStoreError.make({
|
|
110
|
+
operation,
|
|
111
|
+
message: 'A Thread storage value does not satisfy its schema',
|
|
112
|
+
diagnostic: ThreadStoreDiagnostic.make({
|
|
113
|
+
causeTag: error._tag,
|
|
114
|
+
operation,
|
|
115
|
+
issueTag: error.issue._tag,
|
|
116
|
+
}),
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
const parseOffset = makeObservationOffsetParser(DO_OFFSET_PREFIX, schemaStoreError)
|
|
120
|
+
|
|
121
|
+
const envelopes = new WeakMap<object, CanonicalRecordEnvelope>()
|
|
122
|
+
|
|
123
|
+
const decodeEnvelope = Effect.fnUntraced(function*(row: {
|
|
124
|
+
readonly batch_id: CanonicalRecordEnvelope['batchId']
|
|
125
|
+
readonly thread_id: CanonicalRecordEnvelope['threadId']
|
|
126
|
+
readonly record_json: string
|
|
127
|
+
readonly sequence: CanonicalSequence
|
|
128
|
+
}) {
|
|
129
|
+
const cached = envelopes.get(row)
|
|
130
|
+
|
|
131
|
+
if (cached !== undefined) return cached
|
|
132
|
+
|
|
133
|
+
const record = yield* decodeCanonicalRecord(row.record_json).pipe(
|
|
134
|
+
Effect.mapError((error) =>
|
|
135
|
+
ThreadStoreError.make({
|
|
136
|
+
operation: 'decode canonical record',
|
|
137
|
+
message: 'The canonical record does not satisfy its schema',
|
|
138
|
+
diagnostic: ThreadStoreDiagnostic.make({
|
|
139
|
+
causeTag: error._tag,
|
|
140
|
+
operation: 'decode canonical record',
|
|
141
|
+
decoder: 'CanonicalRecord',
|
|
142
|
+
sequence: row.sequence,
|
|
143
|
+
issueTag: error.issue._tag,
|
|
144
|
+
}),
|
|
145
|
+
})
|
|
146
|
+
),
|
|
147
|
+
Effect.tapError((error) =>
|
|
148
|
+
Effect.annotateCurrentSpan({
|
|
149
|
+
'storage.failure.operation': error.diagnostic?.operation,
|
|
150
|
+
'storage.failure.cause': error.diagnostic?.causeTag,
|
|
151
|
+
'storage.failure.decoder': error.diagnostic?.decoder,
|
|
152
|
+
'storage.failure.sequence': row.sequence,
|
|
153
|
+
'storage.failure.issue': error.diagnostic?.issueTag,
|
|
154
|
+
})
|
|
155
|
+
),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
const { thread_id: threadId, batch_id: batchId } = row
|
|
159
|
+
|
|
160
|
+
const offset = ObservationOffset.make(
|
|
161
|
+
formatObservationOffset(DO_OFFSET_PREFIX, threadId, row.sequence),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
const envelope = CanonicalRecordEnvelope.make(
|
|
165
|
+
{ threadId, batchId, sequence: row.sequence, offset, record },
|
|
166
|
+
{ disableChecks: true },
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
envelopes.set(row, envelope)
|
|
170
|
+
|
|
171
|
+
return envelope
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
const requireThread = Effect.fnUntraced(function*(
|
|
175
|
+
journal: DoJournal,
|
|
176
|
+
threadId: ThreadMaterialization['threadId'],
|
|
177
|
+
) {
|
|
178
|
+
const rows = yield* journal
|
|
179
|
+
.getThread(threadId)
|
|
180
|
+
.pipe(Effect.mapError((error) => storeError('read thread', error)))
|
|
181
|
+
|
|
182
|
+
if (rows.length === 0) {
|
|
183
|
+
return yield* ThreadNotMaterialized.make({ threadId })
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return rows[0]
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
/** Audit excluded rows before paging owners and bounded ranges; never collect Thread payloads. */
|
|
190
|
+
const decodeStartupPayloads = Effect.fnUntraced(function*(journal: DoJournal) {
|
|
191
|
+
yield* journal.archiveRanges.verifyCoverage
|
|
192
|
+
let afterThreadId: string | undefined
|
|
193
|
+
|
|
194
|
+
while (true) {
|
|
195
|
+
const owners = yield* journal.archiveRanges.threadPage(afterThreadId)
|
|
196
|
+
|
|
197
|
+
for (const owner of owners) {
|
|
198
|
+
yield* journal.archiveRanges.verifyThread(owner.thread_id)
|
|
199
|
+
afterThreadId = owner.thread_id
|
|
200
|
+
}
|
|
201
|
+
if (owners.length < MAX_ARCHIVE_RANGE_PAGE) break
|
|
202
|
+
}
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
const makeServices = Effect.fnUntraced(function*() {
|
|
206
|
+
const config = yield* DoStorageConfig
|
|
207
|
+
const failpoint = yield* DoStorageFailpoint
|
|
208
|
+
const sql = yield* SqlClientService.SqlClient
|
|
209
|
+
const crypto = yield* CryptoDigest.Digest
|
|
210
|
+
const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes)
|
|
211
|
+
|
|
212
|
+
if (config.verifyOnOpen) {
|
|
213
|
+
yield* journal.state.read(decodeStartupPayloads(journal)).pipe(
|
|
214
|
+
Effect.mapError((cause) =>
|
|
215
|
+
DoStorageCorruptionError.make({
|
|
216
|
+
table: 'effect_agent_journal_ranges',
|
|
217
|
+
rowKey: 'verification',
|
|
218
|
+
message: cause.message,
|
|
219
|
+
})
|
|
220
|
+
),
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const hitFailpoint = (
|
|
225
|
+
location: DoStorageFailpointLocation,
|
|
226
|
+
): Effect.Effect<void, ThreadStoreError> =>
|
|
227
|
+
failpoint
|
|
228
|
+
.hit(location)
|
|
229
|
+
.pipe(Effect.mapError((error) => storeError(`storage failpoint ${location}`, error)))
|
|
230
|
+
|
|
231
|
+
const materialize: ThreadStore['Service']['materialize'] = Effect.fnUntraced(function*(
|
|
232
|
+
request: ThreadMaterialization,
|
|
233
|
+
) {
|
|
234
|
+
const validated = yield* decodeThreadMaterializationType(request).pipe(
|
|
235
|
+
Effect.mapError((error) => schemaStoreError('validate materialization', error)),
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
const now = yield* Clock.currentTimeMillis
|
|
239
|
+
|
|
240
|
+
yield* hitFailpoint('materialize:before')
|
|
241
|
+
yield* journal
|
|
242
|
+
.materialize(validated.threadId, new Date(now).toISOString())
|
|
243
|
+
.pipe(Effect.mapError((error) => storeError('materialize thread', error)))
|
|
244
|
+
yield* hitFailpoint('materialize:after')
|
|
245
|
+
}, withStorageSpan('DoThreadStore.materialize'))
|
|
246
|
+
|
|
247
|
+
const append: ThreadStore['Service']['append'] = Effect.fnUntraced(
|
|
248
|
+
function*(request: AppendRequest) {
|
|
249
|
+
const validated = yield* PreparedAppend.capture(request)
|
|
250
|
+
const observed = yield* requireThread(journal, validated.threadId)
|
|
251
|
+
|
|
252
|
+
const { raw: rawRequest } = yield* prepareCanonicalAppend(validated).pipe(
|
|
253
|
+
Effect.provideService(CryptoDigest.Digest, crypto),
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
yield* hitFailpoint('append:before')
|
|
257
|
+
|
|
258
|
+
const result = yield* journal.state.owner
|
|
259
|
+
.withProgress(rawRequest.threadId, journal.append(rawRequest, observed))
|
|
260
|
+
.pipe(
|
|
261
|
+
Effect.mapError((error) => {
|
|
262
|
+
if (isDoAppendConflict(error)) {
|
|
263
|
+
return error.actualTailSequence !== undefined
|
|
264
|
+
? AppendConflict.make({
|
|
265
|
+
threadId: validated.threadId,
|
|
266
|
+
batchId: validated.batch.batchId,
|
|
267
|
+
reason: error.reason,
|
|
268
|
+
actualTailSequence: error.actualTailSequence,
|
|
269
|
+
})
|
|
270
|
+
: AppendConflict.make({
|
|
271
|
+
threadId: validated.threadId,
|
|
272
|
+
batchId: validated.batch.batchId,
|
|
273
|
+
reason: error.reason,
|
|
274
|
+
})
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return error._tag === 'ThreadStoreError'
|
|
278
|
+
? error
|
|
279
|
+
: storeError('append canonical batch', error)
|
|
280
|
+
}),
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
yield* hitFailpoint('append:after')
|
|
284
|
+
|
|
285
|
+
return result
|
|
286
|
+
},
|
|
287
|
+
withStorageSpan('DoThreadStore.append', isAppendContention),
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
const loadRecords = Effect.fnUntraced(function*(request: RawReadRequest) {
|
|
291
|
+
const result = yield* journal
|
|
292
|
+
.read(request)
|
|
293
|
+
.pipe(Effect.mapError((error) => storeError('read canonical records', error)))
|
|
294
|
+
|
|
295
|
+
return {
|
|
296
|
+
count: result.count,
|
|
297
|
+
records: result.records.pipe(
|
|
298
|
+
Stream.mapError((error) => storeError('read canonical records', error)),
|
|
299
|
+
Stream.mapEffect(decodeEnvelope),
|
|
300
|
+
),
|
|
301
|
+
}
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
const readEffect = Effect.fnUntraced(function*(request: ThreadReadRequest) {
|
|
305
|
+
const validated = yield* decodeThreadReadRequestType(request).pipe(
|
|
306
|
+
Effect.mapError((error) => schemaStoreError('validate thread read', error)),
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
if ('selection' in validated) return Stream.fromIterable(yield* selectedReads.read(validated))
|
|
310
|
+
yield* requireThread(journal, validated.threadId)
|
|
311
|
+
|
|
312
|
+
const result = yield* loadRecords(
|
|
313
|
+
RawReadRequest.make({
|
|
314
|
+
threadId: validated.threadId,
|
|
315
|
+
fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,
|
|
316
|
+
limit: validated.limit,
|
|
317
|
+
}),
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
return result.records
|
|
321
|
+
})
|
|
322
|
+
|
|
323
|
+
const read: ThreadStore['Service']['read'] = (request) => Stream.unwrap(readEffect(request))
|
|
324
|
+
|
|
325
|
+
const observeEffect = Effect.fnUntraced(function*(request: ThreadObservation) {
|
|
326
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ThreadObservation))(request).pipe(
|
|
327
|
+
Effect.mapError((error) => schemaStoreError('validate thread observation', error)),
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
yield* requireThread(journal, validated.threadId)
|
|
331
|
+
const initialSequence = yield* parseOffset(validated.threadId, validated.afterOffset)
|
|
332
|
+
const cursor = yield* Ref.make(initialSequence)
|
|
333
|
+
let polls = 0
|
|
334
|
+
let emptyPolls = 0
|
|
335
|
+
let deliveredRecords = 0
|
|
336
|
+
|
|
337
|
+
const poll = Effect.fnUntraced(function*() {
|
|
338
|
+
polls++
|
|
339
|
+
const fromSequenceExclusive = yield* Ref.get(cursor)
|
|
340
|
+
|
|
341
|
+
const result = yield* loadRecords(
|
|
342
|
+
RawReadRequest.make({
|
|
343
|
+
threadId: validated.threadId,
|
|
344
|
+
fromSequenceExclusive,
|
|
345
|
+
limit: 1_024,
|
|
346
|
+
}),
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
if (result.count === 0) {
|
|
350
|
+
emptyPolls++
|
|
351
|
+
yield* Effect.sleep(config.observationPollInterval)
|
|
352
|
+
|
|
353
|
+
return Stream.empty
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
return result.records.pipe(
|
|
357
|
+
Stream.tap((record) => {
|
|
358
|
+
deliveredRecords++
|
|
359
|
+
|
|
360
|
+
return Ref.set(cursor, record.sequence)
|
|
361
|
+
}),
|
|
362
|
+
)
|
|
363
|
+
})
|
|
364
|
+
|
|
365
|
+
return Stream.fromEffectRepeat(poll()).pipe(
|
|
366
|
+
Stream.flatten,
|
|
367
|
+
Stream.ensuring(
|
|
368
|
+
Effect.suspend(() =>
|
|
369
|
+
Effect.annotateCurrentSpan({
|
|
370
|
+
'effect_agent.observation.polls': polls,
|
|
371
|
+
'effect_agent.observation.empty_polls': emptyPolls,
|
|
372
|
+
'effect_agent.observation.records': deliveredRecords,
|
|
373
|
+
})
|
|
374
|
+
),
|
|
375
|
+
),
|
|
376
|
+
)
|
|
377
|
+
})
|
|
378
|
+
|
|
379
|
+
const observe: ThreadStore['Service']['observe'] = (request) =>
|
|
380
|
+
Stream.unwrap(observeEffect(request)).pipe(Stream.withSpan('DoThreadStore.observe'))
|
|
381
|
+
|
|
382
|
+
const transfer = yield* makeSqlThreadImport({
|
|
383
|
+
owner: journal.state.owner,
|
|
384
|
+
offsetPrefix: DO_OFFSET_PREFIX,
|
|
385
|
+
maxValueBytes: config.maxStoredValueBytes,
|
|
386
|
+
// Import establishes a new sequence space; discard derivatives in this same transaction.
|
|
387
|
+
afterImport: Effect.fnUntraced(
|
|
388
|
+
function*({ result }) {
|
|
389
|
+
const prefix = promptCheckpointPrefix(result.threadId)
|
|
390
|
+
|
|
391
|
+
yield* sql`DELETE FROM effect_agent_meta WHERE key >= ${prefix} AND key < ${prefix + '~'}`
|
|
392
|
+
// Closed imported history must not emit historical lifecycle notifications again.
|
|
393
|
+
if (journal.lifecycle !== undefined) {
|
|
394
|
+
yield* sql`INSERT INTO effect_agent_lifecycle_cursors(thread_id, through_sequence) VALUES (${result.threadId}, ${result.tailSequence})`
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
(effect) =>
|
|
398
|
+
effect.pipe(
|
|
399
|
+
Effect.catchTag('SqlError', (cause) => storeError('rebuild imported derivatives', cause)),
|
|
400
|
+
),
|
|
401
|
+
),
|
|
402
|
+
afterThreadRead: hitFailpoint('export:after-thread-read'),
|
|
403
|
+
read: (body) =>
|
|
404
|
+
journal.owner.transaction(body).pipe(
|
|
405
|
+
Effect.provideService(SqlClientService.SqlClient, sql),
|
|
406
|
+
Effect.catchIf(SqlError.isSqlError, (cause) => storeError('export transaction', cause)),
|
|
407
|
+
),
|
|
408
|
+
write: (body) =>
|
|
409
|
+
journal.owner.transaction(body.pipe(Effect.tap(() => journal.state.invalidate))).pipe(
|
|
410
|
+
Effect.provideService(SqlClientService.SqlClient, sql),
|
|
411
|
+
Effect.catchIf(SqlError.isSqlError, (cause) => storeError('import transaction', cause)),
|
|
412
|
+
),
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
const inspectTail: ThreadStore['Service']['inspectTail'] = Effect.fnUntraced(function*(
|
|
416
|
+
request: ThreadTailRequest,
|
|
417
|
+
) {
|
|
418
|
+
const validated = yield* decodeThreadTailRequestType(request).pipe(
|
|
419
|
+
Effect.mapError((error) => schemaStoreError('validate tail inspection', error)),
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
const thread = yield* requireThread(journal, validated.threadId)
|
|
423
|
+
|
|
424
|
+
return ThreadTail.make({
|
|
425
|
+
threadId: validated.threadId,
|
|
426
|
+
tailSequence: thread.tail_sequence,
|
|
427
|
+
})
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
const selectedReads = yield* makeSelectedReads(decodeEnvelope).pipe(
|
|
431
|
+
Effect.provideService(SelectedReadOwner, {
|
|
432
|
+
snapshot: journal.state.read,
|
|
433
|
+
tail: (threadId) =>
|
|
434
|
+
journal.getThread(threadId).pipe(
|
|
435
|
+
Effect.map((rows) => rows[0]),
|
|
436
|
+
Effect.mapError((error) => storeError('native thread tail', error)),
|
|
437
|
+
),
|
|
438
|
+
}),
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
const threadStore = ThreadStore.of({
|
|
442
|
+
archives: journal.archives,
|
|
443
|
+
work: journal.work.storage,
|
|
444
|
+
...(journal.lifecycle === undefined
|
|
445
|
+
? {}
|
|
446
|
+
: { lifecyclePublications: journal.lifecycle.storage }),
|
|
447
|
+
readIdentity: selectedReads.readIdentity,
|
|
448
|
+
readFreshRun: selectedReads.readFreshRun,
|
|
449
|
+
readExecution: (request) =>
|
|
450
|
+
journal.state.read(
|
|
451
|
+
requireThread(journal, request.threadId).pipe(
|
|
452
|
+
Effect.andThen(journal.readExecution(request)),
|
|
453
|
+
),
|
|
454
|
+
),
|
|
455
|
+
readWorkerCapacity: selectedReads.readWorkerCapacity,
|
|
456
|
+
verification: transfer.verification,
|
|
457
|
+
countPeerMessages: selectedReads.countPeerMessages,
|
|
458
|
+
append,
|
|
459
|
+
export: transfer.export,
|
|
460
|
+
inspectTail,
|
|
461
|
+
materialize,
|
|
462
|
+
observe,
|
|
463
|
+
read,
|
|
464
|
+
readPrompt: (request) => Stream.fromIterableEffect(selectedReads.readPrompt(request)),
|
|
465
|
+
promptCheckpoints: makePromptCheckpoints(sql, journal, config.maxStoredValueBytes),
|
|
466
|
+
})
|
|
467
|
+
|
|
468
|
+
return Context.make(ThreadStore, threadStore).pipe(
|
|
469
|
+
Context.add(ThreadImport, transfer.importer),
|
|
470
|
+
Context.add(StorageOwner, journal.state.owner),
|
|
471
|
+
)
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Durable Object Thread Store implementation with configuration, failpoint, SQL, and
|
|
476
|
+
* Digest authority kept visible in its input channel.
|
|
477
|
+
*/
|
|
478
|
+
export const threadStoreLayer: Layer.Layer<
|
|
479
|
+
ThreadStore | ThreadReader | ThreadImport | StorageOwner,
|
|
480
|
+
DoStorageInitializationError,
|
|
481
|
+
DoStorageConfig | DoStorageFailpoint | SqlClientService.SqlClient | CryptoDigest.Digest
|
|
482
|
+
> = ThreadReader.layer().pipe(Layer.provideMerge(Layer.effectContext(makeServices())))
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Share one initialized journal between local storage ports in one Object build. Provide
|
|
486
|
+
* this beneath both ports and above their common SQL, owner, configuration, failpoint,
|
|
487
|
+
* progress and lifecycle providers. Standalone ports initialize their own journal.
|
|
488
|
+
*/
|
|
489
|
+
export { initializedDoJournalLayer as journalLayer } from './internal/do-journal'
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Validated Durable Object storage configuration Layer with the documented defaults applied.
|
|
493
|
+
* Shared by the ThreadStore and SubmissionLedger convenience layers so their defaults
|
|
494
|
+
* cannot drift.
|
|
495
|
+
*/
|
|
496
|
+
export const storageConfigLayer = (
|
|
497
|
+
options: DoStorageOptions,
|
|
498
|
+
): Layer.Layer<DoStorageConfig, DoStorageError> =>
|
|
499
|
+
Layer.effect(DoStorageConfig)(
|
|
500
|
+
decodeStorageConfig({
|
|
501
|
+
observationPollInterval: options.observationPollInterval ?? 25,
|
|
502
|
+
maxStoredValueBytes: options.maxStoredValueBytes ?? DEFAULT_MAX_STORED_VALUE_BYTES,
|
|
503
|
+
verifyOnOpen: options.verifyOnOpen ?? false,
|
|
504
|
+
}).pipe(
|
|
505
|
+
Effect.mapError((error) =>
|
|
506
|
+
DoStorageError.make({
|
|
507
|
+
cause: error,
|
|
508
|
+
operation: 'configure Durable Object storage',
|
|
509
|
+
message: error.message,
|
|
510
|
+
})
|
|
511
|
+
),
|
|
512
|
+
),
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
/** The failpoint Layer selected by convenience options: explicit handler or the no-op default. */
|
|
516
|
+
export const storageFailpointLayer = (
|
|
517
|
+
options: DoStorageOptions,
|
|
518
|
+
): Layer.Layer<DoStorageFailpoint> =>
|
|
519
|
+
options.failpoint === undefined
|
|
520
|
+
? DoStorageFailpoint.layer
|
|
521
|
+
: Layer.succeed(DoStorageFailpoint)({ hit: options.failpoint })
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* A composition-root convenience Layer for canonical Threads inside one Durable Object,
|
|
525
|
+
* built over `ctx.storage`. Durable accepted work is served by the separate SubmissionLedger
|
|
526
|
+
* port; point both at the SAME `ctx.storage` so both share the same scoped storage owner
|
|
527
|
+
* (ADR-0011 D7's "same file" rule, transposed to one object's private database).
|
|
528
|
+
*/
|
|
529
|
+
export const layer = (
|
|
530
|
+
options: DoStorageOptions,
|
|
531
|
+
): Layer.Layer<
|
|
532
|
+
ThreadStore | ThreadReader | ThreadImport | StorageOwner,
|
|
533
|
+
DoStorageInitializationError
|
|
534
|
+
> =>
|
|
535
|
+
Layer.unwrap(
|
|
536
|
+
Effect.map(DoStorageConfig, (config) =>
|
|
537
|
+
threadStoreLayer.pipe(
|
|
538
|
+
Layer.provide(
|
|
539
|
+
Layer.mergeAll(
|
|
540
|
+
Layer.succeed(DoStorageConfig)(config),
|
|
541
|
+
storageFailpointLayer(options),
|
|
542
|
+
SqliteClient.layer({ storage: options.storage }),
|
|
543
|
+
BrowserCrypto.layer,
|
|
544
|
+
),
|
|
545
|
+
),
|
|
546
|
+
)),
|
|
547
|
+
).pipe(Layer.provide(storageConfigLayer(options)))
|
|
548
|
+
|
|
549
|
+
/** Read a quiesced current-layout Object without initializing its layout or ownership. */
|
|
550
|
+
export const exportThread = Effect.fn('DoThreadStore.exportThread')(function*(
|
|
551
|
+
options: Pick<DoStorageOptions, 'storage'>,
|
|
552
|
+
request: ThreadExportRequest,
|
|
553
|
+
) {
|
|
554
|
+
yield* checkExportSource(request.threadId)
|
|
555
|
+
|
|
556
|
+
return yield* Effect.gen(function*() {
|
|
557
|
+
const sql = yield* SqlClientService.SqlClient
|
|
558
|
+
const state = yield* ownedState(sql)
|
|
559
|
+
|
|
560
|
+
return yield* state
|
|
561
|
+
.transaction(
|
|
562
|
+
Effect.gen(function*() {
|
|
563
|
+
yield* readDoStorageHeader()
|
|
564
|
+
|
|
565
|
+
const transfer = yield* makeSqlThreadImport({
|
|
566
|
+
owner: state.owner,
|
|
567
|
+
offsetPrefix: DO_OFFSET_PREFIX,
|
|
568
|
+
read: (body) => body,
|
|
569
|
+
write: () => Effect.die('A read-only exporter cannot import'),
|
|
570
|
+
})
|
|
571
|
+
|
|
572
|
+
return yield* transfer.export(request)
|
|
573
|
+
}),
|
|
574
|
+
)
|
|
575
|
+
.pipe(
|
|
576
|
+
Effect.catchTag('SqlError', (cause) =>
|
|
577
|
+
DoStorageError.make({
|
|
578
|
+
operation: 'export Thread snapshot',
|
|
579
|
+
message: cause.message,
|
|
580
|
+
cause,
|
|
581
|
+
})),
|
|
582
|
+
)
|
|
583
|
+
}).pipe(
|
|
584
|
+
Effect.provide(
|
|
585
|
+
Layer.merge(SqliteClient.layer({ storage: options.storage }), BrowserCrypto.layer),
|
|
586
|
+
),
|
|
587
|
+
)
|
|
588
|
+
})
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* Discard the Object's derived thread and ledger state after direct SQL maintenance.
|
|
592
|
+
* Quiesce port operations during the raw write and invalidation, and enroll the write with
|
|
593
|
+
* the host mutation gate. Ordinary ThreadStore/SubmissionLedger writes maintain this view.
|
|
594
|
+
*/
|
|
595
|
+
export const invalidate = invalidateOwnedState
|
|
596
|
+
|
|
597
|
+
/** Share the Object's transaction gate with owner-local SQL Memory compositions. */
|
|
598
|
+
export const sqlOwnerLayer = Layer.effectContext(
|
|
599
|
+
Effect.flatMap(SqlClientService.SqlClient, ownedState).pipe(
|
|
600
|
+
Effect.map((state) => Context.make(SqlStorageOwner, state).pipe(Context.add(StorageOwner, state.owner))),
|
|
601
|
+
),
|
|
602
|
+
)
|