feat: WebSocket upgrade path with lazy optional ws dependency
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+117
-3
No files matched your search
Generated
+35
-1
@@ -13,8 +13,10 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0"
|
||||
"vitest": "^2.0.0",
|
||||
"ws": "^8.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
@@ -782,6 +784,16 @@
|
||||
"undici-types": "~5.26.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/ws": {
|
||||
"version": "8.18.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
|
||||
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
"version": "2.1.9",
|
||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
|
||||
@@ -1459,6 +1471,28 @@
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.21.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
|
||||
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -15,9 +15,19 @@
|
||||
"dependencies": {
|
||||
"reflect-metadata": "0.2.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ws": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.19.0",
|
||||
"@types/ws": "^8.18.1",
|
||||
"typescript": "^5.5.0",
|
||||
"vitest": "^2.0.0",
|
||||
"@types/node": "^18.19.0"
|
||||
"ws": "^8.21.0"
|
||||
}
|
||||
}
|
||||
+34
-1
@@ -1,5 +1,6 @@
|
||||
import http from 'http';
|
||||
import { once } from 'events';
|
||||
import { channel } from './channel';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||
@@ -100,6 +101,37 @@ async function pipeStream(
|
||||
}
|
||||
}
|
||||
|
||||
function loadWss(): any | null {
|
||||
try { return require('ws').WebSocketServer; } catch { return null; }
|
||||
}
|
||||
|
||||
function attachWs(server: http.Server, wsRoutes: WsRouteDef[]): void {
|
||||
if (wsRoutes.length === 0) return;
|
||||
const WSS = loadWss();
|
||||
const wss = WSS ? new WSS({ noServer: true }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const path = (req.url ?? '/').split('?')[0];
|
||||
const route = wsRoutes.map((r) => ({ r, params: matchPattern(r.pattern, path) })).find((x) => x.params);
|
||||
if (!route) { socket.destroy(); return; }
|
||||
if (!wss) { socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.destroy(); return; }
|
||||
wss.handleUpgrade(req, socket, head, async (ws: any) => {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
ws.on('message', (d: Buffer) => inbound.push(d.toString()));
|
||||
ws.on('close', () => { inbound.close(); ac.abort(); });
|
||||
ws.on('error', (e: unknown) => inbound.fail(e));
|
||||
try {
|
||||
const out = await route.r.open({ params: route.params!, inbound, abort: ac.signal, req });
|
||||
for await (const m of out) ws.send(typeof m === 'string' ? m : JSON.stringify(m));
|
||||
ws.close();
|
||||
} catch {
|
||||
try { ws.close(1011); } catch { /* already closed */ }
|
||||
ac.abort();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus): http.Server {
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = req.url ?? '/';
|
||||
@@ -146,5 +178,6 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = []
|
||||
res.writeHead(r.status, r.headers);
|
||||
res.end(r.body);
|
||||
});
|
||||
return server; // Task 7 will insert `attachWs(server, wsRoutes);` before this line
|
||||
attachWs(server, wsRoutes);
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { channel } from '../src/channel';
|
||||
import { createHttpServer, type WsRouteDef } from '../src/http';
|
||||
|
||||
const url = (server: import('http').Server, path: string) => {
|
||||
const a = server.address();
|
||||
if (a && typeof a === 'object') return `ws://127.0.0.1:${a.port}${path}`;
|
||||
throw new Error('no address');
|
||||
};
|
||||
|
||||
describe('ws upgrade', () => {
|
||||
it('echoes inbound to outbound and aborts on close', async () => {
|
||||
let aborted = false;
|
||||
const wsRoutes: WsRouteDef[] = [{
|
||||
pattern: '/echo',
|
||||
open: async ({ inbound, abort }) => {
|
||||
abort.addEventListener('abort', () => { aborted = true; });
|
||||
const out = channel<string>();
|
||||
(async () => { for await (const m of inbound) out.push(`echo:${m}`); out.close(); })();
|
||||
return out;
|
||||
},
|
||||
}];
|
||||
const server = createHttpServer([], wsRoutes);
|
||||
await new Promise<void>((r) => server.listen(0, r));
|
||||
|
||||
const client = new WebSocket(url(server, '/echo'));
|
||||
await new Promise((r) => client.on('open', r));
|
||||
const got = new Promise<string>((r) => client.on('message', (d) => r(d.toString())));
|
||||
client.send('hi');
|
||||
expect(await got).toBe('echo:hi');
|
||||
client.close();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
expect(aborted).toBe(true);
|
||||
server.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user