@orkestrel/server 0.0.20 → 0.0.22

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.
@@ -1555,11 +1555,20 @@ export declare function serializeEvent(message: SSEMessage): string;
1555
1555
  * bind is pending, and transitions `idle → starting → listening`. A
1556
1556
  * cancelled or expired bind closes its partial server and resets to `idle` for
1557
1557
  * another start. `stop()` transitions
1558
- * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1559
- * so in-flight handlers observe cancellation, drains in-flight requests and
1558
+ * to `stopping`: fires a fresh-per-run stop signal so in-flight handlers
1559
+ * observe cancellation (a request that arrives during the drain is served
1560
+ * with that signal already aborted), drains in-flight requests and
1560
1561
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1561
- * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1562
- * still open. `destroy()` is the idempotent final teardown.
1562
+ * busy-loop), then closes → `stopped`. After a clean drain the close
1563
+ * destroys every connection that carries no open request exchange, and a
1564
+ * connection that still carries one ends when its last exchange completes
1565
+ * or the same `drain` deadline expires, whichever comes first.
1566
+ * A request or an upgrade that such a connection sends after the listener
1567
+ * closes is refused: its connection is destroyed before the request is
1568
+ * counted or a handler sees it, so the `stop()` call waits only on work
1569
+ * counted before the close. After an expired drain the close destroys every
1570
+ * socket. A `stop()` call made while a stop runs returns that stop's
1571
+ * promise. `destroy()` is the idempotent final teardown.
1563
1572
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1564
1573
  * `close`); a `Request` is built through the router's `buildRequest`, its
1565
1574
  * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
@@ -1585,7 +1594,7 @@ export declare function serializeEvent(message: SSEMessage): string;
1585
1594
  * throwing handler is treated as declined and surfaced on `error`, an
1586
1595
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1587
1596
  * A claimed socket joins `#upgraded` until it closes: the claimant still
1588
- * owns it, and the tracking exists because node detaches an upgraded socket
1597
+ * owns it, and the tracking exists because Node detaches an upgraded socket
1589
1598
  * from the set its own close calls walk, so nothing else can end it.
1590
1599
  * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1591
1600
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
@@ -1712,14 +1721,15 @@ export declare type ServerEventMap = {
1712
1721
  * from the bound address), exposes that {@link AddressInfo} through `address`,
1713
1722
  * observes caller cancellation plus `timeouts.start` while binding, and resolves
1714
1723
  * the actually-bound port. A cancelled or expired bind closes its partial server
1715
- * and resets to `idle`. `stop()` refuses new
1716
- * connections, fires the stop signal so in-flight handlers can observe it,
1717
- * drains in-flight requests and claimed upgraded sockets up to the configured
1718
- * deadline, then closes — forcing whatever is left. `destroy()` is the final
1719
- * idempotent teardown. Per request: a `Request` is built through the router's
1720
- * `buildRequest` (its signal linked to the server's stop signal), the composed
1721
- * middleware onion runs terminating in `dispatcher.handle`, and the result is
1722
- * written back through `sendResponse` — every escaping throw is caught by the
1724
+ * and resets to `idle`. `stop()` fires the stop signal so in-flight handlers
1725
+ * can observe it, drains in-flight requests and claimed upgraded sockets up to
1726
+ * the configured deadline, then closes the listener and ends each connection
1727
+ * when no request exchange is open on it; when that same deadline expires it
1728
+ * destroys every socket still open. `destroy()` is the final idempotent teardown. Per request: a `Request` is
1729
+ * built through the router's `buildRequest` (its signal linked to the server's
1730
+ * stop signal), the composed middleware onion runs terminating in
1731
+ * `dispatcher.handle`, and the result is written back through
1732
+ * `sendResponse` — every escaping throw is caught by the
1723
1733
  * built-in boundary (`HTTPError` → its status; anything else → a
1724
1734
  * hidden-unless-`expose` `500`) so a handler error can never crash the process.
1725
1735
  */
