@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.0
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,769 @@
|
|
|
1
|
+
import * as SqliteClient from "@effect/sql-sqlite-do/SqliteClient";
|
|
2
|
+
import { makeCanonicalStorage, recordBatchId } from "@systemfsoftware/agent-storage-sql/sql-canonical-storage";
|
|
3
|
+
import { makeSqlExecutions } from "@systemfsoftware/agent-storage-sql/sql-journal";
|
|
4
|
+
import { SqlLifecycleRetainer, SqlLifecycleSource, makeSqlLifecyclePublication } from "@systemfsoftware/agent-storage-sql/sql-lifecycle-publication";
|
|
5
|
+
import { publishCanonicalDeliveries } from "@systemfsoftware/agent-storage-sql/sql-message-delivery-store";
|
|
6
|
+
import { SqlStorageProgress } from "@systemfsoftware/agent-storage-sql/sql-storage-progress";
|
|
7
|
+
import { canonicalRecordJson, makeSqlThreadArchiveRange } from "@systemfsoftware/agent-storage-sql/sql-thread-archive-range";
|
|
8
|
+
import { makeSqlThreadWork } from "@systemfsoftware/agent-storage-sql/sql-thread-work";
|
|
9
|
+
import { ThreadId } from "@systemfsoftware/agent/identifiers";
|
|
10
|
+
import { LifecyclePublicationError, LifecyclePublicationFact } from "@systemfsoftware/agent/lifecycle-publication";
|
|
11
|
+
import { BatchId, CanonicalRecord, CanonicalSequence } from "@systemfsoftware/agent/records";
|
|
12
|
+
import { StorageOwner } from "@systemfsoftware/agent/run-storage";
|
|
13
|
+
import { SqlStorageOwner } from "@systemfsoftware/agent/sql-storage-owner";
|
|
14
|
+
import { AppendResult, ThreadStoreDiagnostic, ThreadStoreError } from "@systemfsoftware/agent/thread-store";
|
|
15
|
+
import { WORK_INDEX_VERSION } from "@systemfsoftware/agent/thread-work";
|
|
16
|
+
import * as Arr from "effect/Array";
|
|
17
|
+
import * as Cause from "effect/Cause";
|
|
18
|
+
import * as Clock from "effect/Clock";
|
|
19
|
+
import * as Context from "effect/Context";
|
|
20
|
+
import * as Effect from "effect/Effect";
|
|
21
|
+
import * as Layer from "effect/Layer";
|
|
22
|
+
import * as Option from "effect/Option";
|
|
23
|
+
import * as Predicate from "effect/Predicate";
|
|
24
|
+
import * as References from "effect/References";
|
|
25
|
+
import * as Result from "effect/Result";
|
|
26
|
+
import * as Schema from "effect/Schema";
|
|
27
|
+
import * as SqlClient from "effect/sql/SqlClient";
|
|
28
|
+
import * as SqlError from "effect/sql/SqlError";
|
|
29
|
+
import * as Statement from "effect/sql/Statement";
|
|
30
|
+
import * as Stream from "effect/Stream";
|
|
31
|
+
import * as Tracer from "effect/Tracer";
|
|
32
|
+
import { n as DoStorageConfig } from "./DoStorageConfig-BqezsbD6.mjs";
|
|
33
|
+
import { a as DoStorageError, i as DoStorageCorruptionError, l as DoValueBoundExceeded, t as DoAppendConflict } from "./DoStorageError-DSQzuCb0.mjs";
|
|
34
|
+
import { r as isDefaultDoStorageFailpoint, t as DoStorageFailpoint } from "./DoStorageFailpoint-WO3B_DQl.mjs";
|
|
35
|
+
import { n as ensureDoStorageLayout } from "./migrations-BRTvj8Ue.mjs";
|
|
36
|
+
import { n as ownedRows, r as ownedState } from "./owned-state-DrOD9s0c.mjs";
|
|
37
|
+
// src/internal/storage-span.ts
|
|
38
|
+
const isAppendContention = (error) => (error._tag === "DoAppendConflict" || error._tag === "AppendConflict") && error.reason === "tail";
|
|
39
|
+
/** Expected refusals remain typed at the port, but are outcomes of the storage operation. */
|
|
40
|
+
const storageResult = (effect, expected) => effect.pipe(Effect.map(Result.succeed), Effect.catchIf(expected, (error) => Effect.succeed(Result.fail(error))));
|
|
41
|
+
/** Only error discriminants enter telemetry; messages, SQL, identities and payloads do not. */
|
|
42
|
+
const annotateStorageError = (error) => Effect.annotateCurrentSpan({
|
|
43
|
+
"error.type": error._tag,
|
|
44
|
+
...Predicate.hasProperty(error, "cause") && Predicate.hasProperty(error.cause, "_tag") && typeof error.cause._tag === "string" ? { "error.cause.type": error.cause._tag } : {}
|
|
45
|
+
});
|
|
46
|
+
const withStorageSpan = (name, expected = () => false) => {
|
|
47
|
+
const span = Effect.withSpan(name);
|
|
48
|
+
return (effect) => Effect.withFiber((fiber) => !fiber.getRef(References.TracerEnabled) || fiber.getRef(Tracer.Tracer) === Tracer.nativeTracer ? effect : storageResult(effect, expected).pipe(Effect.tap((result) => Result.isFailure(result) ? Effect.annotateCurrentSpan({ "storage.outcome": result.failure._tag }) : Effect.void), Effect.tapError(annotateStorageError), span, Effect.flatMap(Effect.fromResult)));
|
|
49
|
+
};
|
|
50
|
+
// src/internal/do-journal.ts
|
|
51
|
+
/**
|
|
52
|
+
* Static schema ceiling for stored text columns. Writes are bounded in BYTES by the
|
|
53
|
+
* configured `maxStoredValueBytes` (always ≤ 2,000,000); UTF-8 byte length is never smaller
|
|
54
|
+
* than UTF-16 string length, so any value that passed the byte bound also passes this
|
|
55
|
+
* decode-side character ceiling.
|
|
56
|
+
*/
|
|
57
|
+
const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2e6));
|
|
58
|
+
const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
|
|
59
|
+
const MAX_IDENTIFIER_LENGTH = 1024;
|
|
60
|
+
const MAX_READ_PAGE_JSON_BYTES = 4194304;
|
|
61
|
+
const MAX_RECORD_CACHE_JSON_BYTES = 8388608;
|
|
62
|
+
const MAX_RECORD_CACHE_ENTRIES = 4096;
|
|
63
|
+
/** Durable Object SQL storage allows at most 100 bound parameters per statement. */
|
|
64
|
+
const MAX_BOUND_PARAMETERS = 100;
|
|
65
|
+
const isSqlError = Schema.is(SqlError.SqlError);
|
|
66
|
+
const isNativeClient = Schema.is(Schema.declare((value) => Predicate.hasProperty(value, SqliteClient.TypeId)));
|
|
67
|
+
const storedTextBytes = (value) => new TextEncoder().encode(value).byteLength;
|
|
68
|
+
var ThreadRow = class extends Schema.Class("ThreadRow")({
|
|
69
|
+
thread_id: BoundedIdentifier,
|
|
70
|
+
created_at: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(128))),
|
|
71
|
+
tail_sequence: CanonicalSequence
|
|
72
|
+
}) {};
|
|
73
|
+
const threadRows = ownedRows(ThreadRow, "effect_agent_threads", (row) => row.thread_id, "thread_id");
|
|
74
|
+
var RecordRow = class extends Schema.Class("RecordRow")({
|
|
75
|
+
batch_id: Schema.fromJsonString(BatchId.check(Schema.isMaxLength(MAX_IDENTIFIER_LENGTH))),
|
|
76
|
+
thread_id: ThreadId.check(Schema.isMaxLength(MAX_IDENTIFIER_LENGTH)),
|
|
77
|
+
record_id: Schema.fromJsonString(BoundedIdentifier),
|
|
78
|
+
record_json: BoundedStoredText,
|
|
79
|
+
sequence: CanonicalSequence
|
|
80
|
+
}) {};
|
|
81
|
+
const isolateRecords = /* @__PURE__ */ new Map();
|
|
82
|
+
let isolateRecordBytes = 0;
|
|
83
|
+
const releaseRecord = (entry) => {
|
|
84
|
+
if (!isolateRecords.delete(entry)) return;
|
|
85
|
+
isolateRecordBytes -= entry.bytes;
|
|
86
|
+
entry.evict();
|
|
87
|
+
};
|
|
88
|
+
const recordCaches = /* @__PURE__ */ new WeakMap();
|
|
89
|
+
const makeRecordCache = () => {
|
|
90
|
+
const records = /* @__PURE__ */ new Map();
|
|
91
|
+
const key = (thread, sequence) => JSON.stringify([thread, sequence]);
|
|
92
|
+
return {
|
|
93
|
+
clear: () => {
|
|
94
|
+
for (const entry of records.values()) releaseRecord(entry);
|
|
95
|
+
},
|
|
96
|
+
get: (thread, sequence) => records.get(key(thread, sequence))?.row,
|
|
97
|
+
prefix: (thread, through) => {
|
|
98
|
+
const prefix = [];
|
|
99
|
+
for (let sequence = 1; sequence <= through; sequence++) {
|
|
100
|
+
const row = records.get(key(thread, sequence));
|
|
101
|
+
if (row === void 0) return void 0;
|
|
102
|
+
prefix.push(row.row);
|
|
103
|
+
}
|
|
104
|
+
return prefix;
|
|
105
|
+
},
|
|
106
|
+
put: (row, capturedBytes) => {
|
|
107
|
+
const id = key(row.thread_id, row.sequence);
|
|
108
|
+
const prior = records.get(id);
|
|
109
|
+
if (prior?.row === row) return;
|
|
110
|
+
const size = capturedBytes ?? storedTextBytes(row.record_json);
|
|
111
|
+
if (prior !== void 0) releaseRecord(prior);
|
|
112
|
+
const entry = {
|
|
113
|
+
row,
|
|
114
|
+
bytes: size,
|
|
115
|
+
evict: () => records.delete(id)
|
|
116
|
+
};
|
|
117
|
+
records.set(id, entry);
|
|
118
|
+
isolateRecords.set(entry, true);
|
|
119
|
+
isolateRecordBytes += size;
|
|
120
|
+
while (isolateRecordBytes > MAX_RECORD_CACHE_JSON_BYTES || isolateRecords.size > MAX_RECORD_CACHE_ENTRIES) {
|
|
121
|
+
const oldest = isolateRecords.keys().next().value;
|
|
122
|
+
if (oldest === void 0) break;
|
|
123
|
+
releaseRecord(oldest);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
};
|
|
128
|
+
const ReadPlanRow = Schema.Struct({
|
|
129
|
+
sequence: CanonicalSequence,
|
|
130
|
+
record_json_bytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_READ_PAGE_JSON_BYTES))
|
|
131
|
+
});
|
|
132
|
+
const LifecycleCursorRow = Schema.Struct({
|
|
133
|
+
thread_id: BoundedIdentifier,
|
|
134
|
+
through_sequence: CanonicalSequence
|
|
135
|
+
});
|
|
136
|
+
const lifecycleCursorRows = ownedRows(LifecycleCursorRow, "effect_agent_lifecycle_cursors", (row) => row.thread_id, "thread_id");
|
|
137
|
+
const initializedLifecycleSources = /* @__PURE__ */ new WeakSet();
|
|
138
|
+
var RawReadRequest = class extends Schema.Class("@effect-agent/storage-cloudflare/RawReadRequest")({
|
|
139
|
+
threadId: BoundedIdentifier,
|
|
140
|
+
fromSequenceExclusive: CanonicalSequence,
|
|
141
|
+
limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1024))
|
|
142
|
+
}) {};
|
|
143
|
+
const noFailpoint = () => Effect.void;
|
|
144
|
+
const storageError = (operation) => (error) => DoStorageError.make({
|
|
145
|
+
cause: error,
|
|
146
|
+
operation,
|
|
147
|
+
message: error.message,
|
|
148
|
+
diagnostic: ThreadStoreDiagnostic.make({
|
|
149
|
+
causeTag: error._tag,
|
|
150
|
+
operation,
|
|
151
|
+
issueTag: error.reason._tag
|
|
152
|
+
})
|
|
153
|
+
});
|
|
154
|
+
/** Decode raw Durable Object SQLite rows against a Schema, reporting failures as typed corruption. */
|
|
155
|
+
const decodeRows = (schema, table, rowKey, rows, decoder = table) => Schema.decodeUnknownEffect(schema)(rows).pipe(Effect.mapError((error) => DoStorageCorruptionError.make({
|
|
156
|
+
table,
|
|
157
|
+
rowKey,
|
|
158
|
+
message: "Stored rows do not satisfy the storage schema",
|
|
159
|
+
diagnostic: ThreadStoreDiagnostic.make({
|
|
160
|
+
causeTag: error._tag,
|
|
161
|
+
operation: "decode storage rows",
|
|
162
|
+
decoder,
|
|
163
|
+
issueTag: error.issue._tag
|
|
164
|
+
})
|
|
165
|
+
})), Effect.tapError((error) => Effect.annotateCurrentSpan({
|
|
166
|
+
"storage.failure.operation": error.diagnostic?.operation,
|
|
167
|
+
"storage.failure.cause": error.diagnostic?.causeTag,
|
|
168
|
+
"storage.failure.decoder": decoder,
|
|
169
|
+
"storage.failure.issue": error.diagnostic?.issueTag
|
|
170
|
+
})));
|
|
171
|
+
/** Open a validated layout and bind this Object's storage owner. */
|
|
172
|
+
const ensureCurrentStorage = Effect.fnUntraced(function* (sql, failpoint = noFailpoint, maxStoredValueBytes) {
|
|
173
|
+
const state = yield* ownedState(sql);
|
|
174
|
+
const owner = (yield* SqlStorageOwner) ?? state;
|
|
175
|
+
yield* ensureDoStorageLayout().pipe(Effect.provideService(SqlStorageOwner, owner), Effect.provideService(SqlClient.SqlClient, sql));
|
|
176
|
+
let journal;
|
|
177
|
+
const lifecycle = yield* makeSqlLifecyclePublication(void 0, maxStoredValueBytes).pipe(Effect.provideService(SqlStorageOwner, owner), Effect.provideService(SqlLifecycleSource, {
|
|
178
|
+
beforeRetain: (threadId) => Effect.suspend(() => journal === void 0 ? Effect.fail(LifecyclePublicationError.make({ reason: "unavailable" })) : journal.flushCanonical(threadId)),
|
|
179
|
+
beforePending: Effect.suspend(() => journal === void 0 ? Effect.fail(LifecyclePublicationError.make({ reason: "unavailable" })) : journal.flushPublications())
|
|
180
|
+
}), Effect.provideService(SqlClient.SqlClient, sql), Effect.mapError((cause) => DoStorageError.make({
|
|
181
|
+
operation: "initialize lifecycle publication",
|
|
182
|
+
message: "Native publication storage unavailable",
|
|
183
|
+
cause
|
|
184
|
+
})));
|
|
185
|
+
journal = yield* makeJournal(sql, failpoint, maxStoredValueBytes, lifecycle, state).pipe(Effect.provideService(SqlStorageOwner, owner));
|
|
186
|
+
if (lifecycle !== void 0) yield* journal.initializeLifecycleSource();
|
|
187
|
+
return journal;
|
|
188
|
+
});
|
|
189
|
+
const makeJournal = Effect.fnUntraced(function* (sql, failpoint, maxStoredValueBytes, lifecycle, state) {
|
|
190
|
+
const owner = (yield* SqlStorageOwner) ?? state;
|
|
191
|
+
const progress = yield* SqlStorageProgress;
|
|
192
|
+
const publishDeliveries = Effect.fnUntraced(function* (records) {
|
|
193
|
+
yield* publishCanonicalDeliveries(records);
|
|
194
|
+
}, Effect.provideService(StorageOwner, state.owner), Effect.mapError((cause) => ThreadStoreError.make({
|
|
195
|
+
operation: "publish canonical message deliveries",
|
|
196
|
+
message: "Canonical message obligations could not be retained",
|
|
197
|
+
deliveryReason: cause.reason,
|
|
198
|
+
cause
|
|
199
|
+
})));
|
|
200
|
+
const nativeDb = isNativeClient(sql) && sql.config.transformQueryNames === void 0 && sql.config.transformResultNames === void 0 && isDefaultDoStorageFailpoint(failpoint) ? sql.config.storage?.sql : void 0;
|
|
201
|
+
const work = yield* makeSqlThreadWork({
|
|
202
|
+
read: (body) => state.read(body),
|
|
203
|
+
write: (body) => owner.transaction(body.pipe(Effect.tap(() => state.invalidate))).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.catchTag("SqlError", (cause) => ThreadStoreError.make({
|
|
204
|
+
operation: "rebuild Thread work",
|
|
205
|
+
message: "Thread work transaction failed",
|
|
206
|
+
cause
|
|
207
|
+
})))
|
|
208
|
+
}).pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
209
|
+
yield* Effect.acquireRelease(Effect.sync(() => state.invalidators.add(work.invalidate)), () => Effect.sync(() => state.invalidators.delete(work.invalidate)));
|
|
210
|
+
const workFailure = (cause) => DoStorageError.make({
|
|
211
|
+
operation: "publish Thread work",
|
|
212
|
+
message: "Canonical work metadata could not be published",
|
|
213
|
+
cause
|
|
214
|
+
});
|
|
215
|
+
const executions = yield* makeSqlExecutions().pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
216
|
+
const executionConflict = (effect) => effect.pipe(Effect.catchTag("AppendConflict", (error) => Effect.fail(DoAppendConflict.make({
|
|
217
|
+
reason: error.reason,
|
|
218
|
+
message: "Active execution conflicts with the captured commit",
|
|
219
|
+
...error.actualTailSequence === void 0 ? {} : { actualTailSequence: error.actualTailSequence }
|
|
220
|
+
}))));
|
|
221
|
+
const threads = threadRows(state, sql);
|
|
222
|
+
const cursors = lifecycleCursorRows(state, sql);
|
|
223
|
+
let records = recordCaches.get(state);
|
|
224
|
+
if (records === void 0) {
|
|
225
|
+
records = makeRecordCache();
|
|
226
|
+
recordCaches.set(state, records);
|
|
227
|
+
state.invalidators.add(records.clear);
|
|
228
|
+
}
|
|
229
|
+
const recordCache = records;
|
|
230
|
+
const archives = yield* makeSqlThreadArchiveRange({
|
|
231
|
+
read: (body) => state.read(body),
|
|
232
|
+
write: (body) => owner.transaction(body.pipe(Effect.tap(() => state.invalidate))).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.catchTag("SqlError", (cause) => ThreadStoreError.make({
|
|
233
|
+
operation: "archive write",
|
|
234
|
+
message: "Archive transaction failed.",
|
|
235
|
+
cause
|
|
236
|
+
})))
|
|
237
|
+
}).pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
238
|
+
const recordJson = canonicalRecordJson(sql);
|
|
239
|
+
const physical = yield* makeCanonicalStorage().pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
240
|
+
/** Typed pre-write refusal for any single value over the configured byte bound. */
|
|
241
|
+
const checkValueBound = (operation, value, actualBytes = storedTextBytes(value)) => {
|
|
242
|
+
return actualBytes > maxStoredValueBytes ? Effect.fail(DoValueBoundExceeded.make({
|
|
243
|
+
actualBytes,
|
|
244
|
+
maxBytes: maxStoredValueBytes,
|
|
245
|
+
operation
|
|
246
|
+
})) : Effect.void;
|
|
247
|
+
};
|
|
248
|
+
/**
|
|
249
|
+
* Runs one journal write transaction on the Durable Object storage-backed
|
|
250
|
+
* `withTransaction` (`ctx.storage.transaction()` under the hood). Within one Durable
|
|
251
|
+
* Object there is exactly ONE writer, so the Node `BEGIN IMMEDIATE` + busy-retry +
|
|
252
|
+
* `SqliteWriteContention` machinery has no analogue here and is deliberately absent.
|
|
253
|
+
* The shared local owner gate covers the transaction and acknowledgement.
|
|
254
|
+
*
|
|
255
|
+
* Journal write transactions are always top level: the Durable Object client rejects
|
|
256
|
+
* nested transactions, so new journal operations must not wrap this helper inside another
|
|
257
|
+
* transaction. Expected outcomes may be captured only when every such refusal precedes
|
|
258
|
+
* mutation; real faults still roll back. Successful preflight reads never authorize a write.
|
|
259
|
+
*/
|
|
260
|
+
const withWriteTransaction = (operation, expected) => {
|
|
261
|
+
const transaction = (effect) => Effect.withFiber((fiber) => {
|
|
262
|
+
const body = state.owner.withMutation(owner.transaction(effect)).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.mapError((error) => isSqlError(error) ? storageError(operation)(error) : error));
|
|
263
|
+
return fiber.getRef(References.TracerEnabled) && fiber.getRef(Tracer.Tracer) !== Tracer.nativeTracer ? body.pipe(Effect.tapError(annotateStorageError), Effect.withSpan("DoJournal.withWriteTransaction", { attributes: { operation } })) : body;
|
|
264
|
+
});
|
|
265
|
+
return (effect) => expected === void 0 ? transaction(effect) : transaction(storageResult(effect, expected)).pipe(Effect.flatMap(Effect.fromResult));
|
|
266
|
+
};
|
|
267
|
+
const materialize = Effect.fnUntraced(function* (threadId, createdAt) {
|
|
268
|
+
if (threadId.length > MAX_IDENTIFIER_LENGTH) return yield* DoStorageError.make({
|
|
269
|
+
operation: "materialize thread",
|
|
270
|
+
message: "Thread identity exceeds the Durable Object storage bounds."
|
|
271
|
+
});
|
|
272
|
+
if ((yield* getThread(threadId)).length === 1) return;
|
|
273
|
+
yield* withWriteTransaction("materialize transaction")(Effect.gen(function* () {
|
|
274
|
+
const existingRows = yield* getThread(threadId);
|
|
275
|
+
const existing = yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, existingRows);
|
|
276
|
+
if (existing.length > 1) return yield* DoStorageCorruptionError.make({
|
|
277
|
+
table: "effect_agent_threads",
|
|
278
|
+
rowKey: threadId,
|
|
279
|
+
message: "A thread primary key returned more than one row."
|
|
280
|
+
});
|
|
281
|
+
if (existing.length === 0) {
|
|
282
|
+
yield* sql`
|
|
283
|
+
INSERT INTO effect_agent_threads (
|
|
284
|
+
thread_id,
|
|
285
|
+
created_at,
|
|
286
|
+
tail_sequence,
|
|
287
|
+
work_version
|
|
288
|
+
) VALUES (
|
|
289
|
+
${threadId},
|
|
290
|
+
${createdAt},
|
|
291
|
+
0,
|
|
292
|
+
${WORK_INDEX_VERSION}
|
|
293
|
+
) ON CONFLICT(thread_id) DO UPDATE SET created_at=excluded.created_at
|
|
294
|
+
WHERE effect_agent_threads.created_at IS NULL
|
|
295
|
+
RETURNING *`.pipe(threads.write, Effect.mapError((error) => error._tag === "SqlError" ? storageError("materialize thread")(error) : error));
|
|
296
|
+
if (lifecycle !== void 0) yield* sql`INSERT INTO effect_agent_lifecycle_cursors (thread_id, through_sequence)
|
|
297
|
+
VALUES (${threadId}, 0) RETURNING *`.pipe(cursors.write, Effect.mapError((error) => error._tag === "SqlError" ? storageError("initialize lifecycle source")(error) : error));
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
}));
|
|
301
|
+
}, withStorageSpan("DoJournal.materialize"));
|
|
302
|
+
const getThread = Effect.fnUntraced(function* (threadId) {
|
|
303
|
+
return (yield* threads.by("thread_id", threadId).pipe(Effect.mapError((error) => error._tag === "SqlError" ? storageError("read thread")(error) : error))).filter((row) => row.thread_id === threadId && row.created_at !== null);
|
|
304
|
+
});
|
|
305
|
+
const hasRecord = Effect.fnUntraced(function* (threadId, recordId) {
|
|
306
|
+
const thread = (yield* getThread(threadId))[0];
|
|
307
|
+
const prefix = recordCache.prefix(threadId, thread?.tail_sequence ?? 0);
|
|
308
|
+
if (prefix !== void 0) return prefix.some((row) => row.record_id === recordId);
|
|
309
|
+
return (yield* sql`SELECT record_id FROM effect_agent_canonical_records
|
|
310
|
+
WHERE thread_id = ${threadId} AND record_id = ${JSON.stringify(recordId)}`.pipe(Effect.mapError(storageError("read canonical record identity")))).length > 0;
|
|
311
|
+
});
|
|
312
|
+
const prepareAppend = Effect.fnUntraced(function* (request) {
|
|
313
|
+
if (request.threadId.length > MAX_IDENTIFIER_LENGTH || request.batchId.length > MAX_IDENTIFIER_LENGTH || request.executionWrites.some(({ update }) => update.checkpoint.progress.runId.length > MAX_IDENTIFIER_LENGTH) || request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH)) return yield* DoStorageError.make({
|
|
314
|
+
operation: "append canonical batch",
|
|
315
|
+
message: "Canonical identifiers exceed the Durable Object storage bounds."
|
|
316
|
+
});
|
|
317
|
+
yield* checkValueBound("append canonical batch", request.batchJson, request.batchBytes);
|
|
318
|
+
for (const record of request.records) if (record.recordBytes > maxStoredValueBytes) return yield* DoValueBoundExceeded.make({
|
|
319
|
+
actualBytes: record.recordBytes,
|
|
320
|
+
maxBytes: maxStoredValueBytes,
|
|
321
|
+
operation: "append canonical record"
|
|
322
|
+
});
|
|
323
|
+
for (const write of request.executionWrites) yield* checkValueBound("commit active execution", write.json, write.bytes);
|
|
324
|
+
const recordIds = request.records.map((record) => record.recordId);
|
|
325
|
+
if (new Set(recordIds).size !== recordIds.length) return yield* DoAppendConflict.make({
|
|
326
|
+
message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
|
|
327
|
+
reason: "record-identity"
|
|
328
|
+
});
|
|
329
|
+
return request;
|
|
330
|
+
});
|
|
331
|
+
const appendNativeBody = Effect.fnUntraced(function* (request, first, last, batchInserted) {
|
|
332
|
+
const db = nativeDb;
|
|
333
|
+
if (yield* Effect.withFiber((fiber) => Effect.succeed(fiber.getRef(Statement.CurrentTransformer) !== void 0 || fiber.getRef(References.TracerEnabled) && fiber.getRef(Tracer.Tracer) !== Tracer.nativeTracer))) return false;
|
|
334
|
+
if (db === void 0 || request.executionWrites.length !== 1 || request.executionWrites[0]?.update.retire || request.executionWrites[0]?.update.facts.length !== 0) return false;
|
|
335
|
+
const workPlan = yield* work.prepareClosedPair(request.threadId, first, last, request.records.map((record) => record.canonical));
|
|
336
|
+
if (workPlan === void 0) return false;
|
|
337
|
+
const native = yield* Effect.suspend(() => {
|
|
338
|
+
const query = (statement, operation) => Result.try({
|
|
339
|
+
try: () => {
|
|
340
|
+
const [text, parameters] = statement.compile();
|
|
341
|
+
return db.exec(text, ...parameters).toArray();
|
|
342
|
+
},
|
|
343
|
+
catch: (cause) => storageError(operation)(SqlError.SqlError.make({ reason: SqlError.classifySqliteError(cause, {
|
|
344
|
+
operation,
|
|
345
|
+
message: "Native canonical statement failed"
|
|
346
|
+
}) }))
|
|
347
|
+
});
|
|
348
|
+
return Effect.fromResult(Result.gen(function* () {
|
|
349
|
+
const captured = physical.cachedRecords(request.threadId, first, request.records);
|
|
350
|
+
if (captured === void 0) return void 0;
|
|
351
|
+
const physicalRecords = yield* captured;
|
|
352
|
+
if (!Arr.isReadonlyArrayNonEmpty(physicalRecords)) return void 0;
|
|
353
|
+
const rows = yield* query(workPlan.advance, "advance native work frontier");
|
|
354
|
+
if (rows.length === 0) return void 0;
|
|
355
|
+
const executionPlans = executions.prepareCommit(request);
|
|
356
|
+
if (!batchInserted) yield* query(sql`INSERT INTO effect_agent_canonical_batches
|
|
357
|
+
(thread_id, batch_id, first_sequence, last_sequence, producer_id_json)
|
|
358
|
+
VALUES (${request.threadId}, ${JSON.stringify(request.batchId)}, ${first}, ${last}, ${request.producerIdJson})`, "insert canonical batch");
|
|
359
|
+
if ((yield* query(sql`INSERT INTO effect_agent_canonical_records ${sql.insert(Arr.map(physicalRecords, (row) => row.columns))}
|
|
360
|
+
ON CONFLICT(thread_id, record_id) DO NOTHING RETURNING 1`, "insert canonical records")).length !== request.records.length) return yield* Result.fail(DoAppendConflict.make({
|
|
361
|
+
message: "A canonical record ID already exists.",
|
|
362
|
+
reason: "record-identity"
|
|
363
|
+
}));
|
|
364
|
+
const memberships = physicalRecords.flatMap((row) => row.memberships);
|
|
365
|
+
for (const group of Arr.chunksOf(memberships, Math.floor(MAX_BOUND_PARAMETERS / 3))) yield* query(sql`INSERT INTO effect_agent_record_runs ${sql.insert(group)}`, "index canonical Run membership");
|
|
366
|
+
for (const pointer of workPlan.pointers) yield* query(pointer, "index canonical pointers");
|
|
367
|
+
for (const plan of executionPlans) {
|
|
368
|
+
const changed = yield* query(plan.statement, "commit active execution");
|
|
369
|
+
const accepted = plan.accept(changed);
|
|
370
|
+
if (Result.isFailure(accepted)) return yield* Result.fail(DoAppendConflict.make({
|
|
371
|
+
reason: accepted.failure.reason,
|
|
372
|
+
message: "Active execution conflicts with the captured commit",
|
|
373
|
+
...accepted.failure.actualTailSequence === void 0 ? {} : { actualTailSequence: accepted.failure.actualTailSequence }
|
|
374
|
+
}));
|
|
375
|
+
}
|
|
376
|
+
for (let index = 0; index < request.records.length; index++) {
|
|
377
|
+
const record = request.records[index];
|
|
378
|
+
recordCache.put(RecordRow.make({
|
|
379
|
+
...physicalRecords[index].columns,
|
|
380
|
+
thread_id: request.threadId,
|
|
381
|
+
record_id: record.recordId,
|
|
382
|
+
batch_id: request.batchId,
|
|
383
|
+
record_json: record.recordJson,
|
|
384
|
+
sequence: CanonicalSequence.make(first + index)
|
|
385
|
+
}), record.recordBytes);
|
|
386
|
+
}
|
|
387
|
+
return rows;
|
|
388
|
+
}));
|
|
389
|
+
});
|
|
390
|
+
if (native === void 0) return false;
|
|
391
|
+
yield* threads.write(Effect.succeed(native));
|
|
392
|
+
return true;
|
|
393
|
+
});
|
|
394
|
+
const appendPreparedBody = Effect.fnUntraced(function* (request) {
|
|
395
|
+
const threadRows = yield* getThread(request.threadId);
|
|
396
|
+
const thread = threadRows.length === 1 ? threadRows[0] : void 0;
|
|
397
|
+
if (thread === void 0) return yield* DoStorageCorruptionError.make({
|
|
398
|
+
table: "effect_agent_threads",
|
|
399
|
+
rowKey: request.threadId,
|
|
400
|
+
message: `Expected exactly one row but found ${threadRows.length}.`
|
|
401
|
+
});
|
|
402
|
+
const canInsert = request.records.length > 0 && request.expectedTailSequence === thread.tail_sequence && Number.isSafeInteger(thread.tail_sequence + request.records.length);
|
|
403
|
+
const inserted = canInsert ? yield* sql`INSERT INTO effect_agent_canonical_batches
|
|
404
|
+
(thread_id, batch_id, first_sequence, last_sequence, producer_id_json)
|
|
405
|
+
SELECT ${request.threadId}, ${JSON.stringify(request.batchId)},
|
|
406
|
+
${thread.tail_sequence + 1}, ${thread.tail_sequence + request.records.length},
|
|
407
|
+
${request.producerIdJson}
|
|
408
|
+
WHERE NOT EXISTS (
|
|
409
|
+
SELECT 1 FROM effect_agent_executions
|
|
410
|
+
WHERE thread_id=${request.threadId} AND last_commit_id=${request.batchId}
|
|
411
|
+
)
|
|
412
|
+
ON CONFLICT(thread_id, batch_id) DO NOTHING RETURNING 1`.pipe(Effect.mapError(storageError("insert canonical batch"))) : [];
|
|
413
|
+
if (inserted.length === 0) {
|
|
414
|
+
const replay = yield* executionConflict(executions.replay(request));
|
|
415
|
+
if (replay !== void 0) return AppendResult.make(replay);
|
|
416
|
+
const prefix = recordCache.prefix(request.threadId, thread.tail_sequence);
|
|
417
|
+
const existing = prefix !== void 0 && !prefix.some((row) => row.batch_id === request.batchId) ? void 0 : yield* archives.replay(request.threadId, request.batchId);
|
|
418
|
+
if (existing !== void 0) {
|
|
419
|
+
if (existing.batch_json !== request.batchJson) return yield* DoAppendConflict.make({
|
|
420
|
+
message: `Batch ${request.batchId} already exists with different canonical content.`,
|
|
421
|
+
reason: "batch-content"
|
|
422
|
+
});
|
|
423
|
+
return AppendResult.make({
|
|
424
|
+
firstSequence: existing.first_sequence,
|
|
425
|
+
lastSequence: existing.last_sequence,
|
|
426
|
+
replayed: true
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
if (canInsert) return yield* DoStorageCorruptionError.make({
|
|
430
|
+
table: "effect_agent_canonical_batches",
|
|
431
|
+
rowKey: request.threadId,
|
|
432
|
+
message: "Batch insertion conflicted without a durable replay receipt."
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
yield* executionConflict(executions.rejectSuperseded(request));
|
|
436
|
+
if (request.expectedTailSequence !== thread.tail_sequence) return yield* DoAppendConflict.make({
|
|
437
|
+
message: `Expected tail ${request.expectedTailSequence} but found ${thread.tail_sequence}.`,
|
|
438
|
+
reason: "tail",
|
|
439
|
+
actualTailSequence: thread.tail_sequence
|
|
440
|
+
});
|
|
441
|
+
const result = yield* Schema.decodeEffect(AppendResult)({
|
|
442
|
+
firstSequence: thread.tail_sequence + (request.records.length === 0 ? 0 : 1),
|
|
443
|
+
lastSequence: thread.tail_sequence + request.records.length,
|
|
444
|
+
replayed: false
|
|
445
|
+
}).pipe(Effect.mapError((error) => DoStorageError.make({
|
|
446
|
+
cause: error,
|
|
447
|
+
operation: "append canonical batch",
|
|
448
|
+
message: error.message
|
|
449
|
+
})));
|
|
450
|
+
const { firstSequence, lastSequence } = result;
|
|
451
|
+
yield* executionConflict(executions.validate(request));
|
|
452
|
+
if (yield* appendNativeBody(request, firstSequence, lastSequence, inserted.length > 0)) {
|
|
453
|
+
yield* progress.committed("canonical").pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => DoStorageError.make({
|
|
454
|
+
operation: "enroll canonical progress",
|
|
455
|
+
message: error.message,
|
|
456
|
+
cause: error
|
|
457
|
+
})))));
|
|
458
|
+
return result;
|
|
459
|
+
}
|
|
460
|
+
if (request.records.length > 0 && inserted.length === 0) yield* sql`
|
|
461
|
+
INSERT INTO effect_agent_canonical_batches (
|
|
462
|
+
thread_id,
|
|
463
|
+
batch_id,
|
|
464
|
+
first_sequence,
|
|
465
|
+
last_sequence,
|
|
466
|
+
producer_id_json
|
|
467
|
+
) VALUES (
|
|
468
|
+
${request.threadId},
|
|
469
|
+
${JSON.stringify(request.batchId)},
|
|
470
|
+
${firstSequence},
|
|
471
|
+
${lastSequence},
|
|
472
|
+
${request.producerIdJson}
|
|
473
|
+
)
|
|
474
|
+
`.pipe(Effect.mapError(storageError("insert canonical batch")));
|
|
475
|
+
yield* failpoint("append:after-batch-insert");
|
|
476
|
+
const records = (yield* physical.records(request.threadId, firstSequence, request.records)).map(({ columns, memberships }, index) => ({
|
|
477
|
+
record: request.records[index],
|
|
478
|
+
canonical: request.records[index].canonical,
|
|
479
|
+
row: columns,
|
|
480
|
+
memberships
|
|
481
|
+
}));
|
|
482
|
+
for (const group of Arr.chunksOf(records, Math.floor(MAX_BOUND_PARAMETERS / 18))) {
|
|
483
|
+
if ((yield* sql`INSERT INTO effect_agent_canonical_records ${sql.insert(Arr.map(group, ({ row }) => row))}
|
|
484
|
+
ON CONFLICT(thread_id, record_id) DO NOTHING RETURNING 1`.pipe(Effect.mapError(storageError("insert canonical records")))).length !== group.length) return yield* DoAppendConflict.make({
|
|
485
|
+
message: "A canonical record ID already exists.",
|
|
486
|
+
reason: "record-identity"
|
|
487
|
+
});
|
|
488
|
+
const memberships = group.flatMap(({ memberships }) => memberships);
|
|
489
|
+
for (const members of Arr.chunksOf(memberships, Math.floor(MAX_BOUND_PARAMETERS / 3))) yield* sql`INSERT INTO effect_agent_record_runs ${sql.insert(members)}`.pipe(Effect.mapError(storageError("index canonical Run membership")));
|
|
490
|
+
for (const { row, record } of group) {
|
|
491
|
+
recordCache.put(RecordRow.make({
|
|
492
|
+
...row,
|
|
493
|
+
thread_id: request.threadId,
|
|
494
|
+
record_id: record.recordId,
|
|
495
|
+
batch_id: request.batchId,
|
|
496
|
+
record_json: record.recordJson,
|
|
497
|
+
sequence: yield* Schema.decodeEffect(CanonicalSequence)(row.sequence).pipe(Effect.orDie)
|
|
498
|
+
}), record.recordBytes);
|
|
499
|
+
yield* failpoint("append:after-record-insert");
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (request.records.length > 0) {
|
|
503
|
+
const workFields = yield* work.apply(request.threadId, firstSequence, request.records.map((record) => record.canonical)).pipe(Effect.mapError(workFailure));
|
|
504
|
+
yield* sql`UPDATE effect_agent_threads SET ${sql.update({
|
|
505
|
+
tail_sequence: lastSequence,
|
|
506
|
+
...workFields
|
|
507
|
+
})}
|
|
508
|
+
WHERE thread_id=${request.threadId} RETURNING *`.pipe(threads.write, Effect.mapError((error) => error._tag === "SqlError" ? storageError("advance thread tail")(error) : error));
|
|
509
|
+
}
|
|
510
|
+
yield* executionConflict(executions.commit(request, result));
|
|
511
|
+
if (request.executionWrites.length > 0) yield* failpoint("append:after-record-insert");
|
|
512
|
+
if (lifecycle !== void 0 && request.executionWrites.some(({ update }) => update.facts.some(({ payload }) => payload._tag === "RunStarted"))) yield* flushCanonical(request.threadId).pipe(Effect.provideService(SqlLifecycleRetainer, { retainMany: lifecycle.retainMany }), Effect.mapError((cause) => DoStorageError.make({
|
|
513
|
+
operation: "retain lifecycle start prefix",
|
|
514
|
+
message: "Lifecycle start intent could not be retained",
|
|
515
|
+
cause
|
|
516
|
+
})));
|
|
517
|
+
for (const { update } of request.executionWrites) for (const fact of update.facts) if (lifecycle !== void 0 && Schema.is(Schema.toType(LifecyclePublicationFact))(fact.payload)) yield* lifecycle.retain({
|
|
518
|
+
id: JSON.stringify([
|
|
519
|
+
request.threadId,
|
|
520
|
+
"record",
|
|
521
|
+
fact.recordId
|
|
522
|
+
]),
|
|
523
|
+
ownerThreadId: request.threadId,
|
|
524
|
+
canonicalSequence: lastSequence,
|
|
525
|
+
createdAt: fact.createdAt,
|
|
526
|
+
fact: fact.payload
|
|
527
|
+
}).pipe(Effect.mapError((cause) => DoStorageError.make({
|
|
528
|
+
operation: "retain operational lifecycle",
|
|
529
|
+
message: cause.message,
|
|
530
|
+
cause
|
|
531
|
+
})));
|
|
532
|
+
yield* failpoint("append:after-tail-update");
|
|
533
|
+
if (lifecycle !== void 0 && records.some(({ canonical: { payload } }) => payload._tag === "RunStarted" || payload._tag === "SubagentStarted")) yield* flushCanonical(request.threadId).pipe(Effect.provideService(SqlLifecycleRetainer, { retainMany: lifecycle.retainMany }), Effect.mapError((cause) => DoStorageError.make({
|
|
534
|
+
operation: "retain lifecycle start prefix",
|
|
535
|
+
message: "Lifecycle start intent could not be retained",
|
|
536
|
+
cause
|
|
537
|
+
})));
|
|
538
|
+
yield* progress.committed("canonical").pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, (error) => DoStorageError.make({
|
|
539
|
+
operation: "enroll canonical progress",
|
|
540
|
+
message: error.message,
|
|
541
|
+
cause: error
|
|
542
|
+
})))));
|
|
543
|
+
return result;
|
|
544
|
+
});
|
|
545
|
+
const appendPrepared = (request) => {
|
|
546
|
+
const appended = appendPreparedBody(request);
|
|
547
|
+
return request.deliveries.length === 0 ? appended : appended.pipe(Effect.tap(() => publishDeliveries(request.deliveries)));
|
|
548
|
+
};
|
|
549
|
+
const append = Effect.fnUntraced(function* (request, observed) {
|
|
550
|
+
yield* prepareAppend(request);
|
|
551
|
+
if (request.records.length > 0 && request.expectedTailSequence !== observed.tail_sequence) {
|
|
552
|
+
if ((yield* sql`
|
|
553
|
+
SELECT batch_id FROM effect_agent_canonical_batches
|
|
554
|
+
WHERE thread_id = ${request.threadId} AND batch_id = ${JSON.stringify(request.batchId)}
|
|
555
|
+
UNION ALL SELECT last_commit_id FROM effect_agent_executions
|
|
556
|
+
WHERE thread_id = ${request.threadId} AND last_commit_id = ${request.batchId}
|
|
557
|
+
LIMIT 1
|
|
558
|
+
`.pipe(Effect.mapError(storageError("preflight append replay")))).length === 0) return yield* DoAppendConflict.make({
|
|
559
|
+
reason: "tail",
|
|
560
|
+
message: "The canonical tail has advanced.",
|
|
561
|
+
actualTailSequence: observed.tail_sequence
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
return yield* withWriteTransaction("append transaction")(appendPrepared(request));
|
|
565
|
+
}, withStorageSpan("DoJournal.append", isAppendContention));
|
|
566
|
+
const read = Effect.fnUntraced(function* (request) {
|
|
567
|
+
const thread = (yield* getThread(request.threadId))[0];
|
|
568
|
+
const through = Math.min(thread?.tail_sequence ?? 0, request.fromSequenceExclusive + request.limit);
|
|
569
|
+
const cached = [];
|
|
570
|
+
for (let sequence = request.fromSequenceExclusive + 1; sequence <= through; sequence++) {
|
|
571
|
+
const record = recordCache.get(request.threadId, sequence);
|
|
572
|
+
if (record === void 0) break;
|
|
573
|
+
cached.push(record);
|
|
574
|
+
}
|
|
575
|
+
if (cached.length === Math.max(0, through - request.fromSequenceExclusive)) return {
|
|
576
|
+
count: cached.length,
|
|
577
|
+
records: Stream.fromIterable(cached)
|
|
578
|
+
};
|
|
579
|
+
const planRows = yield* sql`
|
|
580
|
+
SELECT
|
|
581
|
+
sequence,
|
|
582
|
+
length(CAST(${recordJson} AS BLOB)) AS record_json_bytes
|
|
583
|
+
FROM effect_agent_canonical_records
|
|
584
|
+
WHERE thread_id = ${request.threadId}
|
|
585
|
+
AND sequence > ${request.fromSequenceExclusive}
|
|
586
|
+
ORDER BY sequence
|
|
587
|
+
LIMIT ${request.limit}
|
|
588
|
+
`.pipe(Effect.mapError(storageError("read canonical records")));
|
|
589
|
+
const plan = yield* decodeRows(Schema.Array(ReadPlanRow), "effect_agent_canonical_records", `${request.threadId}>${request.fromSequenceExclusive}`, planRows, "ReadPlanRow");
|
|
590
|
+
const mismatch = () => DoStorageCorruptionError.make({
|
|
591
|
+
table: "effect_agent_canonical_records",
|
|
592
|
+
rowKey: `${request.threadId}>${request.fromSequenceExclusive}`,
|
|
593
|
+
message: "Canonical read membership, sequence, or payload size changed from its read plan."
|
|
594
|
+
});
|
|
595
|
+
if (plan.length > request.limit) return yield* mismatch();
|
|
596
|
+
const pages = [];
|
|
597
|
+
let page;
|
|
598
|
+
let pageBytes = 0;
|
|
599
|
+
let previousSequence = request.fromSequenceExclusive;
|
|
600
|
+
for (const row of plan) {
|
|
601
|
+
if (row.sequence !== previousSequence + 1) return yield* mismatch();
|
|
602
|
+
previousSequence = row.sequence;
|
|
603
|
+
if (page === void 0 || pageBytes + row.record_json_bytes > MAX_READ_PAGE_JSON_BYTES) {
|
|
604
|
+
page = [row];
|
|
605
|
+
pages.push(page);
|
|
606
|
+
pageBytes = row.record_json_bytes;
|
|
607
|
+
} else {
|
|
608
|
+
page.push(row);
|
|
609
|
+
pageBytes += row.record_json_bytes;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const readPage = Effect.fnUntraced(function* (page) {
|
|
613
|
+
const rows = yield* sql`
|
|
614
|
+
SELECT thread_id, sequence, record_id, ${recordBatchId(sql)} AS batch_id, ${recordJson} AS record_json
|
|
615
|
+
FROM effect_agent_canonical_records
|
|
616
|
+
WHERE thread_id = ${request.threadId}
|
|
617
|
+
AND sequence >= ${page[0].sequence}
|
|
618
|
+
AND sequence <= ${page[page.length - 1].sequence}
|
|
619
|
+
ORDER BY sequence
|
|
620
|
+
`.pipe(Effect.mapError(storageError("read canonical records")));
|
|
621
|
+
const decoded = yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.threadId}/${page[0].sequence}`, rows, "RecordRow");
|
|
622
|
+
if (decoded.length !== page.length || decoded.some((row, index) => row.thread_id !== request.threadId || row.sequence !== page[index].sequence || storedTextBytes(row.record_json) !== page[index].record_json_bytes)) return yield* mismatch();
|
|
623
|
+
for (const row of decoded) recordCache.put(row);
|
|
624
|
+
return decoded;
|
|
625
|
+
});
|
|
626
|
+
return {
|
|
627
|
+
count: plan.length,
|
|
628
|
+
records: Stream.fromIterable(pages).pipe(Stream.flatMap((page) => Stream.fromIterableEffect(state.read(readPage(page)))))
|
|
629
|
+
};
|
|
630
|
+
});
|
|
631
|
+
const sourceFailure = (cause) => LifecyclePublicationError.make({
|
|
632
|
+
reason: "unavailable",
|
|
633
|
+
cause
|
|
634
|
+
});
|
|
635
|
+
const sourceThreads = Effect.fnUntraced(function* () {
|
|
636
|
+
const all = yield* threads.matching("lifecycle-owners", (row) => row.created_at !== null, sql`SELECT * FROM effect_agent_threads WHERE created_at IS NOT NULL LIMIT 129`, 128);
|
|
637
|
+
if (all.length <= 128) return all;
|
|
638
|
+
return yield* Schema.decodeUnknownEffect(Schema.Array(ThreadRow))(yield* sql`SELECT t.* FROM effect_agent_threads t LEFT JOIN effect_agent_lifecycle_cursors c ON c.thread_id=t.thread_id
|
|
639
|
+
WHERE t.created_at IS NOT NULL AND (c.thread_id IS NULL OR t.tail_sequence > c.through_sequence) ORDER BY t.thread_id LIMIT 128`);
|
|
640
|
+
});
|
|
641
|
+
const initializeLifecycleSource = Effect.fnUntraced(function* () {
|
|
642
|
+
if (initializedLifecycleSources.has(state)) return;
|
|
643
|
+
yield* state.transaction(Effect.gen(function* () {
|
|
644
|
+
if ((yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_lifecycle_cursors'`).length === 0) yield* sql`CREATE TABLE effect_agent_lifecycle_cursors (
|
|
645
|
+
thread_id TEXT PRIMARY KEY, through_sequence INTEGER NOT NULL
|
|
646
|
+
)`;
|
|
647
|
+
yield* sql`INSERT INTO effect_agent_lifecycle_cursors(thread_id, through_sequence)
|
|
648
|
+
SELECT thread_id, tail_sequence FROM effect_agent_threads WHERE created_at IS NOT NULL
|
|
649
|
+
ON CONFLICT(thread_id) DO NOTHING`;
|
|
650
|
+
yield* sourceThreads();
|
|
651
|
+
})).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.mapError((cause) => DoStorageError.make({
|
|
652
|
+
operation: "initialize lifecycle source",
|
|
653
|
+
message: "Lifecycle source cursor unavailable",
|
|
654
|
+
cause
|
|
655
|
+
})));
|
|
656
|
+
initializedLifecycleSources.add(state);
|
|
657
|
+
});
|
|
658
|
+
/** The journal is durable intent; only the bounded publication wave materializes a write set. */
|
|
659
|
+
const flushCanonical = Effect.fnUntraced(function* (threadId, maxRecords = 1e400) {
|
|
660
|
+
const { retainMany } = yield* SqlLifecycleRetainer;
|
|
661
|
+
const thread = (yield* getThread(threadId))[0];
|
|
662
|
+
if (thread === void 0) return;
|
|
663
|
+
const cursor = (yield* cursors.by("thread_id", threadId))[0];
|
|
664
|
+
if (cursor === void 0 || cursor.through_sequence > thread.tail_sequence) return yield* LifecyclePublicationError.make({ reason: "corrupt" });
|
|
665
|
+
let through = cursor.through_sequence;
|
|
666
|
+
const bound = Math.min(thread.tail_sequence, through + maxRecords);
|
|
667
|
+
while (through < bound) {
|
|
668
|
+
const page = yield* read(RawReadRequest.make({
|
|
669
|
+
threadId,
|
|
670
|
+
fromSequenceExclusive: through,
|
|
671
|
+
limit: Math.min(128, bound - through)
|
|
672
|
+
}));
|
|
673
|
+
const facts = [];
|
|
674
|
+
let bytes = 0;
|
|
675
|
+
yield* Stream.runForEach(page.records, (row) => Effect.gen(function* () {
|
|
676
|
+
const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(row.record_json);
|
|
677
|
+
if (record.recordId !== row.record_id || row.sequence !== through + 1) return yield* LifecyclePublicationError.make({ reason: "corrupt" });
|
|
678
|
+
if (Schema.is(Schema.toType(LifecyclePublicationFact))(record.payload)) {
|
|
679
|
+
if (bytes + storedTextBytes(row.record_json) > MAX_READ_PAGE_JSON_BYTES && facts.length > 0) {
|
|
680
|
+
yield* retainMany(facts);
|
|
681
|
+
facts.length = 0;
|
|
682
|
+
bytes = 0;
|
|
683
|
+
}
|
|
684
|
+
facts.push({
|
|
685
|
+
id: JSON.stringify([
|
|
686
|
+
threadId,
|
|
687
|
+
"record",
|
|
688
|
+
record.recordId
|
|
689
|
+
]),
|
|
690
|
+
ownerThreadId: yield* Schema.decodeEffect(ThreadId)(threadId),
|
|
691
|
+
canonicalSequence: row.sequence,
|
|
692
|
+
createdAt: record.createdAt,
|
|
693
|
+
fact: record.payload
|
|
694
|
+
});
|
|
695
|
+
bytes += storedTextBytes(row.record_json);
|
|
696
|
+
}
|
|
697
|
+
through = row.sequence;
|
|
698
|
+
}));
|
|
699
|
+
if (page.count === 0) return yield* LifecyclePublicationError.make({ reason: "corrupt" });
|
|
700
|
+
yield* retainMany(facts);
|
|
701
|
+
yield* sql`UPDATE effect_agent_lifecycle_cursors SET through_sequence=${through} WHERE thread_id=${threadId} RETURNING *`.pipe(cursors.write);
|
|
702
|
+
}
|
|
703
|
+
}, Effect.mapError(sourceFailure));
|
|
704
|
+
const flushPublications = Effect.fnUntraced(function* () {
|
|
705
|
+
let owners = 0;
|
|
706
|
+
for (const thread of yield* sourceThreads()) {
|
|
707
|
+
const cursor = (yield* cursors.by("thread_id", thread.thread_id))[0];
|
|
708
|
+
if (cursor !== void 0 && cursor.through_sequence === thread.tail_sequence) continue;
|
|
709
|
+
yield* flushCanonical(thread.thread_id, 1024);
|
|
710
|
+
if (++owners === 4) break;
|
|
711
|
+
}
|
|
712
|
+
}, Effect.mapError(sourceFailure));
|
|
713
|
+
const sourcePending = Effect.gen(function* () {
|
|
714
|
+
for (const thread of yield* sourceThreads()) {
|
|
715
|
+
const cursor = (yield* cursors.by("thread_id", thread.thread_id))[0];
|
|
716
|
+
if (cursor === void 0 || cursor.through_sequence > thread.tail_sequence) return yield* LifecyclePublicationError.make({ reason: "corrupt" });
|
|
717
|
+
if (cursor.through_sequence < thread.tail_sequence) return true;
|
|
718
|
+
}
|
|
719
|
+
return false;
|
|
720
|
+
}).pipe(Effect.mapError(sourceFailure));
|
|
721
|
+
const ownedLifecycle = lifecycle === void 0 ? void 0 : {
|
|
722
|
+
...lifecycle,
|
|
723
|
+
storage: {
|
|
724
|
+
...lifecycle.storage,
|
|
725
|
+
retainedPendingDeadline: lifecycle.storage.pendingDeadline,
|
|
726
|
+
pendingDeadline: state.read(Effect.gen(function* () {
|
|
727
|
+
const deadline = yield* lifecycle.storage.pendingDeadline;
|
|
728
|
+
if (!(yield* sourcePending)) return deadline;
|
|
729
|
+
const now = yield* Clock.currentTimeMillis;
|
|
730
|
+
return Option.some(Option.isSome(deadline) ? Math.min(now, deadline.value) : now);
|
|
731
|
+
}))
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
return {
|
|
735
|
+
archives: archives.storage,
|
|
736
|
+
archiveRanges: archives,
|
|
737
|
+
work,
|
|
738
|
+
state,
|
|
739
|
+
owner,
|
|
740
|
+
threads,
|
|
741
|
+
lifecycle: ownedLifecycle,
|
|
742
|
+
initializeLifecycleSource,
|
|
743
|
+
flushCanonical,
|
|
744
|
+
flushPublications,
|
|
745
|
+
append,
|
|
746
|
+
prepareAppend,
|
|
747
|
+
appendPrepared,
|
|
748
|
+
checkCommitIntent: (request) => executionConflict(executions.checkCommitIntent(request)),
|
|
749
|
+
readExecution: executions.read,
|
|
750
|
+
checkValueBound,
|
|
751
|
+
getThread,
|
|
752
|
+
hasRecord,
|
|
753
|
+
materialize,
|
|
754
|
+
read: (request) => state.read(read(request)),
|
|
755
|
+
withWriteTransaction
|
|
756
|
+
};
|
|
757
|
+
});
|
|
758
|
+
const InitializedDoJournal = Context.Reference("@effect-agent/storage-cloudflare/InitializedDoJournal", { defaultValue: () => void 0 });
|
|
759
|
+
/** Build once in the common owner, SQL, configuration, failpoint and lifecycle context. */
|
|
760
|
+
const initializedDoJournalLayer = Layer.effect(InitializedDoJournal)(Effect.gen(function* () {
|
|
761
|
+
const sql = yield* SqlClient.SqlClient;
|
|
762
|
+
const config = yield* DoStorageConfig;
|
|
763
|
+
const failpoint = yield* DoStorageFailpoint;
|
|
764
|
+
return yield* ensureCurrentStorage(sql, failpoint.hit, config.maxStoredValueBytes);
|
|
765
|
+
}));
|
|
766
|
+
const initializeDoJournal = (sql, failpoint, maxStoredValueBytes) => Effect.filterOrElse(InitializedDoJournal, Predicate.isNotUndefined, () => ensureCurrentStorage(sql, failpoint, maxStoredValueBytes));
|
|
767
|
+
export { isAppendContention as a, initializedDoJournalLayer as i, decodeRows as n, withStorageSpan as o, initializeDoJournal as r, RawReadRequest as t };
|
|
768
|
+
|
|
769
|
+
//# sourceMappingURL=do-journal-nPNEAjV5.mjs.map
|