@orkestrel/server 0.0.7 → 0.0.8

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.
@@ -1458,14 +1458,17 @@ export declare function serializeEvent(message: SSEMessage): string;
1458
1458
  * @typeParam TState - The consumer's opaque per-request state type
1459
1459
  *
1460
1460
  * @remarks
1461
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1461
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1462
1462
  * server, binds the configured {@link ServerOptions.host} / {@link
1463
1463
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1464
- * bound address), and transitions `idle → starting → listening`. `stop()`
1465
- * transitions to `stopping`: refuses new connections, fires a fresh-per-run
1466
- * stop signal so in-flight handlers observe cancellation, drains up to the
1467
- * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
1468
- * `destroy()` is the idempotent final teardown.
1464
+ * bound address), observes caller cancellation plus the configured
1465
+ * `timeouts.start` deadline while the bind is pending, and transitions
1466
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1467
+ * partial server and resets to `idle` for another start. `stop()` transitions
1468
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1469
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1470
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1471
+ * is the idempotent final teardown.
1469
1472
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1470
1473
  * `close`); a `Request` is built via the router's `buildRequest`, its
1471
1474
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1505,7 +1508,7 @@ export declare class Server<TState> implements ServerInterface<TState> {
1505
1508
  use(middleware: MiddlewareHandler<TState>): void;
1506
1509
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1507
1510
  upgrade(handler: UpgradeHandler): void;
1508
- start(): Promise<number>;
1511
+ start(signal?: AbortSignal): Promise<number>;
1509
1512
  stop(): Promise<void>;
1510
1513
  destroy(): Promise<void>;
1511
1514
  }
