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 });
if (count > LIMITER_LIMIT) {
socket.close(1008, 'Rate limit exceeded');
closeSocket(1008, 'Rate limit exceeded');
return;
}
}
if (typeof e.data !== 'string') {
socket.close(1003, 'Invalid message');
closeSocket(1003, 'Invalid message');
return;
}
};
socket.onclose = () => {
handleClose();
};
function closeSocket(code?: number, reason?: string) {
socket.close(code, reason);
handleClose();
}
function handleClose(): void {
connections.delete(socket);
streamingConnectionsGauge.set(connections.size);
controller.abort();
};
}
return response;
};