@myclaw163/clawclaw-cli 0.8.13 → 0.8.14
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/package.json +1 -1
- package/skills/clawclaw/SKILL.md +3 -3
- package/skills/clawclaw/references/CHANNELS.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -2
- package/skills/clawclaw/references/STREAM.md +4 -2
- package/src/lib/game-client.ts +12 -4
- package/src/pipeline/event-format.ts +5 -0
- package/src/pipeline/event-hints.ts +10 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
- package/src/runtime/clawclaw/behavior-input.ts +5 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +173 -11
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +6 -0
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +3 -1
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +5 -5
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +213 -6
- package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
- package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
- package/src/runtime/clawclaw/runtime.ts +31 -3
- package/src/runtime/clawclaw-event-catalog.ts +2 -0
- package/src/runtime/framework/events/event-repository.ts +1 -1
- package/src/runtime/framework/events/memory-event-repository.ts +59 -1
- package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
- package/src/runtime/framework/mailbox/types.ts +2 -0
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +380 -0
- package/src/runtime/framework/plugins/contracts.ts +2 -2
- package/src/runtime/framework/plugins/runtime-input-journal.ts +173 -17
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +23 -11
- package/src/runtime/framework/runtime.ts +57 -4
- package/src/runtime/framework/state/history/contracts.ts +9 -1
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +49 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
- package/src/sdk/behavior-plugin/index.ts +5 -24
- package/src/sdk/module-input/index.ts +47 -0
|
@@ -57,7 +57,7 @@ export interface EventRepository {
|
|
|
57
57
|
releaseLease(lease: ConsumerLease): boolean;
|
|
58
58
|
|
|
59
59
|
sourceCheckpoint(sourceId: string): SourceCheckpointRecord | null;
|
|
60
|
-
close?(): void
|
|
60
|
+
close?(): void | Promise<void>;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
export class DeliveryLeaseLostError extends Error {
|
|
@@ -44,6 +44,17 @@ import {
|
|
|
44
44
|
validateDetailDeliveryVia,
|
|
45
45
|
} from './types.js';
|
|
46
46
|
|
|
47
|
+
export interface EventRepositorySnapshot {
|
|
48
|
+
sessions: PlaySessionRecord[];
|
|
49
|
+
segments: EventSegmentRecord[];
|
|
50
|
+
events: CanonicalEvent[];
|
|
51
|
+
deliveries: EventDeliveryRecord[];
|
|
52
|
+
checkpoints: SourceCheckpointRecord[];
|
|
53
|
+
leases: ConsumerLease[];
|
|
54
|
+
mailboxItems: MailboxItem[];
|
|
55
|
+
nextCommitSeq: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
47
58
|
function deliveryKey(eventId: string, consumerId: string): string {
|
|
48
59
|
return `${eventId}\u0000${consumerId}`;
|
|
49
60
|
}
|
|
@@ -84,6 +95,53 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
84
95
|
private readonly mailboxUniqueItems = new Map<string, string>();
|
|
85
96
|
private nextCommitSeq = 1;
|
|
86
97
|
|
|
98
|
+
constructor(snapshot?: EventRepositorySnapshot) {
|
|
99
|
+
if (snapshot) this.restore(snapshot);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
snapshot(): EventRepositorySnapshot {
|
|
103
|
+
return cloneRecord({
|
|
104
|
+
sessions: [...this.sessions.values()],
|
|
105
|
+
segments: [...this.segments.values()],
|
|
106
|
+
events: this.eventOrder.map((eventId) => this.events.get(eventId)!),
|
|
107
|
+
deliveries: [...this.deliveries.values()],
|
|
108
|
+
checkpoints: [...this.checkpoints.values()],
|
|
109
|
+
leases: [...this.leases.values()],
|
|
110
|
+
mailboxItems: [...this.mailboxItems.values()],
|
|
111
|
+
nextCommitSeq: this.nextCommitSeq,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private restore(snapshot: EventRepositorySnapshot): void {
|
|
116
|
+
for (const session of snapshot.sessions) this.sessions.set(session.sessionId, cloneRecord(session));
|
|
117
|
+
for (const segment of snapshot.segments) this.segments.set(segment.segmentId, cloneRecord(segment));
|
|
118
|
+
for (const event of snapshot.events) {
|
|
119
|
+
this.events.set(event.eventId, cloneRecord(event));
|
|
120
|
+
this.eventOrder.push(event.eventId);
|
|
121
|
+
if (event.sourceEventId) this.remoteEventIds.set(sourceEventKey(event.sourceId, event.sourceEventId), event.eventId);
|
|
122
|
+
if (event.sourceSequence) {
|
|
123
|
+
this.remoteSequences.set(
|
|
124
|
+
sourceSequenceKey(event.sourceId, event.sessionId, event.segmentId, event.sourceSequence),
|
|
125
|
+
event.eventId,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const delivery of snapshot.deliveries) {
|
|
130
|
+
this.deliveries.set(deliveryKey(delivery.eventId, delivery.consumerId), cloneRecord(delivery));
|
|
131
|
+
}
|
|
132
|
+
for (const checkpoint of snapshot.checkpoints) {
|
|
133
|
+
this.checkpoints.set(checkpoint.sourceId, cloneRecord(checkpoint));
|
|
134
|
+
}
|
|
135
|
+
for (const lease of snapshot.leases) {
|
|
136
|
+
this.leases.set(leaseKey(lease.consumerId, lease.channel), cloneRecord(lease));
|
|
137
|
+
}
|
|
138
|
+
for (const item of snapshot.mailboxItems) {
|
|
139
|
+
this.mailboxItems.set(item.itemId, cloneRecord(item));
|
|
140
|
+
this.mailboxUniqueItems.set(mailboxUniqueKey(item.consumerId, item.eventId, item.mode), item.itemId);
|
|
141
|
+
}
|
|
142
|
+
this.nextCommitSeq = Math.max(snapshot.nextCommitSeq, 1);
|
|
143
|
+
}
|
|
144
|
+
|
|
87
145
|
saveSession(session: PlaySessionRecord): void {
|
|
88
146
|
const existingSession = this.sessions.get(session.sessionId);
|
|
89
147
|
if (existingSession?.isCurrent && !session.isCurrent) {
|
|
@@ -657,7 +715,7 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
657
715
|
selected.push(item);
|
|
658
716
|
}
|
|
659
717
|
|
|
660
|
-
const claimToken = randomUUID();
|
|
718
|
+
const claimToken = request.claimToken ?? randomUUID();
|
|
661
719
|
const claimExpiresAtMs = nowMs + Math.max(1, request.leaseTtlMs);
|
|
662
720
|
const attemptedAt = new Date(nowMs).toISOString();
|
|
663
721
|
const claimed = selected.map((item) => {
|
|
@@ -4,6 +4,7 @@ import { mkdirSync } from 'fs';
|
|
|
4
4
|
import { dirname } from 'path';
|
|
5
5
|
import { loadNodeSqliteModule } from '../load-node-sqlite.js';
|
|
6
6
|
import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
|
|
7
|
+
import type { EventRepositorySnapshot } from './memory-event-repository.js';
|
|
7
8
|
import type {
|
|
8
9
|
AckMailboxClaimRequest,
|
|
9
10
|
AckMailboxClaimResult,
|
|
@@ -294,6 +295,27 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
294
295
|
this.db.close();
|
|
295
296
|
}
|
|
296
297
|
|
|
298
|
+
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
299
|
+
snapshot(): EventRepositorySnapshot {
|
|
300
|
+
const events = this.db.prepare('SELECT * FROM events ORDER BY commit_seq ASC')
|
|
301
|
+
.all().map(eventFromRow);
|
|
302
|
+
return {
|
|
303
|
+
sessions: this.db.prepare('SELECT * FROM play_sessions').all().map(sessionFromRow),
|
|
304
|
+
segments: this.db.prepare('SELECT * FROM event_segments').all().map(segmentFromRow),
|
|
305
|
+
events,
|
|
306
|
+
deliveries: this.db.prepare('SELECT * FROM event_deliveries').all().map(deliveryFromRow),
|
|
307
|
+
checkpoints: this.db.prepare('SELECT * FROM source_checkpoints').all().map(checkpointFromRow),
|
|
308
|
+
leases: this.db.prepare('SELECT * FROM consumer_leases').all().map((row) => ({
|
|
309
|
+
consumerId: String(row.consumer_id),
|
|
310
|
+
channel: row.channel as ConsumerLease['channel'],
|
|
311
|
+
ownerId: String(row.owner_id),
|
|
312
|
+
expiresAt: numberValue(row.expires_at),
|
|
313
|
+
})),
|
|
314
|
+
mailboxItems: this.db.prepare('SELECT * FROM mailbox_items').all().map(mailboxItemFromRow),
|
|
315
|
+
nextCommitSeq: (events.at(-1)?.commitSeq ?? 0) + 1,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
297
319
|
schemaVersion(): number {
|
|
298
320
|
const row = this.db.prepare('SELECT MAX(version) AS version FROM schema_migrations').get();
|
|
299
321
|
return numberValue(row?.version);
|
|
@@ -1024,7 +1046,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1024
1046
|
}
|
|
1025
1047
|
const itemIds = selected.map((row) => String(row.item_id));
|
|
1026
1048
|
const eventIds = selected.map((row) => String(row.event_id));
|
|
1027
|
-
const claimToken = randomUUID();
|
|
1049
|
+
const claimToken = request.claimToken ?? randomUUID();
|
|
1028
1050
|
const claimExpiresAtMs = nowMs + Math.max(1, request.leaseTtlMs);
|
|
1029
1051
|
const attemptedAt = new Date(nowMs).toISOString();
|
|
1030
1052
|
this.db.prepare(`
|
|
@@ -88,6 +88,8 @@ export interface ClaimMailboxItemsRequest {
|
|
|
88
88
|
* coalesceKey matches, so batching never lets a later topic overtake one.
|
|
89
89
|
*/
|
|
90
90
|
maxItems?: number;
|
|
91
|
+
/** Internal deterministic token used by mirrored persistence stores. */
|
|
92
|
+
claimToken?: string;
|
|
91
93
|
}
|
|
92
94
|
|
|
93
95
|
export interface MailboxClaim<T = unknown> {
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { parentPort, workerData } from 'worker_threads';
|
|
2
|
+
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
3
|
+
import { SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
|
|
4
|
+
import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
|
|
5
|
+
|
|
6
|
+
interface WorkerPaths {
|
|
7
|
+
eventLedgerPath: string;
|
|
8
|
+
stateHistoryPath: string;
|
|
9
|
+
inputJournalPath: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface PersistenceOperation {
|
|
13
|
+
store: 'events' | 'history' | 'input';
|
|
14
|
+
method: string;
|
|
15
|
+
args: unknown[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const paths = workerData as WorkerPaths;
|
|
19
|
+
const opened = SqliteEventRepository.open(paths.eventLedgerPath);
|
|
20
|
+
if (!opened.ok) throw new Error(`${opened.unavailable.code}: ${opened.unavailable.message}`);
|
|
21
|
+
const stores = {
|
|
22
|
+
events: opened.repository,
|
|
23
|
+
history: new SqliteStateHistoryRepository(paths.stateHistoryPath),
|
|
24
|
+
input: new SqliteRuntimeInputJournal(paths.inputJournalPath),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
parentPort?.on('message', (message: {
|
|
28
|
+
type: 'batch' | 'barrier' | 'close';
|
|
29
|
+
id: number;
|
|
30
|
+
operations?: PersistenceOperation[];
|
|
31
|
+
}) => {
|
|
32
|
+
try {
|
|
33
|
+
if (message.type === 'batch') {
|
|
34
|
+
for (const operation of message.operations ?? []) {
|
|
35
|
+
const store = stores[operation.store] as unknown as Record<string, (...args: unknown[]) => unknown>;
|
|
36
|
+
const method = store[operation.method];
|
|
37
|
+
if (typeof method !== 'function') throw new Error(`Unknown persistence operation: ${operation.store}.${operation.method}`);
|
|
38
|
+
method.apply(store, operation.args);
|
|
39
|
+
}
|
|
40
|
+
parentPort?.postMessage({ type: 'ack', id: message.id });
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (message.type === 'barrier') {
|
|
44
|
+
parentPort?.postMessage({ type: 'barrier', id: message.id });
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
stores.history.close();
|
|
48
|
+
stores.input.close();
|
|
49
|
+
stores.events.close();
|
|
50
|
+
parentPort?.postMessage({ type: 'closed', id: message.id });
|
|
51
|
+
} catch (error) {
|
|
52
|
+
parentPort?.postMessage({
|
|
53
|
+
type: 'error',
|
|
54
|
+
id: message.id,
|
|
55
|
+
error: error instanceof Error ? error.message : String(error),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
});
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import { createRequire } from 'module';
|
|
3
|
+
import { pathToFileURL } from 'url';
|
|
4
|
+
import { Worker } from 'worker_threads';
|
|
5
|
+
import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
|
|
6
|
+
import type {
|
|
7
|
+
AckMailboxClaimRequest,
|
|
8
|
+
ClaimMailboxItemsRequest,
|
|
9
|
+
EnqueueMailboxItem,
|
|
10
|
+
MailboxPeekFilter,
|
|
11
|
+
NackMailboxClaimRequest,
|
|
12
|
+
SuppressMailboxItemsFilter,
|
|
13
|
+
} from '../mailbox/types.js';
|
|
14
|
+
import { MemoryEventRepository } from '../events/memory-event-repository.js';
|
|
15
|
+
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
16
|
+
import type { EventRepository } from '../events/event-repository.js';
|
|
17
|
+
import type {
|
|
18
|
+
AcquireLeaseRequest,
|
|
19
|
+
CommittedEventListFilter,
|
|
20
|
+
CommitEventRequest,
|
|
21
|
+
ConsumerLease,
|
|
22
|
+
DetailStateTransition,
|
|
23
|
+
EventAccountScope,
|
|
24
|
+
EventListFilter,
|
|
25
|
+
EventSegmentRecord,
|
|
26
|
+
LatestEventScopeOptions,
|
|
27
|
+
MonitorDeliveryAttempt,
|
|
28
|
+
MonitorStateTransition,
|
|
29
|
+
PlaySessionRecord,
|
|
30
|
+
} from '../events/types.js';
|
|
31
|
+
import type {
|
|
32
|
+
RuntimeEpochPluginProgress,
|
|
33
|
+
RuntimeEpochPluginRecord,
|
|
34
|
+
RuntimeEpochStateRecord,
|
|
35
|
+
RuntimeInputBatch,
|
|
36
|
+
RuntimePersistenceStore,
|
|
37
|
+
} from '../plugins/contracts.js';
|
|
38
|
+
import { MemoryRuntimeInputJournal, SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
|
|
39
|
+
import type { RuntimeScope } from '../state/types.js';
|
|
40
|
+
import type {
|
|
41
|
+
HistoryQuery,
|
|
42
|
+
StateFrameQuery,
|
|
43
|
+
StateFrameRecord,
|
|
44
|
+
StateHistoryRepository,
|
|
45
|
+
TrajectoryRecord,
|
|
46
|
+
} from '../state/history/contracts.js';
|
|
47
|
+
import { MemoryStateHistoryRepository } from '../state/history/memory-state-history-repository.js';
|
|
48
|
+
import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
|
|
49
|
+
|
|
50
|
+
type StoreName = 'events' | 'history' | 'input';
|
|
51
|
+
interface PersistenceOperation { store: StoreName; method: string; args: unknown[] }
|
|
52
|
+
const localRequire = createRequire(import.meta.url);
|
|
53
|
+
|
|
54
|
+
export interface MemoryFirstPersistenceOptions {
|
|
55
|
+
eventLedgerPath: string;
|
|
56
|
+
stateHistoryPath: string;
|
|
57
|
+
inputJournalPath: string;
|
|
58
|
+
maxPendingOperations?: number;
|
|
59
|
+
batchSize?: number;
|
|
60
|
+
flushIntervalMs?: number;
|
|
61
|
+
onDegraded?: (error: Error, health: AsyncPersistenceHealth) => void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface ResolvedMemoryFirstPersistenceOptions {
|
|
65
|
+
eventLedgerPath: string;
|
|
66
|
+
stateHistoryPath: string;
|
|
67
|
+
inputJournalPath: string;
|
|
68
|
+
maxPendingOperations: number;
|
|
69
|
+
batchSize: number;
|
|
70
|
+
flushIntervalMs: number;
|
|
71
|
+
onDegraded?: MemoryFirstPersistenceOptions['onDegraded'];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface AsyncPersistenceHealth {
|
|
75
|
+
mode: 'memory-first-sqlite-mirror';
|
|
76
|
+
pendingOperations: number;
|
|
77
|
+
droppedOperations: number;
|
|
78
|
+
degraded: boolean;
|
|
79
|
+
error?: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
class AsyncSqliteMirror {
|
|
83
|
+
private readonly worker: Worker;
|
|
84
|
+
private readonly local: PersistenceOperation[] = [];
|
|
85
|
+
private readonly waiters = new Map<number, { resolve(): void; reject(error: Error): void }>();
|
|
86
|
+
private timer?: NodeJS.Timeout;
|
|
87
|
+
private nextMessageId = 1;
|
|
88
|
+
private sentOperations = 0;
|
|
89
|
+
private acknowledgedOperations = 0;
|
|
90
|
+
private readonly batchSizes = new Map<number, number>();
|
|
91
|
+
private droppedOperations = 0;
|
|
92
|
+
private degradedError?: Error;
|
|
93
|
+
private closing?: Promise<void>;
|
|
94
|
+
private references = 3;
|
|
95
|
+
|
|
96
|
+
constructor(private readonly options: ResolvedMemoryFirstPersistenceOptions) {
|
|
97
|
+
const workerUrl = new URL('./async-sqlite-persistence-worker.ts', import.meta.url).href;
|
|
98
|
+
// Resolve from this package, not from the process cwd. Installed CCL is
|
|
99
|
+
// commonly launched from an Agent workspace that does not contain tsx.
|
|
100
|
+
const tsxApiUrl = pathToFileURL(localRequire.resolve('tsx/esm/api')).href;
|
|
101
|
+
const bootstrap = `void (async () => {
|
|
102
|
+
const { register } = await import(${JSON.stringify(tsxApiUrl)});
|
|
103
|
+
register();
|
|
104
|
+
await import(${JSON.stringify(workerUrl)});
|
|
105
|
+
})();`;
|
|
106
|
+
this.worker = new Worker(bootstrap, {
|
|
107
|
+
eval: true,
|
|
108
|
+
workerData: {
|
|
109
|
+
eventLedgerPath: options.eventLedgerPath,
|
|
110
|
+
stateHistoryPath: options.stateHistoryPath,
|
|
111
|
+
inputJournalPath: options.inputJournalPath,
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
this.worker.on('message', (message: { type: string; id: number; error?: string }) => {
|
|
115
|
+
if (message.type === 'ack') {
|
|
116
|
+
this.acknowledgedOperations += this.batchSizes.get(message.id) ?? 0;
|
|
117
|
+
this.batchSizes.delete(message.id);
|
|
118
|
+
}
|
|
119
|
+
const waiter = this.waiters.get(message.id);
|
|
120
|
+
if (message.type === 'error') {
|
|
121
|
+
const error = new Error(message.error ?? 'Async SQLite persistence failed.');
|
|
122
|
+
this.degrade(error);
|
|
123
|
+
waiter?.reject(error);
|
|
124
|
+
} else {
|
|
125
|
+
waiter?.resolve();
|
|
126
|
+
}
|
|
127
|
+
this.waiters.delete(message.id);
|
|
128
|
+
});
|
|
129
|
+
this.worker.on('error', (error) => this.degrade(error));
|
|
130
|
+
this.worker.on('exit', (code) => {
|
|
131
|
+
if (code !== 0 && !this.closing) this.degrade(new Error(`Async SQLite worker exited with code ${code}.`));
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
enqueue(operation: PersistenceOperation): void {
|
|
136
|
+
if (this.degradedError || this.closing) {
|
|
137
|
+
this.droppedOperations += 1;
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (this.pendingCount() >= this.options.maxPendingOperations) {
|
|
141
|
+
this.degrade(new Error(`Async SQLite queue exceeded ${this.options.maxPendingOperations} operations.`));
|
|
142
|
+
this.droppedOperations += 1;
|
|
143
|
+
this.local.length = 0;
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
this.local.push(structuredClone(operation));
|
|
147
|
+
if (this.local.length >= this.options.batchSize) this.dispatch();
|
|
148
|
+
else this.timer ??= setTimeout(() => this.dispatch(), this.options.flushIntervalMs);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
health(): AsyncPersistenceHealth {
|
|
152
|
+
return {
|
|
153
|
+
mode: 'memory-first-sqlite-mirror',
|
|
154
|
+
pendingOperations: this.pendingCount(),
|
|
155
|
+
droppedOperations: this.droppedOperations,
|
|
156
|
+
degraded: !!this.degradedError,
|
|
157
|
+
...(this.degradedError ? { error: this.degradedError.message } : {}),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async release(): Promise<void> {
|
|
162
|
+
this.references -= 1;
|
|
163
|
+
if (this.references > 0) return;
|
|
164
|
+
await this.close();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private pendingCount(): number {
|
|
168
|
+
return this.local.length + Math.max(0, this.sentOperations - this.acknowledgedOperations);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private dispatch(): void {
|
|
172
|
+
if (this.timer) clearTimeout(this.timer);
|
|
173
|
+
this.timer = undefined;
|
|
174
|
+
if (this.local.length === 0 || this.degradedError) return;
|
|
175
|
+
const operations = this.local.splice(0, this.options.batchSize);
|
|
176
|
+
const id = this.nextMessageId++;
|
|
177
|
+
this.sentOperations += operations.length;
|
|
178
|
+
this.batchSizes.set(id, operations.length);
|
|
179
|
+
this.worker.postMessage({ type: 'batch', id, operations });
|
|
180
|
+
if (this.local.length > 0) this.timer = setTimeout(() => this.dispatch(), 0);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
private async flush(): Promise<void> {
|
|
184
|
+
if (this.degradedError) return;
|
|
185
|
+
while (this.local.length > 0) this.dispatch();
|
|
186
|
+
const id = this.nextMessageId++;
|
|
187
|
+
await new Promise<void>((resolve, reject) => {
|
|
188
|
+
this.waiters.set(id, { resolve, reject });
|
|
189
|
+
this.worker.postMessage({ type: 'barrier', id });
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
private close(): Promise<void> {
|
|
194
|
+
if (this.closing) return this.closing;
|
|
195
|
+
this.closing = (async () => {
|
|
196
|
+
if (this.timer) clearTimeout(this.timer);
|
|
197
|
+
this.timer = undefined;
|
|
198
|
+
try {
|
|
199
|
+
await this.flush();
|
|
200
|
+
if (!this.degradedError) {
|
|
201
|
+
const id = this.nextMessageId++;
|
|
202
|
+
await new Promise<void>((resolve, reject) => {
|
|
203
|
+
this.waiters.set(id, { resolve, reject });
|
|
204
|
+
this.worker.postMessage({ type: 'close', id });
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
} finally {
|
|
208
|
+
await this.worker.terminate();
|
|
209
|
+
}
|
|
210
|
+
})();
|
|
211
|
+
return this.closing;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private degrade(error: Error): void {
|
|
215
|
+
if (this.degradedError) return;
|
|
216
|
+
this.degradedError = error;
|
|
217
|
+
for (const waiter of this.waiters.values()) waiter.reject(error);
|
|
218
|
+
this.waiters.clear();
|
|
219
|
+
this.options.onDegraded?.(error, this.health());
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
abstract class MirroredStore {
|
|
224
|
+
readonly persistenceKind = 'memory-first-sqlite' as const;
|
|
225
|
+
constructor(protected readonly mirror: AsyncSqliteMirror) {}
|
|
226
|
+
persistenceHealth(): AsyncPersistenceHealth { return this.mirror.health(); }
|
|
227
|
+
close(): Promise<void> { return this.mirror.release(); }
|
|
228
|
+
protected persist(store: StoreName, method: string, ...args: unknown[]): void {
|
|
229
|
+
this.mirror.enqueue({ store, method, args });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
class MemoryFirstEventRepository extends MirroredStore implements EventRepository, MailboxRepository {
|
|
234
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository) { super(mirror); }
|
|
235
|
+
saveSession(value: PlaySessionRecord): void { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
|
|
236
|
+
saveSegment(value: EventSegmentRecord): void { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
|
|
237
|
+
currentScope(account?: EventAccountScope) { return this.memory.currentScope(account); }
|
|
238
|
+
latestScope(account: EventAccountScope, options?: LatestEventScopeOptions) { return this.memory.latestScope(account, options); }
|
|
239
|
+
commitEvent(value: CommitEventRequest) { const result = this.memory.commitEvent(value); this.persist('events', 'commitEvent', value); return result; }
|
|
240
|
+
eventById(eventId: string) { return this.memory.eventById(eventId); }
|
|
241
|
+
latestEventByType(sessionId: string, type: string, segmentId?: string) { return this.memory.latestEventByType(sessionId, type, segmentId); }
|
|
242
|
+
highWaterCommitSeq(sessionId: string, segmentId?: string) { return this.memory.highWaterCommitSeq(sessionId, segmentId); }
|
|
243
|
+
listCommittedEvents(filter: CommittedEventListFilter) { return this.memory.listCommittedEvents(filter); }
|
|
244
|
+
ensureDeliveries(sessionId: string, consumerId: string, channels?: readonly ConsumerLease['channel'][]): void {
|
|
245
|
+
this.memory.ensureDeliveries(sessionId, consumerId, channels);
|
|
246
|
+
this.persist('events', 'ensureDeliveries', sessionId, consumerId, channels);
|
|
247
|
+
}
|
|
248
|
+
delivery(eventId: string, consumerId: string) { return this.memory.delivery(eventId, consumerId); }
|
|
249
|
+
listEvents(filter: EventListFilter, consumerId: string, channels?: readonly ConsumerLease['channel'][]) {
|
|
250
|
+
this.ensureDeliveries(filter.sessionId, consumerId, channels);
|
|
251
|
+
return this.memory.listEvents(filter, consumerId, channels);
|
|
252
|
+
}
|
|
253
|
+
backlogSummary(sessionId: string, consumerId: string) {
|
|
254
|
+
this.ensureDeliveries(sessionId, consumerId, ['details']);
|
|
255
|
+
return this.memory.backlogSummary(sessionId, consumerId);
|
|
256
|
+
}
|
|
257
|
+
transitionDetails(value: DetailStateTransition) {
|
|
258
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
259
|
+
const result = this.memory.transitionDetails(stable); this.persist('events', 'transitionDetails', stable); return result;
|
|
260
|
+
}
|
|
261
|
+
transitionMonitor(value: MonitorStateTransition) {
|
|
262
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
263
|
+
const result = this.memory.transitionMonitor(stable); this.persist('events', 'transitionMonitor', stable); return result;
|
|
264
|
+
}
|
|
265
|
+
recordMonitorAttempt(value: MonitorDeliveryAttempt) {
|
|
266
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
267
|
+
const result = this.memory.recordMonitorAttempt(stable); this.persist('events', 'recordMonitorAttempt', stable); return result;
|
|
268
|
+
}
|
|
269
|
+
acquireLease(value: AcquireLeaseRequest) {
|
|
270
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
271
|
+
const result = this.memory.acquireLease(stable); this.persist('events', 'acquireLease', stable); return result;
|
|
272
|
+
}
|
|
273
|
+
leaseIsValid(lease: ConsumerLease, nowMs?: number) { return this.memory.leaseIsValid(lease, nowMs); }
|
|
274
|
+
releaseLease(lease: ConsumerLease) { const result = this.memory.releaseLease(lease); this.persist('events', 'releaseLease', lease); return result; }
|
|
275
|
+
sourceCheckpoint(sourceId: string) { return this.memory.sourceCheckpoint(sourceId); }
|
|
276
|
+
enqueueMailboxItem<T = unknown>(value: EnqueueMailboxItem<T>) {
|
|
277
|
+
const nowMs = Date.now();
|
|
278
|
+
const stable = { ...value, createdAt: value.createdAt ?? new Date(nowMs).toISOString(), availableAtMs: value.availableAtMs ?? 0 };
|
|
279
|
+
const result = this.memory.enqueueMailboxItem(stable); this.persist('events', 'enqueueMailboxItem', stable); return result;
|
|
280
|
+
}
|
|
281
|
+
mailboxItem<T = unknown>(itemId: string) { return this.memory.mailboxItem<T>(itemId); }
|
|
282
|
+
mailboxItemForEvent<T = unknown>(consumerId: string, eventId: string, mode: 'short') { return this.memory.mailboxItemForEvent<T>(consumerId, eventId, mode); }
|
|
283
|
+
peekMailbox<T = unknown>(filter: MailboxPeekFilter) { return this.memory.peekMailbox<T>(filter); }
|
|
284
|
+
claimMailbox<T = unknown>(value: ClaimMailboxItemsRequest) {
|
|
285
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now(), claimToken: value.claimToken ?? randomUUID() };
|
|
286
|
+
const result = this.memory.claimMailbox<T>(stable); this.persist('events', 'claimMailbox', stable); return result;
|
|
287
|
+
}
|
|
288
|
+
ackMailboxClaim(value: AckMailboxClaimRequest) {
|
|
289
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
290
|
+
const result = this.memory.ackMailboxClaim(stable); this.persist('events', 'ackMailboxClaim', stable); return result;
|
|
291
|
+
}
|
|
292
|
+
nackMailboxClaim(value: NackMailboxClaimRequest) {
|
|
293
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
294
|
+
const result = this.memory.nackMailboxClaim(stable); this.persist('events', 'nackMailboxClaim', stable); return result;
|
|
295
|
+
}
|
|
296
|
+
suppressMailboxItems(value: SuppressMailboxItemsFilter) {
|
|
297
|
+
const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
|
|
298
|
+
const result = this.memory.suppressMailboxItems(stable); this.persist('events', 'suppressMailboxItems', stable); return result;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
class MemoryFirstStateHistory<TPosition, TState extends Record<string, unknown>> extends MirroredStore
|
|
303
|
+
implements StateHistoryRepository<TPosition, TState> {
|
|
304
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryStateHistoryRepository<TPosition, TState>) { super(mirror); }
|
|
305
|
+
openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true) {
|
|
306
|
+
const result = this.memory.openScope(scope, openedAtMs, historyComplete);
|
|
307
|
+
this.persist('history', 'openScope', scope, openedAtMs, historyComplete); return result;
|
|
308
|
+
}
|
|
309
|
+
sealScope(scope: RuntimeScope, sealedAtMs = Date.now()) { this.memory.sealScope(scope, sealedAtMs); this.persist('history', 'sealScope', scope, sealedAtMs); }
|
|
310
|
+
markScopeIncomplete(scope: RuntimeScope) { this.memory.markScopeIncomplete(scope); this.persist('history', 'markScopeIncomplete', scope); }
|
|
311
|
+
getScope(scope: RuntimeScope) { return this.memory.getScope(scope); }
|
|
312
|
+
appendStateFrame(frame: StateFrameRecord<TState>) { const result = this.memory.appendStateFrame(frame); this.persist('history', 'appendStateFrame', frame); return result; }
|
|
313
|
+
queryStateFrames(query: StateFrameQuery) { return this.memory.queryStateFrames(query); }
|
|
314
|
+
latestStateFrame(scope: RuntimeScope) { return this.memory.latestStateFrame(scope); }
|
|
315
|
+
append(records: TrajectoryRecord<TPosition>[]) { const result = this.memory.append(records); this.persist('history', 'append', records); return result; }
|
|
316
|
+
query(query: HistoryQuery) { return this.memory.query(query); }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
class MemoryFirstInputJournal<TState extends Record<string, unknown>, TEvent extends Record<string, unknown>>
|
|
320
|
+
extends MirroredStore implements RuntimePersistenceStore<TState, TEvent> {
|
|
321
|
+
constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryRuntimeInputJournal<TState, TEvent>) { super(mirror); }
|
|
322
|
+
accept(batch: RuntimeInputBatch<TState, TEvent>) { const result = this.memory.accept(batch); if (result.inserted) this.persist('input', 'accept', batch); return result; }
|
|
323
|
+
epoch(epochSeq: number) { return this.memory.epoch(epochSeq); }
|
|
324
|
+
list(scope: RuntimeScope, afterEpochSeq?: number, limit?: number) { return this.memory.list(scope, afterEpochSeq, limit); }
|
|
325
|
+
listOpen(scope: RuntimeScope, afterEpochSeq?: number, limit?: number) { return this.memory.listOpen(scope, afterEpochSeq, limit); }
|
|
326
|
+
inputEventsCommitted(epochSeq: number) { return this.memory.inputEventsCommitted(epochSeq); }
|
|
327
|
+
markInputEventsCommitted(epochSeq: number, watermark: number, committedAt = new Date().toISOString()) { this.memory.markInputEventsCommitted(epochSeq, watermark); this.persist('input', 'markInputEventsCommitted', epochSeq, watermark, committedAt); }
|
|
328
|
+
eventWatermarkThrough(scope: RuntimeScope, epochSeq: number) { return this.memory.eventWatermarkThrough(scope, epochSeq); }
|
|
329
|
+
markEventWatermark(epochSeq: number, watermark: number) { this.memory.markEventWatermark(epochSeq, watermark); this.persist('input', 'markEventWatermark', epochSeq, watermark); }
|
|
330
|
+
markClosed(epochSeq: number, closedAt = new Date().toISOString(), durationMs?: number) { this.memory.markClosed(epochSeq); this.persist('input', 'markClosed', epochSeq, closedAt, durationMs); }
|
|
331
|
+
recordPlugin(record: RuntimeEpochPluginRecord) { this.memory.recordPlugin(record); this.persist('input', 'recordPlugin', record); }
|
|
332
|
+
pluginRecords(epochSeq: number) { return this.memory.pluginRecords(epochSeq); }
|
|
333
|
+
pluginProgress(pluginId: string, scope: RuntimeScope) { return this.memory.pluginProgress(pluginId, scope); }
|
|
334
|
+
savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope) { this.memory.savePluginProgress(progress, scope); this.persist('input', 'savePluginProgress', progress, scope); }
|
|
335
|
+
saveStates(records: readonly RuntimeEpochStateRecord[]) { this.memory.saveStates(records); this.persist('input', 'saveStates', records); }
|
|
336
|
+
states(epochSeq: number) { return this.memory.states(epochSeq); }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export interface MemoryFirstPersistence<TPosition = unknown, TState extends Record<string, unknown> = Record<string, unknown>, TEvent extends Record<string, unknown> = Record<string, unknown>> {
|
|
340
|
+
eventRepository: EventRepository & MailboxRepository;
|
|
341
|
+
stateHistoryRepository: StateHistoryRepository<TPosition, TState>;
|
|
342
|
+
inputJournal: RuntimePersistenceStore<TState, TEvent>;
|
|
343
|
+
health(): AsyncPersistenceHealth;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function createMemoryFirstPersistence<
|
|
347
|
+
TPosition = unknown,
|
|
348
|
+
TState extends Record<string, unknown> = Record<string, unknown>,
|
|
349
|
+
TEvent extends Record<string, unknown> = Record<string, unknown>,
|
|
350
|
+
>(options: MemoryFirstPersistenceOptions): MemoryFirstPersistence<TPosition, TState, TEvent> {
|
|
351
|
+
const eventSqlite = SqliteEventRepository.open(options.eventLedgerPath);
|
|
352
|
+
if (!eventSqlite.ok) throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
|
|
353
|
+
const historySqlite = new SqliteStateHistoryRepository<TPosition, TState>(options.stateHistoryPath);
|
|
354
|
+
const inputSqlite = new SqliteRuntimeInputJournal<TState, TEvent>(options.inputJournalPath);
|
|
355
|
+
let eventMemory: MemoryEventRepository;
|
|
356
|
+
let historyMemory: MemoryStateHistoryRepository<TPosition, TState>;
|
|
357
|
+
let inputMemory: MemoryRuntimeInputJournal<TState, TEvent>;
|
|
358
|
+
try {
|
|
359
|
+
eventMemory = new MemoryEventRepository(eventSqlite.repository.snapshot());
|
|
360
|
+
historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot());
|
|
361
|
+
inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot());
|
|
362
|
+
} finally {
|
|
363
|
+
eventSqlite.repository.close();
|
|
364
|
+
historySqlite.close();
|
|
365
|
+
inputSqlite.close();
|
|
366
|
+
}
|
|
367
|
+
const required: ResolvedMemoryFirstPersistenceOptions = {
|
|
368
|
+
...options,
|
|
369
|
+
maxPendingOperations: options.maxPendingOperations ?? 20_000,
|
|
370
|
+
batchSize: options.batchSize ?? 128,
|
|
371
|
+
flushIntervalMs: options.flushIntervalMs ?? 8,
|
|
372
|
+
};
|
|
373
|
+
const mirror = new AsyncSqliteMirror(required);
|
|
374
|
+
return {
|
|
375
|
+
eventRepository: new MemoryFirstEventRepository(mirror, eventMemory),
|
|
376
|
+
stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
|
|
377
|
+
inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
|
|
378
|
+
health: () => mirror.health(),
|
|
379
|
+
};
|
|
380
|
+
}
|
|
@@ -347,7 +347,7 @@ export interface RuntimeInputJournal<TState = Record<string, unknown>, TEvent =
|
|
|
347
347
|
eventWatermarkThrough(scope: RuntimeScope, epochSeq: number): number;
|
|
348
348
|
markEventWatermark(epochSeq: number, eventWatermark: number): void;
|
|
349
349
|
markClosed(epochSeq: number, closedAt?: string, durationMs?: number): void;
|
|
350
|
-
close?(): void
|
|
350
|
+
close?(): void | Promise<void>;
|
|
351
351
|
}
|
|
352
352
|
|
|
353
353
|
/** Durable outcomes, derived State and independent Event cursors for plugins. */
|
|
@@ -358,7 +358,7 @@ export interface RuntimePluginStore {
|
|
|
358
358
|
savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope): void;
|
|
359
359
|
saveStates(records: readonly RuntimeEpochStateRecord[]): void;
|
|
360
360
|
states(epochSeq: number): RuntimeEpochStateRecord[];
|
|
361
|
-
close?(): void
|
|
361
|
+
close?(): void | Promise<void>;
|
|
362
362
|
}
|
|
363
363
|
|
|
364
364
|
/** One physical database may implement both logical persistence contracts. */
|