feat(app): app.upgrade — neutral WebSocket entry over the graph
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
3 files changed
+107
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user