@@ -1777,26 +1787,59 @@ export declare interface ServerInterface<TState> {
1777
1787
  */
1778
1788
  start(signal?: AbortSignal): Promise<number>;
1779
1789
  /**
1780
- * Stops gracefully: refuses new connections, fires the stop signal, drains in-flight
1781
- * requests and claimed upgraded sockets up to the `drain` deadline, then closes.
1790
+ * Stops gracefully within the `drain` deadline: fires the stop signal, drains in-flight
1791
+ * requests and claimed upgraded sockets, then closes the listener; after a clean drain it
1792
+ * ends each connection when no request exchange is open on it, and when the deadline
1793
+ * expires it destroys every socket still open.
1782
1794
  *
1783
1795
  * @remarks
1784
1796
  * Drainable work is every in-flight request plus every upgraded socket a
1785
1797
  * handler claimed. The drain parks on that work reaching zero or the
1786
- * `drain` deadline expiring, emits `drain` with both remaining counts, and
1787
- * then closes — dropping idle keep-alive sockets on a clean drain, and
1788
- * destroying every open socket (including the claimed upgraded ones node's
1789
- * own force-close cannot reach) when either count is still non-zero. It
1790
- * therefore always resolves; the `drain` counts say whether anything was cut.
1798
+ * `drain` deadline expiring, emits the `drain` event with both remaining
1799
+ * counts, and then closes the listener. A request that arrives while the
1800
+ * drain runs is counted and served with its signal already aborted. A
1801
+ * request or an upgrade that a connection sends after the listener closes
1802
+ * is refused: the server destroys that connection before the request is
1803
+ * counted or a handler sees it. An exchange opens when a request reaches
1804
+ * the handler and stays open until its request message has ended or closed
1805
+ * and its response has finished or closed. The `error` listeners that this
1806
+ * tracking attaches to the message and the response stay attached, so a
1807
+ * later error on either raises no uncaught exception. After a clean drain
1808
+ * the close destroys every connection with no open exchange: an idle
1809
+ * keep-alive one, one that never sent a request, and one partway through
1810
+ * any header block, because a request whose headers never completed is not
1811
+ * counted work. A connection that still carries an open exchange, including
1812
+ * one whose handler answered while its body still uploads, ends when its
1813
+ * last exchange completes, and the `stop()` call resolves after that
1814
+ * connection closes. Each body byte restarts Node's keep-alive socket
1815
+ * timer, so no Node timeout bounds an upload that keeps sending. The
1816
+ * deadline that bounds the drain therefore stays armed through this wait:
1817
+ * when it expires before the server's `close` event, the server destroys
1818
+ * every socket still open, as an expired drain does, so no connection
1819
+ * holds the `stop()` call past the `drain` deadline. A request Node
1820
+ * answers itself, such as the `417` response to an unknown `Expect` value,
1821
+ * never reaches the handler and opens no exchange. When either count is
1822
+ * still non-zero, the close destroys every socket at once, including the
1823
+ * claimed upgraded ones Node's own force-close cannot reach. The `drain`
1824
+ * counts say whether a request or a claimed socket was cut, and a cut
1825
+ * during the clean close's wait reports `[0, 0]`, because every response
1826
+ * had finished at the clean drain. That cut ends the unread part of an
1827
+ * upload the handler had already answered, and destroying its socket can
1828
+ * also reset the connection and lose the answered response the peer has
1829
+ * not yet read. No event reports that cut or that loss. A `stop()` call
1830
+ * made while a stop runs returns that stop's promise, including a call
1831
+ * made from a `stop` event listener or from a listener on the stop signal.
1791
1832
  *
1792
- * @returns Resolves once the listener is closed and the status is `'stopped'`
1833
+ * @returns Resolves after the listener is closed and the status is
1834
+ * `'stopped'`; a call from `'idle'`, `'starting'`, or `'stopped'` while
1835
+ * no stop runs resolves at once and changes nothing
1793
1836
  */
1794
1837
  stop(): Promise<void>;
1795
1838
  /**
1796
1839
  * Tears down for good: force-closes the listener and every socket, then the emitter —
1797
1840
  * terminal and idempotent from any state.
1798
1841
  *
1799
- * @returns Resolves once nothing is left open; idempotent from any state
1842
+ * @returns Resolves after nothing is left open; idempotent from any state
1800
1843
  */
1801
1844
  destroy(): Promise<void>;
1802
1845
  }
