@orkestrel/server 0.0.7 → 0.0.9

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,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";
@@ -1306,20 +1306,35 @@ function enqueueStreamText(controller, encoder, closed, text) {
1306
1306
  * Builds the `Response` immediately with {@link import('./constants.js').SSE_HEADERS}
1307
1307
  * merged under any `options.headers` (a seam-owned key is never overridden),
1308
1308
  * at `options.status` (default `200`). The returned {@link StreamInterface}'s
1309
- * `write` serializes one message ({@link serializeEvent}) and enqueues it;
1309
+ * `write` serializes one message ({@link serializeEvent}), enqueues it, and
1310
+ * returns whether the controller still has positive desired size. A producer
1311
+ * receiving `false` can await `drain()`; its event-driven promise resolves on
1312
+ * the next consumer pull that restores capacity, or on stream closure.
1310
1313
  * `comment` writes a `: text` keep-alive line a conforming parser ignores;
1311
1314
  * `end` closes the stream. Every method is a SAFE NO-OP once `closed` (ended
1312
1315
  * by `end()`, or the consumer cancelled the stream), so a late write never
1313
1316
  * throws.
1314
1317
  *
1318
+ * This readiness reflects only the process-local `ReadableStream` queue — it
1319
+ * is not proof that a remote peer consumed bytes. When the response pump
1320
+ * honors its socket sink's drain state, socket pressure stops body pulls and
1321
+ * therefore keeps this queue full, allowing a cooperative producer to bound
1322
+ * buffering. Ignoring the return value preserves the prior unconditional-
1323
+ * enqueue behavior. The default stream strategy counts chunks rather than
1324
+ * their byte length, so a byte-bounded producer must also cap each message.
1325
+ * Return `response` before awaiting a `false` write, because the consumer
1326
+ * cannot pull until it receives the response.
1327
+ *
1315
1328
  * @param options - Optional `status` + extra `headers`; see {@link StreamOptions}
1316
1329
  * @returns The {@link StreamInterface} handle
1317
1330
  *
1318
1331
  * @example
1319
1332
  * ```ts
1320
1333
  * const stream = openStream()
1321
- * stream.write({ event: 'token', data: 'hello' })
1322
- * stream.end()
1334
+ * void Promise.resolve().then(async () => {
1335
+ * if (!stream.write({ event: 'token', data: 'hello' })) await stream.drain()
1336
+ * stream.end()
1337
+ * })
1323
1338
  * // return stream.response from the route handler
1324
1339
  * ```
1325
1340
  */
@@ -1327,12 +1342,20 @@ function openStream(options) {
1327
1342
  const encoder = new TextEncoder();
1328
1343
  let closed = false;
1329
1344
  let controller;
1345
+ let wakeup;
1330
1346
  const body = new ReadableStream({
1331
1347
  start(streamController) {
1332
1348
  controller = streamController;
1333
1349
  },
1350
+ pull(streamController) {
1351
+ if (streamController.desiredSize === null || streamController.desiredSize <= 0) return;
1352
+ wakeup?.resolve();
1353
+ wakeup = void 0;
1354
+ },
1334
1355
  cancel() {
1335
1356
  closed = true;
1357
+ wakeup?.resolve();
1358
+ wakeup = void 0;
1336
1359
  }
1337
1360
  });
1338
1361
  const headers = new Headers({
@@ -1348,15 +1371,25 @@ function openStream(options) {
1348
1371
  return closed;
1349
1372
  },
1350
1373
  write(message) {
1374
+ if (closed || controller === void 0) return false;
1351
1375
  enqueueStreamText(controller, encoder, closed, serializeEvent(message));
1376
+ return controller.desiredSize !== null && controller.desiredSize > 0;
1352
1377
  },
1353
1378
  comment(text) {
1354
1379
  enqueueStreamText(controller, encoder, closed, `: ${text}\n\n`);
1355
1380
  },
1381
+ drain() {
1382
+ const desired = controller?.desiredSize;
1383
+ if (closed || desired !== void 0 && desired !== null && desired > 0) return Promise.resolve();
1384
+ wakeup ??= Promise.withResolvers();
1385
+ return wakeup.promise;
1386
+ },
1356
1387
  end() {
1357
1388
  if (closed) return;
1358
1389
  closed = true;
1359
1390
  controller?.close();
1391
+ wakeup?.resolve();
1392
+ wakeup = void 0;
1360
1393
  }
1361
1394
  };
1362
1395
  }
@@ -1745,21 +1778,24 @@ var Negotiator = class {
1745
1778
  * @typeParam TState - The consumer's opaque per-request state type
1746
1779
  *
1747
1780
  * @remarks
1748
- * - **Lifecycle (AGENTS §10).** `start()` builds the underlying `node:http`
1781
+ * - **Lifecycle (AGENTS §10).** `start(signal?)` builds the underlying `node:http`
1749
1782
  * server, binds the configured {@link ServerOptions.host} / {@link
1750
1783
  * 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.
1784
+ * bound address), observes caller cancellation plus the configured
1785
+ * `timeouts.start` deadline while the bind is pending, and transitions
1786
+ * `idle → starting → listening`. A cancelled or expired bind closes its
1787
+ * partial server and resets to `idle` for another start. `stop()` transitions
1788
+ * to `stopping`: refuses new connections, fires a fresh-per-run stop signal
1789
+ * so in-flight handlers observe cancellation, drains up to the `drain`
1790
+ * deadline (event-driven, no busy-loop), then closes → `stopped`. `destroy()`
1791
+ * is the idempotent final teardown.
1756
1792
  * - **Per request.** In-flight is tracked (finished on response `finish` or
1757
1793
  * `close`); a `Request` is built via the router's `buildRequest`, its
1758
1794
  * `signal` LINKED to this run's stop signal via `@orkestrel/abort`'s
1759
1795
  * `linkSignal` (a fresh `Request` is constructed with the linked signal —
1760
- * `buildRequest`'s own abort, tied to client disconnect, composes with the
1761
- * server's stop signal via `AbortSignal.any`, so a handler awaiting
1762
- * `request.signal` observes BOTH); `context.state` is built via
1796
+ * `buildRequest`'s own abort, armed by BOTH request-side and response-side
1797
+ * teardown, composes with the server's stop signal via `AbortSignal.any`,
1798
+ * so a handler awaiting `request.signal` observes BOTH); `context.state` is built via
1763
1799
  * {@link ServerOptions.state} from the connection facts; the composed
1764
1800
  * middleware onion runs, terminating in `dispatcher.handle`; the result is
1765
1801
  * written back via `sendResponse`.
@@ -1795,6 +1831,7 @@ var Server = class {
1795
1831
  #expose;
1796
1832
  #report;
1797
1833
  #timeouts;
1834
+ #sockets;
1798
1835
  #http;
1799
1836
  #abort = createAbort();
1800
1837
  #wakeup = createAbort();
@@ -1811,6 +1848,8 @@ var Server = class {
1811
1848
  const timeouts = options.timeouts ?? {};
1812
1849
  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
1850
  if (timeouts.headers !== void 0 && timeouts.keepalive !== void 0 && timeouts.headers > timeouts.keepalive) throw new TypeError("ServerOptions.timeouts.headers must not exceed timeouts.keepalive");
1851
+ const sockets = options.sockets ?? {};
1852
+ 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
1853
  this.#dispatcher = options.dispatcher;
1815
1854
  this.#state = options.state;
1816
1855
  this.#middleware = options.middleware === void 0 ? [] : [...options.middleware];
@@ -1821,6 +1860,7 @@ var Server = class {
1821
1860
  this.#expose = options.expose ?? false;
1822
1861
  this.#report = options.report;
1823
1862
  this.#timeouts = timeouts;
1863
+ this.#sockets = sockets;
1824
1864
  this.#emitter = new Emitter({
1825
1865
  ...options.on === void 0 ? {} : { on: options.on },
1826
1866
  ...options.error === void 0 ? {} : { error: options.error }
@@ -1845,7 +1885,7 @@ var Server = class {
1845
1885
  upgrade(handler) {
1846
1886
  this.#upgradeHandlers.push(handler);
1847
1887
  }
1848
- start() {
1888
+ start(signal) {
1849
1889
  if (this.#status !== "idle" && this.#status !== "stopped") return Promise.reject(/* @__PURE__ */ new Error(`server cannot start from '${this.#status}'`));
1850
1890
  this.#status = "starting";
1851
1891
  this.#abort = createAbort();
@@ -1853,9 +1893,12 @@ var Server = class {
1853
1893
  if (this.#timeouts.request !== void 0) server.requestTimeout = this.#timeouts.request;
1854
1894
  if (this.#timeouts.headers !== void 0) server.headersTimeout = this.#timeouts.headers;
1855
1895
  if (this.#timeouts.keepalive !== void 0) server.keepAliveTimeout = this.#timeouts.keepalive;
1896
+ if (this.#sockets.connections !== void 0) server.maxConnections = this.#sockets.connections;
1897
+ if (this.#sockets.headers !== void 0) server.maxHeadersCount = this.#sockets.headers;
1898
+ if (this.#sockets.requests !== void 0) server.maxRequestsPerSocket = this.#sockets.requests;
1856
1899
  server.on("upgrade", (request, socket, head) => this.#onUpgrade(request, socket, head));
1857
1900
  this.#http = server;
1858
- return this.#listen(server);
1901
+ return this.#listen(server, signal);
1859
1902
  }
1860
1903
  async stop() {
1861
1904
  if (this.#status !== "listening") return;
@@ -1896,7 +1939,7 @@ var Server = class {
1896
1939
  async #accept(message, response) {
1897
1940
  let raw;
1898
1941
  try {
1899
- raw = buildRequest(message);
1942
+ raw = buildRequest(message, { response });
1900
1943
  } catch {
1901
1944
  await this.#respond(this.#boundary(new HTTPError(400, "invalid request")), response);
1902
1945
  return;
@@ -1980,15 +2023,41 @@ var Server = class {
1980
2023
  if (isAddressInfo(address)) return address.port;
1981
2024
  return 0;
1982
2025
  }
1983
- async #listen(server) {
2026
+ async #listen(server, signal) {
2027
+ const deadline = this.#timeouts.start === void 0 ? void 0 : createTimeout({ ms: this.#timeouts.start });
2028
+ const startup = deadline === void 0 ? signal : linkSignal(deadline.signal, signal);
2029
+ const binding = createAbort();
2030
+ const relay = startup === void 0 ? void 0 : addAbortListener(startup, () => binding.abort(startup.reason));
2031
+ let listening;
1984
2032
  try {
1985
- const listening = once(server, "listening");
1986
- server.listen(this.#configuredPort ?? 0, this.#host);
2033
+ signal?.throwIfAborted();
2034
+ deadline?.start();
2035
+ if (deadline?.ms === 0 && startup !== void 0) await once(startup, "abort");
2036
+ startup?.throwIfAborted();
2037
+ listening = once(server, "listening", { signal: binding.signal });
2038
+ if (startup === void 0) server.listen(this.#configuredPort ?? 0, this.#host);
2039
+ else server.listen({
2040
+ port: this.#configuredPort ?? 0,
2041
+ ...this.#host === void 0 ? {} : { host: this.#host },
2042
+ signal: binding.signal
2043
+ });
1987
2044
  await listening;
1988
2045
  } catch (error) {
2046
+ const expired = deadline?.expired === true;
2047
+ const cancelled = startup?.aborted === true;
2048
+ server.on("error", () => void 0);
2049
+ binding.abort(error);
2050
+ if (listening !== void 0) await listening.catch(() => void 0);
2051
+ await this.#close(server, true);
1989
2052
  this.#http = void 0;
2053
+ this.#port = void 0;
1990
2054
  this.#status = "idle";
2055
+ if (expired && deadline !== void 0) throw new DOMException(`Server startup exceeded ${deadline.ms} milliseconds`, "TimeoutError");
2056
+ if (cancelled && startup !== void 0) throw startup.reason;
1991
2057
  throw error;
2058
+ } finally {
2059
+ relay?.[Symbol.dispose]();
2060
+ deadline?.clear();
1992
2061
  }
1993
2062
  const port = this.#resolvePort(server);
1994
2063
  this.#port = port;