Skip to content

Commit

Permalink
fix: Websocket proxy was not working
Browse files Browse the repository at this point in the history
  • Loading branch information
Corey Farrell committed Mar 30, 2024
1 parent f2f9202 commit bbdf304
Showing 1 changed file with 6 additions and 63 deletions.
69 changes: 6 additions & 63 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,65 +25,9 @@ function forwardWSHeaders(headers) {
return headers;
}

// Begin copied from fastify-http-proxy
function liftErrorCode(code) {
if (typeof code !== 'number') {
// Sometimes "close" event emits with a non-numeric value
return 1011;
}

switch (code) {
case 1004:
case 1005:
case 1006:
// ws module forbid those error codes usage, lift to "application level" (4xxx)
return 4000 + (code % 1000);
default:
return code;
}
}

function closeWebSocket(socket, code, reason) {
if (socket.readyState === WebSocket.OPEN) {
socket.close(liftErrorCode(code), reason);
}
}

function waitConnection(socket, write) {
if (socket.readyState === WebSocket.CONNECTING) {
socket.once('open', write);
} else {
write();
}
}

function proxyWebSockets(source, target) {
function close(code, reason) {
closeWebSocket(source, code, reason);
closeWebSocket(target, code, reason);
}

source.on('message', data => waitConnection(target, () => target.send(data)));
source.on('ping', data => waitConnection(target, () => target.ping(data)));
source.on('pong', data => waitConnection(target, () => target.pong(data)));
source.on('close', close);
source.on('error', error => close(1011, error.message));
source.on('unexpected-response', () => close(1011, 'unexpected response'));

// source WebSocket is already connected because it is created by ws server
target.on('message', data => source.send(data));
target.on('ping', data => source.ping(data));
target.on('pong', data => source.pong(data));
target.on('close', close);
target.on('error', error => close(1011, error.message));
target.on('unexpected-response', () => close(1011, 'unexpected response'));
}
// End copied from fastify-http-proxy

export class FastifyIntegrationDaemon {
constructor(fastifyOptions) {
this.daemon = fastify(fastifyOptions);
this.daemon.register(fastifyWebSocket);
}

serveProxy({prefix, upstream, onResponse}) {
Expand All @@ -97,13 +41,12 @@ export class FastifyIntegrationDaemon {
return this;
}

forwardWS({path, destination, forwardHeaders = forwardWSHeaders}) {
this.daemon.get(path, {websocket: true}, (connection, request) => {
const upstream = new WebSocket(destination, {
headers: forwardHeaders({...request.headers})
});

proxyWebSockets(connection.socket, upstream);
forwardWS({path, destination}) {
this.daemon.register(fastifyHttpProxy, {
websocket: true,
prefix: path,
upstream: destination,
wsUpstream: destination
});

return this;
Expand Down

0 comments on commit bbdf304

Please sign in to comment.