@myclaw163/clawclaw-cli 0.8.22 → 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.
|
@@ -73,13 +73,17 @@ Owner 的 GameSync WS、序号校验、delta 还原、ping/pong 和原始收包
|
|
|
73
73
|
|
|
74
74
|
Scheduler 每次重新调度会让出一个事件循环轮次,给待处理的传输/Worker消息进入Source的机会,避免连续微任务一直先执行计算。插件依赖、顺序提交、关键epoch保护和计算并发上限保持原有语义;不会承诺资源耗尽时无限吞吐。
|
|
75
75
|
|
|
76
|
-
Worker
|
|
76
|
+
收流 Worker 完成协议/序号校验,将原始消息成功保存到自己的内存缓存后即推进后端 ACK,不等待 Owner / Source 接纳或插件计算。缓存默认 **32 MiB 原始 JSON UTF-8 载荷**;对象、索引和少量完整状态开销另计。Source 消费后才释放对应缓存。Worker 按投递名额还原完整帧,默认最多十帧已投递但尚未消费;十帧是投递窗口,不再是断连条件,窗口用完后仍继续接收和 ACK。
|
|
77
|
+
|
|
78
|
+
网络恢复位置与 Source 消费位置分开管理:普通 socket 重连使用 Worker 已缓存确认的位置,未消费缓存保留;旧帧消费完后再向 Source 交付新连接的生命周期及恢复帧,保证状态、事件和连接顺序。Source 的 `acknowledgeGameSync` 调用在 threaded 模式下仅确认消费、释放名额,并保留 Source 基线用于 Worker 丢失后的恢复。inline 短命令客户端仍由调用方确认 ACK。
|
|
79
|
+
|
|
80
|
+
真正达到原始缓存字节上限时仍记录 `CCL_INGRESS_BACKLOG_LIMIT`(本地1013);未保存的消息不 ACK,保留已有缓存,排空后从已缓存确认的位置恢复。普通计算落后不会再因十帧限制触发此保护。未完成的网络重放不会暴露给 Source,恢复仍遵循 resume 校验或 snapshot fallback。缓存仅在内存,Worker/进程丢失可能丢失尚未消费的已 ACK 数据;不能承诺跨进程崩溃零丢失或超出后端恢复窗口的历史补回。
|
|
77
81
|
|
|
78
82
|
生产级复盘使用 `CLAWCLAW_OBSERVABILITY_LEVEL=full`,在Owner启动前设置。需要确认日志出现以下记录;仅看CLI版本号或导出目录名不能证明新实现已运行:
|
|
79
83
|
|
|
80
84
|
| 记录 | 关键字段和含义 |
|
|
81
85
|
| --- | --- |
|
|
82
|
-
| `runtime.ws.ingress_window` | 每5秒的Worker计数快照;`implementation=
|
|
86
|
+
| `runtime.ws.ingress_window` | 每5秒的Worker计数快照;`implementation=buffered_gamesync_v2`、package/Node版本、transport_generation、thread_id;`received_seq` / `buffered_seq` / `source_accepted_seq` / `ack_submitted_seq` 区分接收、缓存、Source消费和协议ACK提交;缓存帧数、原始字节及峰值、完整帧在途数/名额、未完成重放字节;`max_source_consumption_delay_ms` 是收到到消费的延迟,不是网络ACK延迟;另含过载次数和ping/pong、Worker事件循环指标 |
|
|
83
87
|
| `runtime.source.frame_admitted` | 每个接纳帧的epoch_seq/source_seq/domain_tick;socket接收、decode完成、Worker发出、Owner收到、Source开始和接纳完成的本机时间;decode、跨线程交付、Source排队和接纳耗时 |
|
|
84
88
|
| `runtime.view.ready` | 同epoch的intake/scheduler/finalize/total时间,以及`received_to_ready_ms`;full级别保留这条记录,不再视作数据库重复项过滤 |
|
|
85
89
|
| `runtime.diagnostics.sample` | Owner进程内存/保留记录数、CPU增量、事件循环利用率和延迟、GC次数/时间、各计算池状态 |
|
package/package.json
CHANGED
|
@@ -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' }); }
|
|
@@ -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 {
|
package/src/runtime/ws-client.ts
CHANGED
|
@@ -34,8 +34,12 @@ export interface WsClientConfig {
|
|
|
34
34
|
resumeState?: GameSyncResumeState;
|
|
35
35
|
maxPayloadBytes?: number;
|
|
36
36
|
handshakeTimeoutMs?: number;
|
|
37
|
-
/**
|
|
37
|
+
/** Optional reconnect gate for consumers that cannot retain input independently. */
|
|
38
38
|
reconnectReady?: () => boolean;
|
|
39
|
+
/** Optional ingress-owned raw cache. Reserve before applying/ACKing a valid message. */
|
|
40
|
+
retainInputMessage?: (raw: string) => boolean;
|
|
41
|
+
/** Release only an incomplete replay; already dispatched frames remain owned by the cache. */
|
|
42
|
+
discardUnappliedMessages?: () => void;
|
|
39
43
|
diagnostic?: (name: string, attributes: Record<string, unknown>, severity?: 'debug' | 'info' | 'warn') => void;
|
|
40
44
|
}
|
|
41
45
|
|
|
@@ -133,7 +137,7 @@ export class WsClient {
|
|
|
133
137
|
private connectionIdValue = '';
|
|
134
138
|
private lastPongAtValue: string | null = null;
|
|
135
139
|
private baseline: GameSyncResumeState | null;
|
|
136
|
-
/** Last baseline
|
|
140
|
+
/** Last baseline accepted by the consumer (Source or the ingress memory cache). */
|
|
137
141
|
private committedBaseline: GameSyncResumeState | null;
|
|
138
142
|
private recovering = false;
|
|
139
143
|
private awaitingSnapshot = false;
|
|
@@ -191,8 +195,8 @@ export class WsClient {
|
|
|
191
195
|
}
|
|
192
196
|
|
|
193
197
|
/**
|
|
194
|
-
* Advance the resume/ACK watermark
|
|
195
|
-
*
|
|
198
|
+
* Advance the resume/ACK watermark after the consumer has accepted the frame.
|
|
199
|
+
* The threaded consumer retains it in memory before ACK; this is not a disk flush.
|
|
196
200
|
*/
|
|
197
201
|
acknowledge(ackToken: string, immediate = false): void {
|
|
198
202
|
if (!ackToken) return;
|
|
@@ -236,12 +240,13 @@ export class WsClient {
|
|
|
236
240
|
|
|
237
241
|
private openSocket(): Promise<void> {
|
|
238
242
|
return new Promise((resolve, reject) => {
|
|
239
|
-
// Discard
|
|
240
|
-
//
|
|
243
|
+
// Discard input not accepted by the consumer. The threaded consumer
|
|
244
|
+
// keeps ACKed raw input across socket reconnects in its own memory cache.
|
|
241
245
|
this.baseline = this.committedBaseline
|
|
242
246
|
? structuredClone(this.committedBaseline)
|
|
243
247
|
: null;
|
|
244
248
|
this.clearPendingApplication();
|
|
249
|
+
this.config.discardUnappliedMessages?.();
|
|
245
250
|
this.connectionIdValue = randomUUID();
|
|
246
251
|
this.recovering = this.baseline !== null;
|
|
247
252
|
this.awaitingSnapshot = false;
|
|
@@ -301,7 +306,7 @@ export class WsClient {
|
|
|
301
306
|
return;
|
|
302
307
|
}
|
|
303
308
|
try {
|
|
304
|
-
this.handleMessage(parsed);
|
|
309
|
+
this.handleMessage(parsed, raw);
|
|
305
310
|
} catch (error) {
|
|
306
311
|
this.reportProtocolError('invalid_game_sync_message', {
|
|
307
312
|
error: error instanceof Error ? error.message : String(error),
|
|
@@ -329,9 +334,11 @@ export class WsClient {
|
|
|
329
334
|
});
|
|
330
335
|
}
|
|
331
336
|
|
|
332
|
-
private handleMessage(raw: unknown): void {
|
|
337
|
+
private handleMessage(raw: unknown, wire = JSON.stringify(raw)): void {
|
|
333
338
|
const message = parseGameSyncMessage(raw);
|
|
334
339
|
if (message.type === 'game.sync.snapshot') {
|
|
340
|
+
this.config.discardUnappliedMessages?.();
|
|
341
|
+
if (this.config.retainInputMessage?.(wire) === false) return;
|
|
335
342
|
const wasRecovering = this.recovering;
|
|
336
343
|
const previousGameId = this.baseline?.gameId;
|
|
337
344
|
if (previousGameId !== undefined && previousGameId !== message.data.game_id) {
|
|
@@ -387,6 +394,7 @@ export class WsClient {
|
|
|
387
394
|
this.requestResync('seq_gap', expectedSeq, message.data.seq);
|
|
388
395
|
return;
|
|
389
396
|
}
|
|
397
|
+
if (this.config.retainInputMessage?.(wire) === false) return;
|
|
390
398
|
this.baseline = {
|
|
391
399
|
...baseline,
|
|
392
400
|
seq: message.data.seq,
|
|
@@ -433,6 +441,7 @@ export class WsClient {
|
|
|
433
441
|
this.requestResync('invalid_resume', baseline ? baseline.seq + 1 : undefined, message.data.to_seq);
|
|
434
442
|
return;
|
|
435
443
|
}
|
|
444
|
+
if (this.config.retainInputMessage?.(wire) === false) return;
|
|
436
445
|
const events = this.recoveryEvents;
|
|
437
446
|
const replayedEventCount = events.length;
|
|
438
447
|
this.recoveryEvents = [];
|
|
@@ -473,6 +482,7 @@ export class WsClient {
|
|
|
473
482
|
|
|
474
483
|
private requestResync(reason: string, expectedSeq?: number, receivedSeq?: number): void {
|
|
475
484
|
if (this.awaitingSnapshot) return;
|
|
485
|
+
this.config.discardUnappliedMessages?.();
|
|
476
486
|
this.awaitingSnapshot = true;
|
|
477
487
|
this.recovering = true;
|
|
478
488
|
this.recoveryStartSeq = this.baseline?.seq ?? null;
|