@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.1
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/README.md +67 -2
- package/dist/framework/action-diagnostics.d.ts +11 -0
- package/dist/framework/action-diagnostics.js +67 -0
- package/dist/framework/capability-registry.d.ts +58 -0
- package/dist/framework/capability-registry.js +325 -0
- package/dist/framework/contracts.d.ts +121 -0
- package/dist/framework/contracts.js +2 -0
- package/dist/framework/control/control-scheduler.d.ts +69 -0
- package/dist/framework/control/control-scheduler.js +1016 -0
- package/dist/framework/control/domain-set.d.ts +18 -0
- package/dist/framework/control/domain-set.js +70 -0
- package/dist/framework/control/index.d.ts +3 -0
- package/dist/framework/control/index.js +3 -0
- package/dist/framework/control/types.d.ts +142 -0
- package/dist/framework/control/types.js +13 -0
- package/dist/framework/control-coordinator.d.ts +7 -0
- package/dist/framework/control-coordinator.js +7 -0
- package/dist/framework/events/event-catalog.d.ts +23 -0
- package/dist/framework/events/event-catalog.js +52 -0
- package/dist/framework/events/event-delivery-service.d.ts +33 -0
- package/dist/framework/events/event-delivery-service.js +165 -0
- package/dist/framework/events/event-ingress.d.ts +28 -0
- package/dist/framework/events/event-ingress.js +76 -0
- package/dist/framework/events/event-repository.d.ts +38 -0
- package/dist/framework/events/event-repository.js +20 -0
- package/dist/framework/events/index.d.ts +7 -0
- package/dist/framework/events/index.js +7 -0
- package/dist/framework/events/memory-event-repository.d.ts +77 -0
- package/dist/framework/events/memory-event-repository.js +909 -0
- package/dist/framework/events/runtime-resume.d.ts +11 -0
- package/dist/framework/events/runtime-resume.js +7 -0
- package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
- package/dist/framework/events/sqlite-event-repository.js +2044 -0
- package/dist/framework/events/store-compatibility.d.ts +17 -0
- package/dist/framework/events/store-compatibility.js +17 -0
- package/dist/framework/events/types.d.ts +244 -0
- package/dist/framework/events/types.js +39 -0
- package/dist/framework/index.d.ts +7 -0
- package/dist/framework/index.js +7 -0
- package/dist/framework/load-node-sqlite.d.ts +5 -0
- package/dist/framework/load-node-sqlite.js +19 -0
- package/dist/framework/mailbox/coalescer.d.ts +30 -0
- package/dist/framework/mailbox/coalescer.js +45 -0
- package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
- package/dist/framework/mailbox/host-notification-sink.js +13 -0
- package/dist/framework/mailbox/identity.d.ts +15 -0
- package/dist/framework/mailbox/identity.js +28 -0
- package/dist/framework/mailbox/index.d.ts +7 -0
- package/dist/framework/mailbox/index.js +7 -0
- package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
- package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
- package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
- package/dist/framework/mailbox/mailbox-repository.js +9 -0
- package/dist/framework/mailbox/notification-projector.d.ts +25 -0
- package/dist/framework/mailbox/notification-projector.js +50 -0
- package/dist/framework/mailbox/types.d.ts +128 -0
- package/dist/framework/mailbox/types.js +1 -0
- package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
- package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
- package/dist/framework/modules/runtime-module-loader.js +64 -0
- package/dist/framework/modules/runtime-module-output.d.ts +7 -0
- package/dist/framework/modules/runtime-module-output.js +15 -0
- package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
- package/dist/framework/participation-manager.d.ts +94 -0
- package/dist/framework/participation-manager.js +185 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
- package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
- package/dist/framework/persistence/memory-first-persistence.js +459 -0
- package/dist/framework/plugins/contracts.d.ts +345 -0
- package/dist/framework/plugins/contracts.js +1 -0
- package/dist/framework/plugins/index.d.ts +4 -0
- package/dist/framework/plugins/index.js +4 -0
- package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
- package/dist/framework/plugins/runtime-event-identity.js +11 -0
- package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
- package/dist/framework/plugins/runtime-input-journal.js +716 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
- package/dist/framework/runtime.d.ts +264 -0
- package/dist/framework/runtime.js +1811 -0
- package/dist/framework/serial-task-queue.d.ts +6 -0
- package/dist/framework/serial-task-queue.js +12 -0
- package/dist/framework/state/contracts.d.ts +30 -0
- package/dist/framework/state/contracts.js +1 -0
- package/dist/framework/state/current-state-store.d.ts +17 -0
- package/dist/framework/state/current-state-store.js +153 -0
- package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
- package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
- package/dist/framework/state/freshness.d.ts +7 -0
- package/dist/framework/state/freshness.js +52 -0
- package/dist/framework/state/history/contracts.d.ts +133 -0
- package/dist/framework/state/history/contracts.js +1 -0
- package/dist/framework/state/history/history-writer.d.ts +55 -0
- package/dist/framework/state/history/history-writer.js +157 -0
- package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
- package/dist/framework/state/history/memory-state-history-repository.js +199 -0
- package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
- package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
- package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
- package/dist/framework/state/history/trajectory-projector.js +130 -0
- package/dist/framework/state/index.d.ts +12 -0
- package/dist/framework/state/index.js +12 -0
- package/dist/framework/state/state-ingress.d.ts +18 -0
- package/dist/framework/state/state-ingress.js +68 -0
- package/dist/framework/state/state-provider.d.ts +11 -0
- package/dist/framework/state/state-provider.js +56 -0
- package/dist/framework/state/types.d.ts +107 -0
- package/dist/framework/state/types.js +19 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
- package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
- package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
- package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
- package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
- package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
- package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
- package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
- package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
- package/dist/mailbox/host-monitor-rate-gate.js +93 -0
- package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
- package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
- package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
- package/dist/mailbox/mailbox-host-relay.js +299 -0
- package/dist/mailbox/mailbox-plugin.d.ts +58 -0
- package/dist/mailbox/mailbox-plugin.js +128 -0
- package/dist/mailbox/mailbox-service.d.ts +128 -0
- package/dist/mailbox/mailbox-service.js +582 -0
- package/dist/memory/contracts.d.ts +12 -0
- package/dist/memory/contracts.js +1 -0
- package/dist/memory/strategy-memory-rpc.d.ts +21 -0
- package/dist/memory/strategy-memory-rpc.js +86 -0
- package/dist/memory/strategy-memory.d.ts +15 -0
- package/dist/memory/strategy-memory.js +95 -0
- package/dist/observability/detail-capture.d.ts +25 -0
- package/dist/observability/detail-capture.js +136 -0
- package/dist/observability/index.d.ts +5 -0
- package/dist/observability/index.js +5 -0
- package/dist/observability/process-timing.d.ts +14 -0
- package/dist/observability/process-timing.js +56 -0
- package/dist/observability/recorder.d.ts +56 -0
- package/dist/observability/recorder.js +202 -0
- package/dist/observability/redaction.d.ts +30 -0
- package/dist/observability/redaction.js +166 -0
- package/dist/observability/reporter.d.ts +32 -0
- package/dist/observability/reporter.js +140 -0
- package/dist/observability/sinks.d.ts +36 -0
- package/dist/observability/sinks.js +121 -0
- package/dist/observability/types.d.ts +81 -0
- package/dist/observability/types.js +1 -0
- package/dist/owner/control-channel.d.ts +42 -0
- package/dist/owner/control-channel.js +188 -0
- package/dist/owner/parent-process-watch.d.ts +15 -0
- package/dist/owner/parent-process-watch.js +40 -0
- package/dist/owner/process-identity.d.ts +10 -0
- package/dist/owner/process-identity.js +65 -0
- package/dist/owner/runtime-lock.d.ts +5 -0
- package/dist/owner/runtime-lock.js +47 -0
- package/dist/perception/binding-resolution.d.ts +9 -0
- package/dist/perception/binding-resolution.js +14 -0
- package/dist/perception/contracts.d.ts +85 -0
- package/dist/perception/contracts.js +1 -0
- package/dist/perception/map-concurrent.d.ts +2 -0
- package/dist/perception/map-concurrent.js +12 -0
- package/dist/perception/perception-host.d.ts +114 -0
- package/dist/perception/perception-host.js +338 -0
- package/dist/perception/perception-worker-host.d.ts +11 -0
- package/dist/perception/perception-worker-host.js +44 -0
- package/dist/perception/perception-worker.d.ts +21 -0
- package/dist/perception/perception-worker.js +77 -0
- package/dist/perception/strategy-names.d.ts +7 -0
- package/dist/perception/strategy-names.js +22 -0
- package/dist/sdk/perception.d.ts +5 -0
- package/dist/sdk/perception.js +6 -0
- package/dist/sdk/strategy.d.ts +6 -0
- package/dist/sdk/strategy.js +3 -0
- package/dist/strategy/activation-manager.d.ts +105 -0
- package/dist/strategy/activation-manager.js +367 -0
- package/dist/strategy/behavior-decision-history.d.ts +20 -0
- package/dist/strategy/behavior-decision-history.js +59 -0
- package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
- package/dist/strategy/behavior-instance-snapshot.js +145 -0
- package/dist/strategy/contracts.d.ts +189 -0
- package/dist/strategy/contracts.js +1 -0
- package/dist/strategy/control-driver.d.ts +25 -0
- package/dist/strategy/control-driver.js +131 -0
- package/dist/strategy/in-process-runner.d.ts +25 -0
- package/dist/strategy/in-process-runner.js +40 -0
- package/dist/strategy/strategy-host.d.ts +165 -0
- package/dist/strategy/strategy-host.js +1456 -0
- package/dist/strategy/strategy-script-runner.d.ts +81 -0
- package/dist/strategy/strategy-script-runner.js +235 -0
- package/dist/strategy/strategy-worker-host.d.ts +27 -0
- package/dist/strategy/strategy-worker-host.js +96 -0
- package/dist/strategy/thread-strategy-executor.d.ts +120 -0
- package/dist/strategy/thread-strategy-executor.js +778 -0
- package/examples/grid-game.mjs +129 -0
- package/examples/grid-perception-worker.mjs +6 -0
- package/examples/grid-perception.mjs +12 -0
- package/examples/grid-strategy-worker.mjs +11 -0
- package/examples/grid-strategy.mjs +13 -0
- package/examples/run-grid-game.mjs +24 -0
- package/package.json +53 -4
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { statSync } from 'fs';
|
|
3
|
+
import { getHeapStatistics } from 'v8';
|
|
4
|
+
import { canReuseParticipationSegment } from '../participation-manager.js';
|
|
5
|
+
import { createRequire } from 'module';
|
|
6
|
+
import { pathToFileURL } from 'url';
|
|
7
|
+
import { Worker } from 'worker_threads';
|
|
8
|
+
import { MemoryEventRepository } from '../events/memory-event-repository.js';
|
|
9
|
+
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
10
|
+
import { canResumeRuntimeScope } from '../events/runtime-resume.js';
|
|
11
|
+
import { MemoryRuntimeInputJournal, SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
|
|
12
|
+
import { MemoryStateHistoryRepository } from '../state/history/memory-state-history-repository.js';
|
|
13
|
+
import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
|
|
14
|
+
const localRequire = createRequire(import.meta.url);
|
|
15
|
+
function memorySample() {
|
|
16
|
+
const memory = process.memoryUsage();
|
|
17
|
+
return {
|
|
18
|
+
sampled_at_ms: Date.now(), rss_bytes: memory.rss,
|
|
19
|
+
heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
|
|
20
|
+
external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
|
|
21
|
+
heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function databaseBytes(path) {
|
|
25
|
+
try {
|
|
26
|
+
return statSync(path).size;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
class AsyncSqliteMirror {
|
|
33
|
+
options;
|
|
34
|
+
worker;
|
|
35
|
+
local = [];
|
|
36
|
+
waiters = new Map();
|
|
37
|
+
timer;
|
|
38
|
+
nextMessageId = 1;
|
|
39
|
+
sentOperations = 0;
|
|
40
|
+
acknowledgedOperations = 0;
|
|
41
|
+
batchSizes = new Map();
|
|
42
|
+
droppedOperations = 0;
|
|
43
|
+
degradedError;
|
|
44
|
+
closing;
|
|
45
|
+
references = 3;
|
|
46
|
+
workerMemory;
|
|
47
|
+
constructor(options) {
|
|
48
|
+
this.options = options;
|
|
49
|
+
const workerUrl = new URL(import.meta.url.endsWith('.ts')
|
|
50
|
+
? './async-sqlite-persistence-worker.ts' : './async-sqlite-persistence-worker.js', import.meta.url).href;
|
|
51
|
+
// Resolve from this package, not from the process cwd. Installed CCL is
|
|
52
|
+
// commonly launched from an Agent workspace that does not contain tsx.
|
|
53
|
+
const tsxApiUrl = pathToFileURL(localRequire.resolve('tsx/esm/api')).href;
|
|
54
|
+
const bootstrap = `void (async () => {
|
|
55
|
+
const { register } = await import(${JSON.stringify(tsxApiUrl)});
|
|
56
|
+
register();
|
|
57
|
+
await import(${JSON.stringify(workerUrl)});
|
|
58
|
+
})();`;
|
|
59
|
+
this.worker = new Worker(bootstrap, {
|
|
60
|
+
eval: true,
|
|
61
|
+
workerData: {
|
|
62
|
+
eventLedgerPath: options.eventLedgerPath,
|
|
63
|
+
eventStoreCompatibility: options.eventStoreCompatibility,
|
|
64
|
+
stateHistoryPath: options.stateHistoryPath,
|
|
65
|
+
inputJournalPath: options.inputJournalPath,
|
|
66
|
+
diagnostics: !!options.onDiagnostic,
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
this.worker.on('message', (message) => {
|
|
70
|
+
if (message.type === 'diagnostics') {
|
|
71
|
+
this.workerMemory = message.memory;
|
|
72
|
+
try {
|
|
73
|
+
this.options.onDiagnostic?.('runtime.persistence.worker_memory', { worker_memory: message.memory });
|
|
74
|
+
}
|
|
75
|
+
catch { /* observational */ }
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (message.type === 'ack') {
|
|
79
|
+
this.acknowledgedOperations += this.batchSizes.get(message.id) ?? 0;
|
|
80
|
+
this.batchSizes.delete(message.id);
|
|
81
|
+
}
|
|
82
|
+
const waiter = this.waiters.get(message.id);
|
|
83
|
+
if (message.type === 'error') {
|
|
84
|
+
const error = new Error(message.error ?? 'Async SQLite persistence failed.');
|
|
85
|
+
this.degrade(error);
|
|
86
|
+
waiter?.reject(error);
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
waiter?.resolve();
|
|
90
|
+
}
|
|
91
|
+
this.waiters.delete(message.id);
|
|
92
|
+
});
|
|
93
|
+
this.worker.on('error', (error) => this.degrade(error));
|
|
94
|
+
this.worker.on('exit', (code) => {
|
|
95
|
+
if (code !== 0 && !this.closing)
|
|
96
|
+
this.degrade(new Error(`Async SQLite worker exited with code ${code}.`));
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
enqueue(operation) {
|
|
100
|
+
if (this.degradedError || this.closing) {
|
|
101
|
+
this.droppedOperations += 1;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (this.pendingCount() >= this.options.maxPendingOperations) {
|
|
105
|
+
this.degrade(new Error(`Async SQLite queue exceeded ${this.options.maxPendingOperations} operations.`));
|
|
106
|
+
this.droppedOperations += 1;
|
|
107
|
+
this.local.length = 0;
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
this.local.push(structuredClone(operation));
|
|
111
|
+
if (this.local.length >= this.options.batchSize)
|
|
112
|
+
this.dispatch();
|
|
113
|
+
else
|
|
114
|
+
this.timer ??= setTimeout(() => this.dispatch(), this.options.flushIntervalMs);
|
|
115
|
+
}
|
|
116
|
+
health() {
|
|
117
|
+
return {
|
|
118
|
+
mode: 'memory-first-sqlite-mirror',
|
|
119
|
+
pendingOperations: this.pendingCount(),
|
|
120
|
+
droppedOperations: this.droppedOperations,
|
|
121
|
+
degraded: !!this.degradedError,
|
|
122
|
+
...(this.degradedError ? { error: this.degradedError.message } : {}),
|
|
123
|
+
...(this.workerMemory ? { workerMemory: this.workerMemory } : {}),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
async release() {
|
|
127
|
+
this.references -= 1;
|
|
128
|
+
if (this.references > 0)
|
|
129
|
+
return;
|
|
130
|
+
await this.close();
|
|
131
|
+
}
|
|
132
|
+
pendingCount() {
|
|
133
|
+
return this.local.length + Math.max(0, this.sentOperations - this.acknowledgedOperations);
|
|
134
|
+
}
|
|
135
|
+
dispatch() {
|
|
136
|
+
if (this.timer)
|
|
137
|
+
clearTimeout(this.timer);
|
|
138
|
+
this.timer = undefined;
|
|
139
|
+
if (this.local.length === 0 || this.degradedError)
|
|
140
|
+
return;
|
|
141
|
+
const operations = this.local.splice(0, this.options.batchSize);
|
|
142
|
+
const id = this.nextMessageId++;
|
|
143
|
+
this.sentOperations += operations.length;
|
|
144
|
+
this.batchSizes.set(id, operations.length);
|
|
145
|
+
this.worker.postMessage({ type: 'batch', id, operations });
|
|
146
|
+
if (this.local.length > 0)
|
|
147
|
+
this.timer = setTimeout(() => this.dispatch(), 0);
|
|
148
|
+
}
|
|
149
|
+
async flush() {
|
|
150
|
+
if (this.degradedError)
|
|
151
|
+
return;
|
|
152
|
+
while (this.local.length > 0)
|
|
153
|
+
this.dispatch();
|
|
154
|
+
const id = this.nextMessageId++;
|
|
155
|
+
await new Promise((resolve, reject) => {
|
|
156
|
+
this.waiters.set(id, { resolve, reject });
|
|
157
|
+
this.worker.postMessage({ type: 'barrier', id });
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
close() {
|
|
161
|
+
if (this.closing)
|
|
162
|
+
return this.closing;
|
|
163
|
+
this.closing = (async () => {
|
|
164
|
+
if (this.timer)
|
|
165
|
+
clearTimeout(this.timer);
|
|
166
|
+
this.timer = undefined;
|
|
167
|
+
try {
|
|
168
|
+
await this.flush();
|
|
169
|
+
if (!this.degradedError) {
|
|
170
|
+
const id = this.nextMessageId++;
|
|
171
|
+
await new Promise((resolve, reject) => {
|
|
172
|
+
this.waiters.set(id, { resolve, reject });
|
|
173
|
+
this.worker.postMessage({ type: 'close', id });
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
await this.worker.terminate();
|
|
179
|
+
}
|
|
180
|
+
})();
|
|
181
|
+
return this.closing;
|
|
182
|
+
}
|
|
183
|
+
degrade(error) {
|
|
184
|
+
if (this.degradedError)
|
|
185
|
+
return;
|
|
186
|
+
this.degradedError = error;
|
|
187
|
+
for (const waiter of this.waiters.values())
|
|
188
|
+
waiter.reject(error);
|
|
189
|
+
this.waiters.clear();
|
|
190
|
+
this.options.onDegraded?.(error, this.health());
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
class MirroredStore {
|
|
194
|
+
mirror;
|
|
195
|
+
persistenceKind = 'memory-first-sqlite';
|
|
196
|
+
constructor(mirror) {
|
|
197
|
+
this.mirror = mirror;
|
|
198
|
+
}
|
|
199
|
+
persistenceHealth() { return this.mirror.health(); }
|
|
200
|
+
close() { return this.mirror.release(); }
|
|
201
|
+
persist(store, method, ...args) {
|
|
202
|
+
this.mirror.enqueue({ store, method, args });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
class MemoryFirstEventRepository extends MirroredStore {
|
|
206
|
+
memory;
|
|
207
|
+
closeArchive;
|
|
208
|
+
constructor(mirror, memory, closeArchive) {
|
|
209
|
+
super(mirror);
|
|
210
|
+
this.memory = memory;
|
|
211
|
+
this.closeArchive = closeArchive;
|
|
212
|
+
}
|
|
213
|
+
async close() {
|
|
214
|
+
try {
|
|
215
|
+
await super.close();
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
this.closeArchive();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
222
|
+
saveSession(value) { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
|
|
223
|
+
saveSegment(value) { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
|
|
224
|
+
currentScope(account) { return this.memory.currentScope(account); }
|
|
225
|
+
latestScope(account, options) { return this.memory.latestScope(account, options); }
|
|
226
|
+
commitEvent(value) { const result = this.memory.commitEvent(value); this.persist('events', 'commitEvent', value); return result; }
|
|
227
|
+
resolveEventDelivery(value) {
|
|
228
|
+
this.memory.resolveEventDelivery(value);
|
|
229
|
+
this.persist('events', 'resolveEventDelivery', value);
|
|
230
|
+
}
|
|
231
|
+
eventById(eventId) { return this.memory.eventById(eventId); }
|
|
232
|
+
latestEventByType(sessionId, type, segmentId) { return this.memory.latestEventByType(sessionId, type, segmentId); }
|
|
233
|
+
highWaterCommitSeq(sessionId, segmentId) { return this.memory.highWaterCommitSeq(sessionId, segmentId); }
|
|
234
|
+
listCommittedEvents(filter) { return this.memory.listCommittedEvents(filter); }
|
|
235
|
+
ensureDeliveries(sessionId, consumerId, channels) {
|
|
236
|
+
this.memory.ensureDeliveries(sessionId, consumerId, channels);
|
|
237
|
+
this.persist('events', 'ensureDeliveries', sessionId, consumerId, channels);
|
|
238
|
+
}
|
|
239
|
+
delivery(eventId, consumerId) { return this.memory.delivery(eventId, consumerId); }
|
|
240
|
+
listEvents(filter, consumerId, channels) {
|
|
241
|
+
this.ensureDeliveries(filter.sessionId, consumerId, channels);
|
|
242
|
+
return this.memory.listEvents(filter, consumerId, channels);
|
|
243
|
+
}
|
|
244
|
+
backlogSummary(sessionId, consumerId) {
|
|
245
|
+
this.ensureDeliveries(sessionId, consumerId, ['details']);
|
|
246
|
+
return this.memory.backlogSummary(sessionId, consumerId);
|
|
247
|
+
}
|
|
248
|
+
transitionDetails(value) {
|
|
249
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
250
|
+
const result = this.memory.transitionDetails(stable);
|
|
251
|
+
this.persist('events', 'transitionDetails', stable);
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
transitionMonitor(value) {
|
|
255
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
256
|
+
const result = this.memory.transitionMonitor(stable);
|
|
257
|
+
this.persist('events', 'transitionMonitor', stable);
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
260
|
+
recordMonitorAttempt(value) {
|
|
261
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
262
|
+
const result = this.memory.recordMonitorAttempt(stable);
|
|
263
|
+
this.persist('events', 'recordMonitorAttempt', stable);
|
|
264
|
+
return result;
|
|
265
|
+
}
|
|
266
|
+
acquireLease(value) {
|
|
267
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
268
|
+
const result = this.memory.acquireLease(stable);
|
|
269
|
+
this.persist('events', 'acquireLease', stable);
|
|
270
|
+
return result;
|
|
271
|
+
}
|
|
272
|
+
leaseIsValid(lease, nowMs) { return this.memory.leaseIsValid(lease, nowMs); }
|
|
273
|
+
releaseLease(lease) { const result = this.memory.releaseLease(lease); this.persist('events', 'releaseLease', lease); return result; }
|
|
274
|
+
sourceCheckpoint(sourceId) { return this.memory.sourceCheckpoint(sourceId); }
|
|
275
|
+
enqueueMailboxItem(value) {
|
|
276
|
+
const nowMs = Date.now();
|
|
277
|
+
const stable = { ...value, createdAt: value.createdAt ?? new Date(nowMs).toISOString(), availableAtMs: value.availableAtMs ?? 0 };
|
|
278
|
+
const result = this.memory.enqueueMailboxItem(stable);
|
|
279
|
+
this.persist('events', 'enqueueMailboxItem', stable);
|
|
280
|
+
return result;
|
|
281
|
+
}
|
|
282
|
+
mailboxItem(itemId) { return this.memory.mailboxItem(itemId); }
|
|
283
|
+
mailboxItemForEvent(consumerId, eventId, mode) { return this.memory.mailboxItemForEvent(consumerId, eventId, mode); }
|
|
284
|
+
peekMailbox(filter) { return this.memory.peekMailbox(filter); }
|
|
285
|
+
claimMailbox(value) {
|
|
286
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now(), claimToken: value.claimToken ?? randomUUID() };
|
|
287
|
+
const result = this.memory.claimMailbox(stable);
|
|
288
|
+
this.persist('events', 'claimMailbox', stable);
|
|
289
|
+
return result;
|
|
290
|
+
}
|
|
291
|
+
ackMailboxClaim(value) {
|
|
292
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
293
|
+
const result = this.memory.ackMailboxClaim(stable);
|
|
294
|
+
this.persist('events', 'ackMailboxClaim', stable);
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
nackMailboxClaim(value) {
|
|
298
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
299
|
+
const result = this.memory.nackMailboxClaim(stable);
|
|
300
|
+
this.persist('events', 'nackMailboxClaim', stable);
|
|
301
|
+
return result;
|
|
302
|
+
}
|
|
303
|
+
suppressMailboxItems(value) {
|
|
304
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
305
|
+
const result = this.memory.suppressMailboxItems(stable);
|
|
306
|
+
this.persist('events', 'suppressMailboxItems', stable);
|
|
307
|
+
return result;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
class MemoryFirstStateHistory extends MirroredStore {
|
|
311
|
+
memory;
|
|
312
|
+
constructor(mirror, memory) {
|
|
313
|
+
super(mirror);
|
|
314
|
+
this.memory = memory;
|
|
315
|
+
}
|
|
316
|
+
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
317
|
+
openScope(scope, openedAtMs = Date.now(), historyComplete = true) {
|
|
318
|
+
const result = this.memory.openScope(scope, openedAtMs, historyComplete);
|
|
319
|
+
this.persist('history', 'openScope', scope, openedAtMs, historyComplete);
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
sealScope(scope, sealedAtMs = Date.now()) { this.memory.sealScope(scope, sealedAtMs); this.persist('history', 'sealScope', scope, sealedAtMs); }
|
|
323
|
+
markScopeIncomplete(scope) { this.memory.markScopeIncomplete(scope); this.persist('history', 'markScopeIncomplete', scope); }
|
|
324
|
+
getScope(scope) { return this.memory.getScope(scope); }
|
|
325
|
+
appendStateFrame(frame) { const result = this.memory.appendStateFrame(frame); this.persist('history', 'appendStateFrame', frame); return result; }
|
|
326
|
+
queryStateFrames(query) { return this.memory.queryStateFrames(query); }
|
|
327
|
+
latestStateFrame(scope) { return this.memory.latestStateFrame(scope); }
|
|
328
|
+
append(records) { const result = this.memory.append(records); this.persist('history', 'append', records); return result; }
|
|
329
|
+
query(query) { return this.memory.query(query); }
|
|
330
|
+
}
|
|
331
|
+
class MemoryFirstInputJournal extends MirroredStore {
|
|
332
|
+
memory;
|
|
333
|
+
constructor(mirror, memory) {
|
|
334
|
+
super(mirror);
|
|
335
|
+
this.memory = memory;
|
|
336
|
+
}
|
|
337
|
+
diagnosticCounts() { return this.memory.diagnosticCounts(); }
|
|
338
|
+
accept(batch) { const result = this.memory.accept(batch); if (result.inserted)
|
|
339
|
+
this.persist('input', 'accept', batch); return result; }
|
|
340
|
+
epoch(epochSeq) { return this.memory.epoch(epochSeq); }
|
|
341
|
+
list(scope, afterEpochSeq, limit) { return this.memory.list(scope, afterEpochSeq, limit); }
|
|
342
|
+
listOpen(scope, afterEpochSeq, limit) { return this.memory.listOpen(scope, afterEpochSeq, limit); }
|
|
343
|
+
inputEventsCommitted(epochSeq) { return this.memory.inputEventsCommitted(epochSeq); }
|
|
344
|
+
markInputEventsCommitted(epochSeq, watermark, committedAt = new Date().toISOString()) { this.memory.markInputEventsCommitted(epochSeq, watermark); this.persist('input', 'markInputEventsCommitted', epochSeq, watermark, committedAt); }
|
|
345
|
+
eventWatermarkThrough(scope, epochSeq) { return this.memory.eventWatermarkThrough(scope, epochSeq); }
|
|
346
|
+
markEventWatermark(epochSeq, watermark) { this.memory.markEventWatermark(epochSeq, watermark); this.persist('input', 'markEventWatermark', epochSeq, watermark); }
|
|
347
|
+
markClosed(epochSeq, closedAt = new Date().toISOString(), durationMs) { this.memory.markClosed(epochSeq); this.persist('input', 'markClosed', epochSeq, closedAt, durationMs); }
|
|
348
|
+
recordPlugin(record) { this.memory.recordPlugin(record); this.persist('input', 'recordPlugin', record); }
|
|
349
|
+
pluginRecords(epochSeq) { return this.memory.pluginRecords(epochSeq); }
|
|
350
|
+
pluginProgress(pluginId, scope) { return this.memory.pluginProgress(pluginId, scope); }
|
|
351
|
+
savePluginProgress(progress, scope) { this.memory.savePluginProgress(progress, scope); this.persist('input', 'savePluginProgress', progress, scope); }
|
|
352
|
+
saveStates(records) { this.memory.saveStates(records); this.persist('input', 'saveStates', records); }
|
|
353
|
+
states(epochSeq) { return this.memory.states(epochSeq); }
|
|
354
|
+
}
|
|
355
|
+
export function createMemoryFirstPersistence(options) {
|
|
356
|
+
const startedAt = performance.now();
|
|
357
|
+
const diagnostic = (stage, attributes = {}) => {
|
|
358
|
+
if (!options.onDiagnostic)
|
|
359
|
+
return;
|
|
360
|
+
try {
|
|
361
|
+
options.onDiagnostic('runtime.persistence.hydration', {
|
|
362
|
+
stage, elapsed_ms: performance.now() - startedAt,
|
|
363
|
+
process_memory: memorySample(), ...attributes,
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
catch { /* Diagnostics must not prevent startup. */ }
|
|
367
|
+
};
|
|
368
|
+
diagnostic('started', {
|
|
369
|
+
event_db_bytes: databaseBytes(options.eventLedgerPath),
|
|
370
|
+
event_wal_bytes: databaseBytes(`${options.eventLedgerPath}-wal`),
|
|
371
|
+
history_db_bytes: databaseBytes(options.stateHistoryPath),
|
|
372
|
+
history_wal_bytes: databaseBytes(`${options.stateHistoryPath}-wal`),
|
|
373
|
+
input_db_bytes: databaseBytes(options.inputJournalPath),
|
|
374
|
+
input_wal_bytes: databaseBytes(`${options.inputJournalPath}-wal`),
|
|
375
|
+
});
|
|
376
|
+
const eventSqlite = SqliteEventRepository.open(options.eventLedgerPath, options.eventStoreCompatibility);
|
|
377
|
+
if (!eventSqlite.ok) {
|
|
378
|
+
diagnostic('failed', { error_name: eventSqlite.unavailable.code });
|
|
379
|
+
throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
|
|
380
|
+
}
|
|
381
|
+
let historySqlite;
|
|
382
|
+
let inputSqlite;
|
|
383
|
+
let eventMemory;
|
|
384
|
+
let historyMemory;
|
|
385
|
+
let inputMemory;
|
|
386
|
+
let hydrated = false;
|
|
387
|
+
try {
|
|
388
|
+
historySqlite = new SqliteStateHistoryRepository(options.stateHistoryPath);
|
|
389
|
+
inputSqlite = new SqliteRuntimeInputJournal(options.inputJournalPath);
|
|
390
|
+
const current = eventSqlite.repository.currentScope(options.recovery?.account);
|
|
391
|
+
const restore = options.recovery
|
|
392
|
+
? canResumeRuntimeScope(current, options.recovery)
|
|
393
|
+
: current?.session.status === 'open';
|
|
394
|
+
const sessionId = restore && current ? current.session.sessionId : null;
|
|
395
|
+
const reuseSegment = !options.recovery || (current && current.segment.status === 'open'
|
|
396
|
+
&& canReuseParticipationSegment({ kind: current.segment.kind, identity: current.segment.scopeRef }, options.recovery.initialSegment.kind, options.recovery.initialSegment.identity));
|
|
397
|
+
const scope = restore && current && reuseSegment ? {
|
|
398
|
+
adapterId: current.session.adapterId, accountId: current.session.accountId,
|
|
399
|
+
sessionId: current.session.sessionId, segmentId: current.segment.segmentId,
|
|
400
|
+
segmentSeq: current.segment.sequence,
|
|
401
|
+
} : null;
|
|
402
|
+
diagnostic('selected', {
|
|
403
|
+
restore_session: !!sessionId, event_selection: sessionId ? 'current_session' : 'metadata_only',
|
|
404
|
+
state_selection: scope ? 'current_segment' : 'none',
|
|
405
|
+
});
|
|
406
|
+
// Event consumers can still own pending deliveries in earlier segments of
|
|
407
|
+
// the same session. State/plugin recovery, however, reads the active scope only.
|
|
408
|
+
const events = eventSqlite.repository.snapshot(sessionId);
|
|
409
|
+
if (!sessionId && current) {
|
|
410
|
+
// Runtime must still seal the previous durable scope on a fresh start.
|
|
411
|
+
events.sessions = [current.session];
|
|
412
|
+
events.segments = [current.segment];
|
|
413
|
+
}
|
|
414
|
+
const archiveThrough = events.nextCommitSeq - 1;
|
|
415
|
+
eventMemory = new MemoryEventRepository(events, (event) => eventSqlite.repository.archivedEventIdentities(event, sessionId, archiveThrough));
|
|
416
|
+
diagnostic('events_loaded', { loaded_records: eventMemory.diagnosticCounts() });
|
|
417
|
+
historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot(scope));
|
|
418
|
+
diagnostic('history_loaded', { loaded_records: historyMemory.diagnosticCounts() });
|
|
419
|
+
inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot(scope));
|
|
420
|
+
diagnostic('input_loaded', { loaded_records: inputMemory.diagnosticCounts() });
|
|
421
|
+
hydrated = true;
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
|
|
425
|
+
throw error;
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
if (!hydrated)
|
|
429
|
+
eventSqlite.repository.close();
|
|
430
|
+
historySqlite?.close();
|
|
431
|
+
inputSqlite?.close();
|
|
432
|
+
}
|
|
433
|
+
const required = {
|
|
434
|
+
...options,
|
|
435
|
+
maxPendingOperations: options.maxPendingOperations ?? 20_000,
|
|
436
|
+
batchSize: options.batchSize ?? 128,
|
|
437
|
+
flushIntervalMs: options.flushIntervalMs ?? 8,
|
|
438
|
+
};
|
|
439
|
+
let mirror;
|
|
440
|
+
try {
|
|
441
|
+
mirror = new AsyncSqliteMirror(required);
|
|
442
|
+
}
|
|
443
|
+
catch (error) {
|
|
444
|
+
eventSqlite.repository.close();
|
|
445
|
+
diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
|
|
446
|
+
throw error;
|
|
447
|
+
}
|
|
448
|
+
diagnostic('completed', {
|
|
449
|
+
loaded_records: {
|
|
450
|
+
events: eventMemory.diagnosticCounts(), history: historyMemory.diagnosticCounts(), input: inputMemory.diagnosticCounts(),
|
|
451
|
+
},
|
|
452
|
+
});
|
|
453
|
+
return {
|
|
454
|
+
eventRepository: new MemoryFirstEventRepository(mirror, eventMemory, () => eventSqlite.repository.close()),
|
|
455
|
+
stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
|
|
456
|
+
inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
|
|
457
|
+
health: () => mirror.health(),
|
|
458
|
+
};
|
|
459
|
+
}
|