@@ -1823,12 +1866,14 @@ export declare interface ServerInterface<TState> {
1823
1866
  * `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
1824
1867
  * guaranteed-free port up front).
1825
1868
  * @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
1826
- * server stops accepting new connections and gives in-flight requests and
1827
- * claimed upgraded sockets this long to finish before forcing every
1828
- * remaining socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be a
1829
- * non-negative finite number. A long-lived upgraded socket that nothing
1830
- * closes therefore costs `stop()` this whole budget, so a WebSocket
1831
- * handler closes its sockets on the `stop` event to settle sooner.
1869
+ * server stops accepting new connections and gives in-flight requests,
1870
+ * claimed upgraded sockets, and connections that still carry an open
1871
+ * request exchange this long to finish before forcing every remaining
1872
+ * socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be an integer from
1873
+ * 0 through 2_147_483_647; construction throws a `TypeError` otherwise.
1874
+ * A long-lived upgraded socket that nothing closes therefore costs
1875
+ * `stop()` this whole budget, so a WebSocket handler closes its sockets
1876
+ * on the `stop` event to settle sooner.
1832
1877
  * @param limit - The default request-body byte cap the context's `body()`
1833
1878
  * reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
1834
1879
  * finite number.
@@ -1846,8 +1891,10 @@ export declare interface ServerInterface<TState> {
1846
1891
  * to receive the request headers, `headersTimeout`), and `keepalive` (idle
1847
1892
  * keep-alive socket timeout, `keepAliveTimeout`). `headers` must not exceed
1848
1893
  * `keepalive` (the Slowloris footgun) — construction throws a `TypeError`
1849
- * otherwise. Every present value must be a non-negative finite number. A
1850
- * startup expiry rejects with a `DOMException` named `TimeoutError`; caller
1894
+ * otherwise. A present `start` must be an integer from 0 through
1895
+ * 2_147_483_647, and every other present value a non-negative finite
1896
+ * number; construction throws a `TypeError` otherwise. A startup expiry
1897
+ * rejects with a `DOMException` named `TimeoutError`; caller
1851
1898
  * cancellation rejects with the caller signal's `reason`.
1852
1899
  * @param sockets - `node:http` socket caps: `connections` maps to
1853
1900
  * `maxConnections` (`0` rejects every incoming connection), `headers` maps
@@ -2158,7 +2205,7 @@ export declare function unwrapETag(tag: string): string;
2158
2205
  * over verbatim — no assertion at this boundary.
2159
2206
  *
2160
2207
  * A claimed socket is tracked until it closes. The handler still owns it —
2161
- * the server only watches — but `stop()` now drains that socket like an
2208
+ * the server only watches — but `stop()` drains that socket like an
2162
2209
  * in-flight request and destroys it if the `drain` deadline expires first.
2163
2210
  * Node detaches an upgraded socket from its own connection set, so neither
2164
2211
  * `closeIdleConnections()` nor `closeAllConnections()` reaches it and this
@@ -1555,11 +1555,20 @@ export declare function serializeEvent(message: SSEMessage): string;
1555
1555
  * bind is pending, and transitions `idle → starting → listening`. A
1556
1556
  * cancelled or expired bind closes its partial server and resets to `idle` for
1557
1557
  * another start. `stop()` transitions
1558
- * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1559
- * so in-flight handlers observe cancellation, drains in-flight requests and
1558
+ * to `stopping`: fires a fresh-per-run stop signal so in-flight handlers
1559
+ * observe cancellation (a request that arrives during the drain is served
1560
+ * with that signal already aborted), drains in-flight requests and
1560
1561
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1561
- * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1562
- * still open. `destroy()` is the idempotent final teardown.
1562
+ * busy-loop), then closes → `stopped`. After a clean drain the close
1563
+ * destroys every connection that carries no open request exchange, and a
1564
+ * connection that still carries one ends when its last exchange completes
1565
+ * or the same `drain` deadline expires, whichever comes first.
1566
+ * A request or an upgrade that such a connection sends after the listener
1567
+ * closes is refused: its connection is destroyed before the request is
1568
+ * counted or a handler sees it, so the `stop()` call waits only on work
1569
+ * counted before the close. After an expired drain the close destroys every
1570
+ * socket. A `stop()` call made while a stop runs returns that stop's
1571
+ * promise. `destroy()` is the idempotent final teardown.
1563
1572
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1564
1573
  * `close`); a `Request` is built through the router's `buildRequest`, its
1565
1574
  * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
@@ -1585,7 +1594,7 @@ export declare function serializeEvent(message: SSEMessage): string;
1585
1594
  * throwing handler is treated as declined and surfaced on `error`, an
1586
1595
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1587
1596
  * A claimed socket joins `#upgraded` until it closes: the claimant still
1588
- * owns it, and the tracking exists because node detaches an upgraded socket
1597
+ * owns it, and the tracking exists because Node detaches an upgraded socket
1589
1598
  * from the set its own close calls walk, so nothing else can end it.
1590
1599
  * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1591
1600
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
@@ -1712,14 +1721,15 @@ export declare type ServerEventMap = {
1712
1721
  * from the bound address), exposes that {@link AddressInfo} through `address`,
1713
1722
  * observes caller cancellation plus `timeouts.start` while binding, and resolves
1714
1723
  * the actually-bound port. A cancelled or expired bind closes its partial server
1715
- * and resets to `idle`. `stop()` refuses new
1716
- * connections, fires the stop signal so in-flight handlers can observe it,
1717
- * drains in-flight requests and claimed upgraded sockets up to the configured
1718
- * deadline, then closes — forcing whatever is left. `destroy()` is the final
1719
- * idempotent teardown. Per request: a `Request` is built through the router's
1720
- * `buildRequest` (its signal linked to the server's stop signal), the composed
1721
- * middleware onion runs terminating in `dispatcher.handle`, and the result is
1722
- * written back through `sendResponse` — every escaping throw is caught by the
1724
+ * and resets to `idle`. `stop()` fires the stop signal so in-flight handlers
1725
+ * can observe it, drains in-flight requests and claimed upgraded sockets up to
1726
+ * the configured deadline, then closes the listener and ends each connection
1727
+ * when no request exchange is open on it; when that same deadline expires it
1728
+ * destroys every socket still open. `destroy()` is the final idempotent teardown. Per request: a `Request` is
1729
+ * built through the router's `buildRequest` (its signal linked to the server's
1730
+ * stop signal), the composed middleware onion runs terminating in
1731
+ * `dispatcher.handle`, and the result is written back through
1732
+ * `sendResponse` — every escaping throw is caught by the
1723
1733
  * built-in boundary (`HTTPError` → its status; anything else → a
1724
1734
  * hidden-unless-`expose` `500`) so a handler error can never crash the process.
1725
1735
  */
@@ -1777,26 +1787,59 @@ export declare interface ServerInterface<TState> {
1777
1787
  */
1778
1788
  start(signal?: AbortSignal): Promise<number>;
1779
1789
  /**
1780
- * Stops gracefully: refuses new connections, fires the stop signal, drains in-flight
1781
- * requests and claimed upgraded sockets up to the `drain` deadline, then closes.
1790
+ * Stops gracefully within the `drain` deadline: fires the stop signal, drains in-flight
1791
+ * requests and claimed upgraded sockets, then closes the listener; after a clean drain it
1792
+ * ends each connection when no request exchange is open on it, and when the deadline
1793
+ * expires it destroys every socket still open.
1782
1794
  *
1783
1795
  * @remarks
1784
1796
  * Drainable work is every in-flight request plus every upgraded socket a
1785
1797
  * handler claimed. The drain parks on that work reaching zero or the
1786
- * `drain` deadline expiring, emits `drain` with both remaining counts, and
1787
- * then closes — dropping idle keep-alive sockets on a clean drain, and
1788
- * destroying every open socket (including the claimed upgraded ones node's
1789
- * own force-close cannot reach) when either count is still non-zero. It
1790
- * therefore always resolves; the `drain` counts say whether anything was cut.
1798
+ * `drain` deadline expiring, emits the `drain` event with both remaining
1799
+ * counts, and then closes the listener. A request that arrives while the
1800
+ * drain runs is counted and served with its signal already aborted. A
1801
+ * request or an upgrade that a connection sends after the listener closes
1802
+ * is refused: the server destroys that connection before the request is
1803
+ * counted or a handler sees it. An exchange opens when a request reaches
1804
+ * the handler and stays open until its request message has ended or closed
1805
+ * and its response has finished or closed. The `error` listeners that this
1806
+ * tracking attaches to the message and the response stay attached, so a
1807
+ * later error on either raises no uncaught exception. After a clean drain
1808
+ * the close destroys every connection with no open exchange: an idle
1809
+ * keep-alive one, one that never sent a request, and one partway through
1810
+ * any header block, because a request whose headers never completed is not
1811
+ * counted work. A connection that still carries an open exchange, including
1812
+ * one whose handler answered while its body still uploads, ends when its
1813
+ * last exchange completes, and the `stop()` call resolves after that
1814
+ * connection closes. Each body byte restarts Node's keep-alive socket
1815
+ * timer, so no Node timeout bounds an upload that keeps sending. The
1816
+ * deadline that bounds the drain therefore stays armed through this wait:
1817
+ * when it expires before the server's `close` event, the server destroys
1818
+ * every socket still open, as an expired drain does, so no connection
1819
+ * holds the `stop()` call past the `drain` deadline. A request Node
1820
+ * answers itself, such as the `417` response to an unknown `Expect` value,
1821
+ * never reaches the handler and opens no exchange. When either count is
1822
+ * still non-zero, the close destroys every socket at once, including the
1823
+ * claimed upgraded ones Node's own force-close cannot reach. The `drain`
1824
+ * counts say whether a request or a claimed socket was cut, and a cut
1825
+ * during the clean close's wait reports `[0, 0]`, because every response
1826
+ * had finished at the clean drain. That cut ends the unread part of an
1827
+ * upload the handler had already answered, and destroying its socket can
1828
+ * also reset the connection and lose the answered response the peer has
1829
+ * not yet read. No event reports that cut or that loss. A `stop()` call
1830
+ * made while a stop runs returns that stop's promise, including a call
1831
+ * made from a `stop` event listener or from a listener on the stop signal.
1791
1832
  *
1792
- * @returns Resolves once the listener is closed and the status is `'stopped'`
1833
+ * @returns Resolves after the listener is closed and the status is
1834
+ * `'stopped'`; a call from `'idle'`, `'starting'`, or `'stopped'` while
1835
+ * no stop runs resolves at once and changes nothing
1793
1836
  */
1794
1837
  stop(): Promise<void>;
1795
1838
  /**
1796
1839
  * Tears down for good: force-closes the listener and every socket, then the emitter —
1797
1840
  * terminal and idempotent from any state.
1798
1841
  *
1799
- * @returns Resolves once nothing is left open; idempotent from any state
1842
+ * @returns Resolves after nothing is left open; idempotent from any state
1800
1843
  */
1801
1844
  destroy(): Promise<void>;
1802
1845
  }
@@ -1823,12 +1866,14 @@ export declare interface ServerInterface<TState> {
1823
1866
  * `EADDRINUSE` — no silent ephemeral fallback (use `discoverPort` to pick a
1824
1867
  * guaranteed-free port up front).
1825
1868
  * @param drain - The graceful-stop deadline in milliseconds: on `stop()` the
1826
- * server stops accepting new connections and gives in-flight requests and
1827
- * claimed upgraded sockets this long to finish before forcing every
1828
- * remaining socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be a
1829
- * non-negative finite number. A long-lived upgraded socket that nothing
1830
- * closes therefore costs `stop()` this whole budget, so a WebSocket
1831
- * handler closes its sockets on the `stop` event to settle sooner.
1869
+ * server stops accepting new connections and gives in-flight requests,
1870
+ * claimed upgraded sockets, and connections that still carry an open
1871
+ * request exchange this long to finish before forcing every remaining
1872
+ * socket closed. Defaults to `DEFAULT_DRAIN_MS`. Must be an integer from
1873
+ * 0 through 2_147_483_647; construction throws a `TypeError` otherwise.
1874
+ * A long-lived upgraded socket that nothing closes therefore costs
1875
+ * `stop()` this whole budget, so a WebSocket handler closes its sockets
1876
+ * on the `stop` event to settle sooner.
1832
1877
  * @param limit - The default request-body byte cap the context's `body()`
1833
1878
  * reads through. Defaults to `DEFAULT_BODY_LIMIT`. Must be a non-negative
1834
1879
  * finite number.
@@ -1846,8 +1891,10 @@ export declare interface ServerInterface<TState> {
1846
1891
  * to receive the request headers, `headersTimeout`), and `keepalive` (idle
1847
1892
  * keep-alive socket timeout, `keepAliveTimeout`). `headers` must not exceed
1848
1893
  * `keepalive` (the Slowloris footgun) — construction throws a `TypeError`
1849
- * otherwise. Every present value must be a non-negative finite number. A
1850
- * startup expiry rejects with a `DOMException` named `TimeoutError`; caller
1894
+ * otherwise. A present `start` must be an integer from 0 through
1895
+ * 2_147_483_647, and every other present value a non-negative finite
1896
+ * number; construction throws a `TypeError` otherwise. A startup expiry
1897
+ * rejects with a `DOMException` named `TimeoutError`; caller
1851
1898
  * cancellation rejects with the caller signal's `reason`.
1852
1899
  * @param sockets - `node:http` socket caps: `connections` maps to
1853
1900
  * `maxConnections` (`0` rejects every incoming connection), `headers` maps
@@ -2158,7 +2205,7 @@ export declare function unwrapETag(tag: string): string;
2158
2205
  * over verbatim — no assertion at this boundary.
2159
2206
  *
2160
2207
  * A claimed socket is tracked until it closes. The handler still owns it —
2161
- * the server only watches — but `stop()` now drains that socket like an
2208
+ * the server only watches — but `stop()` drains that socket like an
2162
2209
  * in-flight request and destroys it if the `drain` deadline expires first.
2163
2210
  * Node detaches an upgraded socket from its own connection set, so neither
2164
2211
  * `closeIdleConnections()` nor `closeAllConnections()` reaches it and this
@@ -3,8 +3,9 @@ import { addAbortListener, once } from "node:events";
3
3
  import { createServer as createServer$1 } from "node:net";
4
4
  import { decodeBase64URL, encodeBase64URL, encodeHex } from "@orkestrel/codec";
5
5
  import { createServer as createServer$2 } from "node:http";
6
+ import { finished } from "node:stream/promises";
6
7
  import { createAbort, linkSignal } from "@orkestrel/abort";
7
- import { createTimeout } from "@orkestrel/timeout";
8
+ import { createTimeout, isTimeoutDuration } from "@orkestrel/timeout";
8
9
  import { buildRequest, isEncryptedSocket, sendResponse } from "@orkestrel/router/server";
9
10
  import { Emitter } from "@orkestrel/emitter";
10
11
  //#region src/server/constants.ts
@@ -1743,11 +1744,20 @@ var Negotiator = class {
1743
1744
  * bind is pending, and transitions `idle → starting → listening`. A
1744
1745
  * cancelled or expired bind closes its partial server and resets to `idle` for
1745
1746
  * another start. `stop()` transitions
1746
- * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1747
- * so in-flight handlers observe cancellation, drains in-flight requests and
1747
+ * to `stopping`: fires a fresh-per-run stop signal so in-flight handlers
1748
+ * observe cancellation (a request that arrives during the drain is served
1749
+ * with that signal already aborted), drains in-flight requests and
1748
1750
  * claimed upgraded sockets up to the `drain` deadline (event-driven, no
1749
- * busy-loop), then closes → `stopped`, forcing whatever the deadline caught
1750
- * still open. `destroy()` is the idempotent final teardown.
1751
+ * busy-loop), then closes → `stopped`. After a clean drain the close
1752
+ * destroys every connection that carries no open request exchange, and a
1753
+ * connection that still carries one ends when its last exchange completes
1754
+ * or the same `drain` deadline expires, whichever comes first.
1755
+ * A request or an upgrade that such a connection sends after the listener
1756
+ * closes is refused: its connection is destroyed before the request is
1757
+ * counted or a handler sees it, so the `stop()` call waits only on work
1758
+ * counted before the close. After an expired drain the close destroys every
1759
+ * socket. A `stop()` call made while a stop runs returns that stop's
1760
+ * promise. `destroy()` is the idempotent final teardown.
1751
1761
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1752
1762
  * `close`); a `Request` is built through the router's `buildRequest`, its
1753
1763
  * `signal` linked to this run's stop signal through `@orkestrel/abort`'s
@@ -1773,7 +1783,7 @@ var Negotiator = class {
1773
1783
  * throwing handler is treated as declined and surfaced on `error`, an
1774
1784
  * unclaimed upgrade destroys the socket), bound per-run to this instance.
1775
1785
  * A claimed socket joins `#upgraded` until it closes: the claimant still
1776
- * owns it, and the tracking exists because node detaches an upgraded socket
1786
+ * owns it, and the tracking exists because Node detaches an upgraded socket
1777
1787
  * from the set its own close calls walk, so nothing else can end it.
1778
1788
  * - **Observable.** Owns an {@link Emitter} over {@link ServerEventMap}
1779
1789
  * exposed as `readonly emitter`; the emitter isolates a listener throw and
@@ -1786,6 +1796,7 @@ var Server = class {
1786
1796
  #middleware;
1787
1797
  #upgradeHandlers = [];
1788
1798
  #upgraded = /* @__PURE__ */ new Set();
1799
+ #exchanges = /* @__PURE__ */ new Map();
1789
1800
  #emitter;
1790
1801
  #host;
1791
1802
  #configuredPort;
@@ -1801,14 +1812,16 @@ var Server = class {
1801
1812
  #status = "idle";
1802
1813
  #port;
1803
1814
  #pending = 0;
1815
+ #stopping;
1804
1816
  constructor(options) {
1805
1817
  if (!isFunction(options.state)) throw new TypeError("ServerOptions.state must be a function");
1806
1818
  if (options.report !== void 0 && !isFunction(options.report)) throw new TypeError("ServerOptions.report must be a function");
1807
1819
  const drain = options.drain ?? 1e4;
1808
- if (!isFiniteNumber(drain) || drain < 0) throw new TypeError("ServerOptions.drain must be a non-negative finite number");
1820
+ if (!isTimeoutDuration(drain)) throw new TypeError("ServerOptions.drain must be an integer from 0 through 2_147_483_647");
1809
1821
  const limit = options.limit ?? 1048576;
1810
1822
  if (!isFiniteNumber(limit) || limit < 0) throw new TypeError("ServerOptions.limit must be a non-negative finite number");
1811
1823
  const timeouts = options.timeouts ?? {};
1824
+ if (timeouts.start !== void 0 && !isTimeoutDuration(timeouts.start)) throw new TypeError("ServerOptions.timeouts.start must be an integer from 0 through 2_147_483_647");
1812
1825
  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
1826
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1814
1827
  const sockets = options.sockets ?? {};
@@ -1868,26 +1881,18 @@ var Server = class {
1868
1881
  if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
1869
1882
  if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
1870
1883
  server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
1884
+ server.on("connection", (socket) => this.#trackConnection(socket));
1871
1885
  this.#http = server;
1872
1886
  return this.#listen(server, signal);
1873
1887
  }
1874
- async stop() {
1875
- if (this.#status !== "listening") return;
1876
- this.#status = "stopping";
1877
- this.#emitter.emit("stop");
1878
- const server = this.#http;
1879
- this.#abort.abort();
1880
- const deadline = createTimeout({ ms: this.#drain });
1881
- deadline.start();
1882
- await this.#drainPending(deadline.signal);
1883
- deadline.clear();
1884
- const pending = this.#pending;
1885
- const upgraded = this.#upgraded.size;
1886
- this.#emitter.emit("drain", pending, upgraded);
1887
- if (server !== void 0) await this.#close(server, pending + upgraded > 0);
1888
- this.#http = void 0;
1889
- this.#port = void 0;
1890
- this.#status = "stopped";
1888
+ stop() {
1889
+ if (this.#status !== "listening") return this.#stopping ?? Promise.resolve();
1890
+ const { promise, resolve, reject } = Promise.withResolvers();
1891
+ this.#stopping = promise;
1892
+ this.#stopGracefully().finally(() => {
1893
+ if (this.#stopping === promise) this.#stopping = void 0;
1894
+ }).then(resolve, reject);
1895
+ return promise;
1891
1896
  }
1892
1897
  async destroy() {
1893
1898
  if (this.#status === "stopped" && this.#http === void 0) {
@@ -1902,10 +1907,42 @@ var Server = class {
1902
1907
  this.#status = "stopped";
1903
1908
  this.#emitter.destroy();
1904
1909
  }
1910
+ async #stopGracefully() {
1911
+ this.#status = "stopping";
1912
+ this.#emitter.emit("stop");
1913
+ const server = this.#http;
1914
+ this.#abort.abort();
1915
+ const deadline = createTimeout({ ms: this.#drain });
1916
+ deadline.start();
1917
+ try {
1918
+ await this.#drainPending(deadline.signal);
1919
+ const pending = this.#pending;
1920
+ const upgraded = this.#upgraded.size;
1921
+ this.#emitter.emit("drain", pending, upgraded);
1922
+ if (server !== void 0) {
1923
+ const relay = addAbortListener(deadline.signal, () => this.#cut(server));
1924
+ try {
1925
+ await this.#close(server, pending + upgraded > 0);
1926
+ } finally {
1927
+ relay[Symbol.dispose]();
1928
+ }
1929
+ }
1930
+ } finally {
1931
+ deadline.clear();
1932
+ }
1933
+ this.#http = void 0;
1934
+ this.#port = void 0;
1935
+ this.#status = "stopped";
1936
+ }
1905
1937
  #handle(message, response) {
1938
+ if (this.#closed) {
1939
+ message.socket.destroy();
1940
+ return;
1941
+ }
1906
1942
  const finish = this.#trackStart();
1907
1943
  response.once("finish", finish);
1908
1944
  response.once("close", finish);
1945
+ this.#trackExchange(message, response);
1909
1946
  this.#accept(message, response);
1910
1947
  }
1911
1948
  async #accept(message, response) {
@@ -1978,6 +2015,10 @@ var Server = class {
1978
2015
  return new Response(message, { status: 500 });
1979
2016
  }
1980
2017
  #onUpgrade(request, socket, head) {
2018
+ if (this.#closed) {
2019
+ socket.destroy();
2020
+ return;
2021
+ }
1981
2022
  let handled = false;
1982
2023
  for (const handler of this.#upgradeHandlers) try {
1983
2024
  if (handler(request, socket, head)) {
@@ -2046,12 +2087,32 @@ var Server = class {
2046
2087
  #close(server, force) {
2047
2088
  return new Promise((resolve) => {
2048
2089
  server.close(() => resolve());
2049
- if (force) {
2050
- server.closeAllConnections();
2051
- for (const socket of this.#upgraded) socket.destroy();
2052
- } else server.closeIdleConnections();
2090
+ if (force) this.#cut(server);
2091
+ else for (const [socket, open] of this.#exchanges) if (open === 0) socket.destroy();
2053
2092
  });
2054
2093
  }
2094
+ #cut(server) {
2095
+ server.closeAllConnections();
2096
+ for (const socket of this.#upgraded) socket.destroy();
2097
+ }
2098
+ #trackConnection(socket) {
2099
+ this.#exchanges.set(socket, 0);
2100
+ socket.once("close", () => this.#exchanges.delete(socket));
2101
+ }
2102
+ async #trackExchange(message, response) {
2103
+ const socket = message.socket;
2104
+ const open = this.#exchanges.get(socket);
2105
+ if (open === void 0) return;
2106
+ this.#exchanges.set(socket, open + 1);
2107
+ await Promise.allSettled([finished(message), finished(response)]);
2108
+ const left = this.#exchanges.get(socket);
2109
+ if (left === void 0) return;
2110
+ this.#exchanges.set(socket, left - 1);
2111
+ if (left === 1 && this.#closed) socket.destroy();
2112
+ }
2113
+ get #closed() {
2114
+ return this.#status === "stopping" && this.#http?.listening === false;
2115
+ }
2055
2116
  get #inflight() {
2056
2117
  return this.#pending + this.#upgraded.size;
2057
2118
  }
@@ -2064,10 +2125,10 @@ var Server = class {
2064
2125
  #trackStart() {
2065
2126
  this.#enter();
2066
2127
  this.#pending += 1;
2067
- let finished = false;
2128
+ let done = false;
2068
2129
  return () => {
2069
- if (finished) return;
2070
- finished = true;
2130
+ if (done) return;
2131
+ done = true;
2071
2132
  this.#pending -= 1;
2072
2133
  this.#settle();
2073
2134
  };