@amritk/nish-aarch64-linux 0.37.0 → 0.39.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.
Files changed (73) hide show
  1. package/INSTALL.md +28 -16
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +380 -47
  4. package/package.json +1 -1
  5. package/runtime/core/arrays.d.ts +4 -0
  6. package/runtime/core/arrays.mjs +33 -0
  7. package/runtime/core/host.d.ts +11 -0
  8. package/runtime/core/host.mjs +35 -0
  9. package/runtime/nish.d.ts +645 -66
  10. package/runtime/nish.h +101 -15
  11. package/runtime/nish.mjs +69 -6
  12. package/runtime/node.mjs +117 -0
  13. package/runtime/runtime-aes.c +12 -4
  14. package/runtime/runtime-async.c +267 -51
  15. package/runtime/runtime-checksum.c +207 -15
  16. package/runtime/runtime-cross.c +2 -1
  17. package/runtime/runtime-net.c +32 -3
  18. package/runtime/runtime-os.c +174 -27
  19. package/runtime/runtime-region.c +170 -8
  20. package/runtime/runtime-sandbox.c +377 -17
  21. package/runtime/runtime-sha256.c +11 -4
  22. package/runtime/runtime-text.c +1068 -0
  23. package/runtime/runtime-wasm.c +18 -3
  24. package/runtime/runtime.c +55 -961
  25. package/runtime/vite.mjs +48 -11
  26. package/scripts/build.sh +113 -36
  27. package/std/LICENSE-fdlibm +8 -0
  28. package/std/README.md +7 -4
  29. package/std/array.ts +266 -0
  30. package/std/compress/checksum.ts +13 -0
  31. package/std/compress/deflate.ts +0 -2
  32. package/std/crypto/p256.ts +247 -74
  33. package/std/crypto/p384.ts +3 -1
  34. package/std/crypto/pki.ts +35 -9
  35. package/std/crypto/x25519.ts +153 -64
  36. package/std/crypto/x509.ts +113 -10
  37. package/std/host/text.ts +86 -0
  38. package/std/json-tokenizer.ts +20 -0
  39. package/std/json-typed.ts +217 -8
  40. package/std/math.ts +743 -41
  41. package/std/net/dns-resolver.ts +46 -6
  42. package/std/net/dns.ts +50 -13
  43. package/std/net/fetch.ts +691 -129
  44. package/std/net/handler.ts +142 -16
  45. package/std/net/http-compress.ts +17 -9
  46. package/std/net/http-fields.ts +19 -4
  47. package/std/net/http1-codec.ts +517 -154
  48. package/std/net/http1-server.ts +508 -25
  49. package/std/net/http2-cleartext.ts +526 -0
  50. package/std/net/http2-tls.ts +48 -0
  51. package/std/net/http2.ts +84 -0
  52. package/std/net/postgres-async.ts +2223 -0
  53. package/std/net/postgres-carrier.ts +343 -10
  54. package/std/net/postgres.ts +129 -11
  55. package/std/net/prefork.ts +195 -11
  56. package/std/net/quic-datagram.ts +30 -0
  57. package/std/net/quic-listener.ts +38 -12
  58. package/std/net/quic-packet.ts +19 -6
  59. package/std/net/quic-recovery.ts +134 -19
  60. package/std/net/quic-stream.ts +174 -36
  61. package/std/net/quic.ts +418 -18
  62. package/std/net/router.ts +39 -17
  63. package/std/net/serve.ts +867 -0
  64. package/std/net/tls/codec.ts +110 -32
  65. package/std/net/tls/record-server.ts +37 -7
  66. package/std/net/tls-tcp.ts +56 -1
  67. package/std/net/tls.ts +196 -50
  68. package/std/net/websocket.ts +55 -18
  69. package/std/net/webtransport.ts +179 -1
  70. package/std/regex.ts +69 -47
  71. package/std/region.ts +62 -11
  72. package/std/secret.ts +26 -59
  73. package/std/text.ts +464 -5
@@ -124,8 +124,9 @@
124
124
  * of an exchange SCRAM began is refused.
125
125
  *
126
126
  * Cleartext and MD5 passwords, and SASL mechanisms other than SCRAM-SHA-256,
127
- * are refused: with no TLS here the first sends the password as it is, and the
128
- * second is a hash any eavesdropper can replay. The password's bytes are used
127
+ * are refused: the first sends the password as it is, and the second is a
128
+ * hash any eavesdropper can replay, over a connection that need not be
129
+ * encrypted (TLS is off unless `PgConfig.tls` asks for it). The password's bytes are used
129
130
  * as they are, without SASLprep (RFC 4013): an ASCII password works, and a