@@ -1566,18 +1569,19 @@ export declare type ServerEventMap = {
1566
1569
  *
1567
1570
  * @remarks
1568
1571
  * `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
1569
- * both configurable before or after `start()`. `start()` binds the configured
1570
- * `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
1571
- * bound address) and resolves the actually-bound port. `stop()` refuses new
1572
+ * both configurable before or after `start()`. `start(signal?)` binds the
1573
+ * configured `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved
1574
+ * from the bound address), observes caller cancellation plus `timeouts.start`
1575
+ * while binding, and resolves the actually-bound port. A cancelled or expired
1576
+ * bind closes its partial server and resets to `idle`. `stop()` refuses new
1572
1577
  * connections, fires the stop signal so in-flight handlers can observe it,
1573
1578
  * drains up to the configured deadline, then closes. `destroy()` is the final
1574
1579
  * idempotent teardown. Per request: a `Request` is built via the router's
1575
- * `buildRequest` (its signal linked to the server's stop signal), the
1576
- * composed middleware onion runs terminating in `dispatcher.handle`, and the
1577
- * result is written back via `sendResponse` — every escaping throw is caught
1578
- * by the built-in boundary (`HTTPError` → its status; anything else → a
1579
- * hidden-unless-`expose` `500`) so a handler error can never crash the
1580
- * process.
1580
+ * `buildRequest` (its signal linked to the server's stop signal), the composed
1581
+ * middleware onion runs terminating in `dispatcher.handle`, and the result is
1582
+ * written back via `sendResponse` — every escaping throw is caught by the
1583
+ * built-in boundary (`HTTPError` → its status; anything else → a
1584
+ * hidden-unless-`expose` `500`) so a handler error can never crash the process.
1581
1585
  */
1582
1586
  export declare interface ServerInterface<TState> {
1583
1587
  readonly id: string;
@@ -1588,7 +1592,14 @@ export declare interface ServerInterface<TState> {
1588
1592
  use(middleware: MiddlewareHandler<TState>): void;
1589
1593
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1590
1594
  upgrade(handler: UpgradeHandler): void;
1591
- start(): Promise<number>;
1595
+ /**
1596
+ * Bind the configured listener and resolve its actually-bound port.
1597
+ *
1598
+ * @param signal - Optional caller cancellation observed only while startup
1599
+ * is pending; aborting after this method resolves does not stop the server.
1600
+ * @returns The actually-bound TCP port
1601
+ */
1602
+ start(signal?: AbortSignal): Promise<number>;
1592
1603
  stop(): Promise<void>;
1593
1604
  destroy(): Promise<void>;
1594
1605
  }
@@ -1627,11 +1638,20 @@ export declare interface ServerInterface<TState> {
1627
1638
  * request's method + parsed `url` when one is available (absent on an
1628
1639
  * upgrade-path fault); its own throw is swallowed so reporting can never
1629
1640
  * crash the response.
1630
- * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
1631
- * receive + respond, `requestTimeout`), `headers` (max time to receive the
1632
- * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
1633
- * timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
1634
- * Slowloris footgun) — construction throws a `TypeError` otherwise.
1641
+ * @param timeouts - Lifecycle and `node:http` tuning knobs: `start` (maximum
1642
+ * time to bind the listener; `0` permits no startup window), `request` (max
1643
+ * time to fully receive + respond, `requestTimeout`), `headers` (max time
1644
+ * to receive the request headers, `headersTimeout`), and `keepalive` (idle
1645
+ * keep-alive socket timeout, `keepAliveTimeout`). `headers` must not exceed
1646
+ * `keepalive` (the Slowloris footgun) — construction throws a `TypeError`
1647
+ * otherwise. Every present value must be a non-negative finite number. A
1648
+ * startup expiry rejects with a `DOMException` named `TimeoutError`; caller
1649
+ * cancellation rejects with the caller signal's `reason`.
1650
+ * @param sockets - `node:http` socket caps: `connections` maps to
1651
+ * `maxConnections` (`0` rejects every incoming connection), `headers` maps
1652
+ * to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
1653
+ * `maxRequestsPerSocket` (`0` disables the limit). Every present value must
1654
+ * be a non-negative integer. Omitted leaves preserve node's defaults.
1635
1655
  * @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
1636
1656
  * (AGENTS §8), wiring initial lifecycle listeners at construction.
1637
1657
  * @param error - The emitter's listener-error handler (AGENTS §13) — a
@@ -1651,10 +1671,16 @@ export declare interface ServerOptions<TState> {
1651
1671
  url: URL;
1652
1672
  }) => void;
1653
1673
  readonly timeouts?: {
1674
+ readonly start?: number;
1654
1675
  readonly request?: number;
1655
1676
  readonly headers?: number;
1656
1677
  readonly keepalive?: number;
1657
1678
  };
1679
+ readonly sockets?: {
1680
+ readonly connections?: number;
1681
+ readonly headers?: number;
1682
+ readonly requests?: number;
1683
+ };
1658
1684
  readonly on?: EmitterHooks<ServerEventMap>;
1659
1685
  readonly error?: EmitterErrorHandler;
1660
1686
  }
@@ -1458,14 +1458,17 @@ export declare function serializeEvent(message: SSEMessage): string;
1458
1458
  * @typeParam TState - The consumer's opaque per-request state type
1459
1459
  *
1460
1460
  * @remarks
1461
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1461
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1462
1462
  * server, binds the configured {@link ServerOptions.host} / {@link
1463
1463
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1464
- * bound address), and transitions `idle → starting → listening`. `stop()`
1465
- * transitions to `stopping`: refuses new connections, fires a fresh-per-run
1466
- * stop signal so in-flight handlers observe cancellation, drains up to the
1467
- * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
1468
- * `destroy()` is the idempotent final teardown.
1464
+ * bound address), observes caller cancellation plus the configured
1465
+ * `timeouts.start` deadline while the bind is pending, and transitions
1466
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1467
+ * partial server and resets to `idle` for another start. `stop()` transitions
1468
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1469
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1470
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1471
+ * is the idempotent final teardown.
1469
1472
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1470
1473
  * `close`); a `Request` is built via the router's `buildRequest`, its
1471
1474
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1505,7 +1508,7 @@ export declare class Server<TState> implements ServerInterface<TState> {
1505
1508
  use(middleware: MiddlewareHandler<TState>): void;
1506
1509
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1507
1510
  upgrade(handler: UpgradeHandler): void;
1508
- start(): Promise<number>;
1511
+ start(signal?: AbortSignal): Promise<number>;
1509
1512
  stop(): Promise<void>;
1510
1513
  destroy(): Promise<void>;
1511
1514
  }
@@ -1566,18 +1569,19 @@ export declare type ServerEventMap = {
1566
1569
  *
1567
1570
  * @remarks
1568
1571
  * `use` adds middleware and `upgrade` registers a protocol-upgrade claimant,
1569
- * both configurable before or after `start()`. `start()` binds the configured
1570
- * `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved from the
1571
- * bound address) and resolves the actually-bound port. `stop()` refuses new
1572
+ * both configurable before or after `start()`. `start(signal?)` binds the
1573
+ * configured `host`/`port` (an omitted/`0` port ⇒ an EPHEMERAL port, resolved
1574
+ * from the bound address), observes caller cancellation plus `timeouts.start`
1575
+ * while binding, and resolves the actually-bound port. A cancelled or expired
1576
+ * bind closes its partial server and resets to `idle`. `stop()` refuses new
1572
1577
  * connections, fires the stop signal so in-flight handlers can observe it,
