feat(framework): net 收包超时看门狗(注入 Clock 可测)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user