130
131
  * non-ASCII one works only when it is already in the form SASLprep would give
131
132
  * (PostgreSQL itself falls back to the raw bytes when it cannot prepare one).
@@ -248,6 +249,43 @@ export const PG_ERR_ENCODING: i32 = 8
248
249
  export const PG_ERR_CLOSED: i32 = 9
249
250
  /** The server's `DateStyle` is not ISO or its `TimeZone` is not UTC, the two the decoders read: at startup, or after a `SET`. */
250
251
  export const PG_ERR_SETTING: i32 = 10
252
+ /**
253
+ * TLS to the server failed, reported by the carrier (`tlsFailed()`): the
254
+ * server answered `N` to the SSLRequest while `PgConfig.tls` asks for TLS,
255
+ * its certificate was refused, or the handshake failed.
256
+ */
257
+ export const PG_ERR_TLS: i32 = 11
258
+
259
+ /** `PgConfig.tls`: no SSLRequest; the connection is cleartext. The default. */
260
+ export const PG_TLS_DISABLE: i32 = 0
261
+ /**
262
+ * `PgConfig.tls`: an SSLRequest first, and TLS 1.3 or nothing, the
263
+ * server's certificate not checked. Keeps a passive eavesdropper out; an
264
+ * active one who answers in the server's place is not.
265
+ */
266
+ export const PG_TLS_REQUIRE: i32 = 1
267
+ /**
268
+ * `PgConfig.tls`: an SSLRequest first, and TLS 1.3 or nothing, the
269
+ * server's chain checked against the trusted roots and its name against the
270
+ * host (libpq's `sslmode=verify-full`).
271
+ */
272
+ export const PG_TLS_VERIFY_FULL: i32 = 2
273
+ /** The SSLRequest's code, in place of a protocol version: 1234 in the high 16 bits, 5679 in the low. */
274
+ export const PG_SSL_REQUEST_CODE: i32 = 80877103
275
+
276
+ /**
277
+ * The 8-byte SSLRequest a client sends before its StartupMessage to ask for
278
+ * TLS: its length, 8, and `PG_SSL_REQUEST_CODE`, both big-endian. The server
279
+ * answers one byte, `S` to go on with a TLS handshake or `N` to refuse.
280
+ *
281
+ * @returns A new 8-byte array holding the message.
282
+ */
283
+ export const pgSslRequest = (): u8[] => {
284
+ const out: u8[] = new Array<u8>(8)
285
+ setI32BE(out, 0, 8)
286
+ setI32BE(out, 4, PG_SSL_REQUEST_CODE)
287
+ return out
288
+ }
251
289
 
252
290
  /** `PgArrayWalker.next()`: an element, at `start` for `length` bytes. */
253
291
  export const PG_ARRAY_ELEMENT: i32 = 0
@@ -349,6 +387,21 @@ export class PgConfig {
349
387
  * output cannot grow the buffer without bound.
350
388
  */
351
389
  maxOutput: i32 = 1048576
390
+ /**
391
+ * Read by the carrier only: `PG_TLS_DISABLE` (the default), `PG_TLS_REQUIRE`
392
+ * or `PG_TLS_VERIFY_FULL`. TLS needs a TCP target.
393
+ */
394
+ tls: i32 = 0
395
+ /**
396
+ * Read by the carrier only, under `PG_TLS_VERIFY_FULL`: a PEM file of the
397
+ * roots to trust; empty means the system's store.
398
+ */
399
+ tlsRootsPath: string = ""
400
+ /**
401
+ * Read by the carrier only: the name the server's certificate must carry,
402
+ * and the SNI sent; empty means the target's host.
403
+ */
404
+ tlsServerName: string = ""
352
405
  }
353
406
 
354
407
  /** A server's ErrorResponse or NoticeResponse: the fields a program acts on. */
@@ -465,7 +518,9 @@ const pgCheckConfig = (config: PgConfig): void => {
465
518
  config.maxColumns > 65535 ||
466
519
  config.minIterations < 1 ||
467
520
  config.maxIterations < config.minIterations ||
468
- config.maxIterations > PG_MAX_ITERATIONS
521
+ config.maxIterations > PG_MAX_ITERATIONS ||
522
+ config.tls < PG_TLS_DISABLE ||
523
+ config.tls > PG_TLS_VERIFY_FULL
469
524
  ) {
470
525
  panic("nish/net/postgres: a PgConfig cap out of range")
471
526
  }
