streaming: ensure close handler is called even when socket is closed by server

This commit is contained in:
Alex Gleason 2025-03-16 18:02:28 -05:00
parent f27609feb8
commit 497b02002e
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7

View file

@ -179,22 +179,31 @@ const streamingController: AppController = async (c) => {
limiter.set(ip, count + 1, { ttl: LIMITER_WINDOW }); limiter.set(ip, count + 1, { ttl: LIMITER_WINDOW });
if (count > LIMITER_LIMIT) { if (count > LIMITER_LIMIT) {
socket.close(1008, 'Rate limit exceeded'); closeSocket(1008, 'Rate limit exceeded');
return; return;
} }
} }
if (typeof e.data !== 'string') { if (typeof e.data !== 'string') {
socket.close(1003, 'Invalid message'); closeSocket(1003, 'Invalid message');
return; return;
} }
}; };
socket.onclose = () => { socket.onclose = () => {
handleClose();
};
function closeSocket(code?: number, reason?: string) {
socket.close(code, reason);
handleClose();
}
function handleClose(): void {
connections.delete(socket); connections.delete(socket);
streamingConnectionsGauge.set(connections.size); streamingConnectionsGauge.set(connections.size);
controller.abort(); controller.abort();
}; }
return response; return response;
}; };