@orkestrel/server 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/core/index.cjs +1695 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/{helpers.d.ts → index.d.cts} +1538 -890
- package/dist/src/core/index.d.ts +1538 -6
- package/dist/src/core/index.js +32 -119
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +44 -964
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +334 -0
- package/dist/src/server/index.d.ts +334 -4
- package/dist/src/server/index.js +406 -0
- package/dist/src/server/index.js.map +1 -0
- package/package.json +28 -16
- package/dist/src/core/Negotiator.d.ts +0 -32
- package/dist/src/core/constants.d.ts +0 -68
- package/dist/src/core/errors.d.ts +0 -73
- package/dist/src/core/factories.d.ts +0 -21
- package/dist/src/core/types.d.ts +0 -362
- package/dist/src/server/Server.d.ts +0 -63
- package/dist/src/server/factories.d.ts +0 -26
- package/dist/src/server/helpers.d.ts +0 -45
- package/dist/src/server/types.d.ts +0 -163
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { AddressInfo } from 'node:net';
|
|
2
|
+
import { ConnectionInfo } from '../core/index.ts';
|
|
3
|
+
import { DispatcherInterface } from '@orkestrel/router';
|
|
4
|
+
import { Duplex } from 'node:stream';
|
|
5
|
+
import { EmitterErrorHandler } from '@orkestrel/emitter';
|
|
6
|
+
import { EmitterHooks } from '@orkestrel/emitter';
|
|
7
|
+
import { EmitterInterface } from '@orkestrel/emitter';
|
|
8
|
+
import { IncomingMessage } from 'node:http';
|
|
9
|
+
import { MiddlewareHandler } from '../core/index.ts';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Derives a consumer's per-request `TState` from the adapter-injected
|
|
13
|
+
* {@link ConnectionInfo} — `ServerOptions.state`, invoked once per request
|
|
14
|
+
* before the middleware onion runs.
|
|
15
|
+
*
|
|
16
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
17
|
+
*/
|
|
18
|
+
export declare type ConnectionStateFunction<TState> = (connection: ConnectionInfo) => TState;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Create a {@link ServerInterface} — the node face's HTTP server facade over
|
|
22
|
+
* a consumed `@orkestrel/router` dispatcher.
|
|
23
|
+
*
|
|
24
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
25
|
+
* @param options - {@link ServerOptions}
|
|
26
|
+
* @returns A {@link ServerInterface}, not yet started
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* import { createServer } from '@src/server'
|
|
31
|
+
* import { createDispatcher } from '@orkestrel/router'
|
|
32
|
+
*
|
|
33
|
+
* const dispatcher = createDispatcher<{ readonly ip?: string }>()
|
|
34
|
+
* dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
|
|
35
|
+
*
|
|
36
|
+
* const server = createServer({
|
|
37
|
+
* dispatcher,
|
|
38
|
+
* state: (connection) => ({ ip: connection.ip }),
|
|
39
|
+
* })
|
|
40
|
+
* const port = await server.start()
|
|
41
|
+
* await server.stop()
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Find a FREE TCP port — bind a throwaway `node:net` server, read the
|
|
48
|
+
* OS-assigned port, close it, and resolve that port.
|
|
49
|
+
*
|
|
50
|
+
* @remarks
|
|
51
|
+
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
52
|
+
* and returns it. With a `preferred` port it tries THAT port first and
|
|
53
|
+
* returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
|
|
54
|
+
* ephemeral free port rather than rejecting — a caller always gets a usable
|
|
55
|
+
* port. It binds then immediately closes a probe server, so the returned
|
|
56
|
+
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
57
|
+
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
58
|
+
* `preferred` port (e.g. a permission fault).
|
|
59
|
+
*
|
|
60
|
+
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
61
|
+
* fall back to an ephemeral port
|
|
62
|
+
* @returns A free TCP port number
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* import { createServer, discoverPort } from '@src/server'
|
|
67
|
+
*
|
|
68
|
+
* const port = await discoverPort() // a guaranteed-free ephemeral port
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export declare function discoverPort(preferred?: number): Promise<number>;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Whether a `node:net` `server.address()` return is the structured
|
|
75
|
+
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
76
|
+
* or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
|
|
77
|
+
* and the `Server`'s own port resolution read the bound port through.
|
|
78
|
+
*
|
|
79
|
+
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
80
|
+
* @returns `true` when `value` is an `AddressInfo` with a numeric `port`
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* import { isAddressInfo } from '@src/server'
|
|
85
|
+
*
|
|
86
|
+
* isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
|
|
87
|
+
* isAddressInfo(null) // false
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The HTTP server facade — an observable `node:http` lifecycle composing the
|
|
94
|
+
* `@src/core` middleware onion around a consumed `@orkestrel/router`
|
|
95
|
+
* dispatcher.
|
|
96
|
+
*
|
|
97
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
98
|
+
*
|
|
99
|
+
* @remarks
|
|
100
|
+
* - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
|
|
101
|
+
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
102
|
+
* ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
|
|
103
|
+
* bound address), and transitions `idle → starting → listening`. `stop()`
|
|
104
|
+
* transitions to `stopping`: refuses new connections, fires a fresh-per-run
|
|
105
|
+
* stop signal so in-flight handlers observe cancellation, drains up to the
|
|
106
|
+
* `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
|
|
107
|
+
* `destroy()` is the idempotent final teardown.
|
|
108
|
+
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
109
|
+
* `close`); a `Request` is built via the router's `buildRequest`, its
|
|
110
|
+
* `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
|
|
111
|
+
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
112
|
+
* `buildRequest`'s own abort, tied to client disconnect, composes with the
|
|
113
|
+
* server's stop signal via `AbortSignal.any`, so a handler awaiting
|
|
114
|
+
* `request.signal` observes BOTH); `context.state` is built via
|
|
115
|
+
* {@link ServerOptions.state} from the connection facts; the composed
|
|
116
|
+
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
117
|
+
* written back via `sendResponse`.
|
|
118
|
+
* - **The built-in boundary** wraps the WHOLE per-request chain, including
|
|
119
|
+
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
120
|
+
* throw (e.g. a malformed `Host` header) to a silent `400` with no
|
|
121
|
+
* `error` emit; everything after (`Request` reconstruction, connection
|
|
122
|
+
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
123
|
+
* behind the outer boundary — a thrown `HTTPError` renders as its status +
|
|
124
|
+
* message; any other throw renders `500` (message hidden unless
|
|
125
|
+
* `expose`), `report` is invoked (its own throw swallowed), and `error` is
|
|
126
|
+
* emitted. A server-owned last resort wraps the final `sendResponse`
|
|
127
|
+
* write itself: if even that fails, the connection is destroyed rather
|
|
128
|
+
* than left to escape as an unhandled error.
|
|
129
|
+
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
130
|
+
* throwing handler is treated as declined and surfaced on `error`, an
|
|
131
|
+
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
132
|
+
* - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
133
|
+
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
134
|
+
* routes it to the `error` OPTION (not the domain `error` event).
|
|
135
|
+
*/
|
|
136
|
+
export declare class Server<TState> implements ServerInterface<TState> {
|
|
137
|
+
#private;
|
|
138
|
+
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
139
|
+
constructor(options: ServerOptions<TState>);
|
|
140
|
+
get status(): ServerStatus;
|
|
141
|
+
get port(): number | undefined;
|
|
142
|
+
get dispatcher(): DispatcherInterface<TState>;
|
|
143
|
+
get emitter(): EmitterInterface<ServerEventMap>;
|
|
144
|
+
use(middleware: MiddlewareHandler<TState>): void;
|
|
145
|
+
use(middleware: readonly MiddlewareHandler<TState>[]): void;
|
|
146
|
+
upgrade(handler: UpgradeHandler): void;
|
|
147
|
+
start(): Promise<number>;
|
|
148
|
+
stop(): Promise<void>;
|
|
149
|
+
destroy(): Promise<void>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The `Server`'s observable lifecycle events (AGENTS §13).
|
|
154
|
+
*
|
|
155
|
+
* @remarks
|
|
156
|
+
* - `start` — `listen()` resolved; carries the actually-bound port (an
|
|
157
|
+
* ephemeral `0` resolves to the OS-assigned one).
|
|
158
|
+
* - `request` — fired once per incoming request, before the middleware onion
|
|
159
|
+
* runs, carrying the raw method + the parsed pathname.
|
|
160
|
+
* - `upgrade` — a raw protocol-upgrade fan-out settled; carries the original
|
|
161
|
+
* `IncomingMessage` and whether a registered {@link UpgradeHandler} claimed it.
|
|
162
|
+
* - `error` — a server-level fault: an escaping throw past the built-in
|
|
163
|
+
* boundary, an upgrade handler's throw, or a listen failure. Carries the
|
|
164
|
+
* originating request's method + parsed `url` when the fault happened on
|
|
165
|
+
* the per-request path; `undefined` for an upgrade-handler throw (no fetch
|
|
166
|
+
* `Request` exists on that path — only a raw `IncomingMessage`) or a listen
|
|
167
|
+
* failure.
|
|
168
|
+
* - `stop` — `stop()` began (status just moved to `'stopping'`).
|
|
169
|
+
* - `drain` — the graceful drain settled (deadline hit or all finished);
|
|
170
|
+
* carries the still-pending request count (`0` on a clean drain).
|
|
171
|
+
* - `response` — fired after the response has been sent, for every request
|
|
172
|
+
* that reaches the middleware pipeline (the success path and the
|
|
173
|
+
* outer-boundary error path); carries the method, parsed pathname, final
|
|
174
|
+
* status, and elapsed time in milliseconds. A request rejected at the
|
|
175
|
+
* `buildRequest` INNER boundary (a plain `400`, e.g. a malformed `Host`
|
|
176
|
+
* header) emits no `response` — no parsed `Request` exists yet to derive
|
|
177
|
+
* its facts from.
|
|
178
|
+
*/
|
|
179
|
+
export declare type ServerEventMap = {
|
|
180
|
+
readonly start: readonly [port: number];
|
|
181
|
+
readonly request: readonly [method: string, pathname: string];
|
|
182
|
+
readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
|
|
183
|
+
readonly error: readonly [error: unknown, request?: {
|
|
184
|
+
method: string;
|
|
185
|
+
url: URL;
|
|
186
|
+
}];
|
|
187
|
+
readonly stop: readonly [];
|
|
188
|
+
readonly drain: readonly [pending: number];
|
|
189
|
+
readonly response: readonly [
|
|
190
|
+
event: {
|
|
191
|
+
method: string;
|
|
192
|
+
pathname: string;
|
|
193
|
+
status: number;
|
|
194
|
+
ms: number;
|
|
195
|
+
}
|
|
196
|
+
];
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The HTTP server facade — an observable `node:http` lifecycle that composes
|
|
201
|
+
* a middleware onion (the `@src/core` seam) around a consumed
|
|
202
|
+
* `@orkestrel/router` {@link DispatcherInterface}.
|
|
203
|
+
*
|
|
204
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
205
|
+
*
|
|
206
|
+
* @remarks
|
|
207
|
+
* `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
|
|
208
|
+
* both configurable before or after `start()`. `start()` binds the configured
|
|
209
|
+
* `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
|
|
210
|
+
* bound address) and resolves the actually-bound port. `stop()` refuses new
|
|
211
|
+
* connections, fires the stop signal so in-flight handlers can observe it,
|
|
212
|
+
* drains up to the configured deadline, then closes. `destroy()` is the final
|
|
213
|
+
* idempotent teardown. Per request: a `Request` is built via the router's
|
|
214
|
+
* `buildRequest` (its signal linked to the server's stop signal), the
|
|
215
|
+
* composed middleware onion runs terminating in `dispatcher.handle`, and the
|
|
216
|
+
* result is written back via `sendResponse` — every escaping throw is caught
|
|
217
|
+
* by the built-in boundary (`HTTPError` → its status; anything else → a
|
|
218
|
+
* hidden-unless-`expose` `500`) so a handler error can never crash the
|
|
219
|
+
* process.
|
|
220
|
+
*/
|
|
221
|
+
export declare interface ServerInterface<TState> {
|
|
222
|
+
readonly id: string;
|
|
223
|
+
readonly status: ServerStatus;
|
|
224
|
+
readonly port: number | undefined;
|
|
225
|
+
readonly dispatcher: DispatcherInterface<TState>;
|
|
226
|
+
readonly emitter: EmitterInterface<ServerEventMap>;
|
|
227
|
+
use(middleware: MiddlewareHandler<TState>): void;
|
|
228
|
+
use(middleware: readonly MiddlewareHandler<TState>[]): void;
|
|
229
|
+
upgrade(handler: UpgradeHandler): void;
|
|
230
|
+
start(): Promise<number>;
|
|
231
|
+
stop(): Promise<void>;
|
|
232
|
+
destroy(): Promise<void>;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Options for `createServer`.
|
|
237
|
+
*
|
|
238
|
+
* @param dispatcher - The `@orkestrel/router` {@link DispatcherInterface} the
|
|
239
|
+
* composed middleware onion terminates into — bring-your-own router (the
|
|
240
|
+
* composition seam stays explicit and independently testable).
|
|
241
|
+
* @param state - {@link ConnectionStateFunction} — builds each request's
|
|
242
|
+
* `TState` from the connection facts (peer IP, TLS flag). `X-Forwarded-For`
|
|
243
|
+
* is never implicitly trusted here; a deployment behind a trusted proxy
|
|
244
|
+
* derives its own client key in this function or in middleware.
|
|
245
|
+
* @param middleware - Initial middleware, run in array order (outer-first);
|
|
246
|
+
* more may be added later via `use`.
|
|
247
|
+
* @param host - The network interface `start()` binds to (`node:http`
|
|
248
|
+
* `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
|
|
249
|
+
* @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
|
|
250
|
+
* EPHEMERAL, OS-assigned free port (the default); `start()` always resolves
|
|
251
|
+
* the actually-bound port. A port already in use rejects `start()` with
|
|
252
|
+
* `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
|
|
253
|
+
* guaranteed-free port up front).
|
|
254
|
+
* @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
|
|
255
|
+
* server stops accepting new connections and gives in-flight requests this
|
|
256
|
+
* long to finish before forcing sockets closed. Defaults to
|
|
257
|
+
* `DEFAULT_DRAIN_MS`. Must be a non-negative finite number.
|
|
258
|
+
* @param limit - The default request-body byte cap the context's `body()`
|
|
259
|
+
* reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
|
|
260
|
+
* finite number.
|
|
261
|
+
* @param expose - Whether a non-`HTTPError` throw's message is sent in the
|
|
262
|
+
* 500 response body (an `HTTPError`'s own message is always client-facing).
|
|
263
|
+
* Defaults to `false`.
|
|
264
|
+
* @param report - A fire-and-forget sink the built-in boundary hands every
|
|
265
|
+
* caught error to (logging / metrics), along with the originating
|
|
266
|
+
* request's method + parsed `url` when one is available (absent on an
|
|
267
|
+
* upgrade-path fault); its own throw is swallowed so reporting can never
|
|
268
|
+
* crash the response.
|
|
269
|
+
* @param timeouts - `node:http` tuning knobs: `request` (max time to fully
|
|
270
|
+
* receive + respond, `requestTimeout`), `headers` (max time to receive the
|
|
271
|
+
* request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
|
|
272
|
+
* timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
|
|
273
|
+
* Slowloris footgun) — construction throws a `TypeError` otherwise.
|
|
274
|
+
* @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
|
|
275
|
+
* (AGENTS §8), wiring initial lifecycle listeners at construction.
|
|
276
|
+
* @param error - The emitter's listener-error handler (AGENTS §13) — a
|
|
277
|
+
* listener throw routes here, never to the domain `error` event.
|
|
278
|
+
*/
|
|
279
|
+
export declare interface ServerOptions<TState> {
|
|
280
|
+
readonly dispatcher: DispatcherInterface<TState>;
|
|
281
|
+
readonly state: ConnectionStateFunction<TState>;
|
|
282
|
+
readonly middleware?: readonly MiddlewareHandler<TState>[];
|
|
283
|
+
readonly host?: string;
|
|
284
|
+
readonly port?: number;
|
|
285
|
+
readonly drain?: number;
|
|
286
|
+
readonly limit?: number;
|
|
287
|
+
readonly expose?: boolean;
|
|
288
|
+
readonly report?: (error: unknown, request?: {
|
|
289
|
+
method: string;
|
|
290
|
+
url: URL;
|
|
291
|
+
}) => void;
|
|
292
|
+
readonly timeouts?: {
|
|
293
|
+
readonly request?: number;
|
|
294
|
+
readonly headers?: number;
|
|
295
|
+
readonly keepalive?: number;
|
|
296
|
+
};
|
|
297
|
+
readonly on?: EmitterHooks<ServerEventMap>;
|
|
298
|
+
readonly error?: EmitterErrorHandler;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* The `Server`'s lifecycle state (AGENTS §10 vocabulary).
|
|
303
|
+
*
|
|
304
|
+
* @remarks
|
|
305
|
+
* `idle` (never started, or a fresh instance) → `starting` (binding the
|
|
306
|
+
* listener) → `listening` (accepting requests) → `stopping` (draining
|
|
307
|
+
* in-flight requests) → `stopped` (closed; `start()` may run again, minting a
|
|
308
|
+
* fresh stop signal). `destroy()` is a terminal teardown reachable from any
|
|
309
|
+
* state, idempotent once `stopped`.
|
|
310
|
+
*/
|
|
311
|
+
export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* A raw `node:http` protocol-upgrade claimant — registered via
|
|
315
|
+
* {@link ServerInterface.upgrade}.
|
|
316
|
+
*
|
|
317
|
+
* @remarks
|
|
318
|
+
* Fan-out semantics (verbatim, PROPOSAL §4): handlers run in registration
|
|
319
|
+
* order, the FIRST to return `true` CLAIMS (owns) the socket and stops the
|
|
320
|
+
* fan-out; a handler that THROWS is treated as declined (the throw surfaces
|
|
321
|
+
* on the `error` event) and the fan-out continues; if NONE claim it, the
|
|
322
|
+
* socket is destroyed so an unhandled upgrade never leaks a dangling
|
|
323
|
+
* connection. `request` / `socket` / `head` are node's own raw values, handed
|
|
324
|
+
* over verbatim — no assertion at this boundary (AGENTS §14).
|
|
325
|
+
*
|
|
326
|
+
* @param request - The raw `node:http` upgrade request
|
|
327
|
+
* @param socket - The raw, now-detached `Duplex` connection
|
|
328
|
+
* @param head - The first packet of the upgraded stream, if any
|
|
329
|
+
* @returns `true` to CLAIM the socket (this handler now owns it), `false` to
|
|
330
|
+
* decline and let a later handler try
|
|
331
|
+
*/
|
|
332
|
+
export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
333
|
+
|
|
334
|
+
export { }
|
|
@@ -1,4 +1,334 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import { AddressInfo } from 'node:net';
|
|
2
|
+
import { ConnectionInfo } from '../core/index.ts';
|
|
3
|
+
import { DispatcherInterface } from '@orkestrel/router';
|
|
4
|
+
import { Duplex } from 'node:stream';
|
|
5
|
+
import { EmitterErrorHandler } from '@orkestrel/emitter';
|
|
6
|
+
import { EmitterHooks } from '@orkestrel/emitter';
|
|
7
|
+
import { EmitterInterface } from '@orkestrel/emitter';
|
|
8
|
+
import { IncomingMessage } from 'node:http';
|
|
9
|
+
import { MiddlewareHandler } from '../core/index.ts';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Derives a consumer's per-request `TState` from the adapter-injected
|
|
13
|
+
* {@link ConnectionInfo} — `ServerOptions.state`, invoked once per request
|
|
14
|
+
* before the middleware onion runs.
|
|
15
|
+
*
|
|
16
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
17
|
+
*/
|
|
18
|
+
export declare type ConnectionStateFunction<TState> = (connection: ConnectionInfo) => TState;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Create a {@link ServerInterface} — the node face's HTTP server facade over
|
|
22
|
+
* a consumed `@orkestrel/router` dispatcher.
|
|
23
|
+
*
|
|
24
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
25
|
+
* @param options - {@link ServerOptions}
|
|
26
|
+
* @returns A {@link ServerInterface}, not yet started
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* import { createServer } from '@src/server'
|
|
31
|
+
* import { createDispatcher } from '@orkestrel/router'
|
|
32
|
+
*
|
|
33
|
+
* const dispatcher = createDispatcher<{ readonly ip?: string }>()
|
|
34
|
+
* dispatcher.add({ method: 'GET', path: '/health', handler: () => new Response('ok') })
|
|
35
|
+
*
|
|
36
|
+
* const server = createServer({
|
|
37
|
+
* dispatcher,
|
|
38
|
+
* state: (connection) => ({ ip: connection.ip }),
|
|
39
|
+
* })
|
|
40
|
+
* const port = await server.start()
|
|
41
|
+
* await server.stop()
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export declare function createServer<TState>(options: ServerOptions<TState>): ServerInterface<TState>;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Find a FREE TCP port — bind a throwaway `node:net` server, read the
|
|
48
|
+
* OS-assigned port, close it, and resolve that port.
|
|
49
|
+
*
|
|
50
|
+
* @remarks
|
|
51
|
+
* With no `preferred` it binds port `0` (an ephemeral OS-assigned free port)
|
|
52
|
+
* and returns it. With a `preferred` port it tries THAT port first and
|
|
53
|
+
* returns it when free; if already in use (`EADDRINUSE`) it FALLS BACK to an
|
|
54
|
+
* ephemeral free port rather than rejecting — a caller always gets a usable
|
|
55
|
+
* port. It binds then immediately closes a probe server, so the returned
|
|
56
|
+
* port is free at the instant of the probe (an inherent TOCTOU race — bind it
|
|
57
|
+
* promptly). Rejects only on an unexpected listen error other than a taken
|
|
58
|
+
* `preferred` port (e.g. a permission fault).
|
|
59
|
+
*
|
|
60
|
+
* @param preferred - An optional port to try first; taken (`EADDRINUSE`) ⇒
|
|
61
|
+
* fall back to an ephemeral port
|
|
62
|
+
* @returns A free TCP port number
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* import { createServer, discoverPort } from '@src/server'
|
|
67
|
+
*
|
|
68
|
+
* const port = await discoverPort() // a guaranteed-free ephemeral port
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export declare function discoverPort(preferred?: number): Promise<number>;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Whether a `node:net` `server.address()` return is the structured
|
|
75
|
+
* {@link AddressInfo} (carrying a numeric `port`) rather than a pipe `string`
|
|
76
|
+
* or `null` — the total, never-throwing narrow (AGENTS §14) `discoverPort`
|
|
77
|
+
* and the `Server`'s own port resolution read the bound port through.
|
|
78
|
+
*
|
|
79
|
+
* @param value - The `server.address()` return (`AddressInfo | string | null`)
|
|
80
|
+
* @returns `true` when `value` is an `AddressInfo` with a numeric `port`
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* import { isAddressInfo } from '@src/server'
|
|
85
|
+
*
|
|
86
|
+
* isAddressInfo({ address: '127.0.0.1', family: 'IPv4', port: 4000 }) // true
|
|
87
|
+
* isAddressInfo(null) // false
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export declare function isAddressInfo(value: unknown): value is AddressInfo;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The HTTP server facade — an observable `node:http` lifecycle composing the
|
|
94
|
+
* `@src/core` middleware onion around a consumed `@orkestrel/router`
|
|
95
|
+
* dispatcher.
|
|
96
|
+
*
|
|
97
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
98
|
+
*
|
|
99
|
+
* @remarks
|
|
100
|
+
* - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
|
|
101
|
+
* server, binds the configured {@link ServerOptions.host} / {@link
|
|
102
|
+
* ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
|
|
103
|
+
* bound address), and transitions `idle → starting → listening`. `stop()`
|
|
104
|
+
* transitions to `stopping`: refuses new connections, fires a fresh-per-run
|
|
105
|
+
* stop signal so in-flight handlers observe cancellation, drains up to the
|
|
106
|
+
* `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
|
|
107
|
+
* `destroy()` is the idempotent final teardown.
|
|
108
|
+
* - **Per request.** In-flight is tracked (finished on response `finish` or
|
|
109
|
+
* `close`); a `Request` is built via the router's `buildRequest`, its
|
|
110
|
+
* `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
|
|
111
|
+
* `linkSignal` (a fresh `Request` is constructed with the linked signal —
|
|
112
|
+
* `buildRequest`'s own abort, tied to client disconnect, composes with the
|
|
113
|
+
* server's stop signal via `AbortSignal.any`, so a handler awaiting
|
|
114
|
+
* `request.signal` observes BOTH); `context.state` is built via
|
|
115
|
+
* {@link ServerOptions.state} from the connection facts; the composed
|
|
116
|
+
* middleware onion runs, terminating in `dispatcher.handle`; the result is
|
|
117
|
+
* written back via `sendResponse`.
|
|
118
|
+
* - **The built-in boundary** wraps the WHOLE per-request chain, including
|
|
119
|
+
* setup: `buildRequest` runs behind its own inner boundary that maps a
|
|
120
|
+
* throw (e.g. a malformed `Host` header) to a silent `400` with no
|
|
121
|
+
* `error` emit; everything after (`Request` reconstruction, connection
|
|
122
|
+
* facts, `state`, the composed onion, and `dispatcher.handle`) runs
|
|
123
|
+
* behind the outer boundary — a thrown `HTTPError` renders as its status +
|
|
124
|
+
* message; any other throw renders `500` (message hidden unless
|
|
125
|
+
* `expose`), `report` is invoked (its own throw swallowed), and `error` is
|
|
126
|
+
* emitted. A server-owned last resort wraps the final `sendResponse`
|
|
127
|
+
* write itself: if even that fails, the connection is destroyed rather
|
|
128
|
+
* than left to escape as an unhandled error.
|
|
129
|
+
* - **Upgrade fan-out** — verbatim old semantics (first-claimer-wins, a
|
|
130
|
+
* throwing handler is treated as declined and surfaced on `error`, an
|
|
131
|
+
* unclaimed upgrade destroys the socket), bound per-run to this instance.
|
|
132
|
+
* - **Observable (§13).** Owns an {@link Emitter} over {@link ServerEventMap}
|
|
133
|
+
* exposed as `readonly emitter`; the emitter isolates a listener throw and
|
|
134
|
+
* routes it to the `error` OPTION (not the domain `error` event).
|
|
135
|
+
*/
|
|
136
|
+
export declare class Server<TState> implements ServerInterface<TState> {
|
|
137
|
+
#private;
|
|
138
|
+
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
139
|
+
constructor(options: ServerOptions<TState>);
|
|
140
|
+
get status(): ServerStatus;
|
|
141
|
+
get port(): number | undefined;
|
|
142
|
+
get dispatcher(): DispatcherInterface<TState>;
|
|
143
|
+
get emitter(): EmitterInterface<ServerEventMap>;
|
|
144
|
+
use(middleware: MiddlewareHandler<TState>): void;
|
|
145
|
+
use(middleware: readonly MiddlewareHandler<TState>[]): void;
|
|
146
|
+
upgrade(handler: UpgradeHandler): void;
|
|
147
|
+
start(): Promise<number>;
|
|
148
|
+
stop(): Promise<void>;
|
|
149
|
+
destroy(): Promise<void>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The `Server`'s observable lifecycle events (AGENTS §13).
|
|
154
|
+
*
|
|
155
|
+
* @remarks
|
|
156
|
+
* - `start` — `listen()` resolved; carries the actually-bound port (an
|
|
157
|
+
* ephemeral `0` resolves to the OS-assigned one).
|
|
158
|
+
* - `request` — fired once per incoming request, before the middleware onion
|
|
159
|
+
* runs, carrying the raw method + the parsed pathname.
|
|
160
|
+
* - `upgrade` — a raw protocol-upgrade fan-out settled; carries the original
|
|
161
|
+
* `IncomingMessage` and whether a registered {@link UpgradeHandler} claimed it.
|
|
162
|
+
* - `error` — a server-level fault: an escaping throw past the built-in
|
|
163
|
+
* boundary, an upgrade handler's throw, or a listen failure. Carries the
|
|
164
|
+
* originating request's method + parsed `url` when the fault happened on
|
|
165
|
+
* the per-request path; `undefined` for an upgrade-handler throw (no fetch
|
|
166
|
+
* `Request` exists on that path — only a raw `IncomingMessage`) or a listen
|
|
167
|
+
* failure.
|
|
168
|
+
* - `stop` — `stop()` began (status just moved to `'stopping'`).
|
|
169
|
+
* - `drain` — the graceful drain settled (deadline hit or all finished);
|
|
170
|
+
* carries the still-pending request count (`0` on a clean drain).
|
|
171
|
+
* - `response` — fired after the response has been sent, for every request
|
|
172
|
+
* that reaches the middleware pipeline (the success path and the
|
|
173
|
+
* outer-boundary error path); carries the method, parsed pathname, final
|
|
174
|
+
* status, and elapsed time in milliseconds. A request rejected at the
|
|
175
|
+
* `buildRequest` INNER boundary (a plain `400`, e.g. a malformed `Host`
|
|
176
|
+
* header) emits no `response` — no parsed `Request` exists yet to derive
|
|
177
|
+
* its facts from.
|
|
178
|
+
*/
|
|
179
|
+
export declare type ServerEventMap = {
|
|
180
|
+
readonly start: readonly [port: number];
|
|
181
|
+
readonly request: readonly [method: string, pathname: string];
|
|
182
|
+
readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
|
|
183
|
+
readonly error: readonly [error: unknown, request?: {
|
|
184
|
+
method: string;
|
|
185
|
+
url: URL;
|
|
186
|
+
}];
|
|
187
|
+
readonly stop: readonly [];
|
|
188
|
+
readonly drain: readonly [pending: number];
|
|
189
|
+
readonly response: readonly [
|
|
190
|
+
event: {
|
|
191
|
+
method: string;
|
|
192
|
+
pathname: string;
|
|
193
|
+
status: number;
|
|
194
|
+
ms: number;
|
|
195
|
+
}
|
|
196
|
+
];
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The HTTP server facade — an observable `node:http` lifecycle that composes
|
|
201
|
+
* a middleware onion (the `@src/core` seam) around a consumed
|
|
202
|
+
* `@orkestrel/router` {@link DispatcherInterface}.
|
|
203
|
+
*
|
|
204
|
+
* @typeParam TState - The consumer's opaque per-request state type
|
|
205
|
+
*
|
|
206
|
+
* @remarks
|
|
207
|
+
* `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
|
|
208
|
+
* both configurable before or after `start()`. `start()` binds the configured
|
|
209
|
+
* `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
|
|
210
|
+
* bound address) and resolves the actually-bound port. `stop()` refuses new
|
|
211
|
+
* connections, fires the stop signal so in-flight handlers can observe it,
|
|
212
|
+
* drains up to the configured deadline, then closes. `destroy()` is the final
|
|
213
|
+
* idempotent teardown. Per request: a `Request` is built via the router's
|
|
214
|
+
* `buildRequest` (its signal linked to the server's stop signal), the
|
|
215
|
+
* composed middleware onion runs terminating in `dispatcher.handle`, and the
|
|
216
|
+
* result is written back via `sendResponse` — every escaping throw is caught
|
|
217
|
+
* by the built-in boundary (`HTTPError` → its status; anything else → a
|
|
218
|
+
* hidden-unless-`expose` `500`) so a handler error can never crash the
|
|
219
|
+
* process.
|
|
220
|
+
*/
|
|
221
|
+
export declare interface ServerInterface<TState> {
|
|
222
|
+
readonly id: string;
|
|
223
|
+
readonly status: ServerStatus;
|
|
224
|
+
readonly port: number | undefined;
|
|
225
|
+
readonly dispatcher: DispatcherInterface<TState>;
|
|
226
|
+
readonly emitter: EmitterInterface<ServerEventMap>;
|
|
227
|
+
use(middleware: MiddlewareHandler<TState>): void;
|
|
228
|
+
use(middleware: readonly MiddlewareHandler<TState>[]): void;
|
|
229
|
+
upgrade(handler: UpgradeHandler): void;
|
|
230
|
+
start(): Promise<number>;
|
|
231
|
+
stop(): Promise<void>;
|
|
232
|
+
destroy(): Promise<void>;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Options for `createServer`.
|
|
237
|
+
*
|
|
238
|
+
* @param dispatcher - The `@orkestrel/router` {@link DispatcherInterface} the
|
|
239
|
+
* composed middleware onion terminates into — bring-your-own router (the
|
|
240
|
+
* composition seam stays explicit and independently testable).
|
|
241
|
+
* @param state - {@link ConnectionStateFunction} — builds each request's
|
|
242
|
+
* `TState` from the connection facts (peer IP, TLS flag). `X-Forwarded-For`
|
|
243
|
+
* is never implicitly trusted here; a deployment behind a trusted proxy
|
|
244
|
+
* derives its own client key in this function or in middleware.
|
|
245
|
+
* @param middleware - Initial middleware, run in array order (outer-first);
|
|
246
|
+
* more may be added later via `use`.
|
|
247
|
+
* @param host - The network interface `start()` binds to (`node:http`
|
|
248
|
+
* `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
|
|
249
|
+
* @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
|
|
250
|
+
* EPHEMERAL, OS-assigned free port (the default); `start()` always resolves
|
|
251
|
+
* the actually-bound port. A port already in use rejects `start()` with
|
|
252
|
+
* `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
|
|
253
|
+
* guaranteed-free port up front).
|
|
254
|
+
* @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
|
|
255
|
+
* server stops accepting new connections and gives in-flight requests this
|
|
256
|
+
* long to finish before forcing sockets closed. Defaults to
|
|
257
|
+
* `DEFAULT_DRAIN_MS`. Must be a non-negative finite number.
|
|
258
|
+
* @param limit - The default request-body byte cap the context's `body()`
|
|
259
|
+
* reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
|
|
260
|
+
* finite number.
|
|
261
|
+
* @param expose - Whether a non-`HTTPError` throw's message is sent in the
|
|
262
|
+
* 500 response body (an `HTTPError`'s own message is always client-facing).
|
|
263
|
+
* Defaults to `false`.
|
|
264
|
+
* @param report - A fire-and-forget sink the built-in boundary hands every
|
|
265
|
+
* caught error to (logging / metrics), along with the originating
|
|
266
|
+
* request's method + parsed `url` when one is available (absent on an
|
|
267
|
+
* upgrade-path fault); its own throw is swallowed so reporting can never
|
|
268
|
+
* crash the response.
|
|
269
|
+
* @param timeouts - `node:http` tuning knobs: `request` (max time to fully
|
|
270
|
+
* receive + respond, `requestTimeout`), `headers` (max time to receive the
|
|
271
|
+
* request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
|
|
272
|
+
* timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
|
|
273
|
+
* Slowloris footgun) — construction throws a `TypeError` otherwise.
|
|
274
|
+
* @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
|
|
275
|
+
* (AGENTS §8), wiring initial lifecycle listeners at construction.
|
|
276
|
+
* @param error - The emitter's listener-error handler (AGENTS §13) — a
|
|
277
|
+
* listener throw routes here, never to the domain `error` event.
|
|
278
|
+
*/
|
|
279
|
+
export declare interface ServerOptions<TState> {
|
|
280
|
+
readonly dispatcher: DispatcherInterface<TState>;
|
|
281
|
+
readonly state: ConnectionStateFunction<TState>;
|
|
282
|
+
readonly middleware?: readonly MiddlewareHandler<TState>[];
|
|
283
|
+
readonly host?: string;
|
|
284
|
+
readonly port?: number;
|
|
285
|
+
readonly drain?: number;
|
|
286
|
+
readonly limit?: number;
|
|
287
|
+
readonly expose?: boolean;
|
|
288
|
+
readonly report?: (error: unknown, request?: {
|
|
289
|
+
method: string;
|
|
290
|
+
url: URL;
|
|
291
|
+
}) => void;
|
|
292
|
+
readonly timeouts?: {
|
|
293
|
+
readonly request?: number;
|
|
294
|
+
readonly headers?: number;
|
|
295
|
+
readonly keepalive?: number;
|
|
296
|
+
};
|
|
297
|
+
readonly on?: EmitterHooks<ServerEventMap>;
|
|
298
|
+
readonly error?: EmitterErrorHandler;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* The `Server`'s lifecycle state (AGENTS §10 vocabulary).
|
|
303
|
+
*
|
|
304
|
+
* @remarks
|
|
305
|
+
* `idle` (never started, or a fresh instance) → `starting` (binding the
|
|
306
|
+
* listener) → `listening` (accepting requests) → `stopping` (draining
|
|
307
|
+
* in-flight requests) → `stopped` (closed; `start()` may run again, minting a
|
|
308
|
+
* fresh stop signal). `destroy()` is a terminal teardown reachable from any
|
|
309
|
+
* state, idempotent once `stopped`.
|
|
310
|
+
*/
|
|
311
|
+
export declare type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* A raw `node:http` protocol-upgrade claimant — registered via
|
|
315
|
+
* {@link ServerInterface.upgrade}.
|
|
316
|
+
*
|
|
317
|
+
* @remarks
|
|
318
|
+
* Fan-out semantics (verbatim, PROPOSAL §4): handlers run in registration
|
|
319
|
+
* order, the FIRST to return `true` CLAIMS (owns) the socket and stops the
|
|
320
|
+
* fan-out; a handler that THROWS is treated as declined (the throw surfaces
|
|
321
|
+
* on the `error` event) and the fan-out continues; if NONE claim it, the
|
|
322
|
+
* socket is destroyed so an unhandled upgrade never leaks a dangling
|
|
323
|
+
* connection. `request` / `socket` / `head` are node's own raw values, handed
|
|
324
|
+
* over verbatim — no assertion at this boundary (AGENTS §14).
|
|
325
|
+
*
|
|
326
|
+
* @param request - The raw `node:http` upgrade request
|
|
327
|
+
* @param socket - The raw, now-detached `Duplex` connection
|
|
328
|
+
* @param head - The first packet of the upgraded stream, if any
|
|
329
|
+
* @returns `true` to CLAIM the socket (this handler now owns it), `false` to
|
|
330
|
+
* decline and let a later handler try
|
|
331
|
+
*/
|
|
332
|
+
export declare type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
|
|
333
|
+
|
|
334
|
+
export { }
|