1573
1578
  * drains up to the configured deadline, then closes. `destroy()` is the final
1574
1579
  * idempotent teardown. Per request: a `Request` is built via the router's
1575
- * `buildRequest` (its signal linked to the server's stop signal), the
1576
- * composed middleware onion runs terminating in `dispatcher.handle`, and the
1577
- * result is written back via `sendResponse` — every escaping throw is caught
1578
- * by the built-in boundary (`HTTPError` → its status; anything else → a
1579
- * hidden-unless-`expose` `500`) so a handler error can never crash the
1580
- * process.
1580
+ * `buildRequest` (its signal linked to the server's stop signal), the composed
1581
+ * middleware onion runs terminating in `dispatcher.handle`, and the result is
1582
+ * written back via `sendResponse` — every escaping throw is caught by the
1583
+ * built-in boundary (`HTTPError` → its status; anything else → a
1584
+ * hidden-unless-`expose` `500`) so a handler error can never crash the process.
1581
1585
  */
1582
1586
  export declare interface ServerInterface<TState> {
1583
1587
  readonly id: string;
@@ -1588,7 +1592,14 @@ export declare interface ServerInterface<TState> {
1588
1592
  use(middleware: MiddlewareHandler<TState>): void;
1589
1593
  use(middleware: readonly MiddlewareHandler<TState>[]): void;
1590
1594
  upgrade(handler: UpgradeHandler): void;
1591
- start(): Promise<number>;
1595
+ /**
1596
+ * Bind the configured listener and resolve its actually-bound port.
1597
+ *
1598
+ * @param signal - Optional caller cancellation observed only while startup
1599
+ * is pending; aborting after this method resolves does not stop the server.
1600
+ * @returns The actually-bound TCP port
1601
+ */
1602
+ start(signal?: AbortSignal): Promise<number>;
1592
1603
  stop(): Promise<void>;
1593
1604
  destroy(): Promise<void>;
1594
1605
  }
@@ -1627,11 +1638,20 @@ export declare interface ServerInterface<TState> {
1627
1638
  * request's method + parsed `url` when one is available (absent on an
1628
1639
  * upgrade-path fault); its own throw is swallowed so reporting can never
1629
1640
  * crash the response.
1630
- * @param timeouts - `node:http` tuning knobs: `request` (max time to fully
1631
- * receive + respond, `requestTimeout`), `headers` (max time to receive the
1632
- * request headers, `headersTimeout`), `keepalive` (idle keep-alive socket
1633
- * timeout, `keepAliveTimeout`). `headers` must not exceed `keepalive` (the
1634
- * Slowloris footgun) — construction throws a `TypeError` otherwise.
1641
+ * @param timeouts - Lifecycle and `node:http` tuning knobs: `start` (maximum
1642
+ * time to bind the listener; `0` permits no startup window), `request` (max
1643
+ * time to fully receive + respond, `requestTimeout`), `headers` (max time
1644
+ * to receive the request headers, `headersTimeout`), and `keepalive` (idle
1645
+ * keep-alive socket timeout, `keepAliveTimeout`). `headers` must not exceed
1646
+ * `keepalive` (the Slowloris footgun) — construction throws a `TypeError`
1647
+ * otherwise. Every present value must be a non-negative finite number. A
1648
+ * startup expiry rejects with a `DOMException` named `TimeoutError`; caller
1649
+ * cancellation rejects with the caller signal's `reason`.
1650
+ * @param sockets - `node:http` socket caps: `connections` maps to
1651
+ * `maxConnections` (`0` rejects every incoming connection), `headers` maps
1652
+ * to `maxHeadersCount` (`0` disables the limit), and `requests` maps to
1653
+ * `maxRequestsPerSocket` (`0` disables the limit). Every present value must
1654
+ * be a non-negative integer. Omitted leaves preserve node's defaults.
1635
1655
  * @param on - The reserved {@link EmitterHooks} for {@link ServerEventMap}
1636
1656
  * (AGENTS §8), wiring initial lifecycle listeners at construction.
1637
1657
  * @param error - The emitter's listener-error handler (AGENTS §13) — a
@@ -1651,10 +1671,16 @@ export declare interface ServerOptions<TState> {
1651
1671
  url: URL;
1652
1672
  }) => void;
1653
1673
  readonly timeouts?: {
1674
+ readonly start?: number;
1654
1675
  readonly request?: number;
1655
1676
  readonly headers?: number;
1656
1677
  readonly keepalive?: number;
1657
1678
  };
1679
+ readonly sockets?: {
1680
+ readonly connections?: number;
1681
+ readonly headers?: number;
1682
+ readonly requests?: number;
1683
+ };
1658
1684
  readonly on?: EmitterHooks<ServerEventMap>;
1659
1685
  readonly error?: EmitterErrorHandler;
1660
1686
  }
@@ -1,5 +1,5 @@
1
- import { isFiniteNumber, isFunction, isNumber, isRecord, isString, parseJSON } from "@orkestrel/contract";
2
- import { once } from "node:events";
1
+ import { isFiniteNumber, isFunction, isInteger, isNumber, isRecord, isString, parseJSON } from "@orkestrel/contract";
2
+ import { addAbortListener, once } from "node:events";
3
3
  import { createServer as createServer$1 } from "node:net";
4
4
  import { createServer as createServer$2 } from "node:http";
5
5
  import { createAbort, linkSignal } from "@orkestrel/abort";
@@ -1745,14 +1745,17 @@ var Negotiator = class {
1745
1745
  * @typeParam TState - The consumer's opaque per-request state type
1746
1746
  *
1747
1747
  * @remarks
1748
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1748
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1749
1749
  * server, binds the configured {@link ServerOptions.host} / {@link
1750
1750
  * ServerOptions.port} (omitted/`0` port ⇒ EPHEMERAL, resolved from the
1751
- * bound address), and transitions `idle → starting → listening`. `stop()`
1752
- * transitions to `stopping`: refuses new connections, fires a fresh-per-run
1753
- * stop signal so in-flight handlers observe cancellation, drains up to the
1754
- * `drain` deadline (event-driven, no busy-loop), then closes → `stopped`.
1755
- * `destroy()` is the idempotent final teardown.
1751
+ * bound address), observes caller cancellation plus the configured
1752
+ * `timeouts.start` deadline while the bind is pending, and transitions
1753
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1754
+ * partial server and resets to `idle` for another start. `stop()` transitions
1755
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1756
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1757
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1758
+ * is the idempotent final teardown.
1756
1759
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1757
1760
  * `close`); a `Request` is built via the router's `buildRequest`, its
