effect-durable-agent 0.1.0-alpha.23 → 0.1.0-alpha.24
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/dist/in-memory-D8qQXNc5.js +150 -0
- package/dist/in-memory-D8qQXNc5.js.map +1 -0
- package/dist/{window-read-BDayZf7O.js → interpreter-BYstFpr4.js} +13 -190
- package/dist/interpreter-BYstFpr4.js.map +1 -0
- package/dist/services/reducer-registry.js +1 -1
- package/dist/services/runtime-layer.js +3 -3
- package/dist/services/runtime.js +1 -1
- package/dist/services/session-query.js +2 -2
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.js +271 -1
- package/dist/services/session-store.js.map +1 -0
- package/dist/services/sink-registry.js +1 -1
- package/dist/{session-state-C6SyphC0.js → session-state-BW0l2aNk.js} +3 -3
- package/dist/{session-state-C6SyphC0.js.map → session-state-BW0l2aNk.js.map} +1 -1
- package/dist/{sink-registry-DtrssBxF.js → sink-registry-D0MetcNq.js} +2 -2
- package/dist/{sink-registry-DtrssBxF.js.map → sink-registry-D0MetcNq.js.map} +1 -1
- package/dist/testkit/layers.js +3 -3
- package/dist/testkit/transcript.d.ts +226 -0
- package/dist/testkit/transcript.js +1475 -0
- package/dist/testkit/transcript.js.map +1 -0
- package/dist/transcript.d.ts +2 -101
- package/dist/transcript.js +2 -1
- package/dist/transcript.js.map +1 -1
- package/dist/window-read-DBf1Iktt.d.ts +104 -0
- package/dist/window-read-U55aAeuz.js +184 -0
- package/dist/window-read-U55aAeuz.js.map +1 -0
- package/package.json +5 -1
- package/dist/session-store-DuEhcqIC.js +0 -414
- package/dist/session-store-DuEhcqIC.js.map +0 -1
- package/dist/window-read-BDayZf7O.js.map +0 -1
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { SequenceNumber } from "./types/core.js";
|
|
2
|
+
import { u as NonNegativeInt } from "./envelope-BCzKUq_z.js";
|
|
3
|
+
import { A as TranscriptRecordFromEnvelope, E as TranscriptOrder, W as isPendingTranscriptUserRecord, Y as transcriptRecordId } from "./records-DWKEjuqb.js";
|
|
4
|
+
import * as Context from "effect/Context";
|
|
5
|
+
import * as Schema from "effect/Schema";
|
|
6
|
+
import * as Result from "effect/Result";
|
|
7
|
+
//#region src/transcript/store.ts
|
|
8
|
+
/** A cursor minted for another log incarnation or transcript version. The client takes `Latest`. */
|
|
9
|
+
var TranscriptCursorMismatch = class extends Schema.TaggedError()("TranscriptCursorMismatch", { message: Schema.String }) {};
|
|
10
|
+
/** Transcript read port, provided alongside `EDASessionStore` by stores that maintain transcripts. */
|
|
11
|
+
var EDATranscriptStore = class extends Context.Service()("@effect-durable-agent/EDATranscriptStore") {};
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/transcript/window-read.ts
|
|
14
|
+
/** Readiness of a served version: why its cut may be behind the log. */
|
|
15
|
+
const transcriptReadiness = (meta, carried) => {
|
|
16
|
+
if (!carried) return { _tag: "UpdatingHistory" };
|
|
17
|
+
switch (meta.status._tag) {
|
|
18
|
+
case "Ok": return { _tag: "Ready" };
|
|
19
|
+
case "Failed": return {
|
|
20
|
+
_tag: "Degraded",
|
|
21
|
+
failedAtSeq: meta.status.failedAtSeq,
|
|
22
|
+
error: meta.status.error
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
/** The empty window served while no version is servable yet. */
|
|
27
|
+
const buildingTranscriptWindow = (incarnation, version) => ({
|
|
28
|
+
incarnation,
|
|
29
|
+
version,
|
|
30
|
+
throughSeq: SequenceNumber.make(0),
|
|
31
|
+
records: [],
|
|
32
|
+
dependencies: [],
|
|
33
|
+
hasOlder: false,
|
|
34
|
+
hasNewer: false,
|
|
35
|
+
readiness: { _tag: "Building" }
|
|
36
|
+
});
|
|
37
|
+
const orderKey = (record) => ({
|
|
38
|
+
anchorSeq: record.position?.anchorSeq ?? 0,
|
|
39
|
+
ordinal: record.position?.ordinal ?? 0,
|
|
40
|
+
recordId: record.id
|
|
41
|
+
});
|
|
42
|
+
const cursorKey = (cursor) => ({
|
|
43
|
+
anchorSeq: cursor.anchorSeq,
|
|
44
|
+
ordinal: cursor.ordinal,
|
|
45
|
+
recordId: cursor.recordId
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* Assemble one window from a source at a single cut.
|
|
49
|
+
*
|
|
50
|
+
* The response never contains anything newer than the served version's cursor: a frozen (failed
|
|
51
|
+
* or no longer carried) version's rows, pending users and session context all stop at its last
|
|
52
|
+
* good cut, which is the degraded-read rule. Bodies above the inline limit become references;
|
|
53
|
+
* if the response still exceeds the byte budget, records are dropped from the far end of the
|
|
54
|
+
* selection, keeping at least one so paging always progresses.
|
|
55
|
+
*/
|
|
56
|
+
const readTranscriptWindowFrom = (source, selector, limits) => {
|
|
57
|
+
const version = source.meta.version;
|
|
58
|
+
for (const cursor of selectorCursors(selector)) if (cursor.incarnation !== source.incarnation || cursor.version !== version) return Result.fail(new TranscriptCursorMismatch({ message: `cursor for ${cursor.incarnation}/${cursor.version} read against ${source.incarnation}/${version}` }));
|
|
59
|
+
const selected = selectTopLevel(source, selector, limits.maxRecords);
|
|
60
|
+
const keepNewest = selector._tag === "Latest" || selector._tag === "Page" && selector.direction === "before";
|
|
61
|
+
let top = selected.map((record) => withBodyRefs(record, limits.maxInlineBodyBytes));
|
|
62
|
+
let dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);
|
|
63
|
+
while (top.length > 1 && windowBytes(top, dependencies) > limits.maxBytes) {
|
|
64
|
+
top = keepNewest ? top.slice(1) : top.slice(0, -1);
|
|
65
|
+
dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);
|
|
66
|
+
}
|
|
67
|
+
const first = top[0];
|
|
68
|
+
const last = top[top.length - 1];
|
|
69
|
+
const [hasOlder, hasNewer] = first === void 0 || last === void 0 ? emptySelectionNeighbours(source, selector) : [source.topLevelBefore(orderKey(first), 1, false).length > 0, source.topLevelAfter(orderKey(last), 1, false).length > 0];
|
|
70
|
+
return Result.succeed({
|
|
71
|
+
incarnation: source.incarnation,
|
|
72
|
+
version,
|
|
73
|
+
throughSeq: source.meta.cursor,
|
|
74
|
+
records: top,
|
|
75
|
+
dependencies,
|
|
76
|
+
hasOlder,
|
|
77
|
+
hasNewer,
|
|
78
|
+
readiness: transcriptReadiness(source.meta, source.carried)
|
|
79
|
+
});
|
|
80
|
+
};
|
|
81
|
+
const selectorCursors = (selector) => {
|
|
82
|
+
switch (selector._tag) {
|
|
83
|
+
case "Latest": return [];
|
|
84
|
+
case "Page": return [selector.cursor];
|
|
85
|
+
case "Range": return [selector.from, selector.to];
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const selectTopLevel = (source, selector, maxRecords) => {
|
|
89
|
+
switch (selector._tag) {
|
|
90
|
+
case "Latest": return [...source.topLevelBefore(void 0, Math.min(selector.count, maxRecords), false)].reverse();
|
|
91
|
+
case "Page": {
|
|
92
|
+
const count = Math.min(selector.count, maxRecords);
|
|
93
|
+
return selector.direction === "before" ? [...source.topLevelBefore(cursorKey(selector.cursor), count, false)].reverse() : source.topLevelAfter(cursorKey(selector.cursor), count, false);
|
|
94
|
+
}
|
|
95
|
+
case "Range": {
|
|
96
|
+
const to = cursorKey(selector.to);
|
|
97
|
+
return source.topLevelAfter(cursorKey(selector.from), maxRecords, true).filter((record) => TranscriptOrder(orderKey(record), to) <= 0);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const emptySelectionNeighbours = (source, selector) => {
|
|
102
|
+
switch (selector._tag) {
|
|
103
|
+
case "Latest": return [false, false];
|
|
104
|
+
case "Page": {
|
|
105
|
+
const key = cursorKey(selector.cursor);
|
|
106
|
+
return selector.direction === "before" ? [false, source.topLevelAfter(key, 1, true).length > 0] : [source.topLevelBefore(key, 1, true).length > 0, false];
|
|
107
|
+
}
|
|
108
|
+
case "Range": return [source.topLevelBefore(cursorKey(selector.from), 1, false).length > 0, source.topLevelAfter(cursorKey(selector.to), 1, false).length > 0];
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
/** Session context, then each record's run group and tools in part order, then pending users. */
|
|
112
|
+
const collectDependencies = (source, top, maxInlineBodyBytes) => {
|
|
113
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
114
|
+
const add = (record) => {
|
|
115
|
+
if (record !== void 0 && !dependencies.has(record.id)) dependencies.set(record.id, withBodyRefs(record, maxInlineBodyBytes));
|
|
116
|
+
};
|
|
117
|
+
add(source.record(transcriptRecordId.session));
|
|
118
|
+
for (const record of top) switch (record.kind) {
|
|
119
|
+
case "assistant": {
|
|
120
|
+
if (record.runGroupId !== void 0) add(source.record(record.runGroupId));
|
|
121
|
+
const partOrder = new Map(record.parts.flatMap((part, index) => part._tag === "ToolCall" && part.toolId !== void 0 ? [[part.toolId, index]] : []));
|
|
122
|
+
[...source.toolsOf(record.id)].sort((left, right) => (partOrder.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (partOrder.get(right.id) ?? Number.MAX_SAFE_INTEGER) || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).forEach(add);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
case "user": {
|
|
126
|
+
const runId = record.state._tag === "Consumed" ? record.state.runId : void 0;
|
|
127
|
+
const groupId = (runId === void 0 ? void 0 : source.alias("runId", runId)) ?? source.alias("runCommand", record.commandId);
|
|
128
|
+
if (groupId !== void 0) add(source.record(groupId));
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
[...source.pendingUsers()].filter(isPendingTranscriptUserRecord).sort((left, right) => left.submittedSeq - right.submittedSeq || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).forEach(add);
|
|
133
|
+
return Array.from(dependencies.values());
|
|
134
|
+
};
|
|
135
|
+
const encoder = new TextEncoder();
|
|
136
|
+
const encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);
|
|
137
|
+
const jsonBytes = (value) => {
|
|
138
|
+
const json = JSON.stringify(value);
|
|
139
|
+
return json === void 0 ? 0 : encoder.encode(json).length;
|
|
140
|
+
};
|
|
141
|
+
const windowBytes = (top, dependencies) => [...top, ...dependencies].reduce((total, record) => total + jsonBytes(encodeRecord(record)), 0);
|
|
142
|
+
const bodyRef = (body, maxInlineBodyBytes) => {
|
|
143
|
+
if (body._tag === "Ref") return body;
|
|
144
|
+
const byteLength = jsonBytes(body.value);
|
|
145
|
+
return byteLength <= maxInlineBodyBytes ? body : {
|
|
146
|
+
_tag: "Ref",
|
|
147
|
+
source: body.source,
|
|
148
|
+
byteLength: NonNegativeInt.make(byteLength)
|
|
149
|
+
};
|
|
150
|
+
};
|
|
151
|
+
/** Replace inline bodies above the limit with references to their immutable log source. */
|
|
152
|
+
const withBodyRefs = (record, maxInlineBodyBytes) => {
|
|
153
|
+
switch (record.kind) {
|
|
154
|
+
case "tool": {
|
|
155
|
+
const tool = {
|
|
156
|
+
...record,
|
|
157
|
+
...record.params === void 0 ? {} : { params: bodyRef(record.params, maxInlineBodyBytes) },
|
|
158
|
+
lifecycle: record.lifecycle._tag === "Completed" ? {
|
|
159
|
+
_tag: "Completed",
|
|
160
|
+
result: bodyRef(record.lifecycle.result, maxInlineBodyBytes)
|
|
161
|
+
} : record.lifecycle
|
|
162
|
+
};
|
|
163
|
+
return {
|
|
164
|
+
...record,
|
|
165
|
+
...tool
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
case "assistant": {
|
|
169
|
+
const parts = record.parts.map((part) => part._tag === "ToolResult" ? {
|
|
170
|
+
...part,
|
|
171
|
+
result: bodyRef(part.result, maxInlineBodyBytes)
|
|
172
|
+
} : part);
|
|
173
|
+
return {
|
|
174
|
+
...record,
|
|
175
|
+
parts
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
default: return record;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
//#endregion
|
|
182
|
+
export { TranscriptCursorMismatch as a, EDATranscriptStore as i, readTranscriptWindowFrom as n, transcriptReadiness as r, buildingTranscriptWindow as t };
|
|
183
|
+
|
|
184
|
+
//# sourceMappingURL=window-read-U55aAeuz.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"window-read-U55aAeuz.js","names":[],"sources":["../src/transcript/store.ts","../src/transcript/window-read.ts"],"sourcesContent":["import * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { EDASessionStoreError } from \"../services/session-store\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport type {\n TranscriptVersionMeta,\n TranscriptWindow,\n TranscriptWindowLimits,\n TranscriptWindowSelector,\n} from \"./window\";\n\n/**\n * The transcript definitions a store maintains, fixed when the store is constructed.\n *\n * `current` is what new sessions start with and every session converges to. `previous` is\n * carried for one release only, so a session not yet rebuilt keeps its active rows maintained.\n * A stored version that matches neither is frozen.\n */\nexport interface TranscriptMaintenanceConfig {\n readonly current: TranscriptDefinition;\n readonly previous?: TranscriptDefinition;\n}\n\n/** A cursor minted for another log incarnation or transcript version. The client takes `Latest`. */\nexport class TranscriptCursorMismatch extends Schema.TaggedError<TranscriptCursorMismatch>()(\n \"TranscriptCursorMismatch\",\n { message: Schema.String },\n) {}\n\n/**\n * Storage-level transcript reads for one session.\n *\n * Maintenance has no method here: the store runs it inside its own append transaction for every\n * carried, healthy version, so `EDASessionStore.append` semantics are unchanged. These reads never\n * construct the model runtime and never include live active content, which only the delivery\n * layer can capture.\n */\nexport interface EDATranscriptStoreShape {\n /** Read one complete window of the served version at a single cut. */\n readonly readTranscriptWindow: (\n selector: TranscriptWindowSelector,\n limits: TranscriptWindowLimits,\n ) => Effect.Effect<TranscriptWindow, EDASessionStoreError | TranscriptCursorMismatch>;\n /** Maintenance state of every version present, for builders, backfill proofs and alerts. */\n readonly readTranscriptMeta: Effect.Effect<\n ReadonlyArray<TranscriptVersionMeta>,\n EDASessionStoreError\n >;\n}\n\n/** Transcript read port, provided alongside `EDASessionStore` by stores that maintain transcripts. */\nexport class EDATranscriptStore extends Context.Service<\n EDATranscriptStore,\n EDATranscriptStoreShape\n>()(\"@effect-durable-agent/EDATranscriptStore\") {}\n","import * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { NonNegativeInt } from \"../types/events/envelope\";\nimport type { TranscriptAliasNamespace } from \"./plan\";\nimport {\n TranscriptOrder,\n TranscriptRecordFromEnvelope,\n isPendingTranscriptUserRecord,\n transcriptRecordId,\n type AssistantRecordId,\n type TranscriptAssistantPart,\n type TranscriptBody,\n type TranscriptCursor,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecord,\n type TranscriptRecordId,\n type TranscriptToolRecord,\n type TranscriptTopLevelRecord,\n type TranscriptUserRecord,\n type TranscriptVersion,\n} from \"./records\";\nimport { TranscriptCursorMismatch } from \"./store\";\nimport type {\n TranscriptReadiness,\n TranscriptVersionMeta,\n TranscriptWindow,\n TranscriptWindowLimits,\n TranscriptWindowSelector,\n} from \"./window\";\n\n/**\n * Synchronous indexed reads of the served version at one cut, as a store provides them.\n *\n * Window assembly (paging, dependency collection, byte budgeting and body references) is shared\n * by every store through `readTranscriptWindowFrom`; a store only supplies these reads.\n */\nexport interface TranscriptWindowSource {\n readonly incarnation: TranscriptLogIncarnation;\n /** Maintenance state of the served (active) version; its cursor is the window's `throughSeq`. */\n readonly meta: TranscriptVersionMeta;\n /** False when this release no longer carries the served version (a missed session). */\n readonly carried: boolean;\n /** Top-level records before `key` (or before the end), newest first. */\n readonly topLevelBefore: (\n key: TranscriptOrderKey | undefined,\n limit: number,\n inclusive: boolean,\n ) => ReadonlyArray<TranscriptTopLevelRecord>;\n /** Top-level records after `key` (or after the start), oldest first. */\n readonly topLevelAfter: (\n key: TranscriptOrderKey | undefined,\n limit: number,\n inclusive: boolean,\n ) => ReadonlyArray<TranscriptTopLevelRecord>;\n readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;\n readonly alias: (\n namespace: TranscriptAliasNamespace,\n key: string,\n ) => TranscriptRecordId | undefined;\n /** Tool records of one assistant (the typed dependency lookup). */\n readonly toolsOf: (assistantId: AssistantRecordId) => ReadonlyArray<TranscriptToolRecord>;\n /** Every user record still waiting for the agent (the pending-membership index). */\n readonly pendingUsers: () => ReadonlyArray<TranscriptUserRecord>;\n}\n\n/** Readiness of a served version: why its cut may be behind the log. */\nexport const transcriptReadiness = (\n meta: TranscriptVersionMeta,\n carried: boolean,\n): TranscriptReadiness => {\n if (!carried) return { _tag: \"UpdatingHistory\" };\n switch (meta.status._tag) {\n case \"Ok\":\n return { _tag: \"Ready\" };\n case \"Failed\":\n return {\n _tag: \"Degraded\",\n failedAtSeq: meta.status.failedAtSeq,\n error: meta.status.error,\n };\n }\n};\n\n/** The empty window served while no version is servable yet. */\nexport const buildingTranscriptWindow = (\n incarnation: TranscriptLogIncarnation,\n version: TranscriptVersion,\n): TranscriptWindow => ({\n incarnation,\n version,\n throughSeq: SequenceNumber.make(0),\n records: [],\n dependencies: [],\n hasOlder: false,\n hasNewer: false,\n readiness: { _tag: \"Building\" },\n});\n\nconst orderKey = (record: TranscriptTopLevelRecord): TranscriptOrderKey => ({\n anchorSeq: record.position?.anchorSeq ?? 0,\n ordinal: record.position?.ordinal ?? 0,\n recordId: record.id,\n});\n\nconst cursorKey = (cursor: TranscriptCursor): TranscriptOrderKey => ({\n anchorSeq: cursor.anchorSeq,\n ordinal: cursor.ordinal,\n recordId: cursor.recordId,\n});\n\n/**\n * Assemble one window from a source at a single cut.\n *\n * The response never contains anything newer than the served version's cursor: a frozen (failed\n * or no longer carried) version's rows, pending users and session context all stop at its last\n * good cut, which is the degraded-read rule. Bodies above the inline limit become references;\n * if the response still exceeds the byte budget, records are dropped from the far end of the\n * selection, keeping at least one so paging always progresses.\n */\nexport const readTranscriptWindowFrom = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n limits: TranscriptWindowLimits,\n): Result.Result<TranscriptWindow, TranscriptCursorMismatch> => {\n const version = source.meta.version;\n for (const cursor of selectorCursors(selector)) {\n if (cursor.incarnation !== source.incarnation || cursor.version !== version) {\n return Result.fail(\n new TranscriptCursorMismatch({\n message: `cursor for ${cursor.incarnation}/${cursor.version} read against ${source.incarnation}/${version}`,\n }),\n );\n }\n }\n\n const selected = selectTopLevel(source, selector, limits.maxRecords);\n // Latest and Page(before) keep the newest records when trimming; the others keep the oldest.\n const keepNewest =\n selector._tag === \"Latest\" || (selector._tag === \"Page\" && selector.direction === \"before\");\n let top = selected.map((record) => withBodyRefs(record, limits.maxInlineBodyBytes));\n let dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);\n while (top.length > 1 && windowBytes(top, dependencies) > limits.maxBytes) {\n top = keepNewest ? top.slice(1) : top.slice(0, -1);\n dependencies = collectDependencies(source, top, limits.maxInlineBodyBytes);\n }\n\n const first = top[0];\n const last = top[top.length - 1];\n const [hasOlder, hasNewer] =\n first === undefined || last === undefined\n ? emptySelectionNeighbours(source, selector)\n : [\n source.topLevelBefore(orderKey(first), 1, false).length > 0,\n source.topLevelAfter(orderKey(last), 1, false).length > 0,\n ];\n\n return Result.succeed({\n incarnation: source.incarnation,\n version,\n throughSeq: source.meta.cursor,\n records: top,\n dependencies,\n hasOlder,\n hasNewer,\n readiness: transcriptReadiness(source.meta, source.carried),\n });\n};\n\nconst selectorCursors = (selector: TranscriptWindowSelector): ReadonlyArray<TranscriptCursor> => {\n switch (selector._tag) {\n case \"Latest\":\n return [];\n case \"Page\":\n return [selector.cursor];\n case \"Range\":\n return [selector.from, selector.to];\n }\n};\n\nconst selectTopLevel = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n maxRecords: number,\n): ReadonlyArray<TranscriptTopLevelRecord> => {\n switch (selector._tag) {\n case \"Latest\":\n return [\n ...source.topLevelBefore(undefined, Math.min(selector.count, maxRecords), false),\n ].reverse();\n case \"Page\": {\n const count = Math.min(selector.count, maxRecords);\n return selector.direction === \"before\"\n ? [...source.topLevelBefore(cursorKey(selector.cursor), count, false)].reverse()\n : source.topLevelAfter(cursorKey(selector.cursor), count, false);\n }\n case \"Range\": {\n const to = cursorKey(selector.to);\n return source\n .topLevelAfter(cursorKey(selector.from), maxRecords, true)\n .filter((record) => TranscriptOrder(orderKey(record), to) <= 0);\n }\n }\n};\n\nconst emptySelectionNeighbours = (\n source: TranscriptWindowSource,\n selector: TranscriptWindowSelector,\n): readonly [boolean, boolean] => {\n switch (selector._tag) {\n case \"Latest\":\n return [false, false];\n case \"Page\": {\n const key = cursorKey(selector.cursor);\n return selector.direction === \"before\"\n ? [false, source.topLevelAfter(key, 1, true).length > 0]\n : [source.topLevelBefore(key, 1, true).length > 0, false];\n }\n case \"Range\":\n return [\n source.topLevelBefore(cursorKey(selector.from), 1, false).length > 0,\n source.topLevelAfter(cursorKey(selector.to), 1, false).length > 0,\n ];\n }\n};\n\n/** Session context, then each record's run group and tools in part order, then pending users. */\nconst collectDependencies = (\n source: TranscriptWindowSource,\n top: ReadonlyArray<TranscriptTopLevelRecord>,\n maxInlineBodyBytes: number,\n): ReadonlyArray<TranscriptRecord> => {\n const dependencies = new Map<string, TranscriptRecord>();\n const add = (record: TranscriptRecord | undefined) => {\n if (record !== undefined && !dependencies.has(record.id)) {\n dependencies.set(record.id, withBodyRefs(record, maxInlineBodyBytes));\n }\n };\n add(source.record(transcriptRecordId.session));\n for (const record of top) {\n switch (record.kind) {\n case \"assistant\": {\n if (record.runGroupId !== undefined) add(source.record(record.runGroupId));\n const partOrder = new Map(\n record.parts.flatMap((part, index) =>\n part._tag === \"ToolCall\" && part.toolId !== undefined ? [[part.toolId, index]] : [],\n ),\n );\n const tools = [...source.toolsOf(record.id)].sort(\n (left, right) =>\n (partOrder.get(left.id) ?? Number.MAX_SAFE_INTEGER) -\n (partOrder.get(right.id) ?? Number.MAX_SAFE_INTEGER) ||\n (left.id < right.id ? -1 : left.id > right.id ? 1 : 0),\n );\n tools.forEach(add);\n break;\n }\n case \"user\": {\n // The consuming run's group, or, for a submission committed at its own run's start (the\n // interrupt path, which records no run on the user), the group that owns its command.\n const runId = record.state._tag === \"Consumed\" ? record.state.runId : undefined;\n const groupId =\n (runId === undefined ? undefined : source.alias(\"runId\", runId)) ??\n source.alias(\"runCommand\", record.commandId);\n if (groupId !== undefined) add(source.record(groupId));\n break;\n }\n case \"compaction\":\n break;\n }\n }\n [...source.pendingUsers()]\n .filter(isPendingTranscriptUserRecord)\n .sort(\n (left, right) =>\n left.submittedSeq - right.submittedSeq ||\n (left.id < right.id ? -1 : left.id > right.id ? 1 : 0),\n )\n .forEach(add);\n return Array.from(dependencies.values());\n};\n\nconst encoder = new TextEncoder();\nconst encodeRecord = Schema.encodeSync(TranscriptRecordFromEnvelope);\n\nconst jsonBytes = (value: unknown): number => {\n const json = JSON.stringify(value);\n return json === undefined ? 0 : encoder.encode(json).length;\n};\n\nconst windowBytes = (\n top: ReadonlyArray<TranscriptRecord>,\n dependencies: ReadonlyArray<TranscriptRecord>,\n): number =>\n [...top, ...dependencies].reduce((total, record) => total + jsonBytes(encodeRecord(record)), 0);\n\nconst bodyRef = (body: TranscriptBody, maxInlineBodyBytes: number): TranscriptBody => {\n if (body._tag === \"Ref\") return body;\n const byteLength = jsonBytes(body.value);\n return byteLength <= maxInlineBodyBytes\n ? body\n : { _tag: \"Ref\", source: body.source, byteLength: NonNegativeInt.make(byteLength) };\n};\n\n/** Replace inline bodies above the limit with references to their immutable log source. */\nconst withBodyRefs = <R extends TranscriptRecord>(record: R, maxInlineBodyBytes: number): R => {\n switch (record.kind) {\n case \"tool\": {\n const tool: TranscriptToolRecord = {\n ...record,\n ...(record.params === undefined\n ? {}\n : { params: bodyRef(record.params, maxInlineBodyBytes) }),\n lifecycle:\n record.lifecycle._tag === \"Completed\"\n ? { _tag: \"Completed\", result: bodyRef(record.lifecycle.result, maxInlineBodyBytes) }\n : record.lifecycle,\n };\n return { ...record, ...tool };\n }\n case \"assistant\": {\n const parts = record.parts.map((part): TranscriptAssistantPart =>\n part._tag === \"ToolResult\"\n ? { ...part, result: bodyRef(part.result, maxInlineBodyBytes) }\n : part,\n );\n return { ...record, parts };\n }\n default:\n return record;\n }\n};\n"],"mappings":";;;;;;;;AA0BA,IAAa,2BAAb,cAA8C,OAAO,YAAsC,CAAC,CAC1F,4BACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;;AAwBH,IAAa,qBAAb,cAAwC,QAAQ,QAG9C,CAAC,CAAC,0CAA0C,CAAC,CAAC,CAAC;;;;ACajD,MAAa,uBACX,MACA,YACwB;CACxB,IAAI,CAAC,SAAS,OAAO,EAAE,MAAM,kBAAkB;CAC/C,QAAQ,KAAK,OAAO,MAApB;EACE,KAAK,MACH,OAAO,EAAE,MAAM,QAAQ;EACzB,KAAK,UACH,OAAO;GACL,MAAM;GACN,aAAa,KAAK,OAAO;GACzB,OAAO,KAAK,OAAO;EACrB;CACJ;AACF;;AAGA,MAAa,4BACX,aACA,aACsB;CACtB;CACA;CACA,YAAY,eAAe,KAAK,CAAC;CACjC,SAAS,CAAC;CACV,cAAc,CAAC;CACf,UAAU;CACV,UAAU;CACV,WAAW,EAAE,MAAM,WAAW;AAChC;AAEA,MAAM,YAAY,YAA0D;CAC1E,WAAW,OAAO,UAAU,aAAa;CACzC,SAAS,OAAO,UAAU,WAAW;CACrC,UAAU,OAAO;AACnB;AAEA,MAAM,aAAa,YAAkD;CACnE,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,UAAU,OAAO;AACnB;;;;;;;;;;AAWA,MAAa,4BACX,QACA,UACA,WAC8D;CAC9D,MAAM,UAAU,OAAO,KAAK;CAC5B,KAAK,MAAM,UAAU,gBAAgB,QAAQ,GAC3C,IAAI,OAAO,gBAAgB,OAAO,eAAe,OAAO,YAAY,SAClE,OAAO,OAAO,KACZ,IAAI,yBAAyB,EAC3B,SAAS,cAAc,OAAO,YAAY,GAAG,OAAO,QAAQ,gBAAgB,OAAO,YAAY,GAAG,UACpG,CAAC,CACH;CAIJ,MAAM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;CACjC,OAAO,SAAS,KAAA,IAAY,IAAI,QAAQ,OAAO,IAAI,CAAC,CAAC;AACvD;AAEA,MAAM,eACJ,KACA,iBAEA,CAAC,GAAG,KAAK,GAAG,YAAY,CAAC,CAAC,QAAQ,OAAO,WAAW,QAAQ,UAAU,aAAa,MAAM,CAAC,GAAG,CAAC;AAEhG,MAAM,WAAW,MAAsB,uBAA+C;CACpF,IAAI,KAAK,SAAS,OAAO,OAAO;CAChC,MAAM,aAAa,UAAU,KAAK,KAAK;CACvC,OAAO,cAAc,qBACjB,OACA;EAAE,MAAM;EAAO,QAAQ,KAAK;EAAQ,YAAY,eAAe,KAAK,UAAU;CAAE;AACtF;;AAGA,MAAM,gBAA4C,QAAW,uBAAkC;CAC7F,QAAQ,OAAO,MAAf;EACE,KAAK,QAAQ;GACX,MAAM,OAA6B;IACjC,GAAG;IACH,GAAI,OAAO,WAAW,KAAA,IAClB,CAAC,IACD,EAAE,QAAQ,QAAQ,OAAO,QAAQ,kBAAkB,EAAE;IACzD,WACE,OAAO,UAAU,SAAS,cACtB;KAAE,MAAM;KAAa,QAAQ,QAAQ,OAAO,UAAU,QAAQ,kBAAkB;IAAE,IAClF,OAAO;GACf;GACA,OAAO;IAAE,GAAG;IAAQ,GAAG;GAAK;EAC9B;EACA,KAAK,aAAa;GAChB,MAAM,QAAQ,OAAO,MAAM,KAAK,SAC9B,KAAK,SAAS,eACV;IAAE,GAAG;IAAM,QAAQ,QAAQ,KAAK,QAAQ,kBAAkB;GAAE,IAC5D,IACN;GACA,OAAO;IAAE,GAAG;IAAQ;GAAM;EAC5B;EACA,SACE,OAAO;CACX;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "effect-durable-agent",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.24",
|
|
4
4
|
"description": "A host-independent, event-sourced durable state-management and execution layer for agentic applications.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -142,6 +142,10 @@
|
|
|
142
142
|
"types": "./dist/testkit/layers.d.ts",
|
|
143
143
|
"import": "./dist/testkit/layers.js"
|
|
144
144
|
},
|
|
145
|
+
"./testkit/transcript": {
|
|
146
|
+
"types": "./dist/testkit/transcript.d.ts",
|
|
147
|
+
"import": "./dist/testkit/transcript.js"
|
|
148
|
+
},
|
|
145
149
|
"./tooling/oxlint": "./tooling/oxlint/index.mjs",
|
|
146
150
|
"./types/commands": {
|
|
147
151
|
"types": "./dist/types/commands.d.ts",
|
|
@@ -1,414 +0,0 @@
|
|
|
1
|
-
import { CommandId, DurablePosition, SequenceNumber, durablePosition } from "./types/core.js";
|
|
2
|
-
import { t as DurableEventEnvelope } from "./envelope-BCzKUq_z.js";
|
|
3
|
-
import { H as DecodedDurableEvent, Nn as commandAdmittedEventType, Un as contextRebasedEventType, Wn as decodeDurableEventSync, kr as decodeRetainingExcess, mr as summaryCreatedEventType, qn as durableEventEnvelope } from "./durable-CD__3ztN.js";
|
|
4
|
-
import { CompactionSummaryArtifact } from "./domain/context-projection.js";
|
|
5
|
-
import { E as TranscriptOrder, G as isTopLevelTranscriptRecord, T as TranscriptLogIncarnation, W as isPendingTranscriptUserRecord } from "./records-DWKEjuqb.js";
|
|
6
|
-
import { i as EDATranscriptStore, n as readTranscriptWindowFrom, o as planTranscriptBatch, t as buildingTranscriptWindow, v as emptyTranscriptMappings, y as makeTranscriptDefinition } from "./window-read-BDayZf7O.js";
|
|
7
|
-
import * as Context from "effect/Context";
|
|
8
|
-
import * as Effect from "effect/Effect";
|
|
9
|
-
import * as Layer from "effect/Layer";
|
|
10
|
-
import * as Schema from "effect/Schema";
|
|
11
|
-
import * as Stream from "effect/Stream";
|
|
12
|
-
import * as Cause from "effect/Cause";
|
|
13
|
-
import * as Ref from "effect/Ref";
|
|
14
|
-
import * as Result from "effect/Result";
|
|
15
|
-
import * as SchemaGetter from "effect/SchemaGetter";
|
|
16
|
-
//#region src/transcript/in-memory.ts
|
|
17
|
-
const aliasKey = (namespace, key) => `${namespace}\u0000${key}`;
|
|
18
|
-
/** The carried definition for a stored version, if this release still carries it. */
|
|
19
|
-
const carriedTranscriptDefinition = (config, version) => config.current.version === version ? config.current : config.previous?.version === version ? config.previous : void 0;
|
|
20
|
-
/** An empty version before any event is projected. */
|
|
21
|
-
const emptyTranscriptVersion = (version, role) => ({
|
|
22
|
-
meta: {
|
|
23
|
-
version,
|
|
24
|
-
role,
|
|
25
|
-
cursor: SequenceNumber.make(0),
|
|
26
|
-
status: { _tag: "Ok" }
|
|
27
|
-
},
|
|
28
|
-
records: /* @__PURE__ */ new Map(),
|
|
29
|
-
aliases: /* @__PURE__ */ new Map(),
|
|
30
|
-
ordinals: /* @__PURE__ */ new Map()
|
|
31
|
-
});
|
|
32
|
-
const lookupOf = (version) => ({
|
|
33
|
-
cursor: version.meta.cursor,
|
|
34
|
-
record: (id) => version.records.get(id),
|
|
35
|
-
alias: (namespace, key) => version.aliases.get(aliasKey(namespace, key)),
|
|
36
|
-
nextOrdinal: (anchorSeq) => version.ordinals.get(anchorSeq) ?? 0
|
|
37
|
-
});
|
|
38
|
-
const applyPlan = (version, plan) => {
|
|
39
|
-
const records = new Map(version.records);
|
|
40
|
-
const aliases = new Map(version.aliases);
|
|
41
|
-
const ordinals = new Map(version.ordinals);
|
|
42
|
-
for (const record of plan.records) {
|
|
43
|
-
records.set(record.id, record);
|
|
44
|
-
if ("position" in record && record.position !== void 0) {
|
|
45
|
-
const { anchorSeq, ordinal } = record.position;
|
|
46
|
-
ordinals.set(anchorSeq, Math.max(ordinals.get(anchorSeq) ?? 0, ordinal + 1));
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
for (const alias of plan.aliases) {
|
|
50
|
-
const key = aliasKey(alias.namespace, alias.key);
|
|
51
|
-
if (!aliases.has(key)) aliases.set(key, alias.recordId);
|
|
52
|
-
}
|
|
53
|
-
return {
|
|
54
|
-
meta: {
|
|
55
|
-
...version.meta,
|
|
56
|
-
cursor: plan.throughSeq
|
|
57
|
-
},
|
|
58
|
-
records,
|
|
59
|
-
aliases,
|
|
60
|
-
ordinals
|
|
61
|
-
};
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* Project committed events into one version, or freeze it.
|
|
65
|
-
*
|
|
66
|
-
* A projection failure marks only this version failed at its unchanged cursor and leaves its
|
|
67
|
-
* rows exactly as they were, so it remains a consistent last-good cut.
|
|
68
|
-
*/
|
|
69
|
-
const advanceTranscriptVersion = (version, definition, committed) => {
|
|
70
|
-
const fresh = committed.filter((entry) => entry.position.seq > version.meta.cursor);
|
|
71
|
-
const first = fresh[0];
|
|
72
|
-
if (first === void 0 || version.meta.status._tag === "Failed") return version;
|
|
73
|
-
try {
|
|
74
|
-
return applyPlan(version, planTranscriptBatch(lookupOf(version), fresh, definition));
|
|
75
|
-
} catch (error) {
|
|
76
|
-
return {
|
|
77
|
-
...version,
|
|
78
|
-
meta: {
|
|
79
|
-
...version.meta,
|
|
80
|
-
status: {
|
|
81
|
-
_tag: "Failed",
|
|
82
|
-
failedAtSeq: first.position.seq,
|
|
83
|
-
error: error instanceof Error ? error.message : String(error)
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
};
|
|
89
|
-
/** Maintain every carried, healthy version for a committed append; others stay frozen. */
|
|
90
|
-
const maintainTranscripts = (state, committed) => ({
|
|
91
|
-
...state,
|
|
92
|
-
versions: state.versions.map((version) => {
|
|
93
|
-
const definition = carriedTranscriptDefinition(state.config, version.meta.version);
|
|
94
|
-
return definition === void 0 ? version : advanceTranscriptVersion(version, definition, committed);
|
|
95
|
-
})
|
|
96
|
-
});
|
|
97
|
-
/**
|
|
98
|
-
* Converge a session to the current definition, as the adapter's builder does in slices.
|
|
99
|
-
*
|
|
100
|
-
* A building version that is not `current` is discarded. If the active version is not `current`,
|
|
101
|
-
* `current` is built from the log (never from old rows) and, once it reaches the head, becomes
|
|
102
|
-
* active and the old version is deleted. A failed build leaves the active version serving; only a
|
|
103
|
-
* new definition repairs it. A brand-new log simply initializes `current`.
|
|
104
|
-
*/
|
|
105
|
-
const convergeTranscripts = (state, log) => {
|
|
106
|
-
const current = state.config.current;
|
|
107
|
-
const versions = state.versions.filter((version) => version.meta.role === "active" || version.meta.version === current.version);
|
|
108
|
-
if (versions.find((version) => version.meta.role === "active")?.meta.version === current.version) return {
|
|
109
|
-
...state,
|
|
110
|
-
versions
|
|
111
|
-
};
|
|
112
|
-
const building = versions.find((version) => version.meta.role === "building") ?? emptyTranscriptVersion(current.version, "building");
|
|
113
|
-
const built = advanceTranscriptVersion(building, current, log);
|
|
114
|
-
if (built.meta.status._tag === "Failed") return {
|
|
115
|
-
...state,
|
|
116
|
-
versions: [...versions.filter((version) => version !== building), built]
|
|
117
|
-
};
|
|
118
|
-
return {
|
|
119
|
-
...state,
|
|
120
|
-
versions: [{
|
|
121
|
-
...built,
|
|
122
|
-
meta: {
|
|
123
|
-
...built.meta,
|
|
124
|
-
role: "active"
|
|
125
|
-
}
|
|
126
|
-
}]
|
|
127
|
-
};
|
|
128
|
-
};
|
|
129
|
-
/** Initial transcript state for a store whose log already holds `log`. */
|
|
130
|
-
const initialTranscriptState = (incarnation, config, log) => convergeTranscripts({
|
|
131
|
-
incarnation,
|
|
132
|
-
config,
|
|
133
|
-
versions: []
|
|
134
|
-
}, log);
|
|
135
|
-
const topLevelOrder = (record) => ({
|
|
136
|
-
anchorSeq: record.position?.anchorSeq ?? 0,
|
|
137
|
-
ordinal: record.position?.ordinal ?? 0,
|
|
138
|
-
recordId: record.id
|
|
139
|
-
});
|
|
140
|
-
/** Window reads over the active version, or undefined while nothing is servable. */
|
|
141
|
-
const inMemoryTranscriptWindowSource = (state) => {
|
|
142
|
-
const active = state.versions.find((version) => version.meta.role === "active");
|
|
143
|
-
if (active === void 0) return void 0;
|
|
144
|
-
const records = Array.from(active.records.values());
|
|
145
|
-
const ordered = records.filter(isTopLevelTranscriptRecord).sort((left, right) => TranscriptOrder(topLevelOrder(left), topLevelOrder(right)));
|
|
146
|
-
const compare = (record, key) => TranscriptOrder(topLevelOrder(record), key);
|
|
147
|
-
return {
|
|
148
|
-
incarnation: state.incarnation,
|
|
149
|
-
meta: active.meta,
|
|
150
|
-
carried: carriedTranscriptDefinition(state.config, active.meta.version) !== void 0,
|
|
151
|
-
topLevelBefore: (key, limit, inclusive) => ordered.filter((record) => key === void 0 || (inclusive ? compare(record, key) <= 0 : compare(record, key) < 0)).reverse().slice(0, limit),
|
|
152
|
-
topLevelAfter: (key, limit, inclusive) => ordered.filter((record) => key === void 0 || (inclusive ? compare(record, key) >= 0 : compare(record, key) > 0)).slice(0, limit),
|
|
153
|
-
record: (id) => active.records.get(id),
|
|
154
|
-
alias: (namespace, key) => active.aliases.get(aliasKey(namespace, key)),
|
|
155
|
-
toolsOf: (assistantId) => records.flatMap((record) => record.kind === "tool" && record.assistantId === assistantId ? [record] : []),
|
|
156
|
-
pendingUsers: () => records.filter(isPendingTranscriptUserRecord)
|
|
157
|
-
};
|
|
158
|
-
};
|
|
159
|
-
//#endregion
|
|
160
|
-
//#region src/services/session-store.ts
|
|
161
|
-
/** A durable event after the store has assigned its replay position. */
|
|
162
|
-
const CommittedDurableEvent = Schema.Struct({
|
|
163
|
-
position: DurablePosition,
|
|
164
|
-
event: DurableEventEnvelope.pipe(Schema.decodeTo(Schema.declare(Schema.is(DecodedDurableEvent)), {
|
|
165
|
-
decode: SchemaGetter.transform(decodeDurableEventSync),
|
|
166
|
-
encode: SchemaGetter.transform(durableEventEnvelope)
|
|
167
|
-
}))
|
|
168
|
-
});
|
|
169
|
-
/**
|
|
170
|
-
* Store-level failure surfaced by durable append, replay, and hydration APIs.
|
|
171
|
-
*
|
|
172
|
-
* The error intentionally stays storage-semantic rather than SQL-specific so
|
|
173
|
-
* framework services can treat SQL-backed hosts, in-memory tests, and future adapters
|
|
174
|
-
* as the same durability boundary.
|
|
175
|
-
*/
|
|
176
|
-
var EDASessionStoreError = class extends Schema.TaggedError()("EDASessionStoreError", { message: Schema.String }) {};
|
|
177
|
-
/** True when a Cause contains an escaped durable-store failure. */
|
|
178
|
-
const hasEDASessionStoreError = (cause) => cause.reasons.some((reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError);
|
|
179
|
-
/**
|
|
180
|
-
* One logical event to persist in the durable session log.
|
|
181
|
-
*
|
|
182
|
-
* Store adapters may split large logical payload fields into sidecar rows after
|
|
183
|
-
* the event insert assigns `seq`, but callers still provide one fat event.
|
|
184
|
-
*/
|
|
185
|
-
const DurableAppendEntry = Schema.Struct({ event: DurableEventEnvelope });
|
|
186
|
-
/**
|
|
187
|
-
* Ordered durable append intent. Adapters assign positions in entry order.
|
|
188
|
-
*
|
|
189
|
-
* This is the single write shape exposed to framework services. It avoids raw
|
|
190
|
-
* SQL and public transaction callbacks while still expressing the full atomic
|
|
191
|
-
* transition EDA needs for events, normalized bodies, and metadata.
|
|
192
|
-
*/
|
|
193
|
-
const DurableAppendBatch = Schema.Struct({ entries: Schema.Array(DurableAppendEntry) });
|
|
194
|
-
/** Indexed command-admission lookup used for idempotent ingress. */
|
|
195
|
-
const FindCommandAdmissionInput = Schema.Struct({
|
|
196
|
-
commandId: Schema.optionalKey(CommandId),
|
|
197
|
-
idempotencyKey: Schema.optionalKey(Schema.String)
|
|
198
|
-
});
|
|
199
|
-
/**
|
|
200
|
-
* SQL-agnostic durable storage port for one EDA session.
|
|
201
|
-
*
|
|
202
|
-
* Framework services depend on this semantic port rather than raw SQL. Host
|
|
203
|
-
* adapters own physical tables and synchronous transaction mechanics; callers
|
|
204
|
-
* only express durable append/replay/lookup intent.
|
|
205
|
-
*/
|
|
206
|
-
var EDASessionStore = class extends Context.Service()("@effect-durable-agent/EDASessionStore") {
|
|
207
|
-
/**
|
|
208
|
-
* Deterministic in-memory implementation used by runtime and recovery tests.
|
|
209
|
-
*
|
|
210
|
-
* It also provides `EDATranscriptStore`, maintaining the transcript inside the same append
|
|
211
|
-
* critical section. Without `options.transcript` it maintains the definition with no host
|
|
212
|
-
* mappings.
|
|
213
|
-
*/
|
|
214
|
-
static InMemory = (sessionId, options) => inMemoryStoreLayer(sessionId, () => [], options);
|
|
215
|
-
/** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */
|
|
216
|
-
static InMemorySeeded = (sessionId, events, options) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);
|
|
217
|
-
};
|
|
218
|
-
const inMemoryStoreLayer = (sessionId, seed, options) => Layer.effectContext(Effect.gen(function* () {
|
|
219
|
-
const committed = seed();
|
|
220
|
-
const config = options?.transcript ?? { current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie) };
|
|
221
|
-
const data = yield* Ref.make({
|
|
222
|
-
committed,
|
|
223
|
-
summaries: summariesFromCommittedEvents(committed),
|
|
224
|
-
reducerCheckpoints: /* @__PURE__ */ new Map(),
|
|
225
|
-
transcript: initialTranscriptState(TranscriptLogIncarnation.make(`memory:${sessionId}`), config, committed)
|
|
226
|
-
});
|
|
227
|
-
return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)));
|
|
228
|
-
}));
|
|
229
|
-
const seedCommittedEvents = (sessionId, events) => {
|
|
230
|
-
const seen = /* @__PURE__ */ new Set();
|
|
231
|
-
return events.map((event, index) => {
|
|
232
|
-
if (event.sessionId !== sessionId) throw new Error(`EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`);
|
|
233
|
-
if (seen.has(event.eventId)) throw new Error(`Duplicate seed eventId ${event.eventId}`);
|
|
234
|
-
seen.add(event.eventId);
|
|
235
|
-
return {
|
|
236
|
-
position: durablePosition(SequenceNumber.make(index + 1)),
|
|
237
|
-
event: decodeDurableEventSync(DurableEventEnvelope.make(event))
|
|
238
|
-
};
|
|
239
|
-
});
|
|
240
|
-
};
|
|
241
|
-
const summariesFromCommittedEvents = (events) => {
|
|
242
|
-
const summaries = /* @__PURE__ */ new Map();
|
|
243
|
-
for (const { event } of events) {
|
|
244
|
-
if (event.type !== summaryCreatedEventType) continue;
|
|
245
|
-
const payload = event.payload;
|
|
246
|
-
if (payload.summary !== void 0) {
|
|
247
|
-
const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
|
|
248
|
-
summaries.set(summary.summaryId, summary);
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
return summaries;
|
|
252
|
-
};
|
|
253
|
-
/**
|
|
254
|
-
* Build an in-memory store with one `Ref.modify` append critical section.
|
|
255
|
-
*
|
|
256
|
-
* The fake models the semantic atomicity of the production adapter without
|
|
257
|
-
* exposing SQL, so runtime tests exercise the same store contract.
|
|
258
|
-
*/
|
|
259
|
-
const makeInMemoryStore = (sessionId, data) => {
|
|
260
|
-
const ensureSession = (event) => Effect.gen(function* () {
|
|
261
|
-
if (event.sessionId === sessionId) return;
|
|
262
|
-
return yield* new EDASessionStoreError({ message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}` });
|
|
263
|
-
});
|
|
264
|
-
const append = (batch) => Effect.gen(function* () {
|
|
265
|
-
for (const entry of batch.entries) yield* ensureSession(entry.event);
|
|
266
|
-
return yield* Ref.modify(data, (current) => {
|
|
267
|
-
const nextEntries = [...current.committed];
|
|
268
|
-
const nextSummaries = new Map(current.summaries);
|
|
269
|
-
const committedEvents = [];
|
|
270
|
-
const appended = [];
|
|
271
|
-
for (const entry of batch.entries) {
|
|
272
|
-
const { event } = entry;
|
|
273
|
-
const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);
|
|
274
|
-
if (existing !== void 0) {
|
|
275
|
-
committedEvents.push(existing);
|
|
276
|
-
continue;
|
|
277
|
-
}
|
|
278
|
-
const committed = {
|
|
279
|
-
position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),
|
|
280
|
-
event: decodeDurableEventSync(DurableEventEnvelope.make(event))
|
|
281
|
-
};
|
|
282
|
-
nextEntries.push(committed);
|
|
283
|
-
committedEvents.push(committed);
|
|
284
|
-
appended.push(committed);
|
|
285
|
-
if (committed.event.type === summaryCreatedEventType) {
|
|
286
|
-
const payload = committed.event.payload;
|
|
287
|
-
if (payload.summary === void 0) throw new Error("SummaryCreated requires summary payload");
|
|
288
|
-
const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);
|
|
289
|
-
if (payload.summaryId !== void 0 && summary.summaryId !== payload.summaryId) throw new Error("SummaryCreated summaryId does not match summary payload");
|
|
290
|
-
nextSummaries.set(summary.summaryId, summary);
|
|
291
|
-
}
|
|
292
|
-
if (committed.event.type === contextRebasedEventType) {
|
|
293
|
-
const payload = committed.event.payload;
|
|
294
|
-
if (payload.summaryId === void 0 || !nextSummaries.has(payload.summaryId)) throw new Error(`ContextRebased references unknown summaryId ${String(payload.summaryId)}`);
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
return [committedEvents, {
|
|
298
|
-
committed: nextEntries,
|
|
299
|
-
summaries: nextSummaries,
|
|
300
|
-
reducerCheckpoints: current.reducerCheckpoints,
|
|
301
|
-
transcript: appended.length === 0 ? current.transcript : maintainTranscripts(current.transcript, appended)
|
|
302
|
-
}];
|
|
303
|
-
});
|
|
304
|
-
});
|
|
305
|
-
return {
|
|
306
|
-
append,
|
|
307
|
-
eventsAfter: (afterSeq) => Stream.fromIterableEffect(Ref.get(data).pipe(Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)))),
|
|
308
|
-
loadCommittedEventsBySeq: (seqs) => Ref.get(data).pipe(Effect.map(({ committed }) => {
|
|
309
|
-
const requested = new Set(seqs.map((seq) => Number(seq)));
|
|
310
|
-
return committed.filter((entry) => requested.has(Number(entry.position.seq)));
|
|
311
|
-
})),
|
|
312
|
-
findCommandAdmission: (input) => Ref.get(data).pipe(Effect.map(({ committed }) => committed.find((entry) => commandAdmissionMatches(entry, input)))),
|
|
313
|
-
loadSummaryArtifact: (summaryId) => Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),
|
|
314
|
-
loadReducerCheckpoint: (name) => Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),
|
|
315
|
-
saveReducerCheckpoint: (checkpoint) => Ref.update(data, (current) => ({
|
|
316
|
-
...current,
|
|
317
|
-
reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint)
|
|
318
|
-
})),
|
|
319
|
-
saveReducerCheckpoints: (checkpoints) => Ref.update(data, (current) => {
|
|
320
|
-
const reducerCheckpoints = new Map(current.reducerCheckpoints);
|
|
321
|
-
for (const checkpoint of checkpoints) reducerCheckpoints.set(checkpoint.name, checkpoint);
|
|
322
|
-
return {
|
|
323
|
-
...current,
|
|
324
|
-
reducerCheckpoints
|
|
325
|
-
};
|
|
326
|
-
})
|
|
327
|
-
};
|
|
328
|
-
};
|
|
329
|
-
/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */
|
|
330
|
-
const makeInMemoryTranscriptStore = (data) => ({
|
|
331
|
-
readTranscriptWindow: (selector, limits) => Effect.gen(function* () {
|
|
332
|
-
const { transcript } = yield* Ref.get(data);
|
|
333
|
-
const source = inMemoryTranscriptWindowSource(transcript);
|
|
334
|
-
if (source === void 0) return buildingTranscriptWindow(transcript.incarnation, transcript.config.current.version);
|
|
335
|
-
const window = readTranscriptWindowFrom(source, selector, limits);
|
|
336
|
-
return Result.isSuccess(window) ? window.success : yield* window.failure;
|
|
337
|
-
}),
|
|
338
|
-
readTranscriptMeta: Ref.get(data).pipe(Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)))
|
|
339
|
-
});
|
|
340
|
-
const commandAdmissionMatches = (entry, input) => {
|
|
341
|
-
if (entry.event.type !== commandAdmittedEventType) return false;
|
|
342
|
-
const admitted = entry.event.payload.command;
|
|
343
|
-
if (admitted === void 0) return false;
|
|
344
|
-
if (input.idempotencyKey !== void 0 && admitted.idempotencyKey === input.idempotencyKey) return true;
|
|
345
|
-
return input.commandId !== void 0 && admitted.commandId === input.commandId;
|
|
346
|
-
};
|
|
347
|
-
const eventNamespaces = (ast) => {
|
|
348
|
-
if (ast._tag === "Union") return ast.types.flatMap(eventNamespaces);
|
|
349
|
-
if (ast._tag === "Objects") {
|
|
350
|
-
const namespace = ast.propertySignatures.find((field) => field.name === "namespace")?.type;
|
|
351
|
-
if (namespace?._tag === "Literal" && typeof namespace.literal === "string") return [namespace.literal];
|
|
352
|
-
}
|
|
353
|
-
throw new Error("App event schemas must be a union of structs with literal namespaces");
|
|
354
|
-
};
|
|
355
|
-
/** Attach the app decoder to every event-returning store operation without changing storage bytes. */
|
|
356
|
-
const registerAppEvents = (store, schema) => {
|
|
357
|
-
const namespaces = new Set(eventNamespaces(schema.ast));
|
|
358
|
-
const decode = decodeRetainingExcess(schema);
|
|
359
|
-
const envelopeKey = (event) => JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));
|
|
360
|
-
const decodeEntry = (entry, prepared) => {
|
|
361
|
-
if (entry.event.namespace !== "__foreign" || !namespaces.has(entry.event.envelope.namespace)) return entry;
|
|
362
|
-
return {
|
|
363
|
-
...entry,
|
|
364
|
-
event: {
|
|
365
|
-
...entry.event,
|
|
366
|
-
decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope)
|
|
367
|
-
}
|
|
368
|
-
};
|
|
369
|
-
};
|
|
370
|
-
const decodeEntryEffect = (entry) => Effect.try({
|
|
371
|
-
try: () => decodeEntry(entry),
|
|
372
|
-
catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
|
|
373
|
-
});
|
|
374
|
-
const decodeEntries = (entries) => Effect.forEach(entries, decodeEntryEffect);
|
|
375
|
-
return {
|
|
376
|
-
...store,
|
|
377
|
-
append: (batch) => Effect.gen(function* () {
|
|
378
|
-
const prepared = yield* Effect.try({
|
|
379
|
-
try: () => {
|
|
380
|
-
const decoded = /* @__PURE__ */ new Map();
|
|
381
|
-
for (const { event } of batch.entries) {
|
|
382
|
-
if (!namespaces.has(event.namespace)) continue;
|
|
383
|
-
const key = envelopeKey(event);
|
|
384
|
-
if (!decoded.has(key)) decoded.set(key, decode(event));
|
|
385
|
-
}
|
|
386
|
-
return decoded;
|
|
387
|
-
},
|
|
388
|
-
catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
|
|
389
|
-
});
|
|
390
|
-
const committed = yield* store.append(batch);
|
|
391
|
-
return yield* Effect.forEach(committed, (entry) => Effect.try({
|
|
392
|
-
try: () => decodeEntry(entry, prepared),
|
|
393
|
-
catch: (cause) => new EDASessionStoreError({ message: `Registered app event decode failed: ${String(cause)}` })
|
|
394
|
-
}));
|
|
395
|
-
}),
|
|
396
|
-
eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),
|
|
397
|
-
loadCommittedEventsBySeq: (seqs) => store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),
|
|
398
|
-
findCommandAdmission: (input) => store.findCommandAdmission(input).pipe(Effect.flatMap((entry) => entry === void 0 ? Effect.succeed(void 0) : decodeEntryEffect(entry)))
|
|
399
|
-
};
|
|
400
|
-
};
|
|
401
|
-
/** Narrow an already decoded fact from one schema, without decoding its payload again. */
|
|
402
|
-
const selectCommittedEvent = (schema, entry) => {
|
|
403
|
-
const event = entry.event.namespace === "__foreign" ? entry.event.decoded ?? entry.event.envelope : entry.event;
|
|
404
|
-
return Schema.is(schema)(event) ? {
|
|
405
|
-
position: entry.position,
|
|
406
|
-
event
|
|
407
|
-
} : void 0;
|
|
408
|
-
};
|
|
409
|
-
/** Typed journal read available to tools and application services without private SQL access. */
|
|
410
|
-
const queryCommittedEvents = (store, schema, options = {}) => store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(Stream.map((entry) => selectCommittedEvent(schema, entry)), Stream.filter((entry) => entry !== void 0), Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER), Stream.runCollect);
|
|
411
|
-
//#endregion
|
|
412
|
-
export { EDASessionStoreError as a, queryCommittedEvents as c, EDASessionStore as i, registerAppEvents as l, DurableAppendBatch as n, FindCommandAdmissionInput as o, DurableAppendEntry as r, hasEDASessionStoreError as s, CommittedDurableEvent as t, selectCommittedEvent as u };
|
|
413
|
-
|
|
414
|
-
//# sourceMappingURL=session-store-DuEhcqIC.js.map
|