nish 0.40.1 → 0.42.0

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.
@@ -44,6 +44,15 @@
44
44
  * correctly, not that it can still compile on a platform with no binary. A
45
45
  * postinstall that can break `npm ci` is a worse bug than the startup cost it
46
46
  * exists to remove.
47
+ *
48
+ * **Its second half points at the package's agent skills**, and links none:
49
+ * a skill can grant an agent tools, so it is linked only when the user accepts
50
+ * it, by running `npx nish-skills` (`bin/nish-skills.js`, whose rules are
51
+ * `scripts/link-skills.mjs`'s). Postinstall writes nothing under `.claude/`; it
52
+ * prints one line saying so, and only for a local install into the project
53
+ * `INIT_CWD` names -- not for `-g`, not for npx's cache, not with
54
+ * `NISH_NO_SKILLS` set. It imports the linker for `projectOf` alone, a read,
55
+ * and like the first half it only reports a failure, never raises one.
47
56
  */
48
57
  import fs from "node:fs"
49
58
  import path from "node:path"
@@ -133,9 +142,43 @@ const swap = async () => {
133
142
  return `bin/nish now execs the native compiler in ${name}`
134
143
  }
135
144
 
145
+ /** The line that points the user at `nish-skills`, when every guard passes. */
146
+ const skills = async () => {
147
+ if (fs.existsSync(path.join(root, "src", "compile.ts"))) {
148
+ return "a checkout, so there are no skills to review"
149
+ }
150
+ if (process.env.npm_config_global === "true") {
151
+ return "a global install has no project to link skills into"
152
+ }
153
+ if ((process.env.NISH_NO_SKILLS ?? "") !== "") {
154
+ return "NISH_NO_SKILLS is set, so skills are not mentioned"
155
+ }
156
+ const initCwd = process.env.INIT_CWD ?? ""
157
+ if (initCwd === "") {
158
+ return "INIT_CWD is not set, so there is no project to link skills into"
159
+ }
160
+ const linker = path.join(root, "scripts", "link-skills.mjs")
161
+ if (!fs.existsSync(linker)) {
162
+ return "scripts/link-skills.mjs is missing, so there are no skills to review"
163
+ }
164
+ const { projectOf } = await import(pathToFileURL(linker).href)
165
+ if (projectOf(initCwd, root) === null) {
166
+ return "not installed in INIT_CWD's project, so there are no skills to review"
167
+ }
168
+ return "run 'npx nish-skills' to review and link the agent skills of installed Nish packages"
169
+ }
170
+
136
171
  try {
137
172
  console.log(`nish: ${await swap()}`)
138
173
  } catch (err) {
139
174
  // Deliberately not an error: the shim is still there and still works.
140
175
  console.log(`nish: keeping the node launcher (${err instanceof Error ? err.message : String(err)})`)
141
176
  }
177
+
178
+ // Its own try, so either half failing leaves the other intact; nothing about
179
+ // skills is ever a reason to fail the install.
180
+ try {
181
+ console.log(`nish: ${await skills()}`)
182
+ } catch (err) {
183
+ console.log(`nish: skills not checked (${err instanceof Error ? err.message : String(err)})`)
184
+ }
@@ -0,0 +1,136 @@
1
+ ---
2
+ name: writing-nish
3
+ description: Write a program in Nish, the strictly static subset of TypeScript that compiles ahead of time to native code through LLVM, and get it accepted by the `nish` compiler. Use when asked to write, port, fix or explain a `.ts` program meant for `nish`, when `nish` rejects a program with an `NL` diagnostic code, or when a TypeScript habit (truthiness, `throw`, `any`, casts, `reduce`, callbacks in variables) needs its Nish replacement.
4
+ ---
5
+
6
+ # Writing Nish
7
+
8
+ Nish programs are legal TypeScript syntax, and with `runtime/nish.d.ts` on the
9
+ include path they type-check under `tsc --strict`. That is the trap: **your
10
+ TypeScript instincts produce programs that `tsc` accepts and `nish` rejects.**
11
+ The subset is much smaller than it looks.
12
+
13
+ This skill is the short form. The whole language, stated as rules for a model,
14
+ is the rules card,
15
+ [`docs/AI.md`](https://github.com/amritk/nish/blob/main/docs/AI.md); the
16
+ normative reference is
17
+ [`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md).
18
+ Where this page and those disagree, they win.
19
+
20
+ ## The loop: compile, read the code, fix
21
+
22
+ Do not reason about whether a program is legal. Ask the compiler; it is fast
23
+ and it is the only authority. Install it with `npm install -g nish`.
24
+
25
+ ```bash
26
+ nish program.ts --json # one JSON object per diagnostic, on stdout
27
+ nish --fix program.ts # apply every machine-applicable fix, in place, then report the rest
28
+ nish run program.ts a b # build into a cache, then run it with `a b`
29
+ nish program.ts --link prog # build a native binary (needs clang)
30
+ nish --help # every flag
31
+ ```
32
+
33
+ - **Key on `code`, never on `message`.** `NL2249` means the same rule next
34
+ release; the prose may change.
35
+ - A warning (`"performance"`, `"portability"`, `"deprecation"`) never changes
36
+ the exit code.
37
+ - Exit codes: `0` ok, `1` the program was rejected, `2` usage, `3` the C
38
+ toolchain is unusable, `70` a bug in `nish` worth reporting.
39
+ - `nish --fix` rewrites files with no backup: run it on a committed tree.
40
+ - When it compiles, check the native build against the TypeScript reading:
41
+ `nish program.ts --emit-ts out/` then `node out/entry.ts`. Both must print
42
+ the same and exit the same.
43
+
44
+ ## The shape of a program
45
+
46
+ ```ts nish:ok
47
+ const gcd = (a: i32, b: i32): i32 => {
48
+ let x = a;
49
+ let y = b;
50
+ while (y !== 0) {
51
+ const t = y;
52
+ y = x % y;
53
+ x = t;
54
+ }
55
+ return x;
56
+ };
57
+
58
+ export const main = (): i32 => {
59
+ console.log(`gcd = ${gcd(1071, 462)}`);
60
+ return 0;
61
+ };
62
+ ```
63
+
64
+ Top-level `const` arrows, an exported `main` returning the exit code, explicit
65
+ types everywhere, a template literal instead of `String(n)`. A module holds only
66
+ declarations at the top level: functions, `class`, `interface`, module `const`s,
67
+ `type` aliases, `enum`s (numeric or string) and `import`s.
68
+
69
+ ## Failure is a `Result`
70
+
71
+ There is no `throw`, no `try` and no unwinding. A function that can fail says
72
+ so in its return type.
73
+
74
+ ```ts nish:ok
75
+ const half = (n: i32): Result<i32, string> => {
76
+ if (n % 2 !== 0) {
77
+ return Err("odd");
78
+ }
79
+ return Ok(n / 2);
80
+ };
81
+
82
+ export const main = (): i32 => {
83
+ const outcome = half(7);
84
+ if (outcome.isErr()) {
85
+ console.error(outcome.error);
86
+ return 1;
87
+ }
88
+ console.log(`${outcome.value}`);
89
+ return 0;
90
+ };
91
+ ```
92
+
93
+ `r.orReturn()` propagates an error like Rust's `?`. `panic(m)` ends the process.
94
+
95
+ ## What you must unlearn
96
+
97
+ | Your reflex | Write instead |
98
+ | --- | --- |
99
+ | `if (xs.length)`, `!s.length` (no truthiness) | `if (xs.length !== 0)`, `s.length === 0` |
100
+ | `x == y` | `x === y` |
101
+ | `throw`, `try` / `catch` | `return Err(m)`, `isErr()`, or `panic(m)` |
102
+ | `any`, `unknown`, `undefined` | name the real type; `T \| null` for absence |
103
+ | `x as T`, `x!`, `typeof`, `instanceof` | there are no casts and no runtime types |
104
+ | `xs.reduce`, `.forEach`, `.find` | a `for` loop; `map`, `filter`, `some`, `every`, `findIndex`, `slice` work |
105
+ | `s.split()`, `s.trim()`, `s.toUpperCase()` | index bytes with `charCodeAt` / `substring` |
106
+ | `String(n)`, `n.toString()` | `` `${n}` `` |
107
+ | a callback in a variable or field | there are no function values; pass an arrow straight to a function-typed parameter |
108
+ | `class B extends A`, `static`, getters | repeat the fields and `implements` an interface; module `const`s and plain methods |
109
+ | `A \| B` of anything but tagged variants | a discriminated union, a tag field first in each variant |
110
+ | top-level `let`, top-level code | a module `const`, or a local inside `main` |
111
+ | destructuring, optional parameters, spread arguments | one name per binding; `n: i32 = 1` for a default |
112
+ | `import fs from "fs"`, `export default` | `readFileSync` is a global (or `nish:fs`); a named `export const` |
113
+ | `let v = m.get(k)` on a `Map` | `m.get(k) ?? 0`, or narrow with `!== undefined` first |
114
+ | `JSON.parse`, `RegExp`, `Promise`, `new Date()` | `nish/json-typed`, `nish/regex`, `await` at the call, `Date.now()` |
115
+
116
+ The most common rejection, NL2188:
117
+
118
+ ```ts nish:err-body NL2188
119
+ const xs = [1, 2, 3];
120
+ if (xs.length) {
121
+ console.log("non-empty");
122
+ }
123
+ ```
124
+
125
+ ## Before you say it compiles
126
+
127
+ 1. Did you **run the compiler**? Nothing else counts.
128
+ 2. Is every condition a `boolean`?
129
+ 3. Is every method you call a real builtin? The list is in
130
+ [the rules card](https://github.com/amritk/nish/blob/main/docs/AI.md#the-builtins-in-full).
131
+ 4. Is every parameter, return type, field and module constant annotated, and
132
+ does every numeric width match exactly (no `i32` meeting `i64`)?
133
+ 5. Is every `Result` read, and every `.value` behind an `isOk()`?
134
+ 6. Is every nullable narrowed with `!== null` before it is touched?
135
+ 7. Does it reach only what you meant? `nish run --capabilities file.ts` lists
136
+ the files, network, processes and C calls it can reach.
package/std/README.md CHANGED
@@ -35,6 +35,7 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
35
35
  | [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#map-and-set)) |
36
36
  | [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-runs-skipblank-skipdigits-skipjsontext-skipjsonplain-and-copybytes-in-nishbytes)). The runs are variable-time. `tests/link/std_bytes*` are its programs |
37
37
  | [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string, `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array panics before a byte is written. It indexes its alphabet by the sextet, so it is not constant-time: it is for pixels, not secrets. A strict decoder, and an encoder for key material, are `crypto/base64url.ts`'s `base64StdPadDecode` and `base64StdPadEncode` (`tests/link/std_base64`, `std_base64_f64`, `std_base64_negative_*`; the two modules in one program: `tests/link/std_base64_two_modules`; [guide](../docs/guide/using-nish/standard-library.md#nishbase64)) |
38
+ | [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin. There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
38
39
  | [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, written with `nish:unsafe`'s `wrappingAdd`, `wrappingSub` and `wrappingMul` so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
39
40
  | [`cli.ts`](https://github.com/amritk/nish/blob/main/std/cli.ts) | a command-line tool's `--help`. `HelpMenu` builds it a line at a time — `header`, `usage`, `section`, `row(flag, placeholder, description)`, `note`, `value` — with descriptions lined up at the caller's columns, counted on the plain text, and answers it with `text()`. `Style` paints it in the basic ANSI colours, bold and faint, which the terminal's theme defines, or in bold and underline alone when `TERM` declares no colours; each role it paints (`heading`, `name`, `flag`, `meta`, `dim`) is a pair of SGR lists, `<role>Themed` and `<role>Mono`, a program may set. `Style` also paints any text: the sixteen colours (`red`, `brightBlack`, ...), their backgrounds (`bgRed`, `bgBrightRed`, ...), the attributes (`bold`, `faint`, `italic`, `underline`, `inverse`, `strikethrough`, which the failsafe keeps) and `sgr(text, codes)` for any parameter list, with the `SGR_` constants spelling the codes. `styleFor(fd, agent)` is the policy `nish --help` follows: plain unless the descriptor is a terminal, `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE`, `CLICOLOR` and `TERM=dumb` honoured, plain for an agent (`agentDriven`), forced colour always the theme's; it reads the environment and, for the terminal check, forks `/bin/sh` once, which runs `tput` by absolute path. `HelpMenu` and `Style` reach no capability. The compiler's own help is built with it through a relative import, so the module may use only what the last release compiles (`tests/link/std_cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli)) |
40
41
  | [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle and every mistake a panic at its call. `parse(argv, start)` walks the arguments once and answers a `ParseResult`: the reached command's id and path, each flag's value with its `source` (the command line, its default or unset), the positionals and what follows `--`, or the first error with a did-you-mean. `finish` prints help (laid out by `HelpMenu`), the version or the error and exits 0 or 2. `parse` reaches no capability (`tests/link/std_cli_args`, `examples/api-cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli-args)) |
package/std/net/fetch.ts CHANGED
@@ -492,6 +492,8 @@ export class FetchSyncClient {
492
492
  private rbuf: u8[]
493
493
  /** Where TLS application data is read before the parser takes it; empty until the first https connection. */
494
494
  private plain: u8[]
495
+ /** Where a redirect's body is read and thrown away; empty until the first redirect that has one. */
496
+ private sink: u8[]
495
497
  /** The fetch's end in monotonic nanoseconds; `HTTP_CLIENT_NEVER` for none. */
496
498
  private deadline: i64 = 0
497
499
  /** The last failure's `HTTP_E_*` code; `HTTP_E_NONE` after a fetch that answered. */
@@ -530,6 +532,7 @@ export class FetchSyncClient {
530
532
  this.ready = new Array<i32>(8)
531
533
  this.rbuf = new Array<u8>(HTTP_CLIENT_READ_BYTES)
532
534
  this.plain = []
535
+ this.sink = []
533
536
  const proxies: string[] = httpClientEnvProxies(options)
534
537
  this.httpProxy = proxies[0]
535
538
  this.httpsProxy = proxies[1]
@@ -1192,9 +1195,14 @@ export class FetchSyncClient {
1192
1195
  /**
1193
1196
  * Reads past a redirect's body so the connection can carry the next
1194
1197
  * request; a body too long to be worth reading, or any failure, closes it.
1198
+ * The sink is the client's, kept for the next hop: one built per call would
1199
+ * stay in the caller's memory for every redirect the fetch follows.
1195
1200
  */
1196
1201
  private drain(): void {
1197
- const sink: u8[] = new Array<u8>(HTTP_CLIENT_DRAIN_CHUNK)
1202
+ if (toI32(this.sink.length) === 0) {
1203
+ this.sink = new Array<u8>(HTTP_CLIENT_DRAIN_CHUNK)
1204
+ }
1205
+ const sink: u8[] = this.sink
1198
1206
  let left: i32 = HTTP_CLIENT_DRAIN_BYTES
1199
1207
  while (this.bodyOpen && left > 0) {
1200
1208
  const n: i32 = this.readBody(this.generation, sink, HTTP_CLIENT_ZERO, HTTP_CLIENT_DRAIN_CHUNK)
@@ -105,7 +105,15 @@ import {
105
105
  routerDecode,
106
106
  } from "nish/net/router"
107
107
  import { URL_DECODE_ALLOW_NUL, URL_DECODE_ERR_SPACE, URL_DECODE_FORM, percentDecode } from "nish/net/url"
108
- import { pollAdd, pollCreate, pollModify, pollRemove, pollWait } from "nish:net"
108
+ import {
109
+ NET_LISTEN_RING,
110
+ pollAdd,
111
+ pollCreate,
112
+ pollModify,
113
+ pollRemove,
114
+ pollWait,
115
+ tcpListenFlags,
116
+ } from "nish:net"
109
117
 
110
118
  /** An answer sent, or queued to be sent. */
111
119
  export const HANDLER_SENT: i32 = 0
@@ -142,7 +150,10 @@ const HANDLER_ONE_MIB: i32 = 1048576
142
150
  /** `tcpAccept`: none is waiting (EAGAIN), or the one that was left before it was taken (ECONNABORTED). */
143
151
  const HANDLER_ACCEPT_NONE: i32 = -11
144
152
  const HANDLER_ACCEPT_ABORTED: i32 = -103
145
- /** How long the listener rests after an accept fails for want of descriptors or memory: 100 ms. */
153
+ /**
154
+ * How long, at most, the listener rests after an accept fails for want of
155
+ * descriptors, ring slots or memory: 100 ms, or until a connection closes.
156
+ */
146
157
  const HANDLER_ACCEPT_REST: i64 = 100000000
147
158
  /** How often, at most, `wait` looks for a body past `bodyTimeout`: a second, in nanoseconds. */
148
159
  const HANDLER_BODY_SWEEP: i64 = 1000000000
@@ -160,8 +171,21 @@ const HANDLER_TOOK_THREE: i32 = 768
160
171
  export class HandlerLimits {
161
172
  /** The carrier's caps and timeouts; `http.maxBody` is the body cap, past which a request is answered 413. */
162
173
  http: Http1Config
163
- /** The most connections at once. */
174
+ /**
175
+ * The most connections at once. It is the handler's own cap, not
176
+ * `RLIMIT_NOFILE`: with `ring` set the connections live in io_uring slots
177
+ * and may outnumber the descriptor limit. Past it a connection is accepted
178
+ * and closed at once.
179
+ */
164
180
  slots: i32 = 256
181
+ /**
182
+ * Whether `listen` opens its listener with `NET_LISTEN_RING`, so each
183
+ * connection is accepted into an io_uring slot rather than a descriptor.
184
+ * Off by default. Where the kernel refuses rings, the listener serves
185
+ * descriptors and `netRingState` says why. A connection is then a slot
186
+ * handle, which `sendFd` and a C library through `nish:ffi` cannot take.
187
+ */
188
+ ring: boolean = false
165
189
  /**
166
190
  * Bytes in the JSON scratch buffer: the largest body `json` and `problem`
167
191
  * can write. A value past it makes `sendJson` answer 500. At least 256.
@@ -188,6 +212,19 @@ export class HandlerLimits {
188
212
  this.http = new Http1Config()
189
213
  this.http.maxBody = HANDLER_ONE_MIB
190
214
  }
215
+
216
+ /**
217
+ * Opens a TCP listener for an `HttpHandler` with these limits:
218
+ * `tcpListenFlags` with `flags`, plus `NET_LISTEN_RING` when `ring` is set.
219
+ * @param host the address to bind, such as "0.0.0.0"
220
+ * @param port the port to bind, or 0 for one the kernel picks
221
+ * @param backlog the kernel's queue of connections not yet accepted
222
+ * @param flags `tcpListenFlags`' other bits: 1 for `SO_REUSEPORT`, 2 for `TCP_NODELAY`
223
+ * @returns the listener, or a negative errno
224
+ */
225
+ listen(host: string, port: i32, backlog: i32, flags: i32): i32 {
226
+ return tcpListenFlags(host, port, backlog, this.ring ? flags | NET_LISTEN_RING : flags)
227
+ }
191
228
  }
192
229
 
193
230
  /**
@@ -523,9 +560,10 @@ export class HttpHandler {
523
560
  private problemType: u8[]
524
561
  private noFields: u8[][]
525
562
  /**
526
- * When an accept failed for want of a resource (EMFILE, ENFILE, ENOMEM):
527
- * the listener is out of the loop until then, which it would otherwise wake
528
- * every turn while its connection waits. 0 while it is in the loop.
563
+ * When an accept failed for want of a resource (EMFILE for descriptors,
564
+ * ENFILE for ring slots, ENOMEM): the listener is out of the loop until
565
+ * then, or until a connection closes (`forget`), which it would otherwise
566
+ * wake every turn while its connection waits. 0 while it is in the loop.
529
567
  */
530
568
  private acceptRestUntil: i64 = 0
531
569
  /** `bodyTimeout` in nanoseconds. */
@@ -559,7 +597,9 @@ export class HttpHandler {
559
597
  * A handler over `listener`, a listening socket the program made
560
598
  * (`tcpListen`, or `tcpListenFlags` with SO_REUSEPORT for a worker of
561
599
  * `nish/net/prefork`), routing through `router`, whose routes are added
562
- * before the first `wait`.
600
+ * before the first `wait`. `limits.ring` acts only through the listener:
601
+ * open it with `limits.listen`, since a listener from `tcpListen` stays on
602
+ * descriptors whatever `ring` says.
563
603
  * @param limits the caps and timeouts. `slots`, `jsonBytes`, `maxEvents`
564
604
  * and `bodyTimeout` are read once here, so changing them later has no
565
605
  * effect; `http` is kept by the carrier, which reads its timeouts and
@@ -652,10 +692,7 @@ export class HttpHandler {
652
692
  this.watchedFired[id] = false
653
693
  }
654
694
  if (this.acceptRestUntil > 0 && monotonicNanos() >= this.acceptRestUntil) {
655
- this.acceptRestUntil = 0
656
- if (!this.draining) {
657
- pollAdd(this.loop, this.listener, H1_WANT_READ, HANDLER_LISTENER)
658
- }
695
+ this.endAcceptRest()
659
696
  }
660
697
  let timeout: i32 = timeoutMs
661
698
  if (this.acceptRestUntil > 0 && !this.draining) {
@@ -759,8 +796,9 @@ export class HttpHandler {
759
796
  slot = this.server.accept()
760
797
  }
761
798
  if (slot !== HANDLER_ACCEPT_NONE) {
762
- // Out of descriptors or memory: the connection stays in the backlog
763
- // and the listener stays readable, so rest it rather than spin.
799
+ // Out of descriptors (-24), ring slots (-23) or memory: the connection
800
+ // stays in the backlog and the listener stays readable, so rest it
801
+ // rather than spin, until a close frees one or the rest ends.
764
802
  pollRemove(this.loop, this.listener)
765
803
  this.acceptRestUntil = monotonicNanos() + HANDLER_ACCEPT_REST
766
804
  }
@@ -1088,8 +1126,22 @@ export class HttpHandler {
1088
1126
  this.forget(slot)
1089
1127
  }
1090
1128
 
1091
- /** The bookkeeping of a slot the carrier has closed. */
1129
+ /** Ends the listener's rest: it is back in the loop unless the handler is draining. */
1130
+ private endAcceptRest(): void {
1131
+ this.acceptRestUntil = 0
1132
+ if (!this.draining) {
1133
+ pollAdd(this.loop, this.listener, H1_WANT_READ, HANDLER_LISTENER)
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * The bookkeeping of a slot the carrier has closed. Its descriptor or ring
1139
+ * slot is free again, so a listener resting for want of one comes back.
1140
+ */
1092
1141
  private forget(slot: i32): void {
1142
+ if (this.acceptRestUntil > 0 && !this.draining) {
1143
+ this.endAcceptRest()
1144
+ }
1093
1145
  this.open[slot] = false
1094
1146
  this.slotGen[slot] = this.slotGen[slot] + 1
1095
1147
  const at: i32 = this.current[slot]
@@ -1191,6 +1243,18 @@ export class HttpHandler {
1191
1243
  return this.server.busy()
1192
1244
  }
1193
1245
 
1246
+ /**
1247
+ * Whether the listener is resting: an accept failed for want of a resource
1248
+ * (EMFILE for descriptors, ENFILE for ring slots, ENOMEM), so the handler
1249
+ * takes no connection until one closes or the 100 ms rest ends. During
1250
+ * `drain()` a close does not end the rest, so it stays true until the
1251
+ * 100 ms pass.
1252
+ * @returns true while the listener is out of the loop for such a rest
1253
+ */
1254
+ resting(): boolean {
1255
+ return this.acceptRestUntil > 0
1256
+ }
1257
+
1194
1258
  // ---- Responses ------------------------------------------------------------------
1195
1259
 
1196
1260
  /**
@@ -1230,6 +1230,19 @@ export class Http1Connection {
1230
1230
  )
1231
1231
  }
1232
1232
 
1233
+ /**
1234
+ * Whether the connection is between requests, so that a server draining
1235
+ * gracefully may close it without cutting a request short: it speaks HTTP,
1236
+ * not upgraded or closing, no request is open, no next head has begun to
1237
+ * arrive (its `headTimeout` clock has not started), and every byte of the
1238
+ * last response is sent.
1239
+ *
1240
+ * @returns true while closing the connection loses nothing its client sent or is owed
1241
+ */
1242
+ betweenRequests(): boolean {
1243
+ return this.state === H1_S_HTTP && !this.requestOpen && !this.headTimed && !this.wantsWrite()
1244
+ }
1245
+
1233
1246
  /** The room at the end of the output, once what was sent is moved out of the way. */
1234
1247
  private room(): i32 {
1235
1248
  // Tested here, so that the usual case, an output already held, is no call.