@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
package/runtime/vite.mjs CHANGED
@@ -23,7 +23,7 @@
23
23
  * `resolveId`, `load`), so `tests/run.js` calls them directly, with no Vite.
24
24
  */
25
25
  import { execFile } from "node:child_process";
26
- import { mkdirSync, readFileSync } from "node:fs";
26
+ import { mkdirSync, readFileSync, statSync } from "node:fs";
27
27
  import path from "node:path";
28
28
  import { fileURLToPath } from "node:url";
29
29
  import { promisify } from "node:util";
@@ -68,6 +68,15 @@ function exportNames(dts) {
68
68
  return names;
69
69
  }
70
70
 
71
+ /** Vite's default `resolve.extensions`, in the order it tries them. */
72
+ const VITE_EXTENSIONS = [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"];
73
+
74
+ /** Whether `p` is a file (`"file"`), a directory (`"dir"`) or neither. */
75
+ const kind = (p) => {
76
+ const st = statSync(p, { throwIfNoEntry: false });
77
+ return st?.isFile() ? "file" : st?.isDirectory() ? "dir" : undefined;
78
+ };
79
+
71
80
  /** The plugin. `compiler` and `buildScript` default to the ones in this package. */
72
81
  export default function nish(options = {}) {
73
82
  const compiler = options.compiler ?? path.join(packageDir, "bin", "nish");
@@ -77,9 +86,11 @@ export default function nish(options = {}) {
77
86
  let building = false;
78
87
  let cacheDir = path.join(root, "node_modules", ".vite");
79
88
  let entries = new Set();
89
+ let extensions = VITE_EXTENSIONS;
80
90
 
81
91
  const configure = (config) => {
82
92
  root = config.root ?? root;
93
+ extensions = config.resolve?.extensions ?? VITE_EXTENSIONS;
83
94
  building = config.command === "build";
84
95
  cacheDir = config.cacheDir ?? path.join(root, "node_modules", ".vite");
85
96
  entries = new Set((options.entries ?? []).map((e) => path.resolve(root, e)));
@@ -96,13 +107,26 @@ export default function nish(options = {}) {
96
107
  const host = (options.host ?? []).flatMap((h) => ["--host", path.resolve(root, h)]);
97
108
  await run(compiler, [entry, "--target", "wasm32", ...host, "--emit-dts", dts, "-o", ll], { cwd: root });
98
109
  const loader = path.join(dir, `${stem}.mjs`);
110
+ const loaderText = readFileSync(loader, "utf8");
111
+ // The generated module imports `loadSync`. A compiler older than it writes
112
+ // a loader without one, which Rollup would report only as a missing
113
+ // export of a file in the cache, naming neither the compiler nor the fix.
114
+ if (!/^export function loadSync\(/m.test(loaderText)) {
115
+ const version = await run(compiler, ["--version"], { cwd: root }).then(
116
+ (r) => r.stdout.trim(),
117
+ () => "an unknown version",
118
+ );
119
+ throw new Error(
120
+ `nish/vite: the compiler ${compiler} (${version}) wrote a loader with no \`loadSync\` export: ` +
121
+ "it predates `loadSync` (WP50 stage 1), which the generated module calls. " +
122
+ "Use a newer one: update the nish package, or pass its path as `nish({ compiler })`.",
123
+ );
124
+ }
99
125
  const ir = readFileSync(ll, "utf8");
100
126
  // runtime-wasm.c is linked when the IR needs a runtime function (a weak
101
127
  // `extern_weak` one, a panic stub wasm-ld writes itself, does not count)
102
128
  // or the loader calls the arena.
103
- const needsRuntime =
104
- /^declare (?!extern_weak)[^"\n]*@nish_/m.test(ir) ||
105
- readFileSync(loader, "utf8").includes("raw.nish_arena_mark(");
129
+ const needsRuntime = /^declare (?!extern_weak)[^"\n]*@nish_/m.test(ir) || loaderText.includes("raw.nish_arena_mark(");
106
130
  const inline = path.join(dir, `${stem}.bytes.mjs`);
107
131
  const inputs = needsRuntime ? [ll, runtimeWasm] : [ll];
108
132
  await run("bash", [buildScript, ...inputs, "-o", path.join(dir, `${stem}.wasm`), "--profile", "wasm-host", "--inline", inline], {
@@ -117,16 +141,29 @@ export default function nish(options = {}) {
117
141
  enforce: "pre",
118
142
  configResolved: configure,
119
143
  async resolveId(source, importer) {
120
- if (!building) return null;
144
+ if (!building || entries.size === 0) return null;
121
145
  // The seam for a `./client.nish` specifier (the page's client module of a
122
146
  // later stage) is here; stage 1 resolves only the entries.
147
+ // A specifier may leave out the `.ts`, or name a directory for its
148
+ // `index.ts`. It is resolved as Vite would, file then extensions in
149
+ // order then the directory's index, so a sibling `add.js` keeps `./add`.
123
150
  const base = importer ? path.dirname(importer) : root;
124
- const candidates = source.startsWith(".")
125
- ? [path.resolve(base, source)]
126
- : path.isAbsolute(source)
127
- ? [source, path.join(root, source)]
128
- : [];
129
- const hit = candidates.find((c) => entries.has(c));
151
+ // A candidate that no entry's path starts with resolves to no entry, so
152
+ // it is dropped before anything is read from the disk.
153
+ const candidates = (
154
+ source.startsWith(".")
155
+ ? [path.resolve(base, source)]
156
+ : path.isAbsolute(source)
157
+ ? [source, path.join(root, source)]
158
+ : []
159
+ ).filter((c) => [...entries].some((e) => e.startsWith(c)));
160
+ if (candidates.length === 0) return null;
161
+ const withExtension = (stem) => extensions.map((e) => stem + e).find((f) => kind(f) === "file");
162
+ const resolve = (c) => {
163
+ if (entries.has(c) || kind(c) === "file") return c;
164
+ return withExtension(c) ?? (kind(c) === "dir" ? withExtension(path.join(c, "index")) : undefined);
165
+ };
166
+ const hit = candidates.map(resolve).find((c) => c !== undefined && entries.has(c));
130
167
  return hit === undefined ? null : PREFIX + hit;
131
168
  },
132
169
  async load(id) {
package/scripts/build.sh CHANGED
@@ -3,8 +3,9 @@
3
3
  #
4
4
  # scripts/build.sh <module.ll> [more .ll/.c files...] -o <out> [--profile debug|speed|size|wasm|wasm-host|wasi|napi]
5
5
  #
6
- # The C runtime is sixteen translation units and is named as one: an input
7
- # <dir>/runtime.c also compiles <dir>/runtime-os.c, the half that wraps the
6
+ # The C runtime is seventeen translation units and is named as one: an input
7
+ # <dir>/runtime.c also compiles <dir>/runtime-text.c, the strings and the digits
8
+ # of numbers, <dir>/runtime-os.c, the half that wraps the
8
9
  # system calls (files, directories, subprocesses, the environment, the clock),
9
10
  # <dir>/runtime-parallel.c, the half that divides a range of work across
10
11
  # threads, <dir>/runtime-cross.c, the copies that carry a string or an array
@@ -15,7 +16,8 @@
15
16
  # <dir>/runtime-aes.c, AES-GCM on the CPU's AES instructions,
16
17
  # <dir>/runtime-sha256.c, SHA-256 on the CPU's SHA instructions,
17
18
  # <dir>/runtime-chacha20.c, ChaCha20's keystream on AVX2 or NEON vectors,
18
- # <dir>/runtime-checksum.c, CRC-32 on its carry-less multiply or CRC instructions,
19
+ # <dir>/runtime-checksum.c, CRC-32 on its carry-less multiply or CRC instructions
20
+ # and Adler-32 on SSSE3 or NEON,
19
21
  # <dir>/runtime-term.c, stdin and the terminal of `nish:term`,
20
22
  # <dir>/runtime-bytes.c, the byte-class runs of `nish/bytes`,
21
23
  # <dir>/runtime-sandbox.c, the confinement `--sandbox` applies,
@@ -41,10 +43,13 @@
41
43
  # when runtime-wasm.c is linked, the arena entry points the
42
44
  # `--emit-dts` loader calls (nish_arena_mark, nish_arena_release,
43
45
  # nish_alloc_array, nish_reset_arena, nish_free_arena). The stack is
44
- # a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz` on the
45
- # module when wasm-opt (binaryen) is on PATH; the build line says
46
- # whether it ran. Two flags take this profile alone, and any other
47
- # refuses them with exit 2:
46
+ # a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz
47
+ # --strip-target-features` on the module when wasm-opt (binaryen)
48
+ # is on PATH; the build line says whether it ran. NISH_WASM_OPT=0
49
+ # links without it even when it is installed (clang's own wasm-opt
50
+ # call too): the module a machine without binaryen builds, which
51
+ # the size guard measures. Two flags take this profile alone, and
52
+ # any other refuses them with exit 2:
48
53
  # --memory <MiB> memory fixed at <MiB> MiB (1 to 4096), the
49
54
  # initial size and the maximum both, so it
50
55
  # never grows and `memory.buffer` is one
@@ -122,7 +127,7 @@
122
127
  #
123
128
  # The runtime compiled once (the debug, speed and size profiles only; `nish
124
129
  # --link` and `nish run` use these through their runtime cache, src/compile.ts):
125
- # --runtime-objects <dir> compile the runtime.c input and its seven siblings,
130
+ # --runtime-objects <dir> compile the runtime.c input, its sixteen halves and runtime-async.c,
126
131
  # one $CC -c each and all at once, into
127
132
  # <dir>/<unit>.o with the profile's compile flags,
128
133
  # and link nothing. speed and size store LTO bitcode,
@@ -267,8 +272,8 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
267
272
  fi
268
273
  [ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
269
274
 
270
- # The runtime is sixteen translation units, and a caller names one: whoever passes
271
- # <dir>/runtime.c gets <dir>/runtime-os.c, <dir>/runtime-parallel.c,
275
+ # The runtime is seventeen translation units, and a caller names one: whoever passes
276
+ # <dir>/runtime.c gets <dir>/runtime-text.c, <dir>/runtime-os.c, <dir>/runtime-parallel.c,
272
277
  # <dir>/runtime-cross.c, <dir>/runtime-host.c, <dir>/runtime-net.c, <dir>/runtime-simd.c,
273
278
  # <dir>/runtime-aes.c, <dir>/runtime-sha256.c, <dir>/runtime-chacha20.c, <dir>/runtime-checksum.c, <dir>/runtime-term.c,
274
279
  # <dir>/runtime-bytes.c, <dir>/runtime-sandbox.c, <dir>/runtime-shm.c and <dir>/runtime-region.c compiled beside it, on every profile,
@@ -280,7 +285,7 @@ fi
280
285
  # compiles to two functions that refuse to run, which no wasm build calls, and
281
286
  # runtime-shm.c answers -95 for every region. They were one file until the
282
287
  # operating-system half was split out for its own size budget, and the parallel
283
- # half followed for the same reason (each file's header comment says why), and
288
+ # and text halves followed for the same reason (each file's header comment says why), and
284
289
  # a link line is where those splits
285
290
  # would otherwise leak: `nish --link` builds its command line in
286
291
  # src/compile.ts, the published package's recipe in every document and
@@ -288,7 +293,7 @@ fi
288
293
  # here keeps every one of those correct, and keeps "the runtime" one thing to
289
294
  # name from the outside. A caller that names one itself is left alone, because
290
295
  # naming one object twice is a duplicate-symbol error.
291
- halves="runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
296
+ halves="runtime-text.c runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
292
297
  for i in ${inputs[@]+"${inputs[@]}"}; do
293
298
  case "$i" in
294
299
  */runtime.c|runtime.c)
@@ -376,6 +381,12 @@ fi
376
381
 
377
382
  CC=${CC:-clang}
378
383
  common=(-Wno-override-module) # our IR is target-neutral; clang fills the triple in
384
+ # -ffp-contract=off on every unit, every profile (WP50 S5): clang's default
385
+ # contracts a*b+c in C into one fused multiply-add wherever the target has one
386
+ # (arm64 always, x86-64 at v3), which rounds once where the source rounds
387
+ # twice, so the runtime would print another float on arm64 than on x86-64.
388
+ # Nish's own IR asks for no contraction, so the flag changes only the C units.
389
+ common+=(-ffp-contract=off)
379
390
  elf=() # flags that only make sense for ELF targets
380
391
  lld=0 # 1 when the link goes through ld.lld
381
392
 
@@ -435,10 +446,11 @@ if [ "$debug" = 1 ]; then common+=(-g); strip_flag=(); fi
435
446
  # own command line instead of using `common`; it is empty on every ordinary
436
447
  # build, hence the bash 3.2 expansion spelling explained below.
437
448
  #
438
- # -pthread is for runtime-parallel.c, the translation unit that divides a range
449
+ # -pthread is here for runtime-parallel.c, the translation unit that divides a range
439
450
  # of work across threads: it is compiled in either configuration and only spawns
440
- # under this macro, so this is the build where the flag has to be on the command
441
- # line. On a current glibc the library half is already inside libc and the link
451
+ # under this macro, so this is the build where it needs the flag on the command
452
+ # line. (Every Linux build has the flag already, for runtime-sandbox.c; see
453
+ # where `common` gets its hardening flags below.) On a current glibc the library half is already inside libc and the link
442
454
  # would succeed without it; passing it is what makes that an implementation
443
455
  # detail rather than something the build depends on.
444
456
  #
@@ -447,10 +459,10 @@ if [ "$debug" = 1 ]; then common+=(-g); strip_flag=(); fi
447
459
  # runtime-parallel.c compiles to its sequential fallback because it tests
448
460
  # __wasi__ and __wasm__ as well as the macro.
449
461
  # --cpu: every unit at the one level, so the module, the runtime and the link
450
- # (LTO generates code there) agree. -ffp-contract=off keeps the meaning fixed:
451
- # v3 has FMA, and contracting a*b+c into one rounding would print a different
452
- # float than the baseline build (docs/LANGUAGE.md, "The CPU level").
453
- if [ -n "$cpu" ]; then common+=(-march=x86-64-v3 -ffp-contract=off); fi
462
+ # (LTO generates code there) agree. v3 has FMA, and the -ffp-contract=off every
463
+ # unit has above keeps a*b+c two roundings, so it prints the float the baseline
464
+ # build does (docs/LANGUAGE.md, "The CPU level").
465
+ if [ -n "$cpu" ]; then common+=(-march=x86-64-v3); fi
454
466
 
455
467
  # Hardening, on every native profile (the wasm and wasi ones build their own
456
468
  # command line and have none of these to give). docs/security/runtime.md
@@ -481,6 +493,22 @@ case "$(uname -s)" in
481
493
  Darwin) ;;
482
494
  *)
483
495
  common+=(-fstack-clash-protection)
496
+ # runtime-sandbox.c runs each spawn under an exec allowlist on threads of
497
+ # its own, and a glibc before 2.34 keeps pthread_create outside libc. The
498
+ # flag is on every build rather than the sandboxed ones because this
499
+ # script cannot tell them apart: an input may be an object file, where
500
+ # the call of `nish_sandbox` is not there to be read. A build without
501
+ # `--sandbox` is the binary it was: on glibc 2.34 and later the flag adds
502
+ # nothing to the link (measured on 2.39: `arena_placement` and
503
+ # `caps_process_spawn` at debug, speed and size are byte for byte the
504
+ # same with and without it). Before 2.34 it names libpthread to the
505
+ # linker, and a build without `--sandbox` can then carry a DT_NEEDED on
506
+ # libpthread.so.0 that it did not have: the debug profile always (its link
507
+ # line has no --as-needed), speed and size wherever the linker still sees
508
+ # the runtime's reference to pthread_create. That is one more library of
509
+ # the same glibc loaded at start, and not measured: no machine the tests
510
+ # run on has such a glibc.
511
+ common+=(-pthread)
484
512
  # shellcheck disable=SC2054 # -Wl,<flag> is one argument: the comma is the linker's
485
513
  common+=(-Wl,-z,relro,-z,now -Wl,-z,noexecstack) ;;
486
514
  esac
@@ -770,15 +798,16 @@ case "$profile" in
770
798
  # IR compiled for the host rather than with `--target wasm32` calls std/crypto/aes.ts's
771
799
  # AES kernels behind `nish_aes_hw`, std/crypto/sha256.ts's block function behind
772
800
  # `nish_sha256_hw`, std/crypto/chacha20poly1305.ts's keystream loop behind
773
- # `nish_chacha20_hw` and std/compress/checksum.ts's CRC-32 kernel behind
774
- # `nish_crc32_hw` (src/kernels.ts). runtime-aes.c's, runtime-sha256.c's,
801
+ # `nish_chacha20_hw` and std/compress/checksum.ts's CRC-32 and Adler-32
802
+ # kernels behind `nish_crc32_hw` and `nish_adler32_hw` (src/kernels.ts). runtime-aes.c's, runtime-sha256.c's,
775
803
  # runtime-chacha20.c's and runtime-checksum.c's wasm32 builds answer 0 there,
776
804
  # so the Nish code runs, and
777
805
  # each is added only for such IR: every other module links the bytes it always did.
778
- # Each pair is a unit and the kernel its probe names.
806
+ # Each pair is a unit and the kernel its probe names; checksum has two, and
807
+ # its second pair sees the unit the first added, so it is added once.
779
808
  # A caller that names the unit itself is left alone, as `halves` leaves it:
780
809
  # one object named twice is a duplicate-symbol error.
781
- for pair in aes:aes sha256:sha256 chacha20:chacha20 checksum:crc32; do
810
+ for pair in aes:aes sha256:sha256 chacha20:chacha20 checksum:crc32 checksum:adler32; do
782
811
  unit=${pair%%:*}
783
812
  kernel=${pair#*:}
784
813
  named=0
@@ -808,6 +837,21 @@ case "$profile" in
808
837
  if [ "$bytes_wanted" = 1 ] && [ "$bytes_named" = 0 ]; then
809
838
  inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-bytes.c")
810
839
  fi
840
+ # IR that builds a string (`+`, a template, `String(x)`, a number's digits)
841
+ # calls runtime-text.c, which compiles freestanding for wasm32 (WP50 stage 4).
842
+ # It is added the same way, only for such IR and only when the caller has not
843
+ # named it; it allocates through runtime-wasm.c's arena, so that is linked too.
844
+ text_named=0
845
+ text_wanted=0
846
+ for i in ${inputs[@]+"${inputs[@]}"}; do
847
+ case "$i" in
848
+ */runtime-text.c|runtime-text.c) text_named=1 ;;
849
+ *.ll) if grep -qE '@nish_(str_|f64_format|json_put_f64)' "$i"; then text_wanted=1; fi ;;
850
+ esac
851
+ done
852
+ if [ "$text_wanted" = 1 ] && [ "$text_named" = 0 ]; then
853
+ inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-text.c")
854
+ fi
811
855
  # IR compiled for the host rounds through runtime-simd.c's `nish_floor` and its
812
856
  # kin behind the constructor `nish_round_init` (#943). runtime-wasm.c has their
813
857
  # wasm32 bodies, and it is added the same way when such IR does not name it.
@@ -819,6 +863,7 @@ case "$profile" in
819
863
  *.ll) if grep -q '@nish_round_init' "$i"; then round_wanted=1; fi ;;
820
864
  esac
821
865
  done
866
+ if [ "$text_wanted" = 1 ]; then round_wanted=1; fi
822
867
  # Under wasm-host a program whose loader guards panics (one with module
823
868
  # storage or a host module: the compiler ends its IR with a
824
869
  # `; nish.sites <count>` line) reports each panic through the page's
@@ -849,7 +894,7 @@ case "$profile" in
849
894
  fi
850
895
  # -mbulk-memory lowers llvm.memset/memcpy (`new Array<T>(n)`, `push` growth) to the
851
896
  # memory.fill/memory.copy instructions instead of libc calls the freestanding link lacks.
852
- wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory)
897
+ wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory -ffp-contract=off)
853
898
  if [ "$profile" = wasm ]; then
854
899
  "$CC" "${wasm_compile[@]}" \
855
900
  ${tls[@]+"${tls[@]}"} \
@@ -967,17 +1012,49 @@ case "$profile" in
967
1012
  bytes=$((memory_mib * 1048576))
968
1013
  memory+=("-Wl,--initial-memory=$bytes" "-Wl,--max-memory=$bytes")
969
1014
  fi
970
- "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
971
- ${tls[@]+"${tls[@]}"} \
972
- -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
973
- "${host_inputs[@]}" -o "$out"
974
1015
  # binaryen's size pass is optional: the module is complete without it.
975
- if command -v wasm-opt >/dev/null 2>&1; then
976
- wasm-opt -Oz --enable-bulk-memory "$out" -o "$out"
977
- wasm_opt="wasm-opt -Oz"
978
- else
979
- wasm_opt="no wasm-opt"
980
- fi
1016
+ # It runs twice when wasm-opt is installed. clang 18 runs it itself after
1017
+ # any link with an -O flag, finding it on PATH, and has wasm-ld keep the
1018
+ # `target_features` section for it: 48 bytes or more that nothing at
1019
+ # run time reads, which put add.wasm at 150 bytes against 102 without
1020
+ # wasm-opt (#1257). The pass below drops that section again.
1021
+ # NISH_WASM_OPT=0 runs neither: each source is compiled alone and the
1022
+ # objects linked with no -O flag, so clang starts no wasm-opt and the
1023
+ # module is byte for byte the one a machine without binaryen links.
1024
+ # That is the build the size guard pins.
1025
+ case "${NISH_WASM_OPT:-1}" in
1026
+ 0)
1027
+ make_work
1028
+ host_objects=()
1029
+ for i in "${host_inputs[@]}"; do
1030
+ # What clang compiles in a one-step link is compiled here (.ll, .c,
1031
+ # .bc, .s, ...); what it hands straight to wasm-ld passes through.
1032
+ case "$i" in
1033
+ *.o|*.a) host_objects+=("$i") ;;
1034
+ *)
1035
+ object="$work/host-${#host_objects[@]}.o"
1036
+ "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
1037
+ ${tls[@]+"${tls[@]}"} -c "$i" -o "$object"
1038
+ host_objects+=("$object") ;;
1039
+ esac
1040
+ done
1041
+ "$CC" --target=wasm32-unknown-unknown -nostdlib \
1042
+ -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
1043
+ "${host_objects[@]}" -o "$out"
1044
+ wasm_opt="no wasm-opt, NISH_WASM_OPT=0" ;;
1045
+ 1)
1046
+ "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
1047
+ ${tls[@]+"${tls[@]}"} \
1048
+ -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
1049
+ "${host_inputs[@]}" -o "$out"
1050
+ if command -v wasm-opt >/dev/null 2>&1; then
1051
+ wasm-opt -Oz --enable-bulk-memory --strip-target-features "$out" -o "$out"
1052
+ wasm_opt="wasm-opt -Oz"
1053
+ else
1054
+ wasm_opt="no wasm-opt"
1055
+ fi ;;
1056
+ *) echo "error: NISH_WASM_OPT must be 0 or 1, not '$NISH_WASM_OPT'" >&2; exit 2 ;;
1057
+ esac
981
1058
  if [ -n "$inline_to" ]; then
982
1059
  # Decimal, one array literal: of the inline forms the smallest after
983
1060
  # compression (docs/wp50-wasm-host.md, Q10). od prints each byte as an
@@ -1027,9 +1104,9 @@ case "$profile" in
1027
1104
  fi
1028
1105
  # SQLite builds on wasi-libc as it is: the amalgamation sees __wasi__ and
1029
1106
  # takes dot-file locking, no mmap and no WAL shared memory.
1030
- sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
1107
+ sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
1031
1108
  ${tls[@]+"${tls[@]}"} -ffunction-sections -fdata-sections
1032
- "$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
1109
+ "$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
1033
1110
  ${tls[@]+"${tls[@]}"} \
1034
1111
  -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--strip-all \
1035
1112
  "${inputs[@]}" ${libs[@]+"${libs[@]}"} -o "$out" ;;
@@ -6,3 +6,11 @@ Permission to use, copy, modify, and distribute this
6
6
  software is freely granted, provided that this notice
7
7
  is preserved.
8
8
  ====================================================
9
+
10
+ ====================================================
11
+ Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
12
+
13
+ Permission to use, copy, modify, and distribute this
14
+ software is freely granted, provided that this notice
15
+ is preserved.
16
+ ====================================================
package/std/README.md CHANGED
@@ -10,7 +10,7 @@ whatever program imports it, and subject to the same rules as `examples/` or
10
10
  | Module | What it is |
11
11
  | --- | --- |
12
12
  | [`testing.ts`](https://github.com/amritk/nish/blob/main/std/testing.ts) | a test runner: a `Suite` a program drives with straight-line assertions, printing the `PASS` / `FAIL` / `SKIP` lines the repository's own harness prints, and answering the exit code |
13
- | [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of 1 to 16 ASCII `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
13
+ | [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of 1 to 16 ASCII `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
14
14
  | [`math.ts`](https://github.com/amritk/nish/blob/main/std/math.ts) | `Math.tan`, `Math.atan2` and `Math.hypot` on `f64`, ported from fdlibm (`LICENSE-fdlibm`) so that every target, wasm included, answers alike without libm. A program never imports it: a call to one of the three loads it, and the compiler copies the functions the call reaches into the calling module as `internal` ones. JavaScript's answer for every NaN, signed zero and infinity, and within one ulp elsewhere (0.83, 0.84 and 0.93 ulp measured against mpmath). `tests/cases/math_std_edges` pins the special values |
15
15
  | [`sort.ts`](https://github.com/amritk/nish/blob/main/std/sort.ts) | `xs.sort(cmp)` on any array: `sortWith`, a stable merge sort over runs of 32 sorted by insertion — one scratch array released before it returns, a pair of runs already in order copied without merging, no bounds check left in it — so its order is element for element Node's `Array.prototype.sort`. Like `math.ts` it is one the compiler knows about: a program never imports it, a `.sort(cmp)` call loads it, the checker rewrites the call to `sortWith`, and each comparator's instantiation — the comparator called directly, no function pointer — is copied into the module that sorts. Under Node the call stays the platform's own. `tests/cases/arr_sort_cmp*` are its programs, a 10,000-element sort with ties among them |
16
16
  | [`regex.ts`](https://github.com/amritk/nish/blob/main/std/regex.ts) | Regular expressions in JavaScript's syntax with the `u` flag's strictness, matched by a Pike VM in time linear in the input whatever the pattern; finding every match is one search per match, so `findAll` and its kin can be quadratic when a long branch is preferred to a short one that wins ([`docs/security/regex.md`](../docs/security/regex.md)). `regexCompile(pattern, flags)` answers a `Regex` or the error text; `test`, `exec` into a reused `RegexMatch`, `find`, `findAll`, `count`, `replace` and `replaceAll` with `$&`, `$1` and `$<name>`, and `split`. Flags `i`, `m`, `s` and `u`; `i` folds by Unicode's simple case folding, ASCII letters only to ASCII. `\p{…}` and `\P{…}` take Unicode 16.0's General_Category, Script, Script_Extensions and binary properties by JavaScript's names, from tables `scripts/gen-regex-unicode.mjs` generates into the module and checks against Node's `RegExp`; backreferences and lookaround are refused at compile time. Offsets are UTF-8 bytes. A search allocates nothing beyond its answer: the thread lists and capture tables are the `Regex`'s, so one `Regex` serves one thread at a time. A leading literal is found with `indexOf`, a small leading set with `indexOfAny`. `tests/link/std_regex` and `tests/link/std_regex_unicode` check it against JavaScript's own answers |
@@ -47,6 +47,7 @@ whatever program imports it, and subject to the same rules as `examples/` or
47
47
  | [`threads.ts`](https://github.com/amritk/nish/blob/main/std/threads.ts) | `parallelMapInto(src, dst, f)` and `parallelReduce(src, f, identity)`: a function over every element of an array, on as many threads as the length is worth. Its bodies are the sequential meaning, which is what runs under Node; the compiler recognises the two templates by module and name, lowers the one loop in each onto `nish_parallel_range`, holds the function to the rules that make that safe, and compiles an importing program with `--threads` ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#data-parallelism-nishthreads)). `tests/link/par_*` are its programs. `scope()`, bound by `using s = scope()`, runs unlike tasks, each on a thread of its own, and joins them at every exit of the block; `s.spawn(entry, arg, dst, at)` stores a task's answer, and `s.spawn(entry, arg)` and `s.spawn(() => ...)`, whose arrow reads the function's `const` locals, run one that answers `void` (`spawnWith` and `spawnThunk` are the methods the compiler reads them as, and under Node `spawn` itself tells them apart) ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#scoped-tasks-using-s--scope)). `scopeWithStack(bytes)` is a scope whose tasks each run on a new thread with at least `bytes` of stack, for a task that recurses deeper than a thread's default allows; under Node and without threads the size is checked and otherwise ignored (`tests/link/thread_stack_deep`). `Mutex<T>` is a lock that owns its data: the value is reachable only through the guard `using g = m.lock()` binds, which releases it at every exit of the block, so a scope's tasks can share and update one value without a data race or a deadlock ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#a-lock-that-owns-its-data-mutext); `tests/link/thread_mutex_*`, and `examples/histogram.ts` measured). `Channel<T>` carries scalars to one receiver, a task of the scope or the parent after the join, from the scope's sender tasks and from the parent before the block that spawns them, and closes when every sending task has returned ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#channels-channelt); [`docs/wp29-thread-surface.md`](https://github.com/amritk/nish/blob/main/docs/wp29-thread-surface.md#44-stage-p3--channels-of-scalars) §4.4). Every body in the module is its meaning under Node, where a task runs at its `spawn` |
48
48
  | [`sync/shm.ts`](https://github.com/amritk/nish/blob/main/std/sync/shm.ts) | `createRegion(name, bytes)`, `openRegion(name)` and `unlinkRegion(name)`: a named region of memory that several processes of one user map at once, through `runtime/runtime-shm.c`. A `SharedRegion` is read and written through checked slots, `loadI32` to `compareExchangeI64` at an ordering the call names (`RELAXED` to `SEQ_CST`), and byte windows (`read`, `write`); an offset outside the region or not a multiple of the slot's width stops the program. `waitI32` and `wake` sleep and wake on a slot across processes (Linux futex; `SHM_UNSUPPORTED` elsewhere). Native only, and it reaches `ffi` ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#shared-memory-between-processes-nishsyncshm-and-nishsyncring); [`docs/wp47-shared-memory.md`](https://github.com/amritk/nish/blob/main/docs/wp47-shared-memory.md); [`docs/security/shm.md`](../docs/security/shm.md)) |
49
49
  | [`sync/ring.ts`](https://github.com/amritk/nish/blob/main/std/sync/ring.ts) | Lock-free rings of byte records in a `SharedRegion`: `SpscRing` (one producer, one consumer, records of any length) and `MpscRing` (many producers, one consumer, fixed slots), made with `initSpscRing` / `initMpscRing` and found from another process with `attachSpscRing` / `attachMpscRing`. `tryPush`, `tryPop` and `popBatch` never block; a ring made with a doorbell adds `popWait`, which sleeps on a futex that a push rings only when the consumer is asleep. A length a peer wrote that the ring cannot hold stops the program as corrupt. `tests/link/sync_ring`, `examples/prefork-jobs.ts` and `bench/ring-latency/` are its programs |
50
+ | [`host/text.ts`](https://github.com/amritk/nish/blob/main/std/host/text.ts) | Text in wasm module storage, for a module and its page (WP50 stage 4). `textWrite(buf, at, s)` writes a string's UTF-8 bytes into a `u8[]` at `at` and answers the offset after them, `textWriteInt` and `textWriteF64` a number as a template literal formats it; text that does not fit writes nothing and answers -1, which every writer passes through, so a chain fails as a whole and never traps. `textRead(buf, n)` is the first `n` bytes as a string, what the page's `encodeInto` wrote, or `null` for an `n` past the buffer. `tests/host-import/text` is its round trip |
50
51
 
51
52
  ## `nish/crypto` — the primitives under TLS 1.3
52
53
 
@@ -263,6 +264,7 @@ reads one, and it still takes its randomness as an argument.
263
264
  | [`net/http-compress.ts`](https://github.com/amritk/nish/blob/main/std/net/http-compress.ts) | Content coding for HTTP responses: `httpAcceptEncoding(buf, start, end, offered)` reads an `Accept-Encoding` value (q-values, `*`, `identity`, `x-gzip`) into `HTTP_CODING_GZIP`, `HTTP_CODING_DEFLATE`, `HTTP_CODING_IDENTITY` or `HTTP_CODING_NONE`, allocating nothing; `HttpCompressor(level, minLength, maxLength)` gzips a body into its own buffer when it is worth it (-1 to send it as it is) and builds the response fields (`addFields`: `Content-Encoding: gzip` and, while `vary`, `Vary: Accept-Encoding`). It sends gzip only when it pays: `minLength`, `minSaving` bytes or `minSavingPercent`, and `segmentMode` (fewer TCP segments of `mss`, head included, than as it is); `decision` says why (`HTTP_COMPRESS_SENT`, `_NOT_ACCEPTED`, `_TOO_SMALL`, `_TOO_LARGE`, `_TOO_LITTLE_SAVED`, `_NO_FEWER_SEGMENTS`). Bodies up to `fixedLimit` use the fixed-Huffman encoder (`encoder`: `HTTP_ENCODER_AUTO`, `_FIXED`, `_LEVEL`). On HTTP/1.1, `Http1Connection.acceptEncoding()` and `respondEncoded(status, names, values, body, off, len, enc, coding)` answer a request in one call with the compressed `Content-Length`, or nothing at all (`H1_AGAIN`, `H1_INVALID`); `identity;q=0` is honoured. Opt-in; BREACH is the program's to avoid (`docs/security/compress.md`) | RFC 9110 §8.4 and §12.5.3: the negotiation table, and sans-IO responses gunzipped back (`tests/link/std_http_compress`) |
264
265
  | [`net/router.ts`](https://github.com/amritk/nish/blob/main/std/net/router.ts) | `Router`, a method and path router that knows no carrier and allocates nothing per match: `add(method, pattern)` answers the route's index (0, 1, 2 in the order added) or a refusal — `ROUTER_BAD_PATTERN`, `ROUTER_BAD_METHOD`, `ROUTER_TOO_LONG`, `ROUTER_AMBIGUOUS` (`*` not last), `ROUTER_DUPLICATE` (the same shape and method, whatever the parameter names) or `ROUTER_FULL`, against `RouterLimits`; `match(method, mStart, mEnd, target, tStart, tEnd, params)` answers the index, `ROUTER_NOT_FOUND` or `ROUTER_METHOD_NOT_ALLOWED`, writing each `:name` and a final `*` as a `[start, end)` pair into the caller's `params` (`ROUTER_TOO_MANY_PARAMS` when it is short). Literal before parameter before `*`, segment by segment, backtracking; a lookup enters each node at most once. The query is left unparsed and nothing is decoded: `routerDecode` decodes one parameter (`ROUTER_BAD_ESCAPE`, `ROUTER_NO_ROOM`) (`docs/security/router.md`) | Every refusal code, precedence and backtracking, 405 against 404, `%2F` kept in one segment, the query, `*` and authority-form targets, a target deeper than any route, the lookup bound, params past storage, and the arena flat over matches (`tests/link/net_router`, `net_router_f64`, five `net_router_negative_*`) |
265
266
  | [`net/handler.ts`](https://github.com/amritk/nish/blob/main/std/net/handler.ts) | `HttpHandler`, complete requests and their answers over the HTTP/1.1 carrier: it owns the readiness loop, routes each request through a `Router` at its head, gathers its body up to `HandlerLimits.http.maxBody` (1 MiB; past it the carrier answers 413), and hands it over whole. The program pulls — `wait(ms)`, `ready()`, `take()` — and switches on `req.route`; `HttpRequest` reads parameters, form-decoded query values and fields as ranges into its own buffers. Each request is answered once, now or in a later turn, by `send`, `sendFields`, `empty`, `json()` + `sendJson`, `problem` (RFC 9457), `refuse` (404, or 405 with `Allow`) or `start`/`write`/`end`; an answer whose connection closed first is `HANDLER_DROPPED` and reaches no later peer. `HEAD` takes a `GET` route. `watch`/`fired` add the program's own descriptors (`signalFd()`), and `drain` stops gracefully. Nothing is allocated per request once warm (`docs/security/handler.md`) | Routing, parameters and form-decoded queries, `HEAD`, 404 and 405 problems, chunked bodies in and out, the body cap at and one past it, pipelining order, late answers dropped across a reused slot, the arena and pool flat over two thousand requests, and the drain (`tests/link/net_handler`, and `net_http_app` over `examples/http-app`) |
267
+ | [`net/serve.ts`](https://github.com/amritk/nish/blob/main/std/net/serve.ts) | `serve(port, router, limits, handle)`, an HTTP/1.1 server for an `async` program over `HttpHandler`: each whole request is copied into a task of its own, which runs the program's `handle(req: Request): Promise<Response>` in its own region and writes the answer into the request slot's preallocated buffers; the loop sends answers in request order. `ServeLimits` caps connections (closed past it), requests in flight (503), the header section (431), the body (413) and the response (500), and closes a connection whose head takes past `headTimeout` or that idles past `idleTimeout`; `deadline` is held, not yet enforced. `Arena.used()` stays flat over thousands of pipelined requests (`tests/link/net_serve_pipelined_flat`). Native only: `--emit-ts` refuses `readable` (NL4017). Record: `docs/security/serve.md`. |
266
268
  | [`net/upstream.ts`](https://github.com/amritk/nish/blob/main/std/net/upstream.ts) | `Upstream`, outbound HTTP/1.1 calls from a route handler that never block it: a pool of keep-alive connections to one `http:` origin on the `HttpHandler`'s own loop (watch ids `UpstreamLimits.firstId` and up). `get(req, path)` returns at once, or `UPSTREAM_E_FULL` with nothing held; each call comes back once through `ready()`/`take()` tagged with `r.req`, `ok` with its status and `body[0 .. length)`, or failed with the codec's `HTTP1_E_` refusal or an `UPSTREAM_E_` code (timeout, closed, connect, origin, lookup, blocked, request), and goes back with `release`. The origin is looked up once at start-up and pinned; `UpstreamLimits.outbound` checks it against an `OutboundPolicy`. A failed call's connection is closed. Each connection keeps one codec in spans mode, so a warm pool allocates nothing per call | A slow upstream while other clients and a second upstream are answered, the timeout, keep-alive and tagging, five codec refusals as failures, the policy refusing loopback, origin and request-target refusals, three thousand warm calls on one connection with `Arena.used()` flat (`tests/link/net_upstream`), and a second `release` panicking (`net_upstream_release`) |
267
269
  | [`net/postgres.ts`](https://github.com/amritk/nish/blob/main/std/net/postgres.ts) | `PgConnection`, a PostgreSQL client that reads no socket: the program fills `inputBuffer()` and sends `outputBuffer()`, and `next()` answers `PG_NEED_MORE`, `PG_READY`, `PG_DESCRIBED`, `PG_ROW`, `PG_COMPLETE`, `PG_ERROR`, `PG_NOTICE`, `PG_GROUP_DONE` or the final `PG_FAILED` (`failure`, one of the `PG_ERR_*` codes). Protocol 3.0: startup, `trust` and SCRAM-SHA-256 with the server's signature checked (cleartext and MD5 refused), the extended query protocol — `prepare`, `bindStart`, `paramInt` / `paramText` / `paramBytes` / `paramTextArray` / `paramIntArray` / `paramNull`, an array built element by element into the Bind (`arrayStart`, `arrayElement`, `arrayInt`, `arrayNull`, `arrayEnd`), binary `int4[]` / `int8[]` parameters (`paramInt4Array` / `paramInt8Array` over an `i64[]` window, or `binaryArrayStart`, `binaryArrayInt`, `binaryArrayNull` and the same `arrayEnd`; per-parameter format codes only once a binary one is bound; an `int4` element out of range panics), `bindEnd`, `bindStartBinary` for a Bind whose result columns come in binary (read in place by `binaryInt`, `binaryBool`, `binaryFloat` and `PgBinary`'s `timestamp` and `iso`, and a one-dimensional `int2[]`, `int4[]` or `int8[]` by `PgBinaryArray`), `bindCancel` to drop a Bind not yet ended, `closeStatement`, `sync` — with up to `maxInFlight` groups pipelined. `PgBatcher` queues keyed reads of one statement shape (`addInt`, `addText`) and `take(conn)` binds up to `maxRequests` of them, each key once, as one execution over `unnest($1) with ordinality`; `row`, `end` and `fail` route its rows by their server-supplied ordinal, checked first (read with `binaryInt` when `PgBatchConfig.binary` is set, so the batch's rows come in binary too), to `next(run)`'s per-request `PG_BATCH_ROW` and `PG_BATCH_DONE` / `PG_BATCH_MISSING` / `PG_BATCH_FAILED`; with `PgBatchConfig.sorted` false the statement has no `order by q.ord`, so no Sort node, rows route as they come and each request's last event waits for `end`; `take` answers a fresh handle each time, so a server's late or repeated event on a spent one is counted in `stray`, never routed or panicked on. It reads no clock and allocates nothing per request or row. `PgBatchClock` says when to take, from times the program passes in: once max(`minCount`, the moving average of batch sizes × `factor`) wait, the oldest has waited `maxWaitUs`, or, with the idle bypass, nothing is in flight and the load is light (its defaults are the fixed window); `PgBatcher.takeDue` takes only then, and `PgBatchTurns` lets one free connection collect while the others execute. A row's columns are windows onto the receive buffer (`colStart`, `colLength`), read in place by `int`, `bool`, `isNull` and `PgText`'s decoders (`timestamptz`, `PgArrayWalker` for `text[]`); no per-row or per-column allocation. The password is a `Secret<u8[]>`, wiped once the proof is made. Caps on message size, columns, groups in flight and SCRAM iterations (`docs/security/postgres.md`) | PostgreSQL 18's frontend/backend protocol chapter, RFC 5802 and RFC 7677: every builder, event and refusal (`tests/link/std_postgres`), and exchanges recorded from PostgreSQL 18 by `tests/postgres/record.mjs` replayed byte for byte (`tests/link/std_postgres_replay`); the batcher's queueing, caps and ordinal refusals (`tests/link/std_postgres_batch`), and unsorted (`tests/link/std_postgres_batch_unsorted`); the clock's reasons, backlog and turns (`tests/link/std_postgres_batch_clock`) |
268
270
  | [`net/postgres-carrier.ts`](https://github.com/amritk/nish/blob/main/std/net/postgres-carrier.ts) | `PgCarrier`, a `PgPool`'s queries on an `HttpHandler`'s loop: its sockets sit in the handler's epoll set, a route handler hands a request to `run` (or `runInt` / `runText` for one of up to 8 attached `PgBatcher`s) and gets its number at once, and `next()` answers `PG_CARRIER_BUILD` to bind a plain query on `connection()`, `PG_CARRIER_ROW`, `PG_CARRIER_COMPLETE`, `PG_CARRIER_ERROR` and one final `PG_CARRIER_DONE`, `PG_CARRIER_MISSING` or `PG_CARRIER_FAILED` (`failure`, `socketError`) with `request()` the request to answer and `tag` the caller's. It connects the pool's slots itself (TCP or a Unix socket), times out a connect after `connectTimeoutMs`, sheds batched keys when no slot can connect, and sizes every table from `PgCarrierLimits` at construction: `run` answers `PG_CARRIER_FULL` rather than grow one, and once connections are up it allocates nothing per query. Kept apart from `net/postgres.ts` so that module reaches no capability (`docs/security/postgres.md`) | A loopback backend in the test itself: routing, a slow query not stalling another client, lost and refused connections, a connect timeout, and `Arena.used()` flat over thousands of queries (`tests/link/std_postgres_carrier`); a live server by `tests/postgres/live/run.mjs` |
@@ -326,8 +328,9 @@ accept into the slot, and after its handshake a connection allocates nothing
326
328
  that outlives a record. The handshake keeps its state in the slot, which
327
329
  `accept` restarts, and a KeyUpdate installs its keys in place, so neither
328
330
  leaves anything in the arena (TLS-3); a connection still takes at most
329
- `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier has
330
- no clock, so closing quiet slots is the program's (TLS-4). On this path the
331
+ `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The program's
332
+ loop calls `expire(monotonicNanos())`, which closes slots idle past
333
+ `idleTimeout`, a minute by default (TLS-4). On this path the
331
334
  record layer wipes `TlsServer`'s traffic and handshake secrets and the
332
335
  ephemeral key once it has what it needs from them, which narrows TLS-1.
333
336
  `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block of
@@ -539,7 +542,7 @@ have, and all three have since landed as builtins:
539
542
  | Was missing | Now |
540
543
  | --- | --- |
541
544
  | a directory listing | `readdirSync(path): string[] \| null`, sorted by bytes, because there is no `sort` for a caller to reach for |
542
- | a child's **output** — `spawnSync` answers a status and nothing else | `spawnSyncTo(argv, stdoutPath, stderrPath)`, each stream to a file, an empty path inheriting; `spawnPiped(argv, stdin, stdout, stderr)`, stdin from a `u8[]` and both outputs into `u8[]`s, for a secret the child reads on stdin |
545
+ | a child's **output** — `spawnSync` answers a status and nothing else | `spawnSyncTo(argv, stdoutPath, stderrPath)`, each stream to a file, an empty path inheriting; `spawnPiped(argv, stdin, stdout, stderr)`, stdin from a `u8[]` and both outputs into `u8[]`s, for a secret the child reads on stdin; `spawnPipedWithin(argv, stdin, stdout, stderr, timeoutMs)`, the same run that answers -3 at a deadline |
543
546
  | a clock | `monotonicNanos(): i64` |
544
547
 
545
548
  So the driver exists, in the language, and it is