@amritk/nish-aarch64-linux 0.45.1 → 0.46.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/INSTALL.md +3 -1
- package/bin/nish +0 -0
- package/package.json +1 -1
- package/runtime/nish.d.ts +41 -0
- package/runtime/nish.h +10 -0
- package/runtime/nish.mjs +1 -0
- package/runtime/runtime-host.c +15 -0
- package/runtime/runtime-net.c +223 -4
- package/runtime/runtime-os.c +15 -1
- package/runtime/runtime-uring.c +291 -31
- package/runtime/sqlite/nish-sqlite.c +301 -128
- package/std/README.md +13 -13
- package/std/net/handler.ts +42 -7
- package/std/sqlite.ts +171 -0
package/std/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Nish modules written in Nish, for Nish programs to import. A module in this
|
|
4
4
|
directory is an ordinary Nish source file, compiled as part of whatever program
|
|
5
5
|
imports it and subject to the same rules as any other
|
|
6
|
-
([`docs/LANGUAGE.md`](
|
|
6
|
+
([`docs/LANGUAGE.md`](../docs/reference/language.md) is the style guide).
|
|
7
7
|
The compiler knows about a few of them, and each such row says how: the modules
|
|
8
8
|
a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
9
9
|
`math.ts`), the functions it lowers in place (`map.ts`, `threads.ts`,
|
|
@@ -13,14 +13,14 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
13
13
|
| Module | What it is |
|
|
14
14
|
| --- | --- |
|
|
15
15
|
| [`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 |
|
|
16
|
-
| [`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 `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`](
|
|
16
|
+
| [`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 `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`](../docs/reference/language/declarations.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
|
|
17
17
|
| [`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 |
|
|
18
18
|
| [`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 |
|
|
19
19
|
| [`array.ts`](https://github.com/amritk/nish/blob/main/std/array.ts) | the array methods that take a callback, and `slice`: `xs.map(f)`, `filter`, `some`, `every`, `findIndex` and `slice`, each a plain loop compiled once per callback, with no function pointer. A program never imports it: a call to one of those methods on an array loads it, and the compiler routes `xs.map(f)` to `map` or `mapIndexed` by how many parameters `f` takes. Each walks the array in order up to the length it had when the call began, as `Array.prototype` does, and `some`, `every` and `findIndex` stop at the element that decides the answer; a callback that shrinks the array ends the walk at the new length, where JavaScript goes on. Under Node the methods are the platform's own (`tests/cases/arr_map`, `arr_filter` and their kin) |
|
|
20
20
|
| [`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 |
|
|
21
21
|
| [`json.ts`](https://github.com/amritk/nish/blob/main/std/json.ts) | `jsonField(object, name)`: the value of one field of one flat JSON object, which is the shape the compiler's own `--json` diagnostics have. A reader and not a parser — it answers text, answers `null` for a field that is not there, and does not validate. `JsonWriter` is the other direction: any JSON value written into a caller-owned `u8[]`, commas and colons included, byte for byte what `JSON.stringify` writes, and allocating nothing per call except an `f64`'s digits, a temporary string the call gives back before it returns (`text()` and `jsonStringifyString` build strings by design); misuse and a full buffer set a sticky negative `JSON_WRITE_*` code in `failed` rather than panicking. `setIndent(n)` and `setIndentTab()` write what `JSON.stringify(v, null, n)` or `(v, null, "\t")` writes, with no allocation for the indent, and `setStrict(true)` makes NaN and the infinities the sticky `JSON_WRITE_NON_FINITE` instead of `null`; both modes are off by default and kept by `reset`. `jsonStringifyString(s)` is the string rule answered as a string. `stringBytes(bytes, off, len)` and `keyBytes(bytes, off, len)` write a window of a byte array as `string` and `key` write a string of those bytes, allocating nothing, and refuse a window outside the array with `JSON_WRITE_BAD_WINDOW` |
|
|
22
22
|
| [`json-tokenizer.ts`](https://github.com/amritk/nish/blob/main/std/json-tokenizer.ts) | `JsonTokenizer`: a validating, streaming tokenizer for RFC 8259 JSON held in a window of a `u8[]`. `next()` answers one `JSON_TOK_*` token at a time — object and array openers and closers, keys, strings, numbers and the three literals — then `JSON_TOK_END`, or a negative `JSON_TOK_ERR_*` code that sticks in `failed`, with the byte in `errorAt`. Strings are checked as UTF-8 and a lone surrogate escape is refused; `stringInto` decodes the current string into the caller's array and `keyEquals` compares it with a name, neither allocating. `numberF64` is correctly rounded; `isInteger` and `numberI64` read an integer that fits an `i64`, and `isU64` and `numberU64` one that fits a `u64`. `isIntegral` asks whether a number's value is whole however it is written (`1.0`, `1e2`, `1e400`), JSON Schema's "integer", from the text and at any exponent. `skipValue` steps over a value. `JsonLimits` caps nesting depth, string, number and total bytes, each with its own code; `reset` reuses the tokenizer, so a reused body keeps the arena flat. Duplicate keys are reported as tokens. No input panics and no byte outside the window is read; [`docs/security/json.md`](../docs/security/json.md) is its record, and `tests/link/std_json_tokenizer` runs JSONTestSuite and a seeded fuzz |
|
|
23
|
-
| [`json-typed.ts`](https://github.com/amritk/nish/blob/main/std/json-typed.ts) | `jsonDecode(d, out)` and `jsonEncode(w, value)`: one JSON object read into a class and written back, with code the compiler writes at each call from the class's fields — scalars (`u64` exact to 2^64 - 1), strings, enums (a numeric one as its number, a string one as its member's string), nested classes, arrays of those, `Map<string, V>` of those and `\| null` — through `JsonDecoder` (a `JsonTokenizer` and a sticky error) and `JsonWriter`. A class's one `static readonly json` literal renames a field's key and makes a key optional, a missing one setting its field to the initializer; otherwise every field is required, each key once, an unknown key refused unless `ignoreUnknown`, and every outcome a sticky `JSON_DECODE_*` or `JSON_TOK_ERR_*` code with its byte in `errorAt`; decoding into a reused object reuses its objects, arrays and equal strings, so the arena stays flat (a map's entries are made anew, at most `maxMapKeys` over all the maps of one decode, 4,096 by default); a key is sent to its field by its length, then one byte. A `JsonNumber` field keeps a number's text byte for byte. Under Node the types are erased and both calls panic ([`docs/LANGUAGE.md`](
|
|
23
|
+
| [`json-typed.ts`](https://github.com/amritk/nish/blob/main/std/json-typed.ts) | `jsonDecode(d, out)` and `jsonEncode(w, value)`: one JSON object read into a class and written back, with code the compiler writes at each call from the class's fields — scalars (`u64` exact to 2^64 - 1), strings, enums (a numeric one as its number, a string one as its member's string), nested classes, arrays of those, `Map<string, V>` of those and `\| null` — through `JsonDecoder` (a `JsonTokenizer` and a sticky error) and `JsonWriter`. A class's one `static readonly json` literal renames a field's key and makes a key optional, a missing one setting its field to the initializer; otherwise every field is required, each key once, an unknown key refused unless `ignoreUnknown`, and every outcome a sticky `JSON_DECODE_*` or `JSON_TOK_ERR_*` code with its byte in `errorAt`; decoding into a reused object reuses its objects, arrays and equal strings, so the arena stays flat (a map's entries are made anew, at most `maxMapKeys` over all the maps of one decode, 4,096 by default); a key is sent to its field by its length, then one byte. A `JsonNumber` field keeps a number's text byte for byte. Under Node the types are erased and both calls panic ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#typed-json-nishjson-typed), [`docs/security/json.md`](../docs/security/json.md)) |
|
|
24
24
|
| [`json-value.ts`](https://github.com/amritk/nish/blob/main/std/json-value.ts) | `JsonDocument`: any JSON document parsed into a tree of `JsonValue` handles (`i32`s into the document), read with `kind`, `boolean`, `string`, `stringEquals`, `length`, `at`, `keyAt` and `get`, built with the `new*` methods, `push` and `set`, and written back through `JsonWriter` with `write`, or as text with `stringify`. A number keeps its source text and is read on request as an `i64` or `u64` that fits (`isI64`, `isU64`), the nearest `f64`, or the text, and `isIntegral` asks whether its value is whole however it is written (`1.0`, `1e2`), so integers and decimals wider than any type round-trip byte for byte. Objects keep insertion order; a repeated key is `JSON_VALUE_ERR_DUPLICATE` unless `duplicates` is `JSON_VALUE_DUPLICATE_LAST`, `JSON.parse`'s rule. Every parse error and limit is the tokenizer's, with the depth held to the writer's 64 so that whatever parses writes back, nothing panics, and a value is in at most one container, so a tree built through `push` and `set` cannot hold itself. A handle carries the generation of the document it came from, so one kept across a `parse` or `clear` reads as nothing; `maxValues` (262,144 by default, `JSON_VALUE_ERR_VALUES` past it) bounds the memory a document keeps. `parseRanged` and `parseTextRanged` also record each value's byte range (`start`, `end`) and each key's (`keyStart`, `keyEnd`), 20 bytes more per value, and `setRange` and `setKeyRange` give built values theirs; after `parse` or `parseText` every range reads `-1`. Each `parse` reuses the document's arrays, so a reused document keeps the arena flat. `tests/link/std_json_value` runs JSONTestSuite through it ([`docs/security/json.md`](../docs/security/json.md)) |
|
|
25
25
|
| [`json-pointer.ts`](https://github.com/amritk/nish/blob/main/std/json-pointer.ts) | RFC 6901 JSON Pointers over a `JsonDocument`: `jsonPointerParse` (the decoded tokens, or `null`), `jsonPointerEscape` (one token, `~0` and `~1`), and `jsonPointerResolve` (the value, `JSON_POINTER_NONE` when the pointer names nothing, `JSON_POINTER_ERR_SYNTAX` when it is not one); `isJsonPointer` and `isRelativeJsonPointer` check JSON Schema's `json-pointer` and `relative-json-pointer` forms, reading the text once and allocating nothing. A resolve costs the pointer's length plus each object step's size. `tests/link/std_json_pointer` runs the suite's two format files through it |
|
|
26
26
|
| [`json-equal.ts`](https://github.com/amritk/nish/blob/main/std/json-equal.ts) | JSON Schema's value equality for `const`, `enum` and `uniqueItems`: `jsonEqual` across two documents (numbers by value, `1` is `1.0`; member order ignored; `true` is not `1`), `jsonEqualCanonical` (a text equal for exactly the equal values), `jsonEqualHash` (64-bit FNV-1a of it, unkeyed) and `jsonEqualFirstDuplicate` (`-1` when the items are unique). Nothing recurses, so any depth a document holds compares; a call costs the values' sizes plus sorting object keys. `tests/link/std_json_equal` runs the suite's `const`, `enum` and `uniqueItems` |
|
|
@@ -31,16 +31,16 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
31
31
|
| [`yaml-lines.ts`](https://github.com/amritk/nish/blob/main/std/yaml-lines.ts) | `YamlLineIndex`: byte offsets turned into 1-based `line` and `column` (characters) or `byteColumn`, by binary search over line starts found once with `indexOf`. LF, CR LF and a lone CR each break a line; an offset is clamped to the text first. |
|
|
32
32
|
| [`yaml-write.ts`](https://github.com/amritk/nish/blob/main/std/yaml-write.ts) | `stringifyYaml(doc, v)`: a `json-value` value written as block-style YAML that `parseYaml` reads back as the same tree. A string YAML would read as something else (a null, bool or number word, an indicator, a `: ` or ` #`, an edge space, a control character) is double-quoted and escaped; a key over 1024 bytes is an explicit `? key`. `""` for a no-value handle or a tree deeper than `JSON_WRITER_MAX_DEPTH`. |
|
|
33
33
|
| [`pair.ts`](https://github.com/amritk/nish/blob/main/std/pair.ts) | `Pair<A, B>`: an interface with `first` and `second`, for a function that answers two values from one call. A type and nothing else — the caller writes an object literal at the return — and for returning two values rather than storing them side by side |
|
|
34
|
-
| [`collections.ts`](https://github.com/amritk/nish/blob/main/std/collections.ts) | the global `Map<K, V>` and `Set<T>`: insertion-ordered tables whose buckets carry a hash fingerprint beside the entry index and whose entries keep their full hash, so every `get`, `set`, `add`, `has` and `delete` is one probe. `get` is not a method here: its `V | undefined` never crosses a call, so the compiler lowers it to `probe` and, where the key was found, `valueAt`. Nor are `keys()` and `values()`: an iterator is not a value, so a `for...of` over one is lowered to `walkOpen`, `walkNext`, `keyAt` or `valueAt`, and `walkClose`, and a count of live walks defers compaction until no loop is walking the table. A program never imports it: naming `Map` or `Set` loads it, and the compiler emits what a module uses of it into that module ([`docs/LANGUAGE.md`](
|
|
35
|
-
| [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](
|
|
36
|
-
| [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](
|
|
34
|
+
| [`collections.ts`](https://github.com/amritk/nish/blob/main/std/collections.ts) | the global `Map<K, V>` and `Set<T>`: insertion-ordered tables whose buckets carry a hash fingerprint beside the entry index and whose entries keep their full hash, so every `get`, `set`, `add`, `has` and `delete` is one probe. `get` is not a method here: its `V | undefined` never crosses a call, so the compiler lowers it to `probe` and, where the key was found, `valueAt`. Nor are `keys()` and `values()`: an iterator is not a value, so a `for...of` over one is lowered to `walkOpen`, `walkNext`, `keyAt` or `valueAt`, and `walkClose`, and a count of live walks defers compaction until no loop is walking the table. A program never imports it: naming `Map` or `Set` loads it, and the compiler emits what a module uses of it into that module ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)). Its `hashKey`, `sameKey` and `storedKey` are lowered by the compiler per key type |
|
|
35
|
+
| [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)) |
|
|
36
|
+
| [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#byte-runs-skipblank-skipdigits-skipjsontext-skipjsonplain-and-copybytes-in-nishbytes)). The runs are variable-time. `tests/link/std_bytes*` are its programs |
|
|
37
37
|
| [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string, `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array panics before a byte is written. It indexes its alphabet by the sextet, so it is not constant-time: it is for pixels, not secrets. A strict decoder, and an encoder for key material, are `crypto/base64url.ts`'s `base64StdPadDecode` and `base64StdPadEncode` (`tests/link/std_base64`, `std_base64_f64`, `std_base64_negative_*`; the two modules in one program: `tests/link/std_base64_two_modules`; [guide](../docs/guide/using-nish/standard-library.md#nishbase64)) |
|
|
38
38
|
| [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin. There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
|
|
39
|
-
| [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, written with `nish:unsafe`'s `wrappingAdd`, `wrappingSub` and `wrappingMul` so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](
|
|
39
|
+
| [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, written with `nish:unsafe`'s `wrappingAdd`, `wrappingSub` and `wrappingMul` so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
|
|
40
40
|
| [`cli.ts`](https://github.com/amritk/nish/blob/main/std/cli.ts) | a command-line tool's `--help`. `HelpMenu` builds it a line at a time — `header`, `usage`, `section`, `row(flag, placeholder, description)`, `note`, `value` — with descriptions lined up at the caller's columns, counted on the plain text, and answers it with `text()`. `Style` paints it in the basic ANSI colours, bold and faint, which the terminal's theme defines, or in bold and underline alone when `TERM` declares no colours; each role it paints (`heading`, `name`, `flag`, `meta`, `dim`) is a pair of SGR lists, `<role>Themed` and `<role>Mono`, a program may set. `Style` also paints any text: the sixteen colours (`red`, `brightBlack`, ...), their backgrounds (`bgRed`, `bgBrightRed`, ...), the attributes (`bold`, `faint`, `italic`, `underline`, `inverse`, `strikethrough`, which the failsafe keeps) and `sgr(text, codes)` for any parameter list, with the `SGR_` constants spelling the codes. `styleFor(fd, agent)` is the policy `nish --help` follows: plain unless the descriptor is a terminal, `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE`, `CLICOLOR` and `TERM=dumb` honoured, plain for an agent (`agentDriven`), forced colour always the theme's; it reads the environment and, for the terminal check, forks `/bin/sh` once, which runs `tput` by absolute path. `HelpMenu` and `Style` reach no capability. The compiler's own help is built with it through a relative import, so the module may use only what the last release compiles (`tests/link/std_cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli)) |
|
|
41
41
|
| [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle and every mistake a panic at its call. `parse(argv, start)` walks the arguments once and answers a `ParseResult`: the reached command's id and path, each flag's value with its `source` (the command line, its default or unset), the positionals and what follows `--`, or the first error with a did-you-mean. `finish` prints help (laid out by `HelpMenu`), the version or the error and exits 0 or 2. `parse` reaches no capability (`tests/link/std_cli_args`, `examples/api-cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli-args)) |
|
|
42
42
|
| [`cli-flags.ts`](https://github.com/amritk/nish/blob/main/std/cli-flags.ts) | `nish/cli-flags`: a command line read against a declared table. `FlagTable` declares `string`, `number` (an `f64`), `boolean` (`--name` / `--no-name`) and `repeatable` flags and `command` paths of one or more words; `parse(args)` (or `parseFrom(process.argv, 1)`) answers a `ParsedFlags` with the longest matched `command`, the `positionals` and each flag by name (`str`, `num`, `bool`, `all`, `has`). `--name value`, `--name=value`, `--` and a lone `-` follow the GNU long-option grammar; there are no short options. A usage error (unknown flag, missing value, not a number, given twice, value on a boolean, unknown command) is carried as `code`, `message` and `argument`, and `exitUsage()` writes it to stderr and exits 2. `writeHelp(menu)` adds the table's rows to a `nish/cli` `HelpMenu`. Reaches `exit` only through `exitUsage` (`tests/link/std_cli_flags`, `std_cli_flags_bad_*`; [guide](../docs/guide/using-nish/standard-library.md#parsing-flags)) |
|
|
43
|
-
| [`sqlite.ts`](https://github.com/amritk/nish/blob/main/std/sqlite.ts) | SQLite, vendored in `runtime/sqlite/` and linked into a program that imports the module, through the C adapter `runtime/sqlite/nish-sqlite.c`. `openDatabase(path, flags)` answers a `Database`: `exec`, `begin` / `commit` / `rollback`, `prepare` into a `Statement`, `lastInsertRowid`, `changes` and `close`, which finalizes the connection's statements. A `Statement` binds (`bindI64`, `bindF64`, `bindNull`, `bindText`, `bindTextBytes`, `bindBlob`), steps, resets and reads columns (`columnType`, `columnI64`, `columnF64`, `columnBytes`, `columnText`, and `columnInto`, a copy into the caller's `u8[]`), so a row allocates nothing. Every failure is a `Result` of SQLite's extended code, and `error(code)` builds the `SqliteError` with its message. A handle is an `i32` into the adapter's thread-local tables, and one used after `close` or `finalize` answers `SQLITE_MISUSE`. Reaches `ffi`; links natively and under `--profile wasi` (`tests/link/std_sqlite*`; [`docs/LANGUAGE.md`](
|
|
43
|
+
| [`sqlite.ts`](https://github.com/amritk/nish/blob/main/std/sqlite.ts) | SQLite, vendored in `runtime/sqlite/` and linked into a program that imports the module, through the C adapter `runtime/sqlite/nish-sqlite.c`. `openDatabase(path, flags)` answers a `Database`: `exec`, `begin` / `commit` / `rollback`, `prepare` into a `Statement`, `lastInsertRowid`, `changes` and `close`, which finalizes the connection's statements. A `Statement` binds (`bindI64`, `bindF64`, `bindNull`, `bindText`, `bindTextBytes`, `bindBlob`), steps, resets and reads columns (`columnType`, `columnI64`, `columnF64`, `columnBytes`, `columnText`, and `columnInto`, a copy into the caller's `u8[]`), so a row allocates nothing. Every failure is a `Result` of SQLite's extended code, and `error(code)` builds the `SqliteError` with its message. A handle is an `i32` into the adapter's thread-local tables, and one used after `close` or `finalize` answers `SQLITE_MISUSE`. Reaches `ffi`; links natively and under `--profile wasi` (`tests/link/std_sqlite*`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#sqlite-nishsqlite)) |
|
|
44
44
|
| [`release.ts`](https://github.com/amritk/nish/blob/main/std/release.ts) | `nish/release`: whether a newer release of a project on GitHub is out, and its `install.sh`. `releaseLatest(base, timeoutMs)` asks `<base>/releases/latest` once without following the redirect and answers the version only when it goes to exactly `<base>/releases/tag/v<version>`, else null; `releaseIsNewer`, `releaseCompare` and `releaseParseVersion` order semantic versions (a prerelease below its release, build metadata ignored, nothing that does not parse ever newer); `releaseValidVersion` is `install.sh`'s rule for a version that may go in a URL. `releaseCheckCached(base, current, path, maxAgeMs, timeoutMs)` keeps the answer in a file believed only when it is a regular file this user owns that nobody else can write, and refreshed when stale or dated in the future; `releaseFetchInstaller` writes a tag's `install.sh` to a file, never to a shell. https only, or http to loopback. The compiler's update notice and `nish upgrade` run on it ([`docs/security/release.md`](../docs/security/release.md); `tests/run.js` "nish/release"; [guide](../docs/guide/using-nish/standard-library.md#nishrelease)) |
|
|
45
45
|
| [`term.ts`](https://github.com/amritk/nish/blob/main/std/term.ts) | a terminal UI with no I/O of its own. `Screen` holds `width × height` cells (code point, 24-bit foreground and background, bold and inverse) for the frame being drawn and the frame last sent; `flush()` answers the string that turns one into the other — cursor moves and only the cells that changed, a style sent only where it differs — for the caller to `write`. A `Screen` made with `palette256` sends the nearest 256-colour index instead. `Canvas` draws pixels on a screen, two to a cell with the half block "▀" (`setPixel`, `fillRect`, `line`, `text`). The escapes (`enterAltScreen`, `hideCursor`, `clearScreen`, `beginSync`, …) are functions answering strings, and a `Screen` with `sync` set wraps each flush that changes anything in synchronized output (mode 2026). `FixedStep` is a fixed-step clock: `advance(nowMs)` answers the whole steps of `1000 / stepsPerSecond` ms since the last call, at most `maxSteps`, and `alpha()` the remainder, for logic at 240 Hz and drawing at 120. `KeyDecoder` turns raw-mode bytes into `KeyEvent`s (arrows as `ESC [` or `ESC O`, Enter, Space, Escape, Ctrl-C, characters), carries a sequence a read cut short into the next `feed`, and decides a lone ESC on a timeout the caller's clock measures. `feedEvents` and `pollEvents` read the same bytes as `TermEvent`s, whose `type` is an `EVENT_` constant: keys with `MOD_` bits and an `ACTION_` (legacy, modifyOtherKeys and the kitty keyboard protocol), SGR mouse reports in cells or pixels, bracketed paste, focus, and the terminal's replies to queries, which never come out as keys. `KeyState` tracks which keys are held, making up the releases a terminal without the kitty protocol never sends and turning Ctrl-C into `EVENT_QUIT`. The size, raw mode and the clock are the caller's, so the module reaches no capability and prints the same bytes under Node (`tests/link/std_term`, `std_term_f64`; [guide](../docs/guide/using-nish/standard-library.md#nishterm)) |
|
|
46
46
|
| [`term-probe.ts`](https://github.com/amritk/nish/blob/main/std/term-probe.ts) | what the terminal can do, asked once at start. `probeQueries(env)` is every query as one string — XTVERSION, DECRQM for synchronized output and pixel mouse, kitty's keyboard flags and a kitty graphics query, XTSMGRAPHICS, the cell and text-area sizes, a true-colour read-back, and DA1 last, wrapped for tmux's or screen's passthrough where only the outer terminal can answer. `TermProbe` takes the replies a read at a time (`feed`), holds back any key typed meanwhile (`heldEvents`), is `done()` once DA1 is answered or `timedOut(now)` after 250 ms, and `result()` reads the replies and a `TermEnv` (the `TERM`, `COLORTERM`, `TMUX`, `SSH_*`, `NO_COLOR` and `NISH_TERM_*` variables) into a `TermCaps`: colours, graphics backend, sync, kitty keyboard, cell size, pixel mouse, multiplexer. Pure: the environment, the bytes and the clock are the caller's (`tests/link/std_term_probe`; [guide](../docs/guide/using-nish/terminal.md#what-it-detects-and-what-it-falls-back-to)) |
|
|
@@ -50,10 +50,10 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
50
50
|
| [`input.ts`](https://github.com/amritk/nish/blob/main/std/input.ts) | `nish/input`: what one fixed step reads from its player, for a program whose steps run the same behind a terminal, a page or a test. `StepInput` holds the step's `events` and the `KeyState` of which keys are down, which a host owns and points at what it read each step; `isDown(key, code)` reads a key. The events and the key state are `nish/term`'s. Pure: no capability, no I/O and no clock |
|
|
51
51
|
| [`raster.ts`](https://github.com/amritk/nish/blob/main/std/raster.ts) | `nish/raster`: drawing into a frame of `0xRRGGBB` pixels held as an `Int32Array` with its width and height, so the same draw fills a terminal's `Framebuffer` (`rasterFrame(fb.pixels)` lends its `i32[]`) and a wasm page's module storage with no copy. Colours (`rasterRgb`, `rasterMix`, `rasterAdd`, `rasterDim`, `rasterHue`, `rasterWeight`), a gradient, rectangles, anti-aliased discs, additive glows, 5×7 pixel text (`rasterText`, `rasterTextWidth`), a fading `RasterTrail` and a `RasterParticles` pool made once and stepped in place. Every shape clips to the frame and to the rows the array has. Pure: no capability, no I/O and no clock. `tests/link/std_raster` |
|
|
52
52
|
| [`synth.ts`](https://github.com/amritk/nish/blob/main/std/synth.ts) | `nish/synth`: short sounds as `f64` samples at the caller's rate. `synthSilence(seconds, rate)` makes the array; `synthTone(out, rate, start, length, f0, f1, wave, volume, decay)` adds a square, triangle or noise voice into it with a log pitch slide, an exponential decay and click-free ends; `synthSemitone` steps a pitch. Samples are not clipped. Pure, and noise is a fixed xorshift sequence, so a call gives the same samples every time. `tests/link/std_synth` |
|
|
53
|
-
| [`region.ts`](https://github.com/amritk/nish/blob/main/std/region.ts) | The source behind the builtin module `nish:region`, and imported only by that name: `Region<T>`, `region`, `regionWith`, `enter`, `enterWith` and `free`. A `Region<T>` is a handle, a 64-bit integer, to memory the program frees when it says so; `region(f)` allocates what `f` builds into a new region and keeps its answer as the root, `enter(r, f)` runs `f(root)` there again and answers its scalar, the `*With` forms pass one argument through, and `free(r)` gives all of it back. A handle used after `free`, entered twice or freed while entered stops the program. The bodies are the meaning; the allocator swap is the emitter's (`src/emit-region.ts`) and what may cross a region's edge is the checker's (`src/region-check.ts`), keyed on this file ([`docs/LANGUAGE.md`](
|
|
54
|
-
| [`secret.ts`](https://github.com/amritk/nish/blob/main/std/secret.ts) | The source behind the builtin module `nish:secret`, and imported only by that name: `Secret<T>`, `secret`, `expose`, `exposeWith` and `wipe`. The bodies are the meaning; what makes a `Secret` one is the checker's, keyed on this file ([`docs/LANGUAGE.md`](
|
|
55
|
-
| [`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`](
|
|
56
|
-
| [`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`](
|
|
53
|
+
| [`region.ts`](https://github.com/amritk/nish/blob/main/std/region.ts) | The source behind the builtin module `nish:region`, and imported only by that name: `Region<T>`, `region`, `regionWith`, `enter`, `enterWith` and `free`. A `Region<T>` is a handle, a 64-bit integer, to memory the program frees when it says so; `region(f)` allocates what `f` builds into a new region and keeps its answer as the root, `enter(r, f)` runs `f(root)` there again and answers its scalar, the `*With` forms pass one argument through, and `free(r)` gives all of it back. A handle used after `free`, entered twice or freed while entered stops the program. The bodies are the meaning; the allocator swap is the emitter's (`src/emit-region.ts`) and what may cross a region's edge is the checker's (`src/region-check.ts`), keyed on this file ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#regions-nishregion); [guide](../docs/guide/language/regions.md)) |
|
|
54
|
+
| [`secret.ts`](https://github.com/amritk/nish/blob/main/std/secret.ts) | The source behind the builtin module `nish:secret`, and imported only by that name: `Secret<T>`, `secret`, `expose`, `exposeWith` and `wipe`. The bodies are the meaning; what makes a `Secret` one is the checker's, keyed on this file ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#secrets-nishsecret)). `wipe`'s body is written by the emitter, one volatile `llvm.memset`, and like `collections.ts` the module writes no `.ll` of its own |
|
|
55
|
+
| [`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`](../docs/reference/language/declarations.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`](../docs/reference/language/declarations.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`](../docs/reference/language/declarations.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`](../docs/reference/language/declarations.md#channels-channelt)). Every body in the module is its meaning under Node, where a task runs at its `spawn` |
|
|
56
|
+
| [`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`](../docs/reference/language/declarations.md#shared-memory-between-processes-nishsyncshm-and-nishsyncring); [`docs/security/shm.md`](../docs/security/shm.md)) |
|
|
57
57
|
| [`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 |
|
|
58
58
|
| [`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. `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 |
|
|
59
59
|
| [`host/ring.ts`](https://github.com/amritk/nish/blob/main/std/host/ring.ts) | `nish/host/ring`: a single-producer, single-consumer ring of `i32` words in an `Int32Array` of module storage, shared by a wasm module and the page that drives it — word 0 the head, word 1 the tail, the slots after. `ringPush`, `ringShift`, `ringSize`, `ringFree`, `ringCapacity` and `ringClear`; the page's half is `nish/page`'s `ringOver`, over the same layout. It needs no atomics because the page and the module run on one thread and never at once. A zero-filled ring is empty, and a ring whose counts a buggy page wrote out of protocol is still never read out of bounds (`tests/link/std_host_ring`) |
|
|
@@ -473,7 +473,7 @@ checklist in
|
|
|
473
473
|
three are what shape an API here more than any style preference — see the
|
|
474
474
|
header of `testing.ts` for what they did to that one, which has one
|
|
475
475
|
assertion per type. A new module can use
|
|
476
|
-
[generic functions and classes](
|
|
476
|
+
[generic functions and classes](../docs/reference/language/declarations.md#generic-functions);
|
|
477
477
|
`pair.ts` exports a generic type.
|
|
478
478
|
- **Ship it with a `tests/link/` case.** `tests/link/<name>/` is the only place a
|
|
479
479
|
multi-module program is exercised end to end, and it is also what puts the
|
package/std/net/handler.ts
CHANGED
|
@@ -124,6 +124,7 @@ import {
|
|
|
124
124
|
pollModify,
|
|
125
125
|
pollRemove,
|
|
126
126
|
pollWait,
|
|
127
|
+
pollWaitBatch,
|
|
127
128
|
tcpListenFlags,
|
|
128
129
|
} from "nish:net"
|
|
129
130
|
import {
|
|
@@ -136,6 +137,8 @@ import {
|
|
|
136
137
|
httpContentEncoding,
|
|
137
138
|
} from "nish/net/http-compress"
|
|
138
139
|
|
|
140
|
+
/** `HandlerLimits.maxWaitMs`' most: a second, the interval `bodyTimeout` is checked at. */
|
|
141
|
+
const HANDLER_MAX_WAIT_MS: i32 = 1000
|
|
139
142
|
/** A core's answer when the call broke its contract: `refusal` says how, and the public method panics with it. */
|
|
140
143
|
const HANDLER_REFUSED: i32 = -24
|
|
141
144
|
/** An answer sent, or queued to be sent. */
|
|
@@ -222,6 +225,24 @@ export class HandlerLimits {
|
|
|
222
225
|
jsonBytes: i32 = 65536
|
|
223
226
|
/** The most readiness events one `wait` takes. */
|
|
224
227
|
maxEvents: i32 = 256
|
|
228
|
+
/**
|
|
229
|
+
* The events one `wait` gathers before it returns, once the first is in:
|
|
230
|
+
* above 1, a busy ring server takes its connections' events in fewer,
|
|
231
|
+
* larger batches (`pollWaitBatch`), waiting up to `maxWaitMs` for them. A
|
|
232
|
+
* batch is at most `maxEvents` and at most 64 events, whatever this says.
|
|
233
|
+
* It acts only on a listener `listen` opened with `ring` set, on Linux;
|
|
234
|
+
* elsewhere, and at 1 (the default), `wait` is `pollWait` as before. At
|
|
235
|
+
* least 1.
|
|
236
|
+
*/
|
|
237
|
+
minEvents: i32 = 1
|
|
238
|
+
/**
|
|
239
|
+
* The most milliseconds one `wait` waits for `minEvents`, after its first
|
|
240
|
+
* event and on top of its own timeout. It is latency added to the batch's
|
|
241
|
+
* first request, and a timer or other descriptor the handler watches may
|
|
242
|
+
* be heard up to this late. 0 (the default) waits no longer than
|
|
243
|
+
* `pollWait` does. From 0 to 1000.
|
|
244
|
+
*/
|
|
245
|
+
maxWaitMs: i32 = 0
|
|
225
246
|
/**
|
|
226
247
|
* Milliseconds from a request's head to the end of its body. A request
|
|
227
248
|
* still reading its body past it has its connection closed: the carrier's
|
|
@@ -240,9 +261,10 @@ export class HandlerLimits {
|
|
|
240
261
|
maxDecoded: i32 = 1048576
|
|
241
262
|
|
|
242
263
|
/**
|
|
243
|
-
* The defaults: 256 slots, a 64 KiB JSON buffer, 256 events a turn
|
|
244
|
-
* second body timeout, a one MiB cap on a
|
|
245
|
-
* own defaults with the body cap lowered to
|
|
264
|
+
* The defaults: 256 slots, a 64 KiB JSON buffer, 256 events a turn and no
|
|
265
|
+
* wait for a batch of them, a 30 second body timeout, a one MiB cap on a
|
|
266
|
+
* decoded body, and the carrier's own defaults with the body cap lowered to
|
|
267
|
+
* one MiB. Set a field to tune it.
|
|
246
268
|
*/
|
|
247
269
|
constructor() {
|
|
248
270
|
this.http = new Http1Config()
|
|
@@ -816,6 +838,10 @@ export class HttpHandler {
|
|
|
816
838
|
private owing: boolean[]
|
|
817
839
|
/** The slots whose send `flush` still owes, `owedCount` of them. */
|
|
818
840
|
private owed: i32[]
|
|
841
|
+
/** `HandlerLimits.minEvents`: above 1 with `maxWaitMs` above 0, `wait` calls `pollWaitBatch`. */
|
|
842
|
+
private minEvents: i32 = 1
|
|
843
|
+
/** `HandlerLimits.maxWaitMs`. */
|
|
844
|
+
private maxWaitMs: i32 = 0
|
|
819
845
|
/** `pollWait`'s output. */
|
|
820
846
|
private readyFds: i32[]
|
|
821
847
|
/** Per watched id: whether its descriptor was ready in the last `wait`. */
|
|
@@ -890,9 +916,9 @@ export class HttpHandler {
|
|
|
890
916
|
* before the first `wait`. `limits.ring` acts only through the listener:
|
|
891
917
|
* open it with `limits.listen`, since a listener from `tcpListen` stays on
|
|
892
918
|
* descriptors whatever `ring` says.
|
|
893
|
-
* @param limits the caps and timeouts. `slots`, `jsonBytes`, `maxEvents
|
|
894
|
-
* and `
|
|
895
|
-
* effect; `http` is kept by the carrier, which reads its timeouts and
|
|
919
|
+
* @param limits the caps and timeouts. `slots`, `jsonBytes`, `maxEvents`,
|
|
920
|
+
* `bodyTimeout`, `minEvents` and `maxWaitMs` are read once here, so
|
|
921
|
+
* changing them later has no effect; `http` is kept by the carrier, which reads its timeouts and
|
|
896
922
|
* caps live
|
|
897
923
|
* @param listener the listening socket's descriptor, still the program's to close
|
|
898
924
|
* @param router the routes, which the handler keeps and consults at each request head
|
|
@@ -910,6 +936,8 @@ export class HttpHandler {
|
|
|
910
936
|
this.maxDecoded = limits.maxDecoded
|
|
911
937
|
this.decoder = new HttpBodyDecoder(limits.maxDecoded > 0 ? limits.maxDecoded : 1)
|
|
912
938
|
this.bodyTimeout = toI64(limits.bodyTimeout) * HANDLER_NANOS_PER_MS
|
|
939
|
+
this.minEvents = limits.minEvents
|
|
940
|
+
this.maxWaitMs = limits.maxWaitMs
|
|
913
941
|
this.server = new Http1Server(limits.http, listener, limits.slots)
|
|
914
942
|
this.router = router
|
|
915
943
|
this.listener = listener
|
|
@@ -1023,7 +1051,11 @@ export class HttpHandler {
|
|
|
1023
1051
|
// is the program's to take, and the turn blocks as it always has.
|
|
1024
1052
|
timeout = 0
|
|
1025
1053
|
}
|
|
1026
|
-
|
|
1054
|
+
// A turn that must not block (`timeout` 0) never waits for a batch.
|
|
1055
|
+
const n: i32 =
|
|
1056
|
+
this.minEvents > 1 && this.maxWaitMs > 0 && timeout !== 0
|
|
1057
|
+
? pollWaitBatch(this.loop, this.readyFds, timeout, this.minEvents, this.maxWaitMs)
|
|
1058
|
+
: pollWait(this.loop, this.readyFds, timeout)
|
|
1027
1059
|
const now: i64 = monotonicNanos()
|
|
1028
1060
|
this.turnAt = now
|
|
1029
1061
|
const fds: i32[] = this.readyFds
|
|
@@ -2635,6 +2667,9 @@ const handlerLimitsFault = (limits: HandlerLimits): string => {
|
|
|
2635
2667
|
if (limits.maxDecoded < 0) {
|
|
2636
2668
|
return `HttpHandler: maxDecoded ${limits.maxDecoded} is negative`
|
|
2637
2669
|
}
|
|
2670
|
+
if (limits.minEvents < 1 || limits.maxWaitMs < 0 || limits.maxWaitMs > HANDLER_MAX_WAIT_MS) {
|
|
2671
|
+
return `HttpHandler: minEvents ${limits.minEvents} and maxWaitMs ${limits.maxWaitMs} need at least 1 and 0 to ${HANDLER_MAX_WAIT_MS}`
|
|
2672
|
+
}
|
|
2638
2673
|
return ""
|
|
2639
2674
|
}
|
|
2640
2675
|
|
package/std/sqlite.ts
CHANGED
|
@@ -719,6 +719,11 @@ export class Statement {
|
|
|
719
719
|
}
|
|
720
720
|
}
|
|
721
721
|
|
|
722
|
+
// Cursor.countRange's two calls: the count, then each count read back.
|
|
723
|
+
declare function nishsqlite_cursor_count_range(h: i32, lo: i64, hi: i64, n: u64): i32
|
|
724
|
+
declare function nishsqlite_cursor_count_at(h: i32, i: u64): i64
|
|
725
|
+
declare function nishsqlite_cursor_read_row(h: i32, io: u8[], n: u64, text: u8[], ntext: u64): i32
|
|
726
|
+
|
|
722
727
|
/**
|
|
723
728
|
* A B-tree cursor on a table or index, which reads rows without a statement.
|
|
724
729
|
* Columns count from 0 in the order `openCursor` named them. A call on a
|
|
@@ -726,8 +731,12 @@ export class Statement {
|
|
|
726
731
|
* `columnI64`).
|
|
727
732
|
*/
|
|
728
733
|
export class Cursor {
|
|
734
|
+
/** `readRow`'s answers from the adapter, sized by `selectRow`. */
|
|
735
|
+
private rowIo: u8[]
|
|
729
736
|
/** The adapter's handle. */
|
|
730
737
|
private handle: i32
|
|
738
|
+
/** The columns `selectRow` chose, -1 before it. */
|
|
739
|
+
private nsel: i32
|
|
731
740
|
|
|
732
741
|
/**
|
|
733
742
|
* Wraps an adapter handle. A program gets a `Cursor` from
|
|
@@ -737,6 +746,8 @@ export class Cursor {
|
|
|
737
746
|
*/
|
|
738
747
|
constructor(handle: i32) {
|
|
739
748
|
this.handle = handle
|
|
749
|
+
this.rowIo = []
|
|
750
|
+
this.nsel = -1
|
|
740
751
|
}
|
|
741
752
|
|
|
742
753
|
/**
|
|
@@ -854,6 +865,46 @@ export class Cursor {
|
|
|
854
865
|
return moved(nishsqlite_cursor_seek(this.handle, op))
|
|
855
866
|
}
|
|
856
867
|
|
|
868
|
+
/**
|
|
869
|
+
* Counts an index's entries whose first key column is `k`, for each `k`
|
|
870
|
+
* from `lo` to `hi`, into `out[k - lo]`, in one seek and one walk of the
|
|
871
|
+
* index, for an index whose first column has INTEGER or NUMERIC affinity.
|
|
872
|
+
* On a full index that is what `SELECT count(*) ... WHERE col = k` answers
|
|
873
|
+
* for each `k`; a partial index holds only the rows its WHERE admits, and
|
|
874
|
+
* counts only those. A count that reaches its walk clears the seek key and
|
|
875
|
+
* leaves the cursor on no row, whatever it answers; one refused first leaves
|
|
876
|
+
* both as they were. Copying the counts into `out` takes one call per key,
|
|
877
|
+
* and one more when `out` is longer than the span. `out` past the span, and
|
|
878
|
+
* all of it on an `Err`, is left as it was.
|
|
879
|
+
*
|
|
880
|
+
* @param lo The first key counted.
|
|
881
|
+
* @param hi The last key counted, at least `lo`.
|
|
882
|
+
* @param out Where the counts go; at least `hi - lo + 1` long.
|
|
883
|
+
* @returns The number of entries counted, or `Err` with `SQLITE_MISUSE` for
|
|
884
|
+
* a table cursor, `SQLITE_MISMATCH` for an index whose first column has
|
|
885
|
+
* another affinity, `SQLITE_RANGE` when `lo > hi` or the span is longer
|
|
886
|
+
* than `out`, or the code SQLite fails with, as for `first`.
|
|
887
|
+
*/
|
|
888
|
+
countRange(lo: i64, hi: i64, out: i64[]): Result<i32, i32> {
|
|
889
|
+
const n: i32 = nishsqlite_cursor_count_range(this.handle, lo, hi, toU64(out.length))
|
|
890
|
+
if (n < 0) {
|
|
891
|
+
// The adapter answers minus a SQLite result code: `~n + 1` is `-n`,
|
|
892
|
+
// spelled in u32 so no negation of an i32 can overflow.
|
|
893
|
+
return Err(toI32(toU32(~n) + toU32(1)))
|
|
894
|
+
}
|
|
895
|
+
for (let i = 0; i < out.length; i++) {
|
|
896
|
+
const c: i64 = nishsqlite_cursor_count_at(this.handle, toU64(i))
|
|
897
|
+
if (c < 0) {
|
|
898
|
+
break
|
|
899
|
+
}
|
|
900
|
+
// The call above ends what the loop proved of `i`.
|
|
901
|
+
if (i < out.length) {
|
|
902
|
+
out[i] = c
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
return Ok(n)
|
|
906
|
+
}
|
|
907
|
+
|
|
857
908
|
/**
|
|
858
909
|
* The current row's rowid: a table row's key, an index entry's `rowid`.
|
|
859
910
|
*
|
|
@@ -914,6 +965,126 @@ export class Cursor {
|
|
|
914
965
|
return Ok(n)
|
|
915
966
|
}
|
|
916
967
|
|
|
968
|
+
/**
|
|
969
|
+
* Chooses the columns `readRow` reads, in order; a column may repeat. The
|
|
970
|
+
* list holds until the next `selectRow`, so a loop chooses it once and
|
|
971
|
+
* calls `readRow` per row. It allocates one buffer of 11 bytes per column
|
|
972
|
+
* and checks no index: `readRow` answers `SQLITE_RANGE` for one outside the
|
|
973
|
+
* cursor's columns.
|
|
974
|
+
*
|
|
975
|
+
* @param cols The columns' indices, from 0.
|
|
976
|
+
* @returns `Ok()`, or `Err` with `SQLITE_MISUSE` for over 65535 columns,
|
|
977
|
+
* which leaves the earlier list chosen.
|
|
978
|
+
*/
|
|
979
|
+
selectRow(cols: readonly i32[]): Result<void, i32> {
|
|
980
|
+
const k: i32 = toI32(cols.length)
|
|
981
|
+
if (k > 0xffff) {
|
|
982
|
+
return Err(SQLITE_MISUSE)
|
|
983
|
+
}
|
|
984
|
+
// Each index goes to the adapter as a little-endian u16; one outside
|
|
985
|
+
// 0..65535 is sent as 65535, which no cursor has, so it is RANGE there.
|
|
986
|
+
// A slot of 9 bytes per column follows, which `readRow` fills.
|
|
987
|
+
const io: u8[] = []
|
|
988
|
+
for (let i: i32 = 0; i < k && i < toI32(cols.length); i++) {
|
|
989
|
+
const c: i32 = cols[i] < 0 || cols[i] > 0xffff ? 0xffff : cols[i]
|
|
990
|
+
io.push(toU8(c & 0xff))
|
|
991
|
+
io.push(toU8(c >> 8))
|
|
992
|
+
}
|
|
993
|
+
for (let i: i32 = 0; i < k; i++) {
|
|
994
|
+
for (let b: i32 = 0; b < 9; b++) {
|
|
995
|
+
io.push(0)
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
this.rowIo = io
|
|
999
|
+
this.nsel = k
|
|
1000
|
+
return Ok()
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
/**
|
|
1004
|
+
* Reads the current row's `selectRow` columns in one call. For the `k`th
|
|
1005
|
+
* of them it writes `spans[3k]`, `spans[3k + 1]` and `spans[3k + 2]`: the
|
|
1006
|
+
* type `columnType` answers, then where its bytes start in `text` and how
|
|
1007
|
+
* many there are, which are the bytes `columnInto` copies (0 and 0 for a
|
|
1008
|
+
* number or NULL); and `ints[k]`, the value `columnI64` answers for an
|
|
1009
|
+
* INTEGER or FLOAT column and 0 for TEXT, BLOB and NULL, which it does not
|
|
1010
|
+
* convert. The row's text and blob bytes sit in `text` in column order. A
|
|
1011
|
+
* refusal, or an answer larger than `text.length`, writes no `ints` or
|
|
1012
|
+
* `spans`, and `text` may hold the first columns' bytes: grow `text` and
|
|
1013
|
+
* call again. An empty list answers `Ok(0)` on a row, and `SQLITE_MISUSE`
|
|
1014
|
+
* with no row or a closed cursor, as any list does. It allocates nothing.
|
|
1015
|
+
*
|
|
1016
|
+
* @param ints Receives each column's integer; at least as long as the list.
|
|
1017
|
+
* @param spans Receives each column's type, offset and length; at least
|
|
1018
|
+
* three times as long as the list.
|
|
1019
|
+
* @param text Receives the text and blob bytes.
|
|
1020
|
+
* @returns The text and blob bytes the row holds, or `Err` with the code
|
|
1021
|
+
* `columnType` answers for the first column it refuses (`SQLITE_RANGE`
|
|
1022
|
+
* for an index outside the cursor's columns, `SQLITE_SCHEMA` for a
|
|
1023
|
+
* record too short for it, `SQLITE_MISUSE` with no row or a closed
|
|
1024
|
+
* cursor), or `SQLITE_MISUSE` before `selectRow` or when `ints` or
|
|
1025
|
+
* `spans` is too short, or `SQLITE_TOOBIG` for over 2^31 - 1 bytes.
|
|
1026
|
+
*/
|
|
1027
|
+
readRow(ints: i64[], spans: i32[], text: u8[]): Result<i32, i32> {
|
|
1028
|
+
const k: i32 = this.nsel
|
|
1029
|
+
const ni: i32 = toI32(ints.length)
|
|
1030
|
+
const ns: i32 = toI32(spans.length)
|
|
1031
|
+
if (k < 0 || ni < k || ns / 3 < k) {
|
|
1032
|
+
return Err(SQLITE_MISUSE)
|
|
1033
|
+
}
|
|
1034
|
+
const io: u8[] = this.rowIo
|
|
1035
|
+
const n: i32 = nishsqlite_cursor_read_row(this.handle, io, toU64(io.length), text, toU64(text.length))
|
|
1036
|
+
if (n < 0) {
|
|
1037
|
+
// The adapter answers minus a SQLite result code: `~n + 1` is `-n`,
|
|
1038
|
+
// spelled in u32 so no negation of an i32 can overflow.
|
|
1039
|
+
return Err(toI32(toU32(~n) + toU32(1)))
|
|
1040
|
+
}
|
|
1041
|
+
if (n > toI32(text.length)) {
|
|
1042
|
+
return Ok(n)
|
|
1043
|
+
}
|
|
1044
|
+
// The slots follow the 2k index bytes: a column's type, then 8
|
|
1045
|
+
// little-endian bytes, the integer, or a TEXT or BLOB column's length,
|
|
1046
|
+
// under 2^31 since the row's bytes fit `text`. Those bytes sit in `text`
|
|
1047
|
+
// one column after another, so each starts where the last one ended.
|
|
1048
|
+
const nio: i32 = toI32(io.length)
|
|
1049
|
+
let at: i32 = toI32(toI64(k) + toI64(k))
|
|
1050
|
+
let s: i32 = 0
|
|
1051
|
+
let off: i32 = 0
|
|
1052
|
+
for (
|
|
1053
|
+
let i: i32 = 0;
|
|
1054
|
+
i < k && i < toI32(ints.length) && s >= 0 && s <= toI32(spans.length) - 3 && at >= 0 && at <= nio - 9;
|
|
1055
|
+
i++
|
|
1056
|
+
) {
|
|
1057
|
+
const ty: i32 = toI32(io[at])
|
|
1058
|
+
spans[s] = ty
|
|
1059
|
+
if (ty === SQLITE_TEXT || ty === SQLITE_BLOB) {
|
|
1060
|
+
const len: i32 =
|
|
1061
|
+
toI32(io[at + 1]) | (toI32(io[at + 2]) << 8) | (toI32(io[at + 3]) << 16) | (toI32(io[at + 4]) << 24)
|
|
1062
|
+
ints[i] = 0
|
|
1063
|
+
spans[s + 1] = off
|
|
1064
|
+
spans[s + 2] = len
|
|
1065
|
+
const end: i64 = toI64(off) + toI64(len)
|
|
1066
|
+
off = len >= 0 && end <= toI64(n) ? toI32(end) : n
|
|
1067
|
+
} else {
|
|
1068
|
+
ints[i] =
|
|
1069
|
+
ty === SQLITE_NULL
|
|
1070
|
+
? 0
|
|
1071
|
+
: toI64(
|
|
1072
|
+
toU64(io[at + 1]) |
|
|
1073
|
+
(toU64(io[at + 2]) << toU64(8)) |
|
|
1074
|
+
((toU64(io[at + 3]) << toU64(16)) | (toU64(io[at + 4]) << toU64(24))) |
|
|
1075
|
+
((toU64(io[at + 5]) << toU64(32)) |
|
|
1076
|
+
(toU64(io[at + 6]) << toU64(40)) |
|
|
1077
|
+
((toU64(io[at + 7]) << toU64(48)) | (toU64(io[at + 8]) << toU64(56))))
|
|
1078
|
+
)
|
|
1079
|
+
spans[s + 1] = 0
|
|
1080
|
+
spans[s + 2] = 0
|
|
1081
|
+
}
|
|
1082
|
+
s += 3
|
|
1083
|
+
at += 9
|
|
1084
|
+
}
|
|
1085
|
+
return Ok(n)
|
|
1086
|
+
}
|
|
1087
|
+
|
|
917
1088
|
/**
|
|
918
1089
|
* Closes the cursor; the handle names nothing after.
|
|
919
1090
|
*
|