@@ -1448,7 +1503,9 @@ export class PgConnection {
1448
1503
  * so the caller may wipe its own; `nonce` must be at least 18 bytes from a
1449
1504
  * cryptographic random source (`crypto.getRandomValues`), and is fixed only
1450
1505
  * in a test. Panics on a `PgConfig` that is a mistake (no user, a cap out
1451
- * of range, a NUL in a startup parameter) or a nonce shorter than 18 bytes.
1506
+ * of range, a NUL in a startup parameter), on one whose `tls` asks for TLS,
1507
+ * which only `PgCarrier` speaks, so a connection driven by hand never runs
1508
+ * in the clear when TLS was asked for, or on a nonce shorter than 18 bytes.
1452
1509
  * @param config The caps and startup parameters; kept, and read for the
1453
1510
  * connection's life, so do not change it afterwards.
1454
1511
  * @param password The role's password as UTF-8 bytes, without SASLprep;
@@ -1461,6 +1518,9 @@ export class PgConnection {
1461
1518
  panic("nish/net/postgres: the SCRAM nonce needs at least 18 random bytes")
1462
1519
  }
1463
1520
  pgCheckConfig(config)
1521
+ if (config.tls !== PG_TLS_DISABLE) {
1522
+ panic("nish/net/postgres: PgConfig.tls asks for TLS, which only PgCarrier speaks")
1523
+ }
1464
1524
  this.config = config
1465
1525
  this.text = new PgText()
1466
1526
  this.binary = new PgBinary()
@@ -1620,6 +1680,19 @@ export class PgConnection {
1620
1680
  return PG_FAILED
1621
1681
  }
1622
1682
 
