@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.
@@ -1,163 +0,0 @@
1
- import type { IncomingMessage } from 'node:http';
2
- import type { Duplex } from 'node:stream';
3
- import type { ConnectionInfo, MiddlewareHandler } from '@src/core';
4
- import type { DispatcherInterface } from '@orkestrel/router';
5
- import type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter';
6
- /**
7
- * The `Server`'s lifecycle state (AGENTS §10 vocabulary).
8
- *
9
- * @remarks
10
- * `idle` (never started, or a fresh instance) → `starting` (binding the
11
- * listener) → `listening` (accepting requests) → `stopping` (draining
12
- * in-flight requests) → `stopped` (closed; `start()` may run again, minting a
13
- * fresh stop signal). `destroy()` is a terminal teardown reachable from any
14
- * state, idempotent once `stopped`.
15
- */
16
- export type ServerStatus = 'idle' | 'starting' | 'listening' | 'stopping' | 'stopped';
17
- /**
18
- * The `Server`'s observable lifecycle events (AGENTS §13).
19
- *
20
- * @remarks
21
- * - `start` — `listen()` resolved; carries the actually-bound port (an
22
- * ephemeral `0` resolves to the OS-assigned one).
23
- * - `request` — fired once per incoming request, before the middleware onion
24
- * runs, carrying the raw method + the parsed pathname.
25
- * - `upgrade` — a raw protocol-upgrade fan-out settled; carries the original
26
- * `IncomingMessage` and whether a registered {@link UpgradeHandler} claimed it.
27
- * - `error` — a server-level fault: an escaping throw past the built-in
28
- * boundary, an upgrade handler's throw, or a listen failure.
29
- * - `stop` — `stop()` began (status just moved to `'stopping'`).
30
- * - `drain` — the graceful drain settled (deadline hit or all finished);
31
- * carries the still-pending request count (`0` on a clean drain).
32
- */
33
- export type ServerEventMap = {
34
- readonly start: readonly [port: number];
35
- readonly request: readonly [method: string, pathname: string];
36
- readonly upgrade: readonly [request: IncomingMessage, handled: boolean];
37
- readonly error: readonly [error: unknown];
38
- readonly stop: readonly [];
39
- readonly drain: readonly [pending: number];
40
- };
41
- /**
42
- * A raw `node:http` protocol-upgrade claimant — registered via
43
- * {@link ServerInterface.upgrade}.
44
- *
45
- * @remarks
46
- * Fan-out semantics (verbatim, PROPOSAL §4): handlers run in registration
47
- * order, the FIRST to return `true` CLAIMS (owns) the socket and stops the
48
- * fan-out; a handler that THROWS is treated as declined (the throw surfaces
49
- * on the `error` event) and the fan-out continues; if NONE claim it, the
50
- * socket is destroyed so an unhandled upgrade never leaks a dangling
51
- * connection. `request` / `socket` / `head` are node's own raw values, handed
52
- * over verbatim — no assertion at this boundary (AGENTS §14).
53
- *
54
- * @param request - The raw `node:http` upgrade request
55
- * @param socket - The raw, now-detached `Duplex` connection
56
- * @param head - The first packet of the upgraded stream, if any
57
- * @returns `true` to CLAIM the socket (this handler now owns it), `false` to
58
- * decline and let a later handler try
59
- */
60
- export type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => boolean;
61
- /**
62
- * Derives a consumer's per-request `TState` from the adapter-injected
63
- * {@link ConnectionInfo} — `ServerOptions.state`, invoked once per request
64
- * before the middleware onion runs.
65
- *
66
- * @typeParam TState - The consumer's opaque per-request state type
67
- */
68
- export type ConnectionStateFunction<TState> = (connection: ConnectionInfo) => TState;
69
- /**
70
- * Options for `createServer`.
71
- *
72
- * @param dispatcher - The `@orkestrel/router` {@link DispatcherInterface} the
73
- * composed middleware onion terminates into — bring-your-own router (the
74
- * composition seam stays explicit and independently testable).
75
- * @param state - {@link ConnectionStateFunction} — builds each request's
76
- * `TState` from the connection facts (peer IP, TLS flag). `X-Forwarded-For`
77
- * is never implicitly trusted here; a deployment behind a trusted proxy
78
- * derives its own client key in this function or in middleware.
79
- * @param middleware - Initial middleware, run in array order (outer-first);
80
- * more may be added later via `use`.
81
- * @param host - The network interface `start()` binds to (`node:http`
82
- * `server.listen`'s host). Omitted ⇒ node's default (all interfaces).
83
- * @param port - The TCP port `start()` binds to. Omitted or `0` ⇒ an
84
- * EPHEMERAL, OS-assigned free port (the default); `start()` always resolves
85
- * the actually-bound port. A port already in use rejects `start()` with
86
- * `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
87
- * guaranteed-free port up front).
88
- * @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
89
- * server stops accepting new connections and gives in-flight requests this
90
- * long to finish before forcing sockets closed. Defaults to
91
- * `DEFAULT_DRAIN_MS`. Must be a non-negative finite number.
92
- * @param limit - The default request-body byte cap the context's `body()`
93
- * reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
94
- * finite number.
95
- * @param expose - Whether a non-`HTTPError` throw's message is sent in the
96
- * 500 response body (an `HTTPError`'s own message is always client-facing).
97
- * Defaults to `false`.
98
- * @param report - A fire-and-forget sink the built-in boundary hands every
99
- * caught error to (logging / metrics); its own throw is swallowed so
100
- * reporting can never crash the response.
101
- * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
102
- * receive + respond, `requestTimeout`), `headers` (max time to receive the
103
- * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
104
- * timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
105
- * Slowloris footgun) — construction throws a `TypeError` otherwise.
106
- * @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
107
- * (AGENTS §8), wiring initial lifecycle listeners at construction.
108
- * @param error - The emitter's listener-error handler (AGENTS §13) — a
109
- * listener throw routes here, never to the domain `error` event.
110
- */
111
- export interface ServerOptions<TState> {
112
- readonly dispatcher: DispatcherInterface<TState>;
113
- readonly state: ConnectionStateFunction<TState>;
114
- readonly middleware?: readonly MiddlewareHandler<TState>[];
115
- readonly host?: string;
116
- readonly port?: number;
117
- readonly drain?: number;
118
- readonly limit?: number;
119
- readonly expose?: boolean;
120
- readonly report?: (error: unknown) => void;
121
- readonly timeouts?: {
122
- readonly request?: number;
123
- readonly headers?: number;
124
- readonly keepalive?: number;
125
- };
126
- readonly on?: EmitterHooks<ServerEventMap>;
127
- readonly error?: EmitterErrorHandler;
128
- }
129
- /**
130
- * The HTTP server facade — an observable `node:http` lifecycle that composes
131
- * a middleware onion (the `@src/core` seam) around a consumed
132
- * `@orkestrel/router` {@link DispatcherInterface}.
133
- *
134
- * @typeParam TState - The consumer's opaque per-request state type
135
- *
136
- * @remarks
137
- * `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
138
- * both configurable before or after `start()`. `start()` binds the configured
139
- * `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
140
- * bound address) and resolves the actually-bound port. `stop()` refuses new
141
- * connections, fires the stop signal so in-flight handlers can observe it,
142
- * drains up to the configured deadline, then closes. `destroy()` is the final
143
- * idempotent teardown. Per request: a `Request` is built via the router's
144
- * `buildRequest` (its signal linked to the server's stop signal), the
145
- * composed middleware onion runs terminating in `dispatcher.handle`, and the
146
- * result is written back via `sendResponse` — every escaping throw is caught
147
- * by the built-in boundary (`HTTPError` → its status; anything else → a
148
- * hidden-unless-`expose` `500`) so a handler error can never crash the
149
- * process.
150
- */
151
- export interface ServerInterface<TState> {
152
- readonly id: string;
153
- readonly status: ServerStatus;
154
- readonly port: number | undefined;
155
- readonly dispatcher: DispatcherInterface<TState>;
156
- readonly emitter: EmitterInterface<ServerEventMap>;
157
- use(middleware: MiddlewareHandler<TState>): void;
158
- use(middleware: readonly MiddlewareHandler<TState>[]): void;
159
- upgrade(handler: UpgradeHandler): void;
160
- start(): Promise<number>;
161
- stop(): Promise<void>;
162
- destroy(): Promise<void>;
163
- }