Skip to content

Commit 0d44dad

Browse files
authored
Handle websocket pong in exec keepalive loop
1 parent 6e6fe18 commit 0d44dad

2 files changed

Lines changed: 16 additions & 4 deletions

File tree

‎src/exec.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,18 +83,26 @@ export class Exec {
8383
private setupPing(conn: WebSocket.WebSocket, pingIntervalMs: number): void {
8484
const socket = conn as WebSocket.WebSocket & {
8585
ping?: () => void;
86-
on?: (event: string, listener: () => void) => void;
86+
on?: (event: string, listener: (...args: unknown[]) => void) => void;
8787
};
8888
if (typeof socket.ping !== 'function') {
8989
return;
9090
}
9191

92+
let awaitingPong = false;
9293
const timer = setInterval(() => {
9394
if (conn.readyState === WebSocket.OPEN) {
94-
socket.ping!();
95+
if (!awaitingPong) {
96+
awaitingPong = true;
97+
socket.ping!();
98+
}
9599
}
96100
}, pingIntervalMs);
97101
const clearKeepAlive = () => clearInterval(timer);
102+
const onPong = () => {
103+
awaitingPong = false;
104+
};
105+
socket.on?.('pong', onPong);
98106
socket.on?.('close', clearKeepAlive);
99107
socket.on?.('error', clearKeepAlive);
100108
}

‎src/exec_test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ describe('Exec', () => {
160160

161161
it('should optionally send websocket pings', async () => {
162162
const pingIntervalMs = 5;
163-
const waitForPingsMs = 25;
163+
const waitForPingsMs = 20;
164164
const kc = new KubeConfig();
165165
const pingHandlers: Record<string, () => void> = {};
166166
let pingCount = 0;
@@ -183,7 +183,11 @@ describe('Exec', () => {
183183
});
184184
await setTimeoutPromise(waitForPingsMs);
185185

186-
ok(pingCount > 0);
186+
strictEqual(pingCount, 1);
187+
strictEqual(typeof pingHandlers.pong, 'function');
188+
pingHandlers.pong();
189+
await setTimeoutPromise(waitForPingsMs);
190+
ok(pingCount > 1);
187191

188192
strictEqual(typeof pingHandlers.close, 'function');
189193
pingHandlers.close();

0 commit comments

Comments
 (0)