1683
+ /**
1684
+ * Reports that TLS under the connection failed, or the server refused it:
1685
+ * unless it already has, the connection fails with `PG_ERR_TLS`, which
1686
+ * wipes the password.
1687
+ * @returns `PG_FAILED`, as every later `next()` does.
1688
+ */
1689
+ tlsFailed(): i32 {
1690
+ if (this.state !== PG_STATE_FAILED) {
1691
+ return this.fail(PG_ERR_TLS)
1692
+ }
1693
+ return PG_FAILED
1694
+ }
1695
+
1623
1696
  /**
1624
1697
  * Whether every byte of the connection's copy of the password is zero: true
1625
1698
  * once the proof is computed, the connection has failed or `dispose()` has
@@ -3359,6 +3432,9 @@ export class PgPool {
3359
3432
  readonly size: i32
3360
3433
 
3361
3434
  private readonly config: PgConfig
3435
+ // The cleartext copy of `config` a `PgCarrier` that runs TLS under the pool's
3436
+ // connections has them made with; null until one takes the pool.
3437
+ private carried: PgConfig | null = null
3362
3438
  private readonly password: PgPassword
3363
3439
  private readonly slots: PgPoolSlot[]
3364
3440
  private readonly queue: i32[]
@@ -3408,6 +3484,40 @@ export class PgPool {
3408
3484
  this.types = []
3409
3485
  }
3410
3486
 
3487
+ /**
3488
+ * The settings the pool's connections are made with, as given to the constructor.
3489
+ *
3490
+ * @returns The pool's `PgConfig`, not a copy.
3491
+ */
3492
+ settings(): PgConfig {
3493
+ return this.config
3494
+ }
3495
+
3496
+ /**
3497
+ * @internal Used by the `PgCarrier` constructor: marks the pool's connections
3498
+ * as carried over TLS, so `connect` makes them with a copy of the config
3499
+ * whose `tls` is `PG_TLS_DISABLE`; without it, a pool whose config asks for
3500
+ * TLS refuses to connect. A program that calls it by hand gets a pool in
3501
+ * the clear, as if it had set `tls` to `PG_TLS_DISABLE`.
3502
+ */
3503
+ carryTls(): void {
3504
+ const c: PgConfig = this.config
3505
+ const plain: PgConfig = new PgConfig()
3506
+ plain.user = c.user
3507
+ plain.database = c.database
3508
+ plain.applicationName = c.applicationName
3509
+ plain.options = c.options
3510
+ plain.maxMessage = c.maxMessage
3511
+ plain.maxInFlight = c.maxInFlight
3512
+ plain.pack = c.pack
3513
+ plain.inputSize = c.inputSize
3514
+ plain.maxColumns = c.maxColumns
3515
+ plain.minIterations = c.minIterations
3516
+ plain.maxIterations = c.maxIterations
3517
+ plain.maxOutput = c.maxOutput
3518
+ this.carried = plain
3519
+ }
3520
+
3411
3521
  /**
3412
3522
  * Registers a statement for every connection to prepare before its first
3413
3523
  * request. False when a connection has been made already, `name` or `sql`
@@ -3588,8 +3698,9 @@ export class PgPool {
3588
3698
  /**
3589
3699
  * Makes the wanted `slot`'s connection, `nonce` as `PgConnection` takes it:
3590
3700
  * send its output once the socket is connected, and if the socket fails,
3591
- * call `connection(slot).closed()`. Panics when `slot` is not wanted or the
3592
- * pool is disposed.
3701
+ * call `connection(slot).closed()`. Panics when `slot` is not wanted, the
3702
+ * pool is disposed, or its `PgConfig.tls` asks for TLS and no `PgCarrier`
3703
+ * drives the pool: only the carrier speaks TLS.
3593
3704
  *
3594
3705
  * @param slot The slot `wanted()` answered.
3595
3706
  * @param nonce At least 18 fresh random bytes for the SCRAM client nonce, as the
@@ -3602,8 +3713,12 @@ export class PgPool {
3602
3713
  if (this.password.gone) {
3603
3714
  panic("nish/net/postgres: PgPool.connect after dispose")
3604
3715
  }
3716
+ const carried: PgConfig | null = this.carried
3717
+ if (this.config.tls !== PG_TLS_DISABLE && carried === null) {
3718
+ panic("nish/net/postgres: PgConfig.tls asks for TLS, which only PgCarrier speaks")
3719
+ }
3605
3720
  const s: PgPoolSlot = this.slots[slot]
3606
- s.conn = new PgConnection(this.config, this.password.bytes, nonce)
3721
+ s.conn = new PgConnection(carried !== null ? carried : this.config, this.password.bytes, nonce)
3607
3722
  s.state = PG_SLOT_STARTING
3608
3723
  s.queued = 0
3609
3724
  s.described = 0
@@ -3770,10 +3885,13 @@ const PG_LOW32: i64 = 4294967295
3770
3885
  * The batcher's table hash of an int8 key, 31 bits: the high half times an
3771
3886
  * odd constant xored into the low half, then MurmurHash3's 32-bit finalizer,
3772
3887
  * whose unsigned multiplies wrap by definition. Every step is a bijection on
3773
- * 32 bits, so keys of one high half never collide, and the finalizer spreads
3774
- * a dense run of ids over the whole table: runs that would land on one
3775
- * another's slots under a near-identity hash do not merge into one cluster
3776
- * longer than `PG_BATCH_PROBES`.
3888
+ * 32 bits, so keys of one high half get distinct 32-bit hashes; the last
3889
+ * `>> 1` drops their lowest bit, so at most two such keys share a 31-bit hash.
3890
+ * The finalizer spreads a dense run of ids over the whole table: runs that
3891
+ * would land on one another's slots under a near-identity hash do not merge
3892
+ * into one cluster longer than `PG_BATCH_PROBES`. Keys of different high
3893
+ * halves can be built to share one hash; each costs up to
3894
+ * `PG_BATCH_PROBES` probes.
3777
3895
  */
3778
3896
  const pgIntHash = (key: i64): i32 => {
3779
3897
  const lo: u32 = toU32(key & PG_LOW32)
@@ -75,6 +75,19 @@
75
75
  * that the workers run unpinned, and the listeners are plain `SO_REUSEPORT`
76
76
  * ones. Both are off by default.
77
77
  *
78
+ * **QUIC.** `listenUdp`, with `listenPort`, binds one UDP socket per worker
79
+ * on the same port before the TCP listeners, held like them, as a group the
80
+ * kernel steers by connection ID (`udpBind` flag 4): a datagram whose
81
+ * destination ID starts with byte k reaches worker k. Worker k reads its
82
+ * socket with `preforkUdpListener(args)` and the group's size N with
83
+ * `preforkUdpCount(args)` (`--nish-prefork-udp=<fd>,<N>`, before the listener
84
+ * flag), and sets `QuicServerConfig.workerIndex` to k and `.workerCount` to N
85
+ * so every ID it issues starts with k. A connection then stays with its
86
+ * worker when the client's address or port changes. More than 255 workers
87
+ * panics; where the kernel refuses the steering (off Linux, or under a
88
+ * seccomp profile that refuses it) the supervisor says so on stderr and runs
89
+ * one worker.
90
+ *
78
91
  * **How many.** `NISH_WORKERS` when it is a positive whole number, else
79
92
  * `PreforkConfig.workers` when that is positive, else
80
93
  * `availableParallelism()` on Linux and 1 elsewhere: Darwin shares a
@@ -113,6 +126,7 @@ import {
113
126
  pollCreate,
114
127
  pollWait,
115
128
  tcpListenFlags,
129
+ udpBind,
116
130
  unixSocketPair,
117
131
  } from "nish:net"
118
132
  import {
@@ -144,6 +158,12 @@ export const PREFORK_CHANNELS_FLAG: string = "--nish-prefork-channels="
144
158
  * descriptor.
145
159
  */
146
160
  export const PREFORK_LISTENER_FLAG: string = "--nish-prefork-listener="
161
+ /**
162
+ * The flag that hands a worker its UDP socket and the size of the steered
163
+ * group, `<fd>,<N>`, before the listener flag, when `listenUdp` is on: read
164
+ * it with `preforkUdpListener` and `preforkUdpCount`.
165
+ */
166
+ export const PREFORK_UDP_FLAG: string = "--nish-prefork-udp="
147
167
 
148
168
  /** What `preforkWith` answers in the supervisor once its workers are gone. */
149
169
  export const PREFORK_STOPPED: i32 = -1
@@ -206,6 +226,16 @@ export class PreforkConfig {
206
226
  * a connection received past the listeners falls back to the kernel's hash.
207
227
  */
208
228
  pin: boolean = false
229
+ /**
230
+ * With `listenPort`, also bind one UDP socket per worker on the same port,
231
+ * before the TCP listeners, as a group the kernel steers by QUIC
232
+ * connection ID (`udpBind` flag 4): a datagram goes to worker k when byte 0
233
+ * of its destination connection ID is k, so a QUIC connection stays with
234
+ * the worker that issued its IDs when the client's address changes. Linux
235
+ * only, and at most 255 workers (more panics). Where the kernel refuses
236
+ * the steering, the supervisor says so on stderr and runs one worker.
237
+ */
238
+ listenUdp: boolean = false
209
239
  }
210
240
 
211
241
  /** True when `s` is one or more ASCII digits and nothing else. */
@@ -270,8 +300,8 @@ export const preforkIndex = (args: string[]): i32 => {
270
300
  }
271
301
 
272
302
  /**
273
- * `args` (`process.argv`) without the worker flag and the channels and
274
- * listener flags before it, the same in every process.
303
+ * `args` (`process.argv`) without the worker flag and the channels,
304
+ * listener and UDP flags before it, the same in every process.
275
305
  *
276
306
  * @param args the process's arguments, `process.argv`
277
307
  * @returns a new list of the arguments the user gave, without the flags the
@@ -287,6 +317,9 @@ export const preforkArgs = (args: string[]): string[] => {
287
317
  if (keep > 1 && args[keep - 1].startsWith(PREFORK_LISTENER_FLAG)) {
288
318
  keep = keep - 1
289
319
  }
320
+ if (keep > 1 && args[keep - 1].startsWith(PREFORK_UDP_FLAG)) {
321
+ keep = keep - 1
322
+ }
290
323
  }
291
324
  const out: string[] = []
292
325
  for (let i: i32 = 0; i < toI32(args.length); i++) {
@@ -368,6 +401,106 @@ export const preforkListener = (args: string[]): i32 => {
368
401
  return -1
369
402
  }
370
403
 
404
+ /** The most workers a steered UDP group may have: the steering reads one byte. */
405
+ const PREFORK_UDP_MAX: i32 = 255
406
+
407
+ /**
408
+ * Field `at` (0 the descriptor, 1 the count) of a worker's well-formed UDP
409
+ * flag, `<fd>,<N>` with N from 1 to `PREFORK_UDP_MAX`; -1 without one.
410
+ */
411
+ const preforkUdpField = (args: string[], at: i32): i32 => {
412
+ if (preforkIndex(args) < 0) {
413
+ return -1
414
+ }
415
+ for (let back: i32 = 2; back <= 4 && back < toI32(args.length); back++) {
416
+ const flag: string = args[toI32(args.length) - back]
417
+ if (flag.startsWith(PREFORK_UDP_FLAG)) {
418
+ const value: string = flag.substring(PREFORK_UDP_FLAG.length)
419
+ const comma: i32 = toI32(value.indexOf(","))
420
+ const fd: string = comma < 0 ? "" : value.slice(0, comma)
421
+ const size: string = comma < 0 ? "" : value.slice(comma + 1)
422
+ if (!preforkDigits(fd) || !preforkDigits(size)) {
423
+ return -1
424
+ }
425
+ const count: i32 = parseInt(size)
426
+ if (count < 1 || count > PREFORK_UDP_MAX) {
427
+ return -1
428
+ }
429
+ return at === 0 ? parseInt(fd) : count
430
+ }
431
+ }
432
+ return -1
433
+ }
434
+
435
+ /**
436
+ * In a worker, the UDP socket the supervisor bound for it (`listenUdp`); -1
437
+ * when none, or when the flag is not the supervisor's `<fd>,<N>`.
438
+ *
439
+ * @param args the worker's arguments, `process.argv`
440
+ * @returns the bound UDP socket's descriptor to serve QUIC on, or -1
441
+ */
442
+ export const preforkUdpListener = (args: string[]): i32 => preforkUdpField(args, 0)
443
+
444
+ /**
445
+ * In a worker, how many workers share its steered UDP port (`listenUdp`): the
446
+ * `QuicServerConfig.workerCount` to pair with `preforkIndex` as its
447
+ * `workerIndex`. 0 exactly when `preforkUdpListener` answers -1.
448
+ *
449
+ * @param args the worker's arguments, `process.argv`
450
+ * @returns the group's size, 1 to 255, or 0 without a UDP socket
451
+ */
452
+ export const preforkUdpCount = (args: string[]): i32 => {
453
+ const count: i32 = preforkUdpField(args, 1)
454
+ return count > 0 ? count : 0
455
+ }
456
+
457
+ /**
458
+ * The UDP group of `listenUdp`, socket i for worker i, bound before anything
459
+ * else on the port: steered by connection ID (`udpBind` flag 4 with the count
460
+ * in bits 8 to 15) for more than one worker. When the kernel refuses the
461
+ * steering, one plain socket and a line on stderr, so the supervisor runs one
462
+ * worker; empty, with a line on stderr and nothing left bound, when even that
463
+ * cannot bind.
464
+ */
465
+ const preforkBindUdp = (config: PreforkConfig, count: i32): i32[] => {
466
+ const host: string = config.listenHost
467
+ const out: i32[] = []
468
+ // Flag 1 (SO_REUSEPORT) and 4 (steer), the group's size in bits 8 to 15.
469
+ const steered: i32 = (count << 8) | 4 | 1
470
+ const first: i32 = udpBind(host, config.listenPort, count > 1 ? steered : 1)
471
+ if (first < 0 && count > 1) {
472
+ const plain: i32 = udpBind(host, config.listenPort, 1)
473
+ if (plain >= 0) {
474
+ console.error(`nish/net/prefork: QUIC steering refused (${first}), running one worker`)
475
+ out.push(plain)
476
+ return out
477
+ }
478
+ }
479
+ if (first < 0) {
480
+ console.error(`nish/net/prefork: cannot bind UDP ${host}:${config.listenPort} (${first})`)
481
+ return out
482
+ }
483
+ out.push(first)
484
+ const port: i32 = config.listenPort === 0 ? netLocalPort(first) : config.listenPort
485
+ if (port <= 0) {
486
+ console.error(`nish/net/prefork: cannot read the UDP port bound (${port})`)
487
+ netClose(first)
488
+ return []
489
+ }
490
+ for (let i: i32 = 1; i < count; i++) {
491
+ const fd: i32 = udpBind(host, port, steered)
492
+ if (fd < 0) {
493
+ console.error(`nish/net/prefork: cannot bind UDP ${host}:${port} (${fd})`)
494
+ for (let j: i32 = 0; j < toI32(out.length); j++) {
495
+ netClose(out[j])
496
+ }
497
+ return []
498
+ }
499
+ out.push(fd)
500
+ }
501
+ return out
502
+ }
503
+
371
504
  /** Milliseconds on the monotonic clock. */
372
505
  const preforkNowMs = (): i64 => monotonicNanos() / 1000000
373
506
 
@@ -449,6 +582,11 @@ class PreforkSupervisor {
449
582
  private cascading: boolean = false
450
583
  /** Worker i's listener at i, held for the whole run; empty without `listenPort`. */
451
584
  private listeners: i32[]
585
+ /**
586
+ * Worker i's UDP socket at i, held for the whole run so its index in the
587
+ * steered group never moves; empty without `listenUdp`.
588
+ */
589
+ private udp: i32[]
452
590
 
453
591
  /**
454
592
  * A supervisor with one empty slot per worker and no worker started yet.
@@ -459,10 +597,13 @@ class PreforkSupervisor {
459
597
  * @param count how many workers to keep running
460
598
  * @param loop the readiness loop each supervisor channel is added to; the
461
599
  * caller owns and closes it
600
+ * @param udp the UDP group `preforkBindUdp` bound, one per worker, kept and
601
+ * closed with the listeners; empty without `listenUdp`
462
602
  */
463
- constructor(config: PreforkConfig, args: string[], count: i32, loop: i32) {
603
+ constructor(config: PreforkConfig, args: string[], count: i32, loop: i32, udp: i32[]) {
464
604
  this.config = config
465
605
  this.loop = loop
606
+ this.udp = udp
466
607
  this.service = config.serviceWorker
467
608
  this.toService = []
468
609
  this.fromWorkers = []
@@ -522,6 +663,10 @@ class PreforkSupervisor {
522
663
  argv.push(this.args[i])
523
664
  }
524
665
  const channels: boolean = fds.length > 0
666
+ if (this.udp.length > 0) {
667
+ fds.push(this.udp[index])
668
+ argv.push(`${PREFORK_UDP_FLAG}${2 + fds.length},${this.udp.length}`)
669
+ }
525
670
  if (this.listeners.length > 0) {
526
671
  fds.push(this.listeners[index])
527
672
  argv.push(`${PREFORK_LISTENER_FLAG}${2 + fds.length}`)
@@ -764,7 +909,14 @@ class PreforkSupervisor {
764
909
  listen(steer: boolean): boolean {
765
910
  const config: PreforkConfig = this.config
766
911
  const flags: i32 = config.listenFlags | 1 | (steer ? 4 : 0)
767
- let port: i32 = config.listenPort
912
+ // With `listenUdp`, port 0 was chosen by the UDP group, bound first.
913
+ let port: i32 =
914
+ config.listenPort === 0 && this.udp.length > 0 ? netLocalPort(this.udp[0]) : config.listenPort
915
+ if (config.listenPort === 0 && this.udp.length > 0 && port <= 0) {
916
+ console.error(`nish/net/prefork: cannot read the UDP port bound (${port})`)
917
+ this.closeListeners()
918
+ return false
919
+ }
768
920
  for (let i: i32 = 0; i < toI32(this.slots.length); i++) {
769
921
  const fd: i32 = tcpListenFlags(config.listenHost, port, config.listenBacklog, flags)
770
922
  if (fd < 0) {
@@ -790,6 +942,10 @@ class PreforkSupervisor {
790
942
  netClose(this.listeners[i])
791
943
  }
792
944
  this.listeners = []
945
+ for (let i: i32 = 0; i < toI32(this.udp.length); i++) {
946
+ netClose(this.udp[i])
947
+ }
948
+ this.udp = []
793
949
  }
794
950
 
795
951
  /** Send `sig` to every running worker. */
@@ -871,6 +1027,9 @@ const preforkInvalid = (config: PreforkConfig): string => {
871
1027
  if (config.listenFlags !== 0 && config.listenFlags !== 2) {
872
1028
  return "listenFlags not 0 or 2"
873
1029
  }
1030
+ if (config.listenUdp && config.listenPort < 0) {
1031
+ return "listenUdp without listenPort"
1032
+ }
874
1033
  return ""
875
1034
  }
876
1035
 
@@ -916,9 +1075,11 @@ export const preforkWith = (args: string[], config: PreforkConfig): i32 => {
916
1075
  * Panics, besides, when `serviceWorker` is not below the worker count or the
917
1076
  * count is above 64 with a service worker (63 with `listenPort`), the most
918
1077
  * `spawnWithFds` hands one child; when `pin`, on Linux, asks for more workers
919
- * than `availableParallelism()`; and, through `preforkInvalid`, on seqpacket
920
- * channels off Linux. A listener that cannot bind answers
921
- * `PREFORK_SPAWN_FAILED` before any worker starts.
1078
+ * than `availableParallelism()`; when `listenUdp` asks for more than 255
1079
+ * workers (62 with a service worker); and, through `preforkInvalid`, on
1080
+ * seqpacket channels off Linux. A listener or UDP socket that cannot bind,
1081
+ * or a refused steering that leaves one worker beside a `serviceWorker` past
1082
+ * 0, answers `PREFORK_SPAWN_FAILED` before any worker starts.
922
1083
  *
923
1084
  * @param args the process's arguments, `process.argv`
924
1085
  * @param config the supervisor's settings, every field checked (a bad one
@@ -949,9 +1110,13 @@ export const preforkSupervise = <S>(
949
1110
  }
950
1111
  return index
951
1112
  }
952
- const count: i32 = preforkWorkerCount(config.workers, getenv("NISH_WORKERS"))
953
- // A held listener is one more descriptor for every worker, the service one too.
954
- const fdMax: i32 = config.listenPort >= 0 ? 63 : 64
1113
+ let count: i32 = preforkWorkerCount(config.workers, getenv("NISH_WORKERS"))
1114
+ if (config.listenUdp && count > PREFORK_UDP_MAX) {
1115
+ panic(`nish/net/prefork: listenUdp with ${count} workers, above ${PREFORK_UDP_MAX}`)
1116
+ }
1117
+ // A held listener is one more descriptor for every worker, the service one
1118
+ // too, and a held UDP socket one more again.
1119
+ const fdMax: i32 = toI32(config.listenPort >= 0 ? 63 : 64) - toI32(config.listenUdp ? 1 : 0)
955
1120
  if (config.serviceWorker >= count || (config.serviceWorker >= 0 && count > fdMax)) {
956
1121
  panic(`nish/net/prefork: serviceWorker not below ${count} workers, or above ${fdMax} workers`)
957
1122
  }
@@ -973,7 +1138,26 @@ export const preforkSupervise = <S>(
973
1138
  }
974
1139
  return PREFORK_SPAWN_FAILED
975
1140
  }
976
- const supervisor = new PreforkSupervisor(config, args, count, loop)
1141
+ // The UDP group first: a refused steering runs one worker, so it decides
1142
+ // the count everything after it is made for.
1143
+ const udp: i32[] = config.listenUdp ? preforkBindUdp(config, count) : []
1144
+ if (config.listenUdp && udp.length === 0) {
1145
+ netClose(loop)
1146
+ return PREFORK_SPAWN_FAILED
1147
+ }
1148
+ if (config.listenUdp) {
1149
+ count = toI32(udp.length)
1150
+ }
1151
+ // The one-worker fallback has no slot for a service worker past worker 0.
1152
+ if (config.serviceWorker >= count) {
1153
+ console.error(`nish/net/prefork: serviceWorker ${config.serviceWorker} with one worker, steering refused`)
1154
+ for (let i: i32 = 0; i < toI32(udp.length); i++) {
1155
+ netClose(udp[i])
1156
+ }
1157
+ netClose(loop)
1158
+ return PREFORK_SPAWN_FAILED
1159
+ }
1160
+ const supervisor = new PreforkSupervisor(config, args, count, loop, udp)
977
1161
  if (config.listenPort >= 0 && !supervisor.listen(pin)) {
978
1162
  netClose(loop)
979
1163
  return PREFORK_SPAWN_FAILED
@@ -120,6 +120,36 @@ export class QuicDatagramQueue {
120
120
  return this.count > 0 && k >= 0 && k < toI32(this.lengths.length) ? this.lengths[k] : -1
121
121
  }
122
122
 
123
+ /**
124
+ * Forgets the oldest datagram unsent and counts it in `dropped`, for one
125
+ * that no packet can carry any more; an empty ring is left as it is.
126
+ */
127
+ dropOldest(): void {
128
+ if (this.count > 0 && this.dropped < 2147483647) {
129
+ this.dropped = this.dropped + 1
130
+ }
131
+ this.drop()
132
+ }
133
+
134
+ /**
135
+ * Moves the oldest datagram behind the newest, unsent and not counted as
136
+ * dropped, so the ones queued after it go out first; for one too large
137
+ * for now that a later packet may carry. A ring of one is left as it is.
138
+ */
139
+ deferOldest(): void {
140
+ const entries: i32 = this.capacity()
141
+ if (this.count < 2) {
142
+ return
143
+ }
144
+ if (this.count < entries) {
145
+ const k: i32 = (this.head + this.count) % entries
146
+ const length: i32 = this.lengths[this.head]
147
+ quicPacketCopy(this.data, k * this.entrySize, this.data, this.head * this.entrySize, length)
148
+ this.lengths[k] = length
149
+ }
150
+ this.head = (this.head + 1) % entries
151
+ }
152
+
123
153
  /** Forgets the oldest datagram. */
124
154
  private drop(): void {
125
155
  if (this.count > 0) {