feat(framework): net 收包超时看门狗(注入 Clock 可测)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-28 14:23:13 +08:00
co-authored by Claude Opus 4.8
parent 90843374f9
commit 08d41cdec1
2 changed files with 71 additions and 0 deletions
@@ -0,0 +1,23 @@
export interface Clock {
setTimeout(fn: () => void, ms: number): unknown;
clearTimeout(handle: unknown): void;
}
export const realClock: Clock = {
setTimeout: (fn, ms) => setTimeout(fn, ms),
clearTimeout: (h) => clearTimeout(h as any),
};
/** 收包超时看门狗。docs/protocol/01 §4.1:每收一包 feed() 重置;超时调 onTimeout。 */
export class HeartbeatWatchdog {
private handle: unknown = null;
constructor(private ms: number, private onTimeout: () => void, private clock: Clock = realClock) {}
feed(): void {
this.stop();
this.handle = this.clock.setTimeout(() => { this.handle = null; this.onTimeout(); }, this.ms);
}
stop(): void {
if (this.handle != null) { this.clock.clearTimeout(this.handle); this.handle = null; }
}
}