1758
1761
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
@@ -1795,6 +1798,7 @@ var Server = class {
1795
1798
  #expose;
1796
1799
  #report;
1797
1800
  #timeouts;
1801
+ #sockets;
1798
1802
  #http;
1799
1803
  #abort = createAbort();
1800
1804
  #wakeup = createAbort();
@@ -1811,6 +1815,8 @@ var Server = class {
1811
1815
  const timeouts = options.timeouts ?? {};
1812
1816
  for (const [name, value] of Object.entries(timeouts)) if (value !== void 0 && (!isFiniteNumber(value) || value < 0)) throw new TypeError(`ServerOptions.timeouts.${name} must be a non-negative finite number`);
1813
1817
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1818
+ const sockets = options.sockets ?? {};
1819
+ for (const [name, value] of Object.entries(sockets)) if (value !== void 0 && (!isInteger(value) || value < 0)) throw new TypeError(`ServerOptions.sockets.${name} must be a non-negative integer`);
1814
1820
  this.#dispatcher = options.dispatcher;
1815
1821
  this.#state = options.state;
1816
1822
  this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
@@ -1821,6 +1827,7 @@ var Server = class {
1821
1827
  this.#expose = options.expose ?? false;
1822
1828
  this.#report = options.report;
1823
1829
  this.#timeouts = timeouts;
1830
+ this.#sockets = sockets;
1824
1831
  this.#emitter = new Emitter({
1825
1832
  ...options.on === void 0 ? {} : { on: options.on },
1826
1833
  ...options.error === void 0 ? {} : { error: options.error }
@@ -1845,7 +1852,7 @@ var Server = class {
1845
1852
  upgrade(handler) {
1846
1853
  this.#upgradeHandlers.push(handler);
1847
1854
  }
1848
- start() {
1855
+ start(signal) {
1849
1856
  if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1850
1857
  this.#status = "starting";
1851
1858
  this.#abort = createAbort();
@@ -1853,9 +1860,12 @@ var Server = class {
1853
1860
  if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
1854
1861
  if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
1855
1862
  if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
1863
+ if (this.#sockets.connections !== void 0) server.maxConnections = this.#sockets.connections;
1864
+ if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
1865
+ if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
1856
1866
  server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
1857
1867
  this.#http = server;
1858
- return this.#listen(server);
1868
+ return this.#listen(server, signal);
1859
1869
  }
1860
1870
  async stop() {
1861
1871
  if (this.#status !== "listening") return;
@@ -1980,15 +1990,41 @@ var Server = class {
1980
1990
  if (isAddressInfo(address)) return address.port;
1981
1991
  return 0;
1982
1992
  }
1983
- async #listen(server) {
1993
+ async #listen(server, signal) {
1994
+ const deadline = this.#timeouts.start === void 0 ? void 0 : createTimeout({ ms: this.#timeouts.start });
1995
+ const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
1996
+ const binding = createAbort();
1997
+ const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
1998
+ let listening;
1984
1999
  try {
1985
- const listening = once(server, "listening");
1986
- server.listen(this.#configuredPort ?? 0, this.#host);
2000
+ signal?.throwIfAborted();
2001
+ deadline?.start();
2002
+ if (deadline?.ms === 0 && startup !== void 0) await once(startup, "abort");
2003
+ startup?.throwIfAborted();
2004
+ listening = once(server, "listening", { signal: binding.signal });
2005
+ if (startup === void 0) server.listen(this.#configuredPort ?? 0, this.#host);
2006
+ else server.listen({
2007
+ port: this.#configuredPort ?? 0,
2008
+ ...this.#host === void 0 ? {} : { host: this.#host },
2009
+ signal: binding.signal
2010
+ });
1987
2011
  await listening;
1988
2012
  } catch (error) {
2013
+ const expired = deadline?.expired === true;
2014
+ const cancelled = startup?.aborted === true;
2015
+ server.on("error", () => void 0);
2016
+ binding.abort(error);
2017
+ if (listening !== void 0) await listening.catch(() => void 0);
2018
+ await this.#close(server, true);
1989
2019
  this.#http = void 0;
2020
+ this.#port = void 0;
1990
2021
  this.#status = "idle";
2022
+ if (expired && deadline !== void 0) throw new DOMException(`Server startup exceeded ${deadline.ms} milliseconds`, "TimeoutError");
2023
+ if (cancelled && startup !== void 0) throw startup.reason;
1991
2024
  throw error;
2025
+ } finally {
2026
+ relay?.[Symbol.dispose]();
2027
+ deadline?.clear();
1992
2028
  }
1993
2029
  const port = this.#resolvePort(server);
1994
2030
  this.#port = port;