nish 0.37.0 → 0.38.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.
- package/README.md +8 -7
- package/docs/AI.md +32 -10
- package/docs/INSTALL.md +28 -16
- package/package.json +8 -7
- package/runtime/core/arrays.d.ts +4 -0
- package/runtime/core/arrays.mjs +33 -0
- package/runtime/nish.d.ts +344 -48
- package/runtime/nish.h +29 -7
- package/runtime/runtime-async.c +228 -45
- package/runtime/runtime-cross.c +2 -1
- package/runtime/runtime-region.c +85 -7
- package/runtime/runtime-text.c +1068 -0
- package/runtime/runtime-wasm.c +3 -3
- package/runtime/runtime.c +50 -961
- package/runtime/vite.mjs +48 -11
- package/scripts/build.sh +86 -28
- package/scripts/fuzz.sh +58 -8
- package/scripts/gen-pow10-table.py +1 -1
- package/scripts/postinstall.mjs +8 -7
- package/scripts/size-report.sh +2 -2
- package/std/LICENSE-fdlibm +8 -0
- package/std/README.md +2 -0
- package/std/array.ts +266 -0
- package/std/host/text.ts +86 -0
- package/std/math.ts +743 -41
- package/std/net/dns-resolver.ts +46 -6
- package/std/net/dns.ts +50 -13
- package/std/net/fetch.ts +691 -129
- package/std/net/handler.ts +12 -0
- package/std/net/http-compress.ts +17 -9
- package/std/net/http-fields.ts +19 -4
- package/std/net/http1-codec.ts +18 -4
- package/std/net/http1-server.ts +13 -3
- package/std/net/postgres-async.ts +1005 -0
- package/std/net/postgres.ts +7 -4
- package/std/net/serve.ts +763 -0
- package/std/text.ts +231 -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
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
|
7
|
-
# <dir>/runtime.c also compiles <dir>/runtime-
|
|
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
|
|
@@ -41,10 +42,13 @@
|
|
|
41
42
|
# when runtime-wasm.c is linked, the arena entry points the
|
|
42
43
|
# `--emit-dts` loader calls (nish_arena_mark, nish_arena_release,
|
|
43
44
|
# 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
|
|
45
|
-
# module when wasm-opt (binaryen)
|
|
46
|
-
#
|
|
47
|
-
#
|
|
45
|
+
# a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz
|
|
46
|
+
# --strip-target-features` on the module when wasm-opt (binaryen)
|
|
47
|
+
# is on PATH; the build line says whether it ran. NISH_WASM_OPT=0
|
|
48
|
+
# links without it even when it is installed (clang's own wasm-opt
|
|
49
|
+
# call too): the module a machine without binaryen builds, which
|
|
50
|
+
# the size guard measures. Two flags take this profile alone, and
|
|
51
|
+
# any other refuses them with exit 2:
|
|
48
52
|
# --memory <MiB> memory fixed at <MiB> MiB (1 to 4096), the
|
|
49
53
|
# initial size and the maximum both, so it
|
|
50
54
|
# never grows and `memory.buffer` is one
|
|
@@ -122,7 +126,7 @@
|
|
|
122
126
|
#
|
|
123
127
|
# The runtime compiled once (the debug, speed and size profiles only; `nish
|
|
124
128
|
# --link` and `nish run` use these through their runtime cache, src/compile.ts):
|
|
125
|
-
# --runtime-objects <dir> compile the runtime.c input
|
|
129
|
+
# --runtime-objects <dir> compile the runtime.c input, its sixteen halves and runtime-async.c,
|
|
126
130
|
# one $CC -c each and all at once, into
|
|
127
131
|
# <dir>/<unit>.o with the profile's compile flags,
|
|
128
132
|
# and link nothing. speed and size store LTO bitcode,
|
|
@@ -267,8 +271,8 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
|
|
|
267
271
|
fi
|
|
268
272
|
[ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
|
|
269
273
|
|
|
270
|
-
# The runtime is
|
|
271
|
-
# <dir>/runtime.c gets <dir>/runtime-os.c, <dir>/runtime-parallel.c,
|
|
274
|
+
# The runtime is seventeen translation units, and a caller names one: whoever passes
|
|
275
|
+
# <dir>/runtime.c gets <dir>/runtime-text.c, <dir>/runtime-os.c, <dir>/runtime-parallel.c,
|
|
272
276
|
# <dir>/runtime-cross.c, <dir>/runtime-host.c, <dir>/runtime-net.c, <dir>/runtime-simd.c,
|
|
273
277
|
# <dir>/runtime-aes.c, <dir>/runtime-sha256.c, <dir>/runtime-chacha20.c, <dir>/runtime-checksum.c, <dir>/runtime-term.c,
|
|
274
278
|
# <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 +284,7 @@ fi
|
|
|
280
284
|
# compiles to two functions that refuse to run, which no wasm build calls, and
|
|
281
285
|
# runtime-shm.c answers -95 for every region. They were one file until the
|
|
282
286
|
# operating-system half was split out for its own size budget, and the parallel
|
|
283
|
-
#
|
|
287
|
+
# and text halves followed for the same reason (each file's header comment says why), and
|
|
284
288
|
# a link line is where those splits
|
|
285
289
|
# would otherwise leak: `nish --link` builds its command line in
|
|
286
290
|
# src/compile.ts, the published package's recipe in every document and
|
|
@@ -288,7 +292,7 @@ fi
|
|
|
288
292
|
# here keeps every one of those correct, and keeps "the runtime" one thing to
|
|
289
293
|
# name from the outside. A caller that names one itself is left alone, because
|
|
290
294
|
# 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"
|
|
295
|
+
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
296
|
for i in ${inputs[@]+"${inputs[@]}"}; do
|
|
293
297
|
case "$i" in
|
|
294
298
|
*/runtime.c|runtime.c)
|
|
@@ -376,6 +380,12 @@ fi
|
|
|
376
380
|
|
|
377
381
|
CC=${CC:-clang}
|
|
378
382
|
common=(-Wno-override-module) # our IR is target-neutral; clang fills the triple in
|
|
383
|
+
# -ffp-contract=off on every unit, every profile (WP50 S5): clang's default
|
|
384
|
+
# contracts a*b+c in C into one fused multiply-add wherever the target has one
|
|
385
|
+
# (arm64 always, x86-64 at v3), which rounds once where the source rounds
|
|
386
|
+
# twice, so the runtime would print another float on arm64 than on x86-64.
|
|
387
|
+
# Nish's own IR asks for no contraction, so the flag changes only the C units.
|
|
388
|
+
common+=(-ffp-contract=off)
|
|
379
389
|
elf=() # flags that only make sense for ELF targets
|
|
380
390
|
lld=0 # 1 when the link goes through ld.lld
|
|
381
391
|
|
|
@@ -447,10 +457,10 @@ if [ "$debug" = 1 ]; then common+=(-g); strip_flag=(); fi
|
|
|
447
457
|
# runtime-parallel.c compiles to its sequential fallback because it tests
|
|
448
458
|
# __wasi__ and __wasm__ as well as the macro.
|
|
449
459
|
# --cpu: every unit at the one level, so the module, the runtime and the link
|
|
450
|
-
# (LTO generates code there) agree. -ffp-contract=off
|
|
451
|
-
#
|
|
452
|
-
#
|
|
453
|
-
if [ -n "$cpu" ]; then common+=(-march=x86-64-v3
|
|
460
|
+
# (LTO generates code there) agree. v3 has FMA, and the -ffp-contract=off every
|
|
461
|
+
# unit has above keeps a*b+c two roundings, so it prints the float the baseline
|
|
462
|
+
# build does (docs/LANGUAGE.md, "The CPU level").
|
|
463
|
+
if [ -n "$cpu" ]; then common+=(-march=x86-64-v3); fi
|
|
454
464
|
|
|
455
465
|
# Hardening, on every native profile (the wasm and wasi ones build their own
|
|
456
466
|
# command line and have none of these to give). docs/security/runtime.md
|
|
@@ -808,6 +818,21 @@ case "$profile" in
|
|
|
808
818
|
if [ "$bytes_wanted" = 1 ] && [ "$bytes_named" = 0 ]; then
|
|
809
819
|
inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-bytes.c")
|
|
810
820
|
fi
|
|
821
|
+
# IR that builds a string (`+`, a template, `String(x)`, a number's digits)
|
|
822
|
+
# calls runtime-text.c, which compiles freestanding for wasm32 (WP50 stage 4).
|
|
823
|
+
# It is added the same way, only for such IR and only when the caller has not
|
|
824
|
+
# named it; it allocates through runtime-wasm.c's arena, so that is linked too.
|
|
825
|
+
text_named=0
|
|
826
|
+
text_wanted=0
|
|
827
|
+
for i in ${inputs[@]+"${inputs[@]}"}; do
|
|
828
|
+
case "$i" in
|
|
829
|
+
*/runtime-text.c|runtime-text.c) text_named=1 ;;
|
|
830
|
+
*.ll) if grep -qE '@nish_(str_|f64_format|json_put_f64)' "$i"; then text_wanted=1; fi ;;
|
|
831
|
+
esac
|
|
832
|
+
done
|
|
833
|
+
if [ "$text_wanted" = 1 ] && [ "$text_named" = 0 ]; then
|
|
834
|
+
inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-text.c")
|
|
835
|
+
fi
|
|
811
836
|
# IR compiled for the host rounds through runtime-simd.c's `nish_floor` and its
|
|
812
837
|
# kin behind the constructor `nish_round_init` (#943). runtime-wasm.c has their
|
|
813
838
|
# wasm32 bodies, and it is added the same way when such IR does not name it.
|
|
@@ -819,6 +844,7 @@ case "$profile" in
|
|
|
819
844
|
*.ll) if grep -q '@nish_round_init' "$i"; then round_wanted=1; fi ;;
|
|
820
845
|
esac
|
|
821
846
|
done
|
|
847
|
+
if [ "$text_wanted" = 1 ]; then round_wanted=1; fi
|
|
822
848
|
# Under wasm-host a program whose loader guards panics (one with module
|
|
823
849
|
# storage or a host module: the compiler ends its IR with a
|
|
824
850
|
# `; nish.sites <count>` line) reports each panic through the page's
|
|
@@ -849,7 +875,7 @@ case "$profile" in
|
|
|
849
875
|
fi
|
|
850
876
|
# -mbulk-memory lowers llvm.memset/memcpy (`new Array<T>(n)`, `push` growth) to the
|
|
851
877
|
# 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)
|
|
878
|
+
wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory -ffp-contract=off)
|
|
853
879
|
if [ "$profile" = wasm ]; then
|
|
854
880
|
"$CC" "${wasm_compile[@]}" \
|
|
855
881
|
${tls[@]+"${tls[@]}"} \
|
|
@@ -967,17 +993,49 @@ case "$profile" in
|
|
|
967
993
|
bytes=$((memory_mib * 1048576))
|
|
968
994
|
memory+=("-Wl,--initial-memory=$bytes" "-Wl,--max-memory=$bytes")
|
|
969
995
|
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
996
|
# binaryen's size pass is optional: the module is complete without it.
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
997
|
+
# It runs twice when wasm-opt is installed. clang 18 runs it itself after
|
|
998
|
+
# any link with an -O flag, finding it on PATH, and has wasm-ld keep the
|
|
999
|
+
# `target_features` section for it: 48 bytes or more that nothing at
|
|
1000
|
+
# run time reads, which put add.wasm at 150 bytes against 102 without
|
|
1001
|
+
# wasm-opt (#1257). The pass below drops that section again.
|
|
1002
|
+
# NISH_WASM_OPT=0 runs neither: each source is compiled alone and the
|
|
1003
|
+
# objects linked with no -O flag, so clang starts no wasm-opt and the
|
|
1004
|
+
# module is byte for byte the one a machine without binaryen links.
|
|
1005
|
+
# That is the build the size guard pins.
|
|
1006
|
+
case "${NISH_WASM_OPT:-1}" in
|
|
1007
|
+
0)
|
|
1008
|
+
make_work
|
|
1009
|
+
host_objects=()
|
|
1010
|
+
for i in "${host_inputs[@]}"; do
|
|
1011
|
+
# What clang compiles in a one-step link is compiled here (.ll, .c,
|
|
1012
|
+
# .bc, .s, ...); what it hands straight to wasm-ld passes through.
|
|
1013
|
+
case "$i" in
|
|
1014
|
+
*.o|*.a) host_objects+=("$i") ;;
|
|
1015
|
+
*)
|
|
1016
|
+
object="$work/host-${#host_objects[@]}.o"
|
|
1017
|
+
"$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
|
|
1018
|
+
${tls[@]+"${tls[@]}"} -c "$i" -o "$object"
|
|
1019
|
+
host_objects+=("$object") ;;
|
|
1020
|
+
esac
|
|
1021
|
+
done
|
|
1022
|
+
"$CC" --target=wasm32-unknown-unknown -nostdlib \
|
|
1023
|
+
-Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
|
|
1024
|
+
"${host_objects[@]}" -o "$out"
|
|
1025
|
+
wasm_opt="no wasm-opt, NISH_WASM_OPT=0" ;;
|
|
1026
|
+
1)
|
|
1027
|
+
"$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
|
|
1028
|
+
${tls[@]+"${tls[@]}"} \
|
|
1029
|
+
-Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
|
|
1030
|
+
"${host_inputs[@]}" -o "$out"
|
|
1031
|
+
if command -v wasm-opt >/dev/null 2>&1; then
|
|
1032
|
+
wasm-opt -Oz --enable-bulk-memory --strip-target-features "$out" -o "$out"
|
|
1033
|
+
wasm_opt="wasm-opt -Oz"
|
|
1034
|
+
else
|
|
1035
|
+
wasm_opt="no wasm-opt"
|
|
1036
|
+
fi ;;
|
|
1037
|
+
*) echo "error: NISH_WASM_OPT must be 0 or 1, not '$NISH_WASM_OPT'" >&2; exit 2 ;;
|
|
1038
|
+
esac
|
|
981
1039
|
if [ -n "$inline_to" ]; then
|
|
982
1040
|
# Decimal, one array literal: of the inline forms the smallest after
|
|
983
1041
|
# compression (docs/wp50-wasm-host.md, Q10). od prints each byte as an
|
|
@@ -1027,9 +1085,9 @@ case "$profile" in
|
|
|
1027
1085
|
fi
|
|
1028
1086
|
# SQLite builds on wasi-libc as it is: the amalgamation sees __wasi__ and
|
|
1029
1087
|
# takes dot-file locking, no mmap and no WAL shared memory.
|
|
1030
|
-
sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
|
|
1088
|
+
sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
|
|
1031
1089
|
${tls[@]+"${tls[@]}"} -ffunction-sections -fdata-sections
|
|
1032
|
-
"$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
|
|
1090
|
+
"$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
|
|
1033
1091
|
${tls[@]+"${tls[@]}"} \
|
|
1034
1092
|
-ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--strip-all \
|
|
1035
1093
|
"${inputs[@]}" ${libs[@]+"${libs[@]}"} -o "$out" ;;
|
package/scripts/fuzz.sh
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
# scripts/fuzz.sh --replay [<name>] every corpus and regression
|
|
8
8
|
# input once; a crash fails
|
|
9
9
|
# scripts/fuzz.sh --smoke every target: build, replay,
|
|
10
|
-
# then a short fixed-seed run
|
|
10
|
+
# then a short fixed-seed run,
|
|
11
|
+
# FUZZ_JOBS targets at a time
|
|
11
12
|
#
|
|
12
13
|
# A target is `tests/fuzz/targets/<name>.ts` exporting
|
|
13
14
|
# `export const fuzzOne = (data: u8[]): void` (tests/fuzz/README.md). It is
|
|
@@ -24,6 +25,12 @@
|
|
|
24
25
|
# std/ beside itself, so the seed would fuzz its own std.
|
|
25
26
|
# FUZZ_SMOKE_SECONDS --smoke's fuzzing time per target (default 20)
|
|
26
27
|
# FUZZ_SEED --smoke's libFuzzer -seed (default 1)
|
|
28
|
+
# FUZZ_JOBS how many targets --smoke builds and fuzzes at once
|
|
29
|
+
# (default: the online cores). Each libFuzzer run is one
|
|
30
|
+
# process on one core, so a serial smoke left three of a
|
|
31
|
+
# CI runner's four idle; four at a time ran as many
|
|
32
|
+
# inputs per target as one at a time, in a quarter of
|
|
33
|
+
# the wall time.
|
|
27
34
|
# FUZZ_OUT where binaries, scratch corpora and artifacts go
|
|
28
35
|
# (default build/fuzz)
|
|
29
36
|
#
|
|
@@ -39,12 +46,14 @@ NISH="${NISH:-build/nish}"
|
|
|
39
46
|
FUZZ_OUT="${FUZZ_OUT:-build/fuzz}"
|
|
40
47
|
FUZZ_SMOKE_SECONDS="${FUZZ_SMOKE_SECONDS:-20}"
|
|
41
48
|
FUZZ_SEED="${FUZZ_SEED:-1}"
|
|
49
|
+
FUZZ_JOBS="${FUZZ_JOBS:-$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)}"
|
|
42
50
|
CC="${CC:-clang}"
|
|
43
51
|
|
|
44
52
|
# The runtime's C units: tests/run.js's RUNTIME_C, which its `fuzz` section
|
|
45
53
|
# checks this list against. runtime-wasm.c is wasm32's alone.
|
|
46
54
|
RUNTIME_C=(
|
|
47
55
|
runtime/runtime.c
|
|
56
|
+
runtime/runtime-text.c
|
|
48
57
|
runtime/runtime-os.c
|
|
49
58
|
runtime/runtime-parallel.c
|
|
50
59
|
runtime/runtime-cross.c
|
|
@@ -72,7 +81,7 @@ die() {
|
|
|
72
81
|
}
|
|
73
82
|
|
|
74
83
|
usage() {
|
|
75
|
-
sed -n '2,
|
|
84
|
+
sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//' >&2
|
|
76
85
|
exit "${1:-2}"
|
|
77
86
|
}
|
|
78
87
|
|
|
@@ -99,7 +108,7 @@ build_runtime() {
|
|
|
99
108
|
local src obj
|
|
100
109
|
for src in "${RUNTIME_C[@]}"; do
|
|
101
110
|
obj="$FUZZ_OUT/obj/$(basename "$src" .c).o"
|
|
102
|
-
"$CC" "${SAN_FLAGS[@]}" -DNISH_FUZZ_ABORT -Iruntime -c "$src" -o "$obj" \
|
|
111
|
+
"$CC" "${SAN_FLAGS[@]}" -ffp-contract=off -DNISH_FUZZ_ABORT -Iruntime -c "$src" -o "$obj" \
|
|
103
112
|
|| die "compiling $src under the sanitizers failed (is libclang-rt-18-dev installed?)"
|
|
104
113
|
runtime_objs+=("$obj")
|
|
105
114
|
done
|
|
@@ -213,13 +222,54 @@ case "$mode" in
|
|
|
213
222
|
[ $# -eq 0 ] || usage
|
|
214
223
|
mapfile -t names < <(targets)
|
|
215
224
|
[ ${#names[@]} -gt 0 ] || die "no targets in tests/fuzz/targets/"
|
|
225
|
+
[[ "$FUZZ_JOBS" =~ ^[1-9][0-9]*$ ]] || die "FUZZ_JOBS must be a positive integer, not '$FUZZ_JOBS'"
|
|
226
|
+
# The lanes share the runtime objects, so they are built here, once,
|
|
227
|
+
# before any lane starts: a lane that found them missing would build them
|
|
228
|
+
# itself, into the same files as the others.
|
|
229
|
+
build_runtime
|
|
230
|
+
logs="$FUZZ_OUT/smoke"
|
|
231
|
+
rm -rf "$logs"
|
|
232
|
+
mkdir -p "$logs"
|
|
233
|
+
# Each target is a lane writing its own log and, as it exits, its status,
|
|
234
|
+
# so the logs are printed whole and in target order once every lane is
|
|
235
|
+
# done, and one target's crash does not stop the others. The status comes
|
|
236
|
+
# from an EXIT trap: the lane stops at its first failing step under
|
|
237
|
+
# `set -e`, which a status written after the lane, or a lane run as a
|
|
238
|
+
# condition, would not keep.
|
|
239
|
+
running=0
|
|
216
240
|
for name in "${names[@]}"; do
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
241
|
+
if [ "$running" -ge "$FUZZ_JOBS" ]; then
|
|
242
|
+
# A lane's status is read from its file below, not from here.
|
|
243
|
+
wait -n || true
|
|
244
|
+
running=$((running - 1))
|
|
245
|
+
fi
|
|
246
|
+
(
|
|
247
|
+
status_file="$logs/$name.status"
|
|
248
|
+
trap 'echo "$?" >"$status_file"' EXIT
|
|
249
|
+
build "$name"
|
|
250
|
+
replay "$name"
|
|
251
|
+
rm -rf "$FUZZ_OUT/work/$name"
|
|
252
|
+
run "$name" -seed="$FUZZ_SEED" -max_total_time="$FUZZ_SMOKE_SECONDS" -print_final_stats=1
|
|
253
|
+
) >"$logs/$name.log" 2>&1 &
|
|
254
|
+
running=$((running + 1))
|
|
221
255
|
done
|
|
222
|
-
|
|
256
|
+
wait
|
|
257
|
+
# Under GitHub Actions each target's log folds into a group of its own.
|
|
258
|
+
group=""
|
|
259
|
+
[ "${GITHUB_ACTIONS:-}" = true ] && group=1
|
|
260
|
+
failed=()
|
|
261
|
+
for name in "${names[@]}"; do
|
|
262
|
+
[ -n "$group" ] && echo "::group::fuzz.sh: $name"
|
|
263
|
+
cat "$logs/$name.log"
|
|
264
|
+
[ -n "$group" ] && echo "::endgroup::"
|
|
265
|
+
status="$(cat "$logs/$name.status" 2>/dev/null || echo missing)"
|
|
266
|
+
[ "$status" = 0 ] || failed+=("$name (exit $status)")
|
|
267
|
+
done
|
|
268
|
+
if [ ${#failed[@]} -gt 0 ]; then
|
|
269
|
+
echo "fuzz.sh: smoke failed in ${#failed[@]} of ${#names[@]} targets: ${failed[*]}" >&2
|
|
270
|
+
exit 1
|
|
271
|
+
fi
|
|
272
|
+
echo "fuzz.sh: smoke passed over ${#names[@]} targets, $FUZZ_JOBS at a time"
|
|
223
273
|
;;
|
|
224
274
|
-h | --help)
|
|
225
275
|
usage 0
|
package/scripts/postinstall.mjs
CHANGED
|
@@ -53,13 +53,14 @@ import { pathToFileURL } from "node:url"
|
|
|
53
53
|
const root = path.resolve(import.meta.dirname, "..")
|
|
54
54
|
|
|
55
55
|
const swap = async () => {
|
|
56
|
-
// A checkout, not an install. The
|
|
57
|
-
//
|
|
58
|
-
//
|
|
59
|
-
// tracked `bin/nish` with
|
|
60
|
-
// landmark is `src/compile.ts`, which is the check
|
|
61
|
-
// makes and is not in `files`; it used to be stage0's
|
|
62
|
-
// being a landmark when the launcher moved
|
|
56
|
+
// A checkout, not an install. The checked-in package.json pins no platform
|
|
57
|
+
// package (release.yml adds them at pack time), but a `node_modules` left from
|
|
58
|
+
// before it stopped can still hold one, and without this guard `npm ci` would
|
|
59
|
+
// overwrite the tracked `bin/nish` with that binary and leave the working
|
|
60
|
+
// tree dirty. The landmark is `src/compile.ts`, which is the check
|
|
61
|
+
// `scripts/bootstrap.sh` makes and is not in `files`; it used to be stage0's
|
|
62
|
+
// `src/launcher.ts`, which stopped being a landmark when the launcher moved
|
|
63
|
+
// into `bin/` and ships.
|
|
63
64
|
if (fs.existsSync(path.join(root, "src", "compile.ts"))) {
|
|
64
65
|
return "a checkout, so the shim stays"
|
|
65
66
|
}
|
package/scripts/size-report.sh
CHANGED
|
@@ -67,9 +67,9 @@ while IFS=$'\t' read -r label src budget constant flags; do
|
|
|
67
67
|
row "$label" "$(text_sum "$obj")" \
|
|
68
68
|
"clang -Oz ${flags:+$flags }-c $src && size -A (.text*; budget $budget, $constant)"
|
|
69
69
|
done <<< "$budgets"
|
|
70
|
-
row rodata "$(sect .rodata build/size/
|
|
70
|
+
row rodata "$(sect .rodata build/size/runtime_text_c.o)" "the text object's .rodata (no budget; the Zmij table lives here)"
|
|
71
71
|
if [ "$budgets_only" = 1 ]; then exit 0; fi
|
|
72
|
-
# `scripts/build.sh` compiles
|
|
72
|
+
# `scripts/build.sh` compiles every other unit (its `halves`) beside any runtime.c it is handed, so naming the
|
|
73
73
|
# core here builds the whole runtime -- and `--gc-sections` then drops whatever this module
|
|
74
74
|
# never calls, which for `examples/add.ts` is all of it.
|
|
75
75
|
for p in debug speed size; do
|
package/std/LICENSE-fdlibm
CHANGED
|
@@ -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
|
@@ -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` |
|