Step 2 runtime-agnostic: Deno adapter + WebSocket capability. - Neutral WS core (ws-core.ts) behind a WsSocket capability - Node adapter rebuilt over it (behaviour byte-identical) - app.upgrade(request, socket) neutral primitive - @green-tea/core/deno serveDeno (HTTP+SSE+WS on Deno), real deno test - docs + CHANGELOG
This commit is contained in:
17 files changed
+697
-108
No files matched your search
@@ -11,10 +11,18 @@ green-tea uses calendar versioning: `YY.MM.PATCH`.
|
||||
- **`app.fetch(request): Promise<Response>`** — a Web-Standards handler so the
|
||||
same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API
|
||||
(WebSocket and mesh remain Node-only).
|
||||
- **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on 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`).
|
||||
|
||||
### Changed
|
||||
- App-scope providers now boot exactly once (memoized): a second `app.listen()`
|
||||
call no longer re-runs provider factories or their side effects.
|
||||
- **`WsOpenCtx.req`** (available in `@Ws`/`@Sse` handlers) is now a neutral
|
||||
`WsRequest` (`{ url, headers, protocol, ip }`) instead of the Node
|
||||
`http.IncomingMessage`, so it works the same across Node and Deno. Node-only
|
||||
fields such as `req.socket` / `req.rawHeaders` are no longer available on
|
||||
`ctx.req`; use `ctx.protocol` / `ctx.ip` / `ctx.query` / `ctx.headers`
|
||||
instead — all still provided.
|
||||
|
||||
## [26.7.0-beta.0] - 2026-07-07
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"lib": ["deno.window", "deno.ns"]
|
||||
},
|
||||
"unstable": ["sloppy-imports"],
|
||||
"imports": {
|
||||
"http": "node:http",
|
||||
"https": "node:https",
|
||||
"crypto": "node:crypto",
|
||||
"events": "node:events",
|
||||
"stream": "node:stream"
|
||||
},
|
||||
"lint": { "exclude": ["dist", "node_modules"] }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"version": "5",
|
||||
"specifiers": {
|
||||
"jsr:@std/assert@*": "1.0.19",
|
||||
"jsr:@std/internal@^1.0.12": "1.0.14"
|
||||
},
|
||||
"jsr": {
|
||||
"@std/assert@1.0.19": {
|
||||
"integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
|
||||
"dependencies": [
|
||||
"jsr:@std/internal"
|
||||
]
|
||||
},
|
||||
"@std/internal@1.0.14": {
|
||||
"integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"packageJson": {
|
||||
"dependencies": [
|
||||
"npm:@eslint/js@^9.39.4",
|
||||
"npm:@nestjs/common@^11.1.27",
|
||||
"npm:@nestjs/core@^11.1.27",
|
||||
"npm:@nestjs/platform-express@^11.1.27",
|
||||
"npm:@nestjs/platform-fastify@^11.1.27",
|
||||
"npm:@stylistic/eslint-plugin@^5.10.0",
|
||||
"npm:@types/autocannon@^7.12.7",
|
||||
"npm:@types/busboy@^1.5.4",
|
||||
"npm:@types/express@^5.0.6",
|
||||
"npm:@types/node@^18.19.0",
|
||||
"npm:@types/ws@^8.18.1",
|
||||
"npm:autocannon@8",
|
||||
"npm:busboy@^1.6.0",
|
||||
"npm:cognitive-complexity-ts@~0.8.2",
|
||||
"npm:eslint@^9.39.4",
|
||||
"npm:express@^5.2.1",
|
||||
"npm:fastify@^5.10.0",
|
||||
"npm:graphql@^16.9.0",
|
||||
"npm:prettier@^3.9.4",
|
||||
"npm:reflect-metadata@0.2.2",
|
||||
"npm:rxjs@^7.8.2",
|
||||
"npm:tsup@^8.5.1",
|
||||
"npm:tsx@^4.23.0",
|
||||
"npm:typescript-eslint@^8.63.0",
|
||||
"npm:typescript@^5.5.0",
|
||||
"npm:vitest@2",
|
||||
"npm:ws@^8.21.0"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,16 @@
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"./deno": {
|
||||
"import": {
|
||||
"types": "./dist/deno.d.mts",
|
||||
"default": "./dist/deno.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/deno.d.ts",
|
||||
"default": "./dist/deno.js"
|
||||
}
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
@@ -49,6 +59,7 @@
|
||||
"build": "tsup",
|
||||
"test": "vitest run",
|
||||
"test:dev": "vitest",
|
||||
"test:deno": "deno test --allow-net --allow-read --no-check test/deno/",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"typecheck:bench": "tsc --noEmit -p bench/tsconfig.json",
|
||||
"lint": "eslint src",
|
||||
|
||||
+49
-3
@@ -7,6 +7,7 @@ import { runPipeline, PipelineStep } from '../pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||
import type { HttpOptions } from '../http';
|
||||
import { buildFetch } from '../http/web';
|
||||
import { matchWsRoute, runWsConnection, type WsRequest, type WsSocket } from '../http/ws-core';
|
||||
import { isAsyncIterable } from '../channel';
|
||||
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
||||
@@ -147,6 +148,13 @@ export function createApp(opts: {
|
||||
fetchOpts,
|
||||
bootAppProviders,
|
||||
);
|
||||
const upgradeFn = buildAppUpgrade(
|
||||
() => booted,
|
||||
routePlans,
|
||||
{ providedSeed, planSteps, bus, onError: opts.onError },
|
||||
streams,
|
||||
bootAppProviders,
|
||||
);
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
|
||||
@@ -203,6 +211,7 @@ export function createApp(opts: {
|
||||
listen,
|
||||
close,
|
||||
fetch: fetchFn,
|
||||
upgrade: upgradeFn,
|
||||
inspect,
|
||||
graph,
|
||||
toMermaid: () => toMermaid(graph()),
|
||||
@@ -643,6 +652,42 @@ function buildAppFetch(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds `app.upgrade`: the neutral WebSocket entry over the same route table `listen()` uses, so
|
||||
* Deno/Bun/edge adapters can drive ws connections without ever calling `listen()`. Node keeps its own
|
||||
* `server.on('upgrade')` path (see `attachWs`) and never calls this.
|
||||
* Mirrors {@link buildAppFetch}'s finalize guard exactly: non-mesh apps finalize eagerly, so
|
||||
* `getBooted()` is already `true` and the ws route table builds on the first call; mesh apps defer
|
||||
* finalize to `listen()`, so this throws until `listen()` finalizes, then works from the next call on.
|
||||
*/
|
||||
function buildAppUpgrade(
|
||||
getBooted: () => boolean,
|
||||
routePlans: RoutePlan[],
|
||||
deps: PipelineDeps,
|
||||
streams: Set<() => void>,
|
||||
ensureBooted: () => Promise<void>,
|
||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||
let wsRoutes: WsRouteDef[] | undefined;
|
||||
|
||||
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
|
||||
if (!wsRoutes) {
|
||||
if (!getBooted()) throw new Error('upgrade() unavailable before listen() for mesh apps');
|
||||
wsRoutes = buildWsRoutes(routePlans, deps);
|
||||
}
|
||||
|
||||
await ensureBooted(); // idempotent: no-op if listen() already booted the providers
|
||||
const path = request.url.split('?')[0];
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
if (!route) {
|
||||
socket.close(1008, 'no matching ws route');
|
||||
return;
|
||||
}
|
||||
|
||||
await runWsConnection(socket, request, route, deps.bus, streams);
|
||||
};
|
||||
}
|
||||
|
||||
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
|
||||
function devGraphRoute(graph: () => GraphView): RouteDef {
|
||||
return {
|
||||
@@ -683,7 +728,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
|
||||
pattern: plan.pattern,
|
||||
open: async ({ params, inbound, abort, req }) => {
|
||||
const provided = await providedSeed(plan);
|
||||
// ws upgrades come in on the raw Node req; trustProxy derivation for ws is out of scope here
|
||||
// ws upgrades carry the neutral WsRequest (protocol/ip pre-derived by the runtime adapter);
|
||||
// trustProxy derivation for ws is out of scope here
|
||||
// context is intentionally `any`: each step merges arbitrary keys into it
|
||||
let context: any = {
|
||||
...provided,
|
||||
@@ -694,8 +740,8 @@ function buildWsRoutes(routePlans: RoutePlan[], deps: PipelineDeps): WsRouteDef[
|
||||
headers: req.headers,
|
||||
inbound,
|
||||
abort,
|
||||
protocol: (req.socket as any).encrypted ? 'https' : 'http',
|
||||
ip: req.socket.remoteAddress ?? '',
|
||||
protocol: req.protocol,
|
||||
ip: req.ip,
|
||||
};
|
||||
|
||||
for (const step of planSteps(plan)) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { GraphView } from '../graph-viz';
|
||||
import type { HttpMethod, Transport } from '../metadata';
|
||||
import type { ArgSpec } from '../params';
|
||||
import type { OpenApiDoc, OpenApiInfo } from '../openapi';
|
||||
import type { WsRequest, WsSocket } from '../http/ws-core';
|
||||
import { JsonTransformer } from '../transformers';
|
||||
|
||||
/** One entry in an {@link App.inspect} listing: a provider, step or handler and where it came from. */
|
||||
@@ -37,6 +38,8 @@ export interface App {
|
||||
close(): Promise<void>;
|
||||
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
|
||||
fetch(request: Request): Promise<Response>;
|
||||
/** Run a WebSocket upgrade through the graph using an adapter-provided socket (Deno/Bun/edge). Node uses its own listener path. */
|
||||
upgrade(request: WsRequest, socket: WsSocket): Promise<void>;
|
||||
inspect(routePath: string): InspectLine[];
|
||||
graph(): GraphView;
|
||||
toMermaid(): string;
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import { channel } from './channel';
|
||||
import type { App } from './app/types';
|
||||
import type { WsSocket, WsRequest } from './http/ws-core';
|
||||
|
||||
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x)
|
||||
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use
|
||||
// (both the instance interface and the `OPEN` static, mirroring the real WebSocket).
|
||||
interface WebSocketEventMap {
|
||||
message: { data: string | ArrayBuffer };
|
||||
close: object;
|
||||
error: object;
|
||||
}
|
||||
interface WebSocket {
|
||||
readonly readyState: number;
|
||||
binaryType: string;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (event: WebSocketEventMap[K]) => void): void;
|
||||
}
|
||||
declare const WebSocket: { readonly OPEN: number };
|
||||
|
||||
// Minimal ambient for the Deno globals we use — avoids a @types/deno devDep.
|
||||
// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call.
|
||||
interface DenoServeOptions {
|
||||
port?: number;
|
||||
hostname?: string;
|
||||
signal?: AbortSignal;
|
||||
onListen?: (addr: { hostname: string; port: number }) => void;
|
||||
}
|
||||
interface DenoServeHandlerInfo {
|
||||
remoteAddr: { hostname: string; port: number; transport: string };
|
||||
}
|
||||
interface DenoHttpServer {
|
||||
finished: Promise<void>;
|
||||
shutdown(): Promise<void>;
|
||||
}
|
||||
type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise<Response>;
|
||||
declare const Deno: {
|
||||
serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer;
|
||||
upgradeWebSocket(request: Request): { socket: WebSocket; response: Response };
|
||||
};
|
||||
|
||||
/** Builds a neutral WsRequest from a Deno upgrade Request + connection info. */
|
||||
function toWsRequest(request: Request, info: DenoServeHandlerInfo): 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: info.remoteAddr.hostname,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wraps a Deno/web WebSocket as a neutral WsSocket. */
|
||||
function denoSocket(ws: WebSocket): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
ws.binaryType = 'arraybuffer';
|
||||
const decoder = new TextDecoder();
|
||||
ws.addEventListener('message', (e) => {
|
||||
const data = e.data;
|
||||
inbound.push(typeof data === 'string' ? data : decoder.decode(data as ArrayBuffer));
|
||||
});
|
||||
ws.addEventListener('close', () => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
});
|
||||
ws.addEventListener('error', () => {
|
||||
inbound.fail(new Error('websocket error'));
|
||||
ac.abort();
|
||||
});
|
||||
return {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
get isOpen() {
|
||||
return ws.readyState === WebSocket.OPEN;
|
||||
},
|
||||
send: (data) => ws.send(data),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
ws.close(code, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
terminate: () => {
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket.
|
||||
* WebSocket messages flow through app.upgrade over the shared neutral core.
|
||||
*/
|
||||
export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer {
|
||||
return Deno.serve(options ?? {}, (request, info) => {
|
||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||
const { socket, response } = Deno.upgradeWebSocket(request);
|
||||
// Fire-and-forget: the upgrade response must be returned synchronously while
|
||||
// the graph runs. app.upgrade can reject BEFORE runWsConnection's own try/catch
|
||||
// (mesh-before-listen throw, or a provider boot failure), so guard the call here —
|
||||
// an uncaught rejection would be fatal on Deno and crash the whole server.
|
||||
void app.upgrade(toWsRequest(request, info), denoSocket(socket)).catch(() => {
|
||||
try {
|
||||
socket.close(1011, 'internal error');
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
return app.fetch(request);
|
||||
});
|
||||
}
|
||||
+3
-2
@@ -3,6 +3,7 @@ import type { Transport } from '../metadata';
|
||||
import type { PipelineResult } from '../pipeline';
|
||||
import type { ErrorRenderer } from '../transformers';
|
||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||
import type { WsRequest } from './ws-core';
|
||||
|
||||
/** Per-request size and timeout ceilings applied by the server. */
|
||||
export interface RequestLimits {
|
||||
@@ -54,12 +55,12 @@ export interface MatchedRoute {
|
||||
def: RouteDef;
|
||||
}
|
||||
|
||||
/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and raw request. */
|
||||
/** Context passed to a WebSocket route's `open`: path params, inbound message stream, abort signal, and neutral request. */
|
||||
export interface WsOpenCtx {
|
||||
params: Record<string, string>;
|
||||
inbound: AsyncIterable<unknown>;
|
||||
abort: AbortSignal;
|
||||
req: http.IncomingMessage;
|
||||
req: WsRequest;
|
||||
}
|
||||
|
||||
/** A registered WebSocket route: path pattern and an `open` that returns the outbound message stream. */
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { isHttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef } from './types';
|
||||
|
||||
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
|
||||
export interface WsRequest {
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
protocol: 'http' | 'https';
|
||||
ip: string;
|
||||
}
|
||||
|
||||
/** Capability an adapter builds from its runtime socket. The neutral core talks only to this. */
|
||||
export interface WsSocket {
|
||||
readonly inbound: AsyncIterable<unknown>;
|
||||
readonly abort: AbortSignal;
|
||||
readonly isOpen: boolean;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate(): void;
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
export function matchWsRoute(
|
||||
wsRoutes: WsRouteDef[],
|
||||
path: string,
|
||||
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
|
||||
return wsRoutes
|
||||
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
|
||||
.find((entry) => entry.params);
|
||||
}
|
||||
|
||||
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
|
||||
function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer: () => void } {
|
||||
const closer = () => {
|
||||
try {
|
||||
socket.terminate();
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
return { closer };
|
||||
}
|
||||
|
||||
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
|
||||
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
if (!socket.isOpen) break;
|
||||
socket.send(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
}
|
||||
|
||||
try {
|
||||
socket.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes with 4000+status for HttpErrors, 1011 otherwise. */
|
||||
function closeOnError(socket: WsSocket, err: unknown): void {
|
||||
if (isHttpError(err)) {
|
||||
const reason = new TextDecoder().decode(new TextEncoder().encode(String(err.message)).subarray(0, 120));
|
||||
|
||||
try {
|
||||
socket.close(4000 + err.status, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
socket.close(1011);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the full per-connection lifecycle over a neutral socket capability. */
|
||||
export async function runWsConnection(
|
||||
socket: WsSocket,
|
||||
request: WsRequest,
|
||||
route: { def: WsRouteDef; params: Record<string, string> | undefined },
|
||||
bus?: Bus,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
const { closer } = trackConnection(socket, streams);
|
||||
const name = route.def.pattern;
|
||||
let iterator: AsyncIterator<unknown> | undefined;
|
||||
|
||||
const onAbort = () => {
|
||||
streams?.delete(closer);
|
||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||
};
|
||||
|
||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||
bus?.emit('stream:open', { name });
|
||||
|
||||
try {
|
||||
const outbound = await route.def.open({
|
||||
params: route.params ?? {},
|
||||
inbound: socket.inbound,
|
||||
abort: socket.abort,
|
||||
req: request,
|
||||
});
|
||||
iterator = outbound[Symbol.asyncIterator]();
|
||||
await pumpOutbound(socket, iterator);
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
closeOnError(socket, err);
|
||||
} finally {
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
+31
-96
@@ -1,8 +1,7 @@
|
||||
import http from 'http';
|
||||
import { channel } from '../channel';
|
||||
import { isHttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { matchPattern } from './router';
|
||||
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from './ws-core';
|
||||
import type { WsRouteDef, MeshControl } from './types';
|
||||
|
||||
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||
@@ -43,108 +42,42 @@ function handleMeshUpgrade(
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
function matchWsRoute(
|
||||
wsRoutes: WsRouteDef[],
|
||||
path: string,
|
||||
): { def: WsRouteDef; params: Record<string, string> | undefined } | undefined {
|
||||
return wsRoutes
|
||||
.map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) }))
|
||||
.find((entry) => entry.params);
|
||||
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
|
||||
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
||||
return {
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
protocol: (req.socket as any).encrypted ? 'https' : 'http',
|
||||
ip: req.socket.remoteAddress ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
/** Wires inbound message/close/error events into a channel and returns the channel plus its abort controller. */
|
||||
function wireInbound(ws: any): { inbound: ReturnType<typeof channel<unknown>>; abortController: AbortController } {
|
||||
/** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */
|
||||
function nodeSocket(ws: any): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const abortController = new AbortController();
|
||||
const ac = new AbortController();
|
||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||
ws.on('close', () => {
|
||||
inbound.close();
|
||||
abortController.abort();
|
||||
ac.abort();
|
||||
});
|
||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||
|
||||
return { inbound, abortController };
|
||||
}
|
||||
|
||||
/** Registers the connection with the stream registry so it can be force-closed on shutdown. */
|
||||
function trackConnection(ws: any, streams?: Set<() => void>): void {
|
||||
const closer = () => {
|
||||
try {
|
||||
(ws.terminate ?? ws.close).call(ws);
|
||||
} catch {
|
||||
/* */
|
||||
}
|
||||
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: () => (ws.terminate ?? ws.close).call(ws),
|
||||
};
|
||||
|
||||
streams?.add(closer);
|
||||
ws.on('close', () => streams?.delete(closer));
|
||||
}
|
||||
|
||||
/** Drives the outbound async iterator, sending each yielded value over the socket until done or closed. */
|
||||
async function pumpOutbound(ws: any, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||
while (true) {
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
if (ws.readyState !== 1) break; // 1 = OPEN; stop if socket gone
|
||||
ws.send(typeof value === 'string' ? value : JSON.stringify(value));
|
||||
}
|
||||
|
||||
try {
|
||||
ws.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes the socket with the appropriate code after an outbound error (4000+status for HTTP errors, 1011 otherwise). */
|
||||
function closeOnError(ws: any, err: unknown): void {
|
||||
if (isHttpError(err)) {
|
||||
const reason = Buffer.from(String(err.message)).subarray(0, 120).toString();
|
||||
|
||||
try {
|
||||
ws.close(4000 + err.status, reason);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
ws.close(1011);
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the full per-connection lifecycle: inbound wiring, opening the route stream, and pumping outbound values. */
|
||||
async function openWsConnection(
|
||||
ws: any,
|
||||
route: { def: WsRouteDef; params: Record<string, string> | undefined },
|
||||
req: http.IncomingMessage,
|
||||
bus?: Bus,
|
||||
streams?: Set<() => void>,
|
||||
): Promise<void> {
|
||||
trackConnection(ws, streams);
|
||||
const { inbound, abortController } = wireInbound(ws);
|
||||
|
||||
const name = route.def.pattern;
|
||||
let iterator: AsyncIterator<unknown> | undefined;
|
||||
ws.on('close', () => {
|
||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||
}); // force-cancel outbound
|
||||
bus?.emit('stream:open', { name });
|
||||
|
||||
try {
|
||||
const outbound = await route.def.open({ params: route.params!, inbound, abort: abortController.signal, req });
|
||||
iterator = outbound[Symbol.asyncIterator]();
|
||||
await pumpOutbound(ws, iterator);
|
||||
} catch (err) {
|
||||
bus?.emit('stream:error', { name, error: err });
|
||||
closeOnError(ws, err);
|
||||
} finally {
|
||||
abortController.abort();
|
||||
bus?.emit('stream:close', { name });
|
||||
}
|
||||
}
|
||||
|
||||
/** Attaches WebSocket upgrade handling to the server: routes to `wsRoutes` or a mesh control path. */
|
||||
@@ -175,6 +108,8 @@ export function attachWs(
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => openWsConnection(ws, route, req, bus, streams));
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createApp, Route, Ws, Module, ctx } from '../src/index';
|
||||
import { channel } from '../src/channel';
|
||||
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
||||
|
||||
@Route('/rt')
|
||||
class Rt {
|
||||
@Ws('/echo')
|
||||
echo(@ctx() { inbound }: any) {
|
||||
return (async function* () {
|
||||
for await (const msg of inbound) yield `echo:${msg}`;
|
||||
})();
|
||||
}
|
||||
}
|
||||
@Module({ mountpoint: '/', controllers: [Rt] })
|
||||
class M {}
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
function fakeSocket() {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
const sent: string[] = [];
|
||||
const socket: WsSocket = {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
isOpen: true,
|
||||
send: (d) => sent.push(d),
|
||||
close: () => ac.abort(),
|
||||
terminate: () => ac.abort(),
|
||||
};
|
||||
return { socket, inbound, sent };
|
||||
}
|
||||
|
||||
describe('app.upgrade', () => {
|
||||
it('routes a matching ws path through the graph', async () => {
|
||||
const { socket, inbound, sent } = fakeSocket();
|
||||
const req: WsRequest = { url: '/rt/echo', headers: {}, protocol: 'http', ip: '' };
|
||||
const run = app.upgrade(req, socket);
|
||||
// let the handler's async generator start subscribing to `inbound` (channel is fan-out:
|
||||
// push before subscription is lost) before pushing — a macrotask flushes every pending
|
||||
// microtask in the upgrade/boot chain first, so this is deterministic, not a sleep-and-hope.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
inbound.push('hi');
|
||||
inbound.close();
|
||||
await run;
|
||||
expect(sent).toEqual(['echo:hi']);
|
||||
});
|
||||
|
||||
it('closes 1008 on an unknown ws path', async () => {
|
||||
const { socket } = fakeSocket();
|
||||
let closedCode: number | undefined;
|
||||
socket.close = (c) => {
|
||||
closedCode = c;
|
||||
};
|
||||
const req: WsRequest = { url: '/rt/nope', headers: {}, protocol: 'http', ip: '' };
|
||||
await app.upgrade(req, socket);
|
||||
expect(closedCode).toBe(1008);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
// Real Deno integration test for serveDeno: boots an app under the actual Deno runtime
|
||||
// and round-trips both HTTP (app.fetch) and WebSocket (Deno.upgradeWebSocket -> app.upgrade).
|
||||
//
|
||||
// Run with: npm run test:deno (or: deno test --allow-net --allow-read --no-check test/deno/)
|
||||
//
|
||||
// `--no-check`: the barrel (`src/index.ts`) re-exports types from Node-only modules
|
||||
// (e.g. `src/http/*`) that reference ambient Node globals like `Buffer`. Those modules
|
||||
// aren't executed under Deno (this test only exercises `serveDeno`'s fetch/WebSocket
|
||||
// path), but Deno's checker still type-checks the whole reachable graph and has no
|
||||
// ambient `Buffer` type without a full `@types/node` setup. Node-side static typing for
|
||||
// those modules is already covered by `npm run typecheck` (tsc); this test's job is to
|
||||
// prove Deno *runtime* behavior of the adapter, not re-typecheck Node-only internals.
|
||||
import 'npm:reflect-metadata';
|
||||
import { assertEquals } from 'jsr:@std/assert';
|
||||
import { createApp, Route, Ws, Get, Module, ctx } from '../../src/index.ts';
|
||||
import { serveDeno } from '../../src/deno.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 {}
|
||||
|
||||
Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () => {
|
||||
const app = createApp({ modules: [M] });
|
||||
|
||||
let port = 0;
|
||||
const server = serveDeno(app, {
|
||||
port: 0,
|
||||
onListen: (addr) => {
|
||||
port = addr.port;
|
||||
},
|
||||
});
|
||||
|
||||
// Let onListen fire before we try to connect.
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
try {
|
||||
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
|
||||
assertEquals(httpRes.status, 200);
|
||||
assertEquals((await httpRes.json()).ok, true);
|
||||
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
|
||||
try {
|
||||
const got = await new Promise<string>((resolve, reject) => {
|
||||
ws.onopen = () => ws.send('hi');
|
||||
ws.onmessage = (e) => resolve(String(e.data));
|
||||
ws.onerror = () => reject(new Error('ws error'));
|
||||
});
|
||||
assertEquals(got, 'echo:hi');
|
||||
} finally {
|
||||
ws.close();
|
||||
// Give the close frame a moment to complete the handshake so no socket is leaked.
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
}
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core';
|
||||
import { channel } from '../src/channel';
|
||||
import { HttpError } from '../src/signals';
|
||||
import type { WsRouteDef } from '../src/http/types';
|
||||
|
||||
/** A controllable fake WsSocket that records sends and closes. */
|
||||
function fakeSocket() {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
const sent: string[] = [];
|
||||
const closes: Array<{ code?: number; reason?: string }> = [];
|
||||
let open = true;
|
||||
const socket: WsSocket = {
|
||||
inbound,
|
||||
abort: ac.signal,
|
||||
get isOpen() {
|
||||
return open;
|
||||
},
|
||||
send: (d) => sent.push(d),
|
||||
close: (code, reason) => {
|
||||
open = false;
|
||||
closes.push({ code, reason });
|
||||
ac.abort();
|
||||
},
|
||||
terminate: () => {
|
||||
open = false;
|
||||
ac.abort();
|
||||
},
|
||||
};
|
||||
return { socket, inbound, sent, closes, ac };
|
||||
}
|
||||
|
||||
const req: WsRequest = { url: '/ws', headers: {}, protocol: 'http', ip: '127.0.0.1' };
|
||||
|
||||
describe('runWsConnection (neutral core)', () => {
|
||||
it('sends each yielded outbound value, string or JSON', async () => {
|
||||
const def: WsRouteDef = {
|
||||
pattern: '/ws',
|
||||
open: async () =>
|
||||
(async function* () {
|
||||
yield 'hi';
|
||||
yield { n: 1 };
|
||||
})(),
|
||||
};
|
||||
const { socket, sent } = fakeSocket();
|
||||
await runWsConnection(socket, req, { def, params: {} });
|
||||
expect(sent).toEqual(['hi', JSON.stringify({ n: 1 })]);
|
||||
});
|
||||
|
||||
it('closes with 4000+status when the route throws an HttpError', async () => {
|
||||
const def: WsRouteDef = {
|
||||
pattern: '/ws',
|
||||
open: async () => {
|
||||
throw new HttpError(401, 'nope');
|
||||
},
|
||||
};
|
||||
const { socket, closes } = fakeSocket();
|
||||
await runWsConnection(socket, req, { def, params: {} });
|
||||
expect(closes[0].code).toBe(4401);
|
||||
expect(closes[0].reason).toBe('nope');
|
||||
});
|
||||
|
||||
it('closes with 1011 on a generic throw', async () => {
|
||||
const def: WsRouteDef = {
|
||||
pattern: '/ws',
|
||||
open: async () => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
};
|
||||
const { socket, closes } = fakeSocket();
|
||||
await runWsConnection(socket, req, { def, params: {} });
|
||||
expect(closes[0].code).toBe(1011);
|
||||
});
|
||||
|
||||
it('registers a closer in the shutdown registry and removes it when done', async () => {
|
||||
const streams = new Set<() => void>();
|
||||
const def: WsRouteDef = {
|
||||
pattern: '/ws',
|
||||
open: async () =>
|
||||
(async function* () {
|
||||
yield 'x';
|
||||
})(),
|
||||
};
|
||||
const { socket } = fakeSocket();
|
||||
await runWsConnection(socket, req, { def, params: {} }, undefined, streams);
|
||||
expect(streams.size).toBe(0); // added then removed
|
||||
});
|
||||
|
||||
it('passes inbound + params + request to route.open', async () => {
|
||||
let seen: any;
|
||||
const def: WsRouteDef = {
|
||||
pattern: '/ws/:id',
|
||||
open: async (ctx) => {
|
||||
seen = ctx;
|
||||
return (async function* () {})();
|
||||
},
|
||||
};
|
||||
const { socket } = fakeSocket();
|
||||
await runWsConnection(socket, req, { def, params: { id: '7' } });
|
||||
expect(seen.params).toEqual({ id: '7' });
|
||||
expect(seen.req).toBe(req);
|
||||
expect(typeof seen.inbound[Symbol.asyncIterator]).toBe('function');
|
||||
expect(seen.abort).toBeInstanceOf(AbortSignal);
|
||||
});
|
||||
|
||||
it('matchWsRoute finds a pattern and captures params', () => {
|
||||
const routes: WsRouteDef[] = [{ pattern: '/ws/:id', open: async () => (async function* () {})() }];
|
||||
expect(matchWsRoute(routes, '/ws/42')?.params).toEqual({ id: '42' });
|
||||
expect(matchWsRoute(routes, '/nope')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+2
-1
@@ -14,5 +14,6 @@
|
||||
"emitDecoratorMetadata": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src", "test", "example"]
|
||||
"include": ["src", "test", "example"],
|
||||
"exclude": ["test/deno"]
|
||||
}
|
||||
+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')
|
||||
// (optional peer deps) keep working there. reflect-metadata and the peer deps stay external.
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
entry: ['src/index.ts', 'src/deno.ts'],
|
||||
format: ['cjs', 'esm'],
|
||||
dts: true,
|
||||
clean: true,
|
||||
|
||||
+9
-2
@@ -1,5 +1,12 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { defineConfig, configDefaults } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: { globals: false, environment: 'node', include: ['test/**/*.test.ts'] },
|
||||
test: {
|
||||
globals: false,
|
||||
environment: 'node',
|
||||
include: ['test/**/*.test.ts'],
|
||||
// test/deno/** holds Deno.test files run separately via `npm run test:deno`;
|
||||
// they use `npm:`/`jsr:` specifiers vitest can't resolve.
|
||||
exclude: [...configDefaults.exclude, 'test/deno/**'],
|
||||
},
|
||||
});
|
||||
@@ -25,10 +25,36 @@ export default { fetch: app.fetch };
|
||||
**Node is the reference implementation** — every runtime returns the same status, headers,
|
||||
and body for the same request (enforced by a parity test suite).
|
||||
|
||||
**Not yet on non-Node runtimes:** WebSocket (`@Ws`) and mesh — Node-only for now; cross-runtime
|
||||
WebSocket is on the roadmap. `app.listen()` and TLS are Node-only; on Deno/Bun/edge you get
|
||||
`app.fetch`.
|
||||
**Not yet on Bun/edge runtimes:** WebSocket (`@Ws`) and mesh — still Node-only there; Deno now
|
||||
has WebSocket support via `serveDeno` (see below). `app.listen()` and 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
|
||||
before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on
|
||||
non-Node runtimes, also bound request size at the platform/runtime layer.
|
||||
|
||||
## WebSocket on Deno
|
||||
|
||||
`app.fetch` covers HTTP + SSE on every runtime. WebSocket needs a runtime-specific
|
||||
upgrade, so Deno gets a dedicated adapter at `@green-tea/core/deno`:
|
||||
|
||||
```ts
|
||||
import { createApp } from '@green-tea/core';
|
||||
import { serveDeno } from '@green-tea/core/deno';
|
||||
|
||||
const app = createApp({ modules: [ChatModule] });
|
||||
|
||||
// HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket — one call:
|
||||
serveDeno(app, { port: 8000 });
|
||||
```
|
||||
|
||||
`serveDeno` 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. Behaviour matches the Node reference.
|
||||
|
||||
**Advanced:** `app.upgrade(request, socket)` is the neutral primitive `serveDeno` uses.
|
||||
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.
|
||||
|
||||
**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you
|
||||
get `app.fetch` + `serveDeno`.
|
||||
Reference in new issue
Block a user