Step 3 runtime-agnostic: Bun adapter + WebSocket. - @green-tea/core/bun serveBun (HTTP+SSE+WS on Bun), real bun test - reuses the neutral WsSocket capability + app.upgrade (zero core changes) - open-deferred WsSocket build via ws.data; binary parity + ws error handler
This commit is contained in:
8 files changed
+230
-7
No files matched your search
@@ -12,6 +12,7 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
|||||||
same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API
|
same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API
|
||||||
(WebSocket and mesh remain Node-only).
|
(WebSocket and mesh remain Node-only).
|
||||||
- **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno.
|
- **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno.
|
||||||
|
- **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno.
|
||||||
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
|
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -46,6 +46,16 @@
|
|||||||
"types": "./dist/deno.d.ts",
|
"types": "./dist/deno.d.ts",
|
||||||
"default": "./dist/deno.js"
|
"default": "./dist/deno.js"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"./bun": {
|
||||||
|
"import": {
|
||||||
|
"types": "./dist/bun.d.mts",
|
||||||
|
"default": "./dist/bun.mjs"
|
||||||
|
},
|
||||||
|
"require": {
|
||||||
|
"types": "./dist/bun.d.ts",
|
||||||
|
"default": "./dist/bun.js"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
@@ -60,6 +70,7 @@
|
|||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:dev": "vitest",
|
"test:dev": "vitest",
|
||||||
"test:deno": "deno test --allow-net --allow-read --no-check test/deno/",
|
"test:deno": "deno test --allow-net --allow-read --no-check test/deno/",
|
||||||
|
"test:bun": "bun test test/bun/",
|
||||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||||
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
|
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
|
||||||
"lint": "eslint src",
|
"lint": "eslint src",
|
||||||
|
|||||||
+139
@@ -0,0 +1,139 @@
|
|||||||
|
import { channel } from './channel';
|
||||||
|
import type { Channel } from './channel';
|
||||||
|
import type { App } from './app/types';
|
||||||
|
import type { WsSocket, WsRequest } from './http/ws-core';
|
||||||
|
|
||||||
|
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
|
||||||
|
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
|
||||||
|
interface BunServerWebSocket {
|
||||||
|
data: unknown;
|
||||||
|
readyState: number;
|
||||||
|
send(data: string): number;
|
||||||
|
close(code?: number, reason?: string): void;
|
||||||
|
terminate?(): void;
|
||||||
|
}
|
||||||
|
interface BunWebSocketHandler {
|
||||||
|
open?(ws: BunServerWebSocket): void;
|
||||||
|
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||||
|
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||||
|
error?(ws: BunServerWebSocket, error?: unknown): void;
|
||||||
|
}
|
||||||
|
interface BunServer {
|
||||||
|
port: number;
|
||||||
|
stop(closeActiveConnections?: boolean): void;
|
||||||
|
upgrade(request: Request, options?: { data?: unknown; headers?: Record<string, string> }): boolean;
|
||||||
|
requestIP(request: Request): { address: string; family: string; port: number } | null;
|
||||||
|
}
|
||||||
|
interface BunServeOptions {
|
||||||
|
port?: number;
|
||||||
|
hostname?: string;
|
||||||
|
fetch(request: Request, server: BunServer): Response | Promise<Response> | undefined;
|
||||||
|
websocket?: BunWebSocketHandler;
|
||||||
|
}
|
||||||
|
type BunServeShortOptions = { port?: number; hostname?: string };
|
||||||
|
declare const Bun: { serve(options: BunServeOptions): BunServer };
|
||||||
|
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
|
||||||
|
/** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */
|
||||||
|
interface BunConnData {
|
||||||
|
wsReq: WsRequest;
|
||||||
|
inbound: Channel<unknown>;
|
||||||
|
ac: AbortController;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Builds a neutral WsRequest from a Bun request + server (for the client IP). */
|
||||||
|
function toWsRequest(request: Request, server: BunServer): WsRequest {
|
||||||
|
const url = new URL(request.url);
|
||||||
|
const headers: Record<string, string> = {};
|
||||||
|
request.headers.forEach((v, k) => {
|
||||||
|
headers[k] = v;
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
url: url.pathname + url.search,
|
||||||
|
headers,
|
||||||
|
protocol: url.protocol === 'https:' ? 'https' : 'http',
|
||||||
|
ip: server.requestIP(request)?.address ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wraps a Bun ServerWebSocket (+ its stashed channel/abort) as a neutral WsSocket. */
|
||||||
|
function bunSocket(ws: BunServerWebSocket): WsSocket {
|
||||||
|
const { inbound, ac } = ws.data as BunConnData;
|
||||||
|
return {
|
||||||
|
inbound,
|
||||||
|
abort: ac.signal,
|
||||||
|
get isOpen() {
|
||||||
|
return ws.readyState === 1; // 1 = OPEN
|
||||||
|
},
|
||||||
|
send: (data) => {
|
||||||
|
ws.send(data);
|
||||||
|
},
|
||||||
|
close: (code, reason) => {
|
||||||
|
try {
|
||||||
|
ws.close(code, reason);
|
||||||
|
} catch {
|
||||||
|
/* already closed */
|
||||||
|
}
|
||||||
|
},
|
||||||
|
terminate: () => {
|
||||||
|
try {
|
||||||
|
(ws.terminate ?? ws.close).call(ws);
|
||||||
|
} catch {
|
||||||
|
/* already closed */
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serve a Green Tea app on Bun: HTTP + SSE via app.fetch, WebSocket via Bun's server-level
|
||||||
|
* websocket handler. The ServerWebSocket only exists in open(), so per-connection state
|
||||||
|
* (inbound channel, abort, WsRequest) is stashed on ws.data during the upgrade.
|
||||||
|
*/
|
||||||
|
export function serveBun(app: App, options?: BunServeShortOptions): BunServer {
|
||||||
|
return Bun.serve({
|
||||||
|
...options,
|
||||||
|
fetch(request, server) {
|
||||||
|
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||||
|
const inbound = channel();
|
||||||
|
const ac = new AbortController();
|
||||||
|
const data: BunConnData = { wsReq: toWsRequest(request, server), inbound, ac };
|
||||||
|
if (server.upgrade(request, { data })) return undefined;
|
||||||
|
return new Response('WebSocket upgrade failed', { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return app.fetch(request);
|
||||||
|
},
|
||||||
|
websocket: {
|
||||||
|
open(ws) {
|
||||||
|
const { wsReq } = ws.data as BunConnData;
|
||||||
|
// fire-and-forget: app.upgrade can reject before runWsConnection's try/catch
|
||||||
|
// (mesh-before-listen, provider boot failure); guard it or an uncaught rejection
|
||||||
|
// could crash the Bun process.
|
||||||
|
void app.upgrade(wsReq, bunSocket(ws)).catch(() => {
|
||||||
|
try {
|
||||||
|
ws.close(1011, 'internal error');
|
||||||
|
} catch {
|
||||||
|
/* already closed */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
message(ws, message) {
|
||||||
|
const { inbound } = ws.data as BunConnData;
|
||||||
|
// decode binary to UTF-8 to match Node's Buffer.toString() (cross-adapter parity)
|
||||||
|
inbound.push(typeof message === 'string' ? message : decoder.decode(message));
|
||||||
|
},
|
||||||
|
close(ws) {
|
||||||
|
const { inbound, ac } = ws.data as BunConnData;
|
||||||
|
inbound.close();
|
||||||
|
ac.abort();
|
||||||
|
},
|
||||||
|
error(ws) {
|
||||||
|
const { inbound, ac } = ws.data as BunConnData;
|
||||||
|
inbound.fail(new Error('websocket error'));
|
||||||
|
ac.abort();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
// Real Bun integration test for serveBun: boots an app under the actual Bun runtime
|
||||||
|
// and round-trips both HTTP (app.fetch) and WebSocket (Bun's server-level websocket
|
||||||
|
// handler -> app.upgrade).
|
||||||
|
//
|
||||||
|
// Run with: npm run test:bun (or: bun test test/bun/)
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { test, expect } from 'bun:test';
|
||||||
|
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index.ts';
|
||||||
|
import { serveBun } from '../../src/bun.ts';
|
||||||
|
|
||||||
|
@Route('/rt')
|
||||||
|
class Rt {
|
||||||
|
@Get('/hello')
|
||||||
|
hello() {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
@Ws('/echo')
|
||||||
|
echo(@ctx() { inbound }: any) {
|
||||||
|
return (async function* () {
|
||||||
|
for await (const msg of inbound) yield `echo:${msg}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
test('serveBun: HTTP + WebSocket round-trip', async () => {
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
const server = serveBun(app, { port: 0 });
|
||||||
|
const port = server.port;
|
||||||
|
try {
|
||||||
|
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||||
|
expect(httpRes.status).toBe(200);
|
||||||
|
expect((await httpRes.json()).ok).toBe(true);
|
||||||
|
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
|
||||||
|
const got = await new Promise<string>((resolve, reject) => {
|
||||||
|
ws.onopen = () => ws.send('hi');
|
||||||
|
ws.onmessage = (e) => {
|
||||||
|
resolve(String(e.data));
|
||||||
|
ws.close();
|
||||||
|
};
|
||||||
|
ws.onerror = () => reject(new Error('ws error'));
|
||||||
|
});
|
||||||
|
expect(got).toBe('echo:hi');
|
||||||
|
} finally {
|
||||||
|
server.stop(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
+1
-1
@@ -15,5 +15,5 @@
|
|||||||
"forceConsistentCasingInFileNames": true
|
"forceConsistentCasingInFileNames": true
|
||||||
},
|
},
|
||||||
"include": ["src", "test", "example"],
|
"include": ["src", "test", "example"],
|
||||||
"exclude": ["test/deno"]
|
"exclude": ["test/deno", "test/bun"]
|
||||||
}
|
}
|
||||||
+1
-1
@@ -4,7 +4,7 @@ import { defineConfig } from 'tsup';
|
|||||||
// tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy')
|
// tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy')
|
||||||
// (optional peer deps) keep working there. reflect-metadata and the peer deps stay external.
|
// (optional peer deps) keep working there. reflect-metadata and the peer deps stay external.
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
entry: ['src/index.ts', 'src/deno.ts'],
|
entry: ['src/index.ts', 'src/deno.ts', 'src/bun.ts'],
|
||||||
format: ['cjs', 'esm'],
|
format: ['cjs', 'esm'],
|
||||||
dts: true,
|
dts: true,
|
||||||
clean: true,
|
clean: true,
|
||||||
|
|||||||
+1
-1
@@ -7,6 +7,6 @@ export default defineConfig({
|
|||||||
include: ['test/**/*.test.ts'],
|
include: ['test/**/*.test.ts'],
|
||||||
// test/deno/** holds Deno.test files run separately via `npm run test:deno`;
|
// test/deno/** holds Deno.test files run separately via `npm run test:deno`;
|
||||||
// they use `npm:`/`jsr:` specifiers vitest can't resolve.
|
// they use `npm:`/`jsr:` specifiers vitest can't resolve.
|
||||||
exclude: [...configDefaults.exclude, 'test/deno/**'],
|
exclude: [...configDefaults.exclude, 'test/deno/**', 'test/bun/**'],
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -25,9 +25,9 @@ export default { fetch: app.fetch };
|
|||||||
**Node is the reference implementation** — every runtime returns the same status, headers,
|
**Node is the reference implementation** — every runtime returns the same status, headers,
|
||||||
and body for the same request (enforced by a parity test suite).
|
and body for the same request (enforced by a parity test suite).
|
||||||
|
|
||||||
**Not yet on Bun/edge runtimes:** WebSocket (`@Ws`) and mesh — still Node-only there; Deno now
|
**Not yet on edge runtimes:** WebSocket (`@Ws`) and mesh — still Node-only there; Deno and Bun
|
||||||
has WebSocket support via `serveDeno` (see below). `app.listen()` and TLS remain Node-only; on
|
now have full WebSocket support via `serveDeno` and `serveBun` (see below). `app.listen()` and
|
||||||
Deno/Bun/edge you get `app.fetch`.
|
TLS remain Node-only; on Deno/Bun/edge you get `app.fetch`.
|
||||||
|
|
||||||
**Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full
|
**Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full
|
||||||
before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on
|
before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on
|
||||||
@@ -54,7 +54,30 @@ run on Node. Behaviour matches the Node reference.
|
|||||||
|
|
||||||
**Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses.
|
**Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses.
|
||||||
Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `send`,
|
Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `send`,
|
||||||
`close`, `terminate`) and drive the graph — this is how Bun and edge support will land.
|
`close`, `terminate`) and drive the graph — `serveBun` builds on the same primitive
|
||||||
|
(see below), and this is how future edge support will land.
|
||||||
|
|
||||||
**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you
|
**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you
|
||||||
get `app.fetch` + `serveDeno`.
|
get `app.fetch` + `serveDeno`.
|
||||||
|
|
||||||
|
## WebSocket on Bun
|
||||||
|
|
||||||
|
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
|
||||||
|
upgrade, so Bun gets a dedicated adapter at `@green-tea/core/bun`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { createApp } from '@green-tea/core';
|
||||||
|
import { serveBun } from '@green-tea/core/bun';
|
||||||
|
|
||||||
|
const app = createApp({ modules: [ChatModule] });
|
||||||
|
|
||||||
|
// HTTP + SSE via app.fetch, WebSocket via Bun's server-level handler — one call:
|
||||||
|
serveBun(app, { port: 8000 });
|
||||||
|
```
|
||||||
|
|
||||||
|
`serveBun` routes normal requests through `app.fetch` and WebSocket upgrades through
|
||||||
|
`app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you
|
||||||
|
run on Node and Deno. Behaviour matches the Node reference.
|
||||||
|
|
||||||
|
**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Bun you
|
||||||
|
get `app.fetch` + `serveBun`.
|
||||||
Reference in new issue
Block a user