@myclaw163/clawclaw-cli 0.8.21 → 0.8.23
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/docs/custom-modules/api-reference.md +2 -0
- package/docs/custom-modules/perception.md +25 -0
- package/docs/runtime/official-perception-modules.md +23 -0
- package/docs/runtime/owner-lifecycle-and-observability.md +6 -2
- package/package.json +1 -1
- package/skills/clawclaw/references/CUSTOM-MODULE-API.md +2 -0
- package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +25 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +7 -0
- package/src/runtime/clawclaw/owner.ts +16 -10
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +18 -11
- package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +2 -0
- package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +10 -1
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +17 -1
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +5 -2
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +46 -15
- package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +2 -1
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +4 -0
- package/src/runtime/framework/events/event-ingress.ts +1 -0
- package/src/runtime/framework/events/memory-event-repository.ts +5 -4
- package/src/runtime/framework/events/sqlite-event-repository.ts +36 -9
- package/src/runtime/framework/events/types.ts +4 -0
- package/src/runtime/framework/mailbox/types.ts +4 -0
- package/src/runtime/framework/plugins/contracts.ts +2 -0
- package/src/runtime/framework/runtime.ts +1 -0
- package/src/runtime/game-sync-ingress-protocol.ts +3 -2
- package/src/runtime/game-sync-ingress-worker.ts +153 -38
- package/src/runtime/mailbox-host-relay.ts +13 -12
- package/src/runtime/threaded-ws-client.ts +17 -9
- package/src/runtime/ws-client.ts +18 -8
- package/src/sdk/perception-plugin/index.ts +4 -0
|
@@ -352,6 +352,9 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
352
352
|
const boundaryBaseline = literalProperty(manifestBlock, 'boundaryBaseline')?.trim();
|
|
353
353
|
const localizations = literalLocalizations(manifestBlock);
|
|
354
354
|
const eventMetadata = literalEventMetadata(manifestBlock);
|
|
355
|
+
const hasWakePolicy = /\bwakeAgent\s*:/.test(manifestBlock);
|
|
356
|
+
const wakeValue = /\bwakeAgent\s*:\s*(true|false)\b\s*(?=,|}|\n|\/\/|\/\*)/.exec(manifestBlock)?.[1];
|
|
357
|
+
if (hasWakePolicy && wakeValue === undefined) return null;
|
|
355
358
|
const parallelClass = classMatch[1] === 'ClawclawParallelPerception';
|
|
356
359
|
if (
|
|
357
360
|
!id
|
|
@@ -388,6 +391,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
|
|
|
388
391
|
name,
|
|
389
392
|
description,
|
|
390
393
|
...(localizations === undefined ? {} : { localizations }),
|
|
394
|
+
...(wakeValue === undefined ? {} : { wakeAgent: wakeValue === 'true' }),
|
|
391
395
|
subjectScope: subjectScope as ClawclawPerceptionManifest['subjectScope'],
|
|
392
396
|
produces,
|
|
393
397
|
...(eventMetadata === undefined ? {} : { eventMetadata }),
|
|
@@ -73,6 +73,7 @@ export class EventIngress {
|
|
|
73
73
|
...(input.producerOutputIndex === undefined
|
|
74
74
|
? {}
|
|
75
75
|
: { producerOutputIndex: input.producerOutputIndex }),
|
|
76
|
+
...(input.wakeAgent === undefined ? {} : { wakeAgent: input.wakeAgent }),
|
|
76
77
|
deliveryClass: policy.deliveryClass,
|
|
77
78
|
occurredAt: input.occurredAt ?? receivedAt,
|
|
78
79
|
receivedAt,
|
|
@@ -642,6 +642,7 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
642
642
|
segmentId: request.segmentId,
|
|
643
643
|
eventId: request.eventId,
|
|
644
644
|
eventCommitSeq: request.eventCommitSeq,
|
|
645
|
+
...(request.deliveryOrder === undefined ? {} : { deliveryOrder: request.deliveryOrder }),
|
|
645
646
|
mode: request.mode,
|
|
646
647
|
coalesceKey: request.coalesceKey,
|
|
647
648
|
payload: cloneRecord(request.payload),
|
|
@@ -688,9 +689,9 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
688
689
|
rows.sort((a, b) => {
|
|
689
690
|
const direction = filter.order === 'desc' ? -1 : 1;
|
|
690
691
|
return direction * (
|
|
691
|
-
a.eventCommitSeq === b.eventCommitSeq
|
|
692
|
+
(a.deliveryOrder ?? a.eventCommitSeq) === (b.deliveryOrder ?? b.eventCommitSeq)
|
|
692
693
|
? a.itemId.localeCompare(b.itemId)
|
|
693
|
-
: a.eventCommitSeq - b.eventCommitSeq
|
|
694
|
+
: (a.deliveryOrder ?? a.eventCommitSeq) - (b.deliveryOrder ?? b.eventCommitSeq)
|
|
694
695
|
);
|
|
695
696
|
});
|
|
696
697
|
const limit = filter.limit === undefined
|
|
@@ -713,9 +714,9 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
713
714
|
&& (item.state === 'pending' || item.state === 'claimed')
|
|
714
715
|
))
|
|
715
716
|
.sort((a, b) => (
|
|
716
|
-
a.eventCommitSeq === b.eventCommitSeq
|
|
717
|
+
(a.deliveryOrder ?? a.eventCommitSeq) === (b.deliveryOrder ?? b.eventCommitSeq)
|
|
717
718
|
? a.itemId.localeCompare(b.itemId)
|
|
718
|
-
: a.eventCommitSeq - b.eventCommitSeq
|
|
719
|
+
: (a.deliveryOrder ?? a.eventCommitSeq) - (b.deliveryOrder ?? b.eventCommitSeq)
|
|
719
720
|
));
|
|
720
721
|
const activeRows: MailboxItem[] = [];
|
|
721
722
|
for (const item of rows) {
|
|
@@ -158,6 +158,7 @@ function segmentFromRow(row: Record<string, unknown>): EventSegmentRecord {
|
|
|
158
158
|
function eventFromRow(row: Record<string, unknown>): CanonicalEvent {
|
|
159
159
|
const payload = JSON.parse(String(row.payload_json)) as Record<string, unknown>;
|
|
160
160
|
return {
|
|
161
|
+
...(row.wake_agent === null || row.wake_agent === undefined ? {} : { wakeAgent: numberValue(row.wake_agent) !== 0 }),
|
|
161
162
|
commitSeq: numberValue(row.commit_seq),
|
|
162
163
|
...(row.epoch_seq === null || row.epoch_seq === undefined
|
|
163
164
|
? {}
|
|
@@ -223,6 +224,7 @@ function mailboxItemFromRow<T = unknown>(row: Record<string, unknown>): MailboxI
|
|
|
223
224
|
segmentId: String(row.segment_id),
|
|
224
225
|
eventId: String(row.event_id),
|
|
225
226
|
eventCommitSeq: numberValue(row.event_commit_seq),
|
|
227
|
+
...(row.delivery_order == null ? {} : { deliveryOrder: numberValue(row.delivery_order) }),
|
|
226
228
|
// New runtime code only creates short notifications. The SQLite schema
|
|
227
229
|
// still accepts historical full rows so existing ledgers open in place.
|
|
228
230
|
mode: 'short',
|
|
@@ -572,8 +574,8 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
572
574
|
event_id, epoch_seq, session_id, segment_id, type, producer,
|
|
573
575
|
producer_plugin_id, producer_output_index, delivery_class,
|
|
574
576
|
occurred_at, received_at, payload_json, source_id, source_event_id,
|
|
575
|
-
source_sequence, connection_id, replayed
|
|
576
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
577
|
+
source_sequence, connection_id, replayed, wake_agent
|
|
578
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
577
579
|
`).run(
|
|
578
580
|
request.event.eventId,
|
|
579
581
|
request.event.epochSeq ?? null,
|
|
@@ -592,6 +594,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
592
594
|
request.event.sourceSequence ?? null,
|
|
593
595
|
request.event.connectionId ?? null,
|
|
594
596
|
booleanInt(request.event.replayed),
|
|
597
|
+
request.event.wakeAgent === undefined ? null : booleanInt(request.event.wakeAgent),
|
|
595
598
|
);
|
|
596
599
|
const event: CanonicalEvent = {
|
|
597
600
|
...cloneRecord(request.event),
|
|
@@ -948,8 +951,8 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
948
951
|
INSERT INTO mailbox_items(
|
|
949
952
|
item_id, schema_version, formatter_version, consumer_id, session_id,
|
|
950
953
|
segment_id, event_id, event_commit_seq, mode, coalesce_key,
|
|
951
|
-
payload_json, state, attempt_count, available_at, created_at, updated_at
|
|
952
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)
|
|
954
|
+
payload_json, state, attempt_count, available_at, created_at, updated_at, delivery_order
|
|
955
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)
|
|
953
956
|
`).run(
|
|
954
957
|
request.itemId,
|
|
955
958
|
request.schemaVersion ?? 1,
|
|
@@ -966,6 +969,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
966
969
|
request.availableAtMs ?? 0,
|
|
967
970
|
createdAt,
|
|
968
971
|
createdAt,
|
|
972
|
+
request.deliveryOrder ?? null,
|
|
969
973
|
);
|
|
970
974
|
const inserted = this.db.prepare('SELECT * FROM mailbox_items WHERE item_id = ?')
|
|
971
975
|
.get(request.itemId);
|
|
@@ -1012,7 +1016,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1012
1016
|
return this.db.prepare(`
|
|
1013
1017
|
SELECT * FROM mailbox_items
|
|
1014
1018
|
WHERE ${clauses.join(' AND ')}
|
|
1015
|
-
ORDER BY event_commit_seq ${order}, item_id ${order}${limit}
|
|
1019
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ${order}, item_id ${order}${limit}
|
|
1016
1020
|
`).all(...params).map((row) => mailboxItemFromRow<T>(row));
|
|
1017
1021
|
}
|
|
1018
1022
|
|
|
@@ -1032,7 +1036,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1032
1036
|
AND m.segment_id = ?
|
|
1033
1037
|
AND m.mode = ?
|
|
1034
1038
|
AND m.state IN ('pending', 'claimed')
|
|
1035
|
-
ORDER BY m.event_commit_seq ASC, m.item_id ASC
|
|
1039
|
+
ORDER BY COALESCE(m.delivery_order, m.event_commit_seq) ASC, m.item_id ASC
|
|
1036
1040
|
`).all(request.consumerId, request.sessionId, request.segmentId, request.mode);
|
|
1037
1041
|
|
|
1038
1042
|
const activeRows: Array<Record<string, unknown>> = [];
|
|
@@ -1098,7 +1102,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1098
1102
|
const claimedRows = this.db.prepare(`
|
|
1099
1103
|
SELECT * FROM mailbox_items
|
|
1100
1104
|
WHERE item_id IN (${placeholders(itemIds.length)})
|
|
1101
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1105
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1102
1106
|
`).all(...itemIds);
|
|
1103
1107
|
return {
|
|
1104
1108
|
ownerId: request.ownerId,
|
|
@@ -1115,7 +1119,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1115
1119
|
const rows = this.db.prepare(`
|
|
1116
1120
|
SELECT * FROM mailbox_items
|
|
1117
1121
|
WHERE claim_owner = ? AND claim_token = ?
|
|
1118
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1122
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1119
1123
|
`).all(request.ownerId, request.claimToken);
|
|
1120
1124
|
if (rows.length === 0) return { status: 'claim_lost', itemIds: [], eventIds: [] };
|
|
1121
1125
|
const itemIds = rows.map((row) => String(row.item_id));
|
|
@@ -1158,7 +1162,7 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1158
1162
|
const rows = this.db.prepare(`
|
|
1159
1163
|
SELECT * FROM mailbox_items
|
|
1160
1164
|
WHERE claim_owner = ? AND claim_token = ? AND state = 'claimed'
|
|
1161
|
-
ORDER BY event_commit_seq ASC, item_id ASC
|
|
1165
|
+
ORDER BY COALESCE(delivery_order, event_commit_seq) ASC, item_id ASC
|
|
1162
1166
|
`).all(request.ownerId, request.claimToken);
|
|
1163
1167
|
if (
|
|
1164
1168
|
rows.length === 0
|
|
@@ -1669,6 +1673,29 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
1669
1673
|
`).run(new Date().toISOString());
|
|
1670
1674
|
});
|
|
1671
1675
|
}
|
|
1676
|
+
const wakeMigration = this.db.prepare('SELECT version FROM schema_migrations WHERE version = 11').get();
|
|
1677
|
+
if (!wakeMigration) {
|
|
1678
|
+
this.transaction(() => {
|
|
1679
|
+
const columns = this.db.prepare('PRAGMA table_info(events)').all();
|
|
1680
|
+
if (!columns.some((row) => row.name === 'wake_agent')) {
|
|
1681
|
+
this.db.exec('ALTER TABLE events ADD COLUMN wake_agent INTEGER CHECK(wake_agent IN (0, 1))');
|
|
1682
|
+
}
|
|
1683
|
+
this.db.prepare('INSERT INTO schema_migrations(version, applied_at) VALUES (11, ?)')
|
|
1684
|
+
.run(new Date().toISOString());
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
if (!this.db.prepare('SELECT version FROM schema_migrations WHERE version = 12').get()) {
|
|
1689
|
+
this.transaction(() => {
|
|
1690
|
+
const columns = this.db.prepare('PRAGMA table_info(mailbox_items)').all();
|
|
1691
|
+
if (!columns.some((row) => row.name === 'delivery_order')) {
|
|
1692
|
+
this.db.exec('ALTER TABLE mailbox_items ADD COLUMN delivery_order INTEGER');
|
|
1693
|
+
}
|
|
1694
|
+
this.db.prepare('INSERT INTO schema_migrations(version, applied_at) VALUES (12, ?)')
|
|
1695
|
+
.run(new Date().toISOString());
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1672
1699
|
}
|
|
1673
1700
|
|
|
1674
1701
|
/**
|
|
@@ -85,6 +85,8 @@ export interface EventSourceRef {
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
export interface PublishEventInput {
|
|
88
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
89
|
+
readonly wakeAgent?: boolean;
|
|
88
90
|
/** Runtime epoch that admitted or derived this Event. */
|
|
89
91
|
epochSeq?: number;
|
|
90
92
|
type: string;
|
|
@@ -103,6 +105,8 @@ export interface PublishEventInput {
|
|
|
103
105
|
}
|
|
104
106
|
|
|
105
107
|
export interface CanonicalEvent {
|
|
108
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
109
|
+
readonly wakeAgent?: boolean;
|
|
106
110
|
commitSeq: number;
|
|
107
111
|
/** Absent only for records written before the epoch runtime migration. */
|
|
108
112
|
epochSeq?: number;
|
|
@@ -24,6 +24,8 @@ export interface MailboxItem<T = unknown> {
|
|
|
24
24
|
segmentId: string;
|
|
25
25
|
eventId: string;
|
|
26
26
|
eventCommitSeq: number;
|
|
27
|
+
/** Optional stable delivery position; canonical event sequence remains unchanged. */
|
|
28
|
+
deliveryOrder?: number;
|
|
27
29
|
mode: MailboxDeliveryMode;
|
|
28
30
|
coalesceKey: string;
|
|
29
31
|
payload: T;
|
|
@@ -51,6 +53,8 @@ export interface EnqueueMailboxItem<T = unknown> {
|
|
|
51
53
|
segmentId: string;
|
|
52
54
|
eventId: string;
|
|
53
55
|
eventCommitSeq: number;
|
|
56
|
+
/** Optional stable delivery position; canonical event sequence remains unchanged. */
|
|
57
|
+
deliveryOrder?: number;
|
|
54
58
|
mode: MailboxDeliveryMode;
|
|
55
59
|
coalesceKey: string;
|
|
56
60
|
payload: T;
|
|
@@ -115,6 +115,8 @@ export interface RuntimeStateProposal<T = unknown> {
|
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
export interface RuntimeEventProposal {
|
|
118
|
+
/** Whether this Event may initiate Agent delivery; omitted means true. */
|
|
119
|
+
readonly wakeAgent?: boolean;
|
|
118
120
|
readonly type: string;
|
|
119
121
|
readonly dedupeKey: string;
|
|
120
122
|
readonly dedupeScope?: 'segment' | 'session';
|
|
@@ -1258,6 +1258,7 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
|
|
|
1258
1258
|
producerOutputIndex: proposalIndex,
|
|
1259
1259
|
sessionId: epoch.scope.sessionId,
|
|
1260
1260
|
segmentId: epoch.scope.segmentId,
|
|
1261
|
+
wakeAgent: proposal.wakeAgent,
|
|
1261
1262
|
payload: proposal.payload,
|
|
1262
1263
|
occurredAt: proposal.occurredAt,
|
|
1263
1264
|
receivedAt: new Date().toISOString(),
|
|
@@ -9,13 +9,14 @@ export interface GameSyncIngressConfig {
|
|
|
9
9
|
resumeState?: GameSyncResumeState;
|
|
10
10
|
reconnectMaxMs?: number;
|
|
11
11
|
ackIntervalMs?: number;
|
|
12
|
-
|
|
12
|
+
/** Credits for complete frames handed to Source, not a socket-disconnect threshold. */
|
|
13
|
+
maxInFlightFrames: number;
|
|
13
14
|
maxPendingBytes: number;
|
|
14
15
|
rawLog?: { path: string; options?: BufferedRawWsLogOptions };
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
export type IngressCommand =
|
|
18
|
-
| { type: '
|
|
19
|
+
| { type: 'consumed'; token: string }
|
|
19
20
|
| { type: 'report'; perceptions: readonly GameSyncPerceptionReport[] }
|
|
20
21
|
| { type: 'telemetry_ack' }
|
|
21
22
|
| { type: 'stop' };
|
|
@@ -5,12 +5,27 @@ import { WsConnectionState } from '../sdk/types.js';
|
|
|
5
5
|
import { WsClient } from './ws-client.js';
|
|
6
6
|
import { BufferedRawWsLog } from './raw-ws-log.js';
|
|
7
7
|
import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
|
|
8
|
+
import { applyGameSyncDelta, type GameSyncServerMessage } from './game-sync-protocol.js';
|
|
9
|
+
import type { GameSyncResumeState, WsFrameMeta, WsInputFrame } from './ws-client.js';
|
|
8
10
|
|
|
9
11
|
const port = parentPort!;
|
|
10
12
|
const config = workerData.config as GameSyncIngressConfig;
|
|
11
13
|
const packageVersion = (JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { version?: string }).version;
|
|
12
14
|
const raw = config.rawLog ? new BufferedRawWsLog(config.rawLog.path, config.rawLog.options) : undefined;
|
|
13
|
-
|
|
15
|
+
interface CachedFrame {
|
|
16
|
+
type: 'cached_frame';
|
|
17
|
+
messages: Buffer[];
|
|
18
|
+
bytes: number;
|
|
19
|
+
meta: WsFrameMeta;
|
|
20
|
+
eventIds: Set<string>;
|
|
21
|
+
}
|
|
22
|
+
const pending = new Map<string, CachedFrame>();
|
|
23
|
+
const inFlight = new Map<string, CachedFrame>();
|
|
24
|
+
let deliveryQueue: Array<IngressEvent | CachedFrame | undefined> = [];
|
|
25
|
+
let deliveryHead = 0;
|
|
26
|
+
let unappliedMessages: Buffer[] = [];
|
|
27
|
+
let unappliedBytes = 0;
|
|
28
|
+
let deliveryBaseline: GameSyncResumeState | undefined = config.resumeState;
|
|
14
29
|
let pendingBytes = 0;
|
|
15
30
|
let stopped = false;
|
|
16
31
|
let overloaded = false;
|
|
@@ -19,6 +34,7 @@ let telemetryPending = false;
|
|
|
19
34
|
let lastLiveness = 0;
|
|
20
35
|
let lastReceivedSeq = 0;
|
|
21
36
|
let acceptedSeq = config.resumeState?.seq ?? 0;
|
|
37
|
+
let bufferedSeq = config.resumeState?.seq ?? 0;
|
|
22
38
|
let ackSubmittedSeq = 0;
|
|
23
39
|
let receivedFrames = 0;
|
|
24
40
|
let pingCount = 0;
|
|
@@ -27,18 +43,20 @@ let pongErrors = 0;
|
|
|
27
43
|
let lastPingAt = 0;
|
|
28
44
|
let lastPongWrittenAt = 0;
|
|
29
45
|
let maxPongWriteMs = 0;
|
|
30
|
-
let
|
|
46
|
+
let maxSourceConsumptionDelayMs = 0;
|
|
31
47
|
let overloadCount = 0;
|
|
32
48
|
let maxOutstanding = 0;
|
|
49
|
+
let maxBufferedBytes = 0;
|
|
33
50
|
const delay = monitorEventLoopDelay({ resolution: 20 });
|
|
34
51
|
delay.enable();
|
|
35
52
|
const post = (message: IngressEvent): void => { if (!stopped || message.type === 'stopped') port.postMessage(message); };
|
|
36
53
|
const client = new WsClient({
|
|
37
54
|
url: config.url, apiKey: config.apiKey, resumeState: config.resumeState,
|
|
38
55
|
reconnectMaxMs: config.reconnectMaxMs, ackIntervalMs: config.ackIntervalMs,
|
|
39
|
-
maxPayloadBytes:
|
|
56
|
+
maxPayloadBytes: 32 * 1024 * 1024, rawMessageSink: raw,
|
|
40
57
|
handshakeTimeoutMs: 10_000,
|
|
41
|
-
|
|
58
|
+
retainInputMessage: retainMessage,
|
|
59
|
+
discardUnappliedMessages,
|
|
42
60
|
diagnostic: (name, attributes) => {
|
|
43
61
|
if (name === 'runtime.ws.ping_received') { pingCount++; lastPingAt = Number(attributes.received_at_ms); }
|
|
44
62
|
if (name === 'runtime.ws.pong_written') {
|
|
@@ -55,14 +73,16 @@ function telemetry(force = false): void {
|
|
|
55
73
|
telemetryPending = true;
|
|
56
74
|
post({ type: 'telemetry', attributes: {
|
|
57
75
|
sampled_at_ms: Date.now(), connection_id: client.connectionId,
|
|
58
|
-
implementation: '
|
|
76
|
+
implementation: 'buffered_gamesync_v2', package_version: packageVersion, node_version: process.version, thread_id: threadId,
|
|
59
77
|
last_liveness_at_ms: lastLiveness, received_frames: receivedFrames,
|
|
60
|
-
received_seq: lastReceivedSeq, source_accepted_seq: acceptedSeq, ack_submitted_seq: ackSubmittedSeq,
|
|
78
|
+
received_seq: lastReceivedSeq, buffered_seq: bufferedSeq, source_accepted_seq: acceptedSeq, ack_submitted_seq: ackSubmittedSeq,
|
|
61
79
|
outstanding_frames: pending.size, outstanding_bytes: pendingBytes, max_outstanding_frames: maxOutstanding,
|
|
62
|
-
|
|
80
|
+
in_flight_frames: inFlight.size, max_in_flight_frames: config.maxInFlightFrames,
|
|
81
|
+
buffered_raw_bytes: pendingBytes, max_buffered_raw_bytes: maxBufferedBytes,
|
|
82
|
+
unapplied_raw_bytes: unappliedBytes, max_pending_bytes: config.maxPendingBytes,
|
|
63
83
|
received_ping_count: pingCount, written_pong_count: pongCount, pong_write_errors: pongErrors,
|
|
64
84
|
last_ping_received_at_ms: lastPingAt, last_pong_written_at_ms: lastPongWrittenAt,
|
|
65
|
-
max_pong_write_ms: maxPongWriteMs,
|
|
85
|
+
max_pong_write_ms: maxPongWriteMs, max_source_consumption_delay_ms: maxSourceConsumptionDelayMs,
|
|
66
86
|
overload_count: overloadCount, worker_event_loop_delay_p95_ms: delay.percentile(95) / 1e6,
|
|
67
87
|
worker_event_loop_delay_max_ms: delay.max / 1e6, worker_heap_used_bytes: process.memoryUsage().heapUsed,
|
|
68
88
|
...(raw ? { raw_log: raw.stats() } : {}),
|
|
@@ -70,6 +90,103 @@ function telemetry(force = false): void {
|
|
|
70
90
|
delay.reset();
|
|
71
91
|
}
|
|
72
92
|
|
|
93
|
+
function discardUnappliedMessages(): void {
|
|
94
|
+
pendingBytes -= unappliedBytes;
|
|
95
|
+
unappliedBytes = 0;
|
|
96
|
+
unappliedMessages = [];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function retainMessage(message: string): boolean {
|
|
100
|
+
if (stopped || overloaded) return false;
|
|
101
|
+
const bytes = Buffer.byteLength(message);
|
|
102
|
+
if (pendingBytes + bytes > config.maxPendingBytes) {
|
|
103
|
+
overloadCount++;
|
|
104
|
+
overloaded = true;
|
|
105
|
+
// This message has not been applied or ACKed. Retained completed frames
|
|
106
|
+
// survive; an incomplete replay can be retried from the buffered baseline.
|
|
107
|
+
discardUnappliedMessages();
|
|
108
|
+
client.disconnect();
|
|
109
|
+
enqueue({ type: 'close', connectionId: client.connectionId, info: {
|
|
110
|
+
code: 1013, reason: 'CCL_INGRESS_BACKLOG_LIMIT', wasClean: false,
|
|
111
|
+
} });
|
|
112
|
+
enqueue({ type: 'state', state: WsConnectionState.Reconnecting });
|
|
113
|
+
telemetry(true);
|
|
114
|
+
reconnectWhenDrained();
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
unappliedMessages.push(Buffer.from(message));
|
|
118
|
+
unappliedBytes += bytes;
|
|
119
|
+
pendingBytes += bytes;
|
|
120
|
+
maxBufferedBytes = Math.max(maxBufferedBytes, pendingBytes);
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Preserve lifecycle ordering across reconnects while old frames await Source. */
|
|
125
|
+
function enqueue(message: IngressEvent | CachedFrame): void {
|
|
126
|
+
deliveryQueue.push(message);
|
|
127
|
+
pump();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function materialize(cached: CachedFrame): WsInputFrame {
|
|
131
|
+
const events: Record<string, any>[] = [];
|
|
132
|
+
const emitted = new Set<string>();
|
|
133
|
+
for (const bytes of cached.messages) {
|
|
134
|
+
const message = JSON.parse(bytes.toString('utf8')) as GameSyncServerMessage;
|
|
135
|
+
if (message.type === 'game.sync.snapshot') {
|
|
136
|
+
deliveryBaseline = {
|
|
137
|
+
gameId: message.data.game_id, seq: message.data.seq, tick: message.data.tick,
|
|
138
|
+
locale: message.data.locale, state: message.data.state,
|
|
139
|
+
};
|
|
140
|
+
} else if (message.type === 'game.sync.update') {
|
|
141
|
+
if (!deliveryBaseline || message.data.game_id !== deliveryBaseline.gameId
|
|
142
|
+
|| message.data.seq !== deliveryBaseline.seq + 1) throw new Error('INGRESS_CACHE_SEQUENCE_INVALID');
|
|
143
|
+
deliveryBaseline = { ...deliveryBaseline, seq: message.data.seq, tick: message.data.tick,
|
|
144
|
+
state: applyGameSyncDelta(deliveryBaseline.state, message.data.state_delta) };
|
|
145
|
+
} else if (message.type === 'game.sync.resume') {
|
|
146
|
+
if (!deliveryBaseline || deliveryBaseline.seq !== message.data.to_seq) throw new Error('INGRESS_CACHE_RESUME_INVALID');
|
|
147
|
+
deliveryBaseline = { ...deliveryBaseline, tick: message.data.tick };
|
|
148
|
+
}
|
|
149
|
+
if (message.type === 'game.sync.snapshot' || message.type === 'game.sync.update') {
|
|
150
|
+
for (const event of message.data.events ?? []) {
|
|
151
|
+
const id = String(event.event_id);
|
|
152
|
+
if (cached.eventIds.has(id) && !emitted.has(id)) { emitted.add(id); events.push(event); }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (!deliveryBaseline) throw new Error('INGRESS_CACHE_BASELINE_MISSING');
|
|
157
|
+
return {
|
|
158
|
+
kind: 'state',
|
|
159
|
+
state: { ...structuredClone(deliveryBaseline.state), game_id: deliveryBaseline.gameId, tick: deliveryBaseline.tick },
|
|
160
|
+
events, meta: { ...cached.meta, ingress: {
|
|
161
|
+
...cached.meta.ingress!, workerPostedAtMs: Date.now(),
|
|
162
|
+
outstandingFrames: pending.size, outstandingBytes: pendingBytes,
|
|
163
|
+
} },
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function pump(): void {
|
|
168
|
+
if (stopped) return;
|
|
169
|
+
while (deliveryHead < deliveryQueue.length) {
|
|
170
|
+
const message = deliveryQueue[deliveryHead]!;
|
|
171
|
+
if (message.type === 'cached_frame') {
|
|
172
|
+
if (inFlight.size >= config.maxInFlightFrames) break;
|
|
173
|
+
const frame = materialize(message);
|
|
174
|
+
inFlight.set(message.meta.ackToken, message);
|
|
175
|
+
post({ type: 'frame', frame });
|
|
176
|
+
} else {
|
|
177
|
+
// In particular, do not change the Source connection id ahead of its
|
|
178
|
+
// pending frames; transport reconnect itself does not wait for this queue.
|
|
179
|
+
if (inFlight.size) break;
|
|
180
|
+
post(message);
|
|
181
|
+
}
|
|
182
|
+
deliveryQueue[deliveryHead++] = undefined;
|
|
183
|
+
}
|
|
184
|
+
if (deliveryHead > 1024 && deliveryHead * 2 > deliveryQueue.length) {
|
|
185
|
+
deliveryQueue = deliveryQueue.slice(deliveryHead);
|
|
186
|
+
deliveryHead = 0;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
73
190
|
function reconnectWhenDrained(): void {
|
|
74
191
|
if (!overloaded || pending.size || restartTimer || stopped) return;
|
|
75
192
|
restartTimer = setTimeout(() => {
|
|
@@ -80,57 +197,55 @@ function reconnectWhenDrained(): void {
|
|
|
80
197
|
}, 1000);
|
|
81
198
|
}
|
|
82
199
|
|
|
83
|
-
client.onStateChange(state =>
|
|
200
|
+
client.onStateChange(state => enqueue({ type: 'state', state }));
|
|
84
201
|
client.onConnectionOpened(connectionId => {
|
|
85
202
|
// Socket generation is deliberately separate from monotonically ordered source seq.
|
|
86
|
-
|
|
203
|
+
enqueue({ type: 'opened', connectionId });
|
|
87
204
|
});
|
|
88
205
|
client.onLiveness((_connection, atMs) => { lastLiveness = atMs; });
|
|
89
|
-
client.onDisconnect(info =>
|
|
206
|
+
client.onDisconnect(info => {
|
|
207
|
+
discardUnappliedMessages();
|
|
208
|
+
enqueue({ type: 'close', connectionId: client.connectionId, info });
|
|
209
|
+
});
|
|
90
210
|
const reportedProtocolErrors = new Set<string>();
|
|
91
211
|
client.onProtocolError(info => {
|
|
92
212
|
if (reportedProtocolErrors.has(info.reason)) return;
|
|
93
213
|
reportedProtocolErrors.add(info.reason);
|
|
94
|
-
|
|
214
|
+
enqueue({ type: 'protocol', info });
|
|
95
215
|
});
|
|
96
|
-
client.onRecoveryStarted(info =>
|
|
216
|
+
client.onRecoveryStarted(info => enqueue({ type: 'recovery', info }));
|
|
97
217
|
client.onInputFrame(frame => {
|
|
98
218
|
if (stopped || overloaded) return;
|
|
99
219
|
receivedFrames++;
|
|
100
220
|
lastReceivedSeq = Number(frame.meta.sourceSeq);
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
overloaded = true;
|
|
105
|
-
client.disconnect();
|
|
106
|
-
post({ type: 'close', connectionId: client.connectionId, info: {
|
|
107
|
-
code: 1013, reason: 'CCL_INGRESS_BACKLOG_LIMIT', wasClean: false,
|
|
108
|
-
} });
|
|
109
|
-
post({ type: 'state', state: WsConnectionState.Reconnecting });
|
|
110
|
-
telemetry(true);
|
|
111
|
-
reconnectWhenDrained();
|
|
112
|
-
return;
|
|
113
|
-
}
|
|
114
|
-
pending.set(frame.meta.ackToken, { seq: Number(frame.meta.sourceSeq), bytes, receivedAtMs: Date.parse(frame.meta.receivedAt) });
|
|
115
|
-
pendingBytes += bytes;
|
|
116
|
-
maxOutstanding = Math.max(maxOutstanding, pending.size);
|
|
117
|
-
frame.meta.ingress = {
|
|
118
|
-
...frame.meta.ingress!, workerPostedAtMs: Date.now(), outstandingFrames: pending.size, outstandingBytes: pendingBytes,
|
|
221
|
+
const cached: CachedFrame = {
|
|
222
|
+
type: 'cached_frame', messages: unappliedMessages, bytes: unappliedBytes,
|
|
223
|
+
meta: frame.meta, eventIds: new Set(frame.events.map(event => String(event.event_id))),
|
|
119
224
|
};
|
|
120
|
-
|
|
225
|
+
unappliedMessages = [];
|
|
226
|
+
unappliedBytes = 0;
|
|
227
|
+
pending.set(frame.meta.ackToken, cached);
|
|
228
|
+
maxOutstanding = Math.max(maxOutstanding, pending.size);
|
|
229
|
+
// The entire validated input is now retained independently of the Owner.
|
|
230
|
+
client.acknowledge(frame.meta.ackToken, true);
|
|
231
|
+
bufferedSeq = Math.max(bufferedSeq, Number(frame.meta.sourceSeq));
|
|
232
|
+
enqueue(cached);
|
|
121
233
|
});
|
|
122
234
|
|
|
123
235
|
const timer = setInterval(() => { reportedProtocolErrors.clear(); telemetry(); }, 5000);
|
|
124
236
|
timer.unref();
|
|
125
237
|
port.on('message', (message: IngressCommand) => {
|
|
126
238
|
if (stopped) return;
|
|
127
|
-
if (message.type === '
|
|
128
|
-
const entry =
|
|
239
|
+
if (message.type === 'consumed') {
|
|
240
|
+
const entry = inFlight.get(message.token);
|
|
129
241
|
if (!entry) return;
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
242
|
+
acceptedSeq = Math.max(acceptedSeq, Number(entry.meta.sourceSeq));
|
|
243
|
+
maxSourceConsumptionDelayMs = Math.max(maxSourceConsumptionDelayMs, Date.now() - Date.parse(entry.meta.receivedAt));
|
|
244
|
+
for (const [token, item] of inFlight) {
|
|
245
|
+
inFlight.delete(token); pending.delete(token); pendingBytes -= item.bytes;
|
|
246
|
+
if (token === message.token) break;
|
|
247
|
+
}
|
|
248
|
+
pump();
|
|
134
249
|
reconnectWhenDrained();
|
|
135
250
|
} else if (message.type === 'report') {
|
|
136
251
|
try { client.reportPerceptions(message.perceptions); } finally { post({ type: 'report_done' }); }
|
|
@@ -62,6 +62,7 @@ export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Recor
|
|
|
62
62
|
readonly mode: MailboxDeliveryMode,
|
|
63
63
|
private readonly consumerId = DEFAULT_EVENT_CONSUMER_ID,
|
|
64
64
|
private readonly maxItems = DEFAULT_RELAY_BATCH_SIZE,
|
|
65
|
+
private readonly onDelivered?: (eventIds: readonly string[]) => void,
|
|
65
66
|
) {}
|
|
66
67
|
|
|
67
68
|
handle(request: OwnerControlRequest): OwnerControlResponse | undefined {
|
|
@@ -123,18 +124,18 @@ export class MailboxRelayBroker<TPayload extends Record<string, unknown> = Recor
|
|
|
123
124
|
const claimToken = boundedString(request.claim_token, CLAIM_TOKEN_MAX_CHARS);
|
|
124
125
|
if (!claimToken) return { ok: false, error: 'invalid_mailbox_claim_token' };
|
|
125
126
|
if (request.type === 'mailbox_ack') {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
};
|
|
127
|
+
const result = this.repository.ackMailboxClaim({
|
|
128
|
+
ownerId: relayId,
|
|
129
|
+
claimToken,
|
|
130
|
+
acceptedAt: typeof request.accepted_at === 'string'
|
|
131
|
+
? request.accepted_at
|
|
132
|
+
: undefined,
|
|
133
|
+
acceptanceLevel: 'sink_emitted',
|
|
134
|
+
});
|
|
135
|
+
if (result.status !== 'claim_lost') {
|
|
136
|
+
try { this.onDelivered?.(result.eventIds); } catch { /* Best-effort display only. */ }
|
|
137
|
+
}
|
|
138
|
+
return { ok: true, type: 'mailbox_ack', result };
|
|
138
139
|
}
|
|
139
140
|
return {
|
|
140
141
|
ok: true,
|
|
@@ -5,9 +5,10 @@ import { gameSyncPerceptionReportMessage, type GameSyncPerceptionReport } from '
|
|
|
5
5
|
import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
|
|
6
6
|
import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
|
|
7
7
|
|
|
8
|
-
export interface ThreadedWsClientConfig extends Omit<WsClientConfig, 'rawMessageSink' | 'reconnectReady'> {
|
|
8
|
+
export interface ThreadedWsClientConfig extends Omit<WsClientConfig, 'rawMessageSink' | 'reconnectReady' | 'retainInputMessage' | 'discardUnappliedMessages'> {
|
|
9
9
|
rawLog?: GameSyncIngressConfig['rawLog'];
|
|
10
|
-
|
|
10
|
+
/** Complete-frame delivery credits. Raw reception/ACK continues when these are exhausted. */
|
|
11
|
+
maxInFlightFrames?: number;
|
|
11
12
|
maxPendingBytes?: number;
|
|
12
13
|
transportGeneration?: number;
|
|
13
14
|
}
|
|
@@ -32,8 +33,8 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
|
|
|
32
33
|
private startupTimer?: ReturnType<typeof setTimeout>;
|
|
33
34
|
|
|
34
35
|
constructor(private readonly config: ThreadedWsClientConfig) {
|
|
35
|
-
const frames = config.
|
|
36
|
-
const bytes = config.maxPendingBytes ??
|
|
36
|
+
const frames = config.maxInFlightFrames ?? 10;
|
|
37
|
+
const bytes = config.maxPendingBytes ?? 32 * 1024 * 1024;
|
|
37
38
|
if (!Number.isSafeInteger(frames) || frames < 1 || frames > 1000) throw new Error('GAME_SYNC_FRAME_LIMIT_INVALID');
|
|
38
39
|
if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > 32 * 1024 * 1024) throw new Error('GAME_SYNC_BYTE_LIMIT_INVALID');
|
|
39
40
|
this.committed = config.resumeState ? structuredClone(config.resumeState) : undefined;
|
|
@@ -56,8 +57,8 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
|
|
|
56
57
|
const config: GameSyncIngressConfig = {
|
|
57
58
|
url: this.config.url, apiKey: this.config.apiKey, resumeState: this.committed,
|
|
58
59
|
reconnectMaxMs: this.config.reconnectMaxMs, ackIntervalMs: this.config.ackIntervalMs,
|
|
59
|
-
|
|
60
|
-
maxPendingBytes: this.config.maxPendingBytes ??
|
|
60
|
+
maxInFlightFrames: this.config.maxInFlightFrames ?? 10,
|
|
61
|
+
maxPendingBytes: this.config.maxPendingBytes ?? 32 * 1024 * 1024,
|
|
61
62
|
rawLog: this.config.rawLog,
|
|
62
63
|
};
|
|
63
64
|
try {
|
|
@@ -130,7 +131,7 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
|
|
|
130
131
|
}
|
|
131
132
|
}
|
|
132
133
|
|
|
133
|
-
acknowledge(token: string,
|
|
134
|
+
acknowledge(token: string, _immediate = false): void {
|
|
134
135
|
const frame = this.pending.get(token);
|
|
135
136
|
if (this.stopped || !frame || frame.meta.connectionId !== this.connectionIdValue) return;
|
|
136
137
|
const seq = Number(frame.meta.sourceSeq);
|
|
@@ -138,8 +139,15 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
|
|
|
138
139
|
const { game_id: _gameId, tick: _tick, ...state } = frame.state;
|
|
139
140
|
this.committed = { gameId: frame.meta.gameId, seq, tick: frame.meta.domainTick, locale: frame.meta.locale ?? 'zh-CN', state: structuredClone(state) };
|
|
140
141
|
}
|
|
141
|
-
|
|
142
|
-
|
|
142
|
+
// A snapshot/resume barrier can share a seq with an earlier frame. Only
|
|
143
|
+
// consume the delivered prefix through this token, not later same-seq input.
|
|
144
|
+
for (const key of this.pending.keys()) {
|
|
145
|
+
this.pending.delete(key);
|
|
146
|
+
if (key === token) break;
|
|
147
|
+
}
|
|
148
|
+
// Source consumption releases delivery credits/cache, not the network ACK.
|
|
149
|
+
// Keep this baseline Source-owned for recovery if the ingress Worker is lost.
|
|
150
|
+
this.post({ type: 'consumed', token });
|
|
143
151
|
}
|
|
144
152
|
|
|
145
153
|
reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
|