diff --git a/docs/web/std/http.md b/docs/web/std/http.md new file mode 100644 index 00000000..7ed7e118 --- /dev/null +++ b/docs/web/std/http.md @@ -0,0 +1,241 @@ +--- +title: HTTP +description: The std::http request parser, response serializer and blocking HTTP/1.1 server — framing rules, limits and how a handler works. +section: std +order: 4 +status: stable +--- + +`std::http` speaks HTTP/1.1 on the server side. It has two layers: + +| Layer | What it is | Use it when | +| --- | --- | --- | +| Sans-IO core | A request parser and a response serializer that never touch a socket | You build a proxy, a test harness, or your own server driver | +| `Http::Server` | A blocking driver that accepts connections and calls your handler | You just want to serve requests | + +## A minimal server + +A handler is a record that implements `Http::Handler`. Outside the `Http` namespace the trait is +reached by its path, `@implements(Http::Handler)`. + +```ignis +import Http from "std::http"; +import IpAddress, SocketAddress from "std::net"; + +@implements(Http::Handler) +record Greeter { + public greeting: static str; + + handle(&self, request: &Http::Request, response: &mut Http::Response): void { + if (!request.head.target.equals("/")) { + response.setStatus(404); + return; + } + + response.setHeader("Content-Type", "text/plain"); + response.writeStr(self.greeting); + } +} + +function main(): i32 { + let address: SocketAddress = SocketAddress::create(IpAddress::v4(127, 0, 0, 1), 8080); + let Result::OK(server) = Http::Server::bind(&address, Http::ServerConfig::new()) else { + return 1; + }; + + return server.run(Greeter { greeting: "hello" }).isOk() ? 0 : 1; +} +``` + +`Server::bind` takes an address and a `ServerConfig`. Port 0 picks a free port, and `localAddress()` +tells you which one. + +## Request and Response + +The handler receives a complete request and fills in a response. + +| `Http::Request` | Description | +| --- | --- | +| `head` | The `RequestHead`: `method`, `target`, `version`, `headers` | +| `body` | The whole body as bytes, with chunked coding already removed | +| `target()` | The request target as received, such as `/search?q=1` | +| `header(name)` | The first header named `name`, ignoring ASCII case: `Option` | +| `bodyText()` | A copy of the body as text, or `NONE` if it is not valid UTF-8 | + +| `Http::Response` | Description | +| --- | --- | +| `Response::new()` | An empty 200 response with no headers | +| `setStatus(status)` | Sets the status; the reason phrase is the standard one | +| `setHeader(name, value)` | Replaces every header with that name | +| `addHeader(name, value)` | Appends a header and keeps any with the same name | +| `write(&bytes)` / `writeStr(text)` | Appends to the body | + +The driver writes the response after `handle` returns. It adds `Content-Length` itself, and a +`Content-Length` or `Transfer-Encoding` you set is dropped. If the head cannot be serialized at +all — a status outside 100–999, a header value holding CR, LF or another control byte, or a header +name that is not a token, such as one with a space or a colon — the driver sends an empty 500 +instead. + +## ServerConfig + +| Field | Default | Meaning | +| --- | --- | --- | +| `threads` | 8 | Threads accepting and serving connections; each serves one connection at a time. 0 counts as 1 | +| `limits` | `Limits::new()` | Parser limits applied to every request | +| `idleTimeout` | 30 seconds | How long a read may wait for the client. When it expires the connection closes without a response | +| `maxRequestsPerConnection` | 0 | Requests served on one connection before the server closes it. 0 means no limit | + +## Threads and shared state + +`Server::run` shares **one handler among all its threads**, so the handler must be `Send` and `Sync` +and `handle` takes `&self`. State that a handler changes has to sit behind a `Mutex` or an atomic. + +`run` returns only when its workers stop. A worker leaves its loop only when `accept` fails with +`EBADF` or `EINVAL`; a failure it can recover from, such as `EMFILE` or `ENFILE`, is retried and +does not end the server. There is no way to stop a running server yet, so in practice it blocks for +as long as the process lives. + +If your state cannot be shared, call `Http::acceptConnections` on threads of your own. Each thread +then gets its own handler, and the listener is shared (for example through an `Arc`). `std::web` +builds one router per thread this way. `Http::serveConnection` serves a single accepted connection +on the calling thread, which is handy in tests. + +## What the server does for you + +- A request reaches the handler once its whole body is in, bounded by `Limits.maxBody`. + `Expect: 100-continue` is not answered; the client sends the body after its own wait. +- A `HEAD` request gets the head with the length the body would have, and no body. +- The connection stays open unless the request does not keep it alive (`RequestHead.keepAlive`), + the response lists `Connection: close`, or `maxRequestsPerConnection` is reached. When it closes, + the response carries `Connection: close`. +- A malformed request gets an empty response with the parser's suggested status and + `Connection: close`, and then the connection ends. +- Before closing, the server shuts its writing side and discards what the client still sends, for + up to 2 seconds or 1 048 576 bytes, so the close does not reset the connection before the client + reads the response. + +## Using the parser directly + +`Http::RequestParser` is sans-IO. `feed(&bytes)` or `feedStr(text)` copies bytes in, and `next()` +reports what they mean. + +| `ParseEvent` | Meaning | +| --- | --- | +| `NEED_MORE` | The bytes fed so far are not enough to report anything else | +| `HEAD(RequestHead)` | A request head arrived. Reported once per request | +| `BODY_CHUNK(Vector)` | A piece of the body. Zero or more per request | +| `DONE` | The request is complete | +| `MALFORMED(ParseError)` | The request is invalid. This is terminal | + +After `DONE` the parser starts on the next request of the same connection. Bytes already fed past +the end of a request belong to the next one, so keep-alive and pipelining need nothing special. +Events own their payloads, so a `RequestHead` or a chunk stays valid after more bytes are fed. + +`MALFORMED` is terminal: every later `next()` reports the same error, because the rest of the +connection cannot be framed. The `ParseError` carries the status to answer with (400, 413, 414, 431, +501 or 505) before closing. Malformed input never panics. + +### Message syntax + +- Lines end with CRLF. A bare LF is accepted too (RFC 9112 section 2.2). A CR anywhere else is + malformed. Empty lines before a request line are skipped. +- The request line is `method SP target SP HTTP/1.x`, with exactly one space between the parts. + The method is a case-sensitive token; anything other than the nine standard methods becomes + `Method::OTHER`. The target is kept as received and must be visible ASCII. +- The version is `HTTP/.`, eight characters exactly. A version spelled that way but + other than `HTTP/1.0` or `HTTP/1.1` is `UNSUPPORTED_VERSION` (505); anything else, such as + `HTTP/2` or `HTTP/1`, is not a version at all and makes the request line + `INVALID_REQUEST_LINE`. +- A header line is `name: value`. Whitespace before the colon, obsolete line folding and control + bytes in the value are `INVALID_HEADER`. Names keep their casing, and lookups ignore ASCII case. + +### Body framing (RFC 9112 section 6.3) + +| Head | Body | +| --- | --- | +| `Transfer-Encoding: chunked` | Chunked, reported without the chunk framing | +| Any other `Transfer-Encoding` | `UNSUPPORTED_TRANSFER_CODING` (501) | +| `Transfer-Encoding` and `Content-Length` together | `CONFLICTING_LENGTH` (400), to prevent request smuggling | +| `Content-Length: n` | Exactly `n` bytes | +| `Content-Length` values that disagree | `CONFLICTING_LENGTH` (400) | +| A `Content-Length` that is not a count | `INVALID_CONTENT_LENGTH` (400) | +| Neither | No body | + +Repeated `Content-Length` fields, or a comma list in one, are accepted when every value is the same. +Chunk extensions are ignored. Trailer fields after the last chunk are checked like headers, counted +against `maxHeaders`, and discarded. + +### Limits + +| Limit | Default | Violation | +| --- | --- | --- | +| `maxRequestLine` | 8192 | `REQUEST_LINE_TOO_LONG` (414) | +| `maxHeaderLine` | 8192 | `HEADER_TOO_LONG` (431); `INVALID_CHUNK` for a chunk-size line | +| `maxHeaders` | 100 | `TOO_MANY_HEADERS` (431) | +| `maxBody` | 1048576 | `BODY_TOO_LARGE` (413) | + +Line lengths exclude the terminator, and a length exactly at the limit is accepted. A line is +rejected as soon as it grows past its limit, and a body as soon as its declared size passes +`maxBody`, so a client cannot make the parser buffer without bound. + +## Headers + +`Http::Headers` is an ordered list of fields shared by requests and responses. + +| Method | Description | +| --- | --- | +| `Headers::new()` | An empty list | +| `get(name)` | The first value for `name`, ignoring ASCII case: `Option` | +| `getAll(name)` | Every value for `name`: `Vector` | +| `contains(name)` | Whether a field with that name exists | +| `hasToken(name, token)` | Whether the comma-separated value of `name` lists `token` | +| `add(name, value)` | Appends a field | +| `set(name, value)` | Replaces every field with that name by one | +| `remove(name)` | Removes the fields with that name and returns how many | +| `length()`, `isEmpty()` | How many fields | +| `nameAt(i)`, `valueAt(i)`, `fieldAt(i)` | Fields by position | + +## Media types + +`Http::MediaType::parse(text)` reads a `Content-Type` value (RFC 9110 section 8.3.1) and returns +`Option`. Malformed input gives `NONE`. The type, subtype and parameter names are +lowercased, parameter values keep their case, and a quoted value loses its quotes and escapes. +`essence()` is `type/subtype`, and `parameter("charset")` finds a parameter ignoring case. + +## Writing responses by hand + +When you use the parser without `Http::Server`, build a `ResponseHead` and serialize it yourself. + +| Function | Appends | +| --- | --- | +| `Http::writeHead` | `HTTP/1.1 `, every header, and the blank line | +| `Http::writeResponse` | A head with `Content-Length`, then the body. It rejects a head that already carries `Content-Length` or `Transfer-Encoding` | +| `Http::writeBody` | Body bytes unchanged | +| `Http::writeChunk` | One chunk of a chunked body | +| `Http::writeLastChunk` | The chunk that ends a chunked body | + +`writeResponse` writes `Content-Length` itself, so it refuses a head that already carries +`Content-Length` or `Transfer-Encoding`, with `FRAMING_HEADER_PRESENT`. For a chunked body, add +`Transfer-Encoding: chunked` to the head, write the head with `writeHead`, call `writeChunk` for +each piece, and finish with `writeLastChunk`. A header name that is not a token, or a header value +or reason phrase containing CR or LF, could split the response, so it is a `SerializeError` and +nothing is appended. Byte inputs are `&Vector`. + +```ignis +import Http from "std::http"; + +function answer(request: str, out: &mut Vector): i32 { + let mut parser: Http::RequestParser = Http::RequestParser::new(Http::Limits::new()); + parser.feedStr(request); + + let Http::ParseEvent::HEAD(head) = parser.next() else { + return 1; + }; + + let mut response: Http::ResponseHead = Http::ResponseHead::create(200); + response.headers.add("Content-Type", "text/plain"); + let body: Vector = head.target.toBytes(); + + return Http::writeResponse(&response, &body, out).isOk() ? 0 : 1; +} +``` diff --git a/docs/web/std/json.md b/docs/web/std/json.md new file mode 100644 index 00000000..7bee7825 --- /dev/null +++ b/docs/web/std/json.md @@ -0,0 +1,104 @@ +--- +title: JSON +description: Parsing JSON into a JsonValue tree, building values in code, and writing compact or pretty text with std::json. +section: std +order: 3 +status: stable +--- + +`std::json` has two halves. One reads and writes whole documents as a `JsonValue` tree. The other +writes typed values straight to JSON through the shared `std::serializer` contracts. + +| You need | Use | +| --- | --- | +| Read JSON text whose shape you do not know | `Json::parse` | +| Build a document in code | The `JsonValue` constructors | +| Turn a tree into text | `Json::toJsonString` or `Json::toJsonStringPretty` | +| Write a scalar or a string as a JSON document | `Json::writeRoot` | +| Write a `Serialize` record as JSON text | `Json::stringify` | + +## Parsing + +`Json::parse(source: &String)` returns `Result`. The error is a message with a +line and column, for example `trailing characters at line 1 column 5`. There is no line tracking: +the line is always `1` and the column is a byte offset into that one line. Whitespace around the +document is allowed and anything after the value is an error. + +A document may nest at most 127 containers. Opening the 128th gives a `recursion limit exceeded` +error instead of exhausting the stack; that same limit is `serde_json`'s default. + +## The JsonValue tree + +A `JsonValue` has a `kind` and an `endOffset`. The `kind` is a `JsonValueKind`: + +| Variant | Holds | +| --- | --- | +| `NULL` | Nothing | +| `BOOL(boolean)` | The value | +| `NUMBER(String)` | The number as source text, unparsed | +| `STRING(String)` | The decoded string | +| `ARRAY(Vector)` | The elements, in order | +| `OBJECT(Vector)` | `key` and `value` entries, in source order, duplicates included | + +Numbers keep their source text, so a parsed float is written back exactly as it was read. For the +same reason there is no float constructor: `f64.toString()` uses C `%g` formatting (six significant +digits, `42.0` becomes `42`), which neither round-trips nor matches what `serde_json` writes. + +Objects keep every member in order and do not merge duplicate keys. If you want "last one wins", +walk the entries in order yourself. + +`endOffset` is the 0-based byte offset just after the value's own token in the source. Values built +in code have no source text, so their `endOffset` is `0`. + +## Building values + +| Constructor | Builds | +| --- | --- | +| `JsonValue::nullValue()` | `null` | +| `JsonValue::boolValue(value)` | `true` or `false` | +| `JsonValue::stringValue(value: str)` | A string, copying `value` | +| `JsonValue::fromString(value: String)` | A string that takes ownership of `value`; keeps interior NUL bytes, which a `str` cannot hold | +| `JsonValue::integerValue(value: i64)` | A number written in decimal | +| `JsonValue::unsignedValue(value: u64)` | A number written in decimal | +| `JsonValue::array(items)` | An array from a `Vector` | +| `JsonValue::object(entries)` | An object from a `Vector`; build entries with `JsonObjectEntry::create(key, value)` | + +## Writing a tree + +| Function | Result | +| --- | --- | +| `Json::toJsonString(&value)` | A fresh `String` of compact JSON, no whitespace between tokens | +| `Json::toJsonStringPretty(&value)` | A fresh `String` of pretty JSON | +| `Json::writeValue(&mut output, &value)` | Appends compact JSON to `output` | +| `Json::writeValuePretty(&mut output, &value)` | Appends pretty JSON to `output` | + +Pretty output uses two-space indentation, one element or member per line, `": "` between a key and +its value, `[]` and `{}` for empty containers, and no trailing newline. + +These writers match `serde_json::to_string` and `serde_json::to_string_pretty` byte for byte, string +escaping included: `\"`, `\\`, `\b`, `\f`, `\n`, `\r`, `\t`, other bytes below `0x20` as lowercase +`\u00xx`, and everything else (`/`, `0x7f`, non-ASCII UTF-8) unchanged. + +## Writing typed values + +`Json::writeRoot(&mut output, value)` appends a document to `output` and returns +`Result`. It has one overload per scalar type: `boolean`, `char`, the +integer types, `f32`, `f64`, `str` and `&String`. A record that implements `Serialize` has no +overload here: `Json::stringify(value: &T)` returns the document as a fresh +`Result` instead. + +```ignis +import Json from "std::json"; + +function main(): i32 { + let mut output: String = String::create(""); + Json::writeRoot(&mut output, true); + + return 0; +} +``` + +JSON allows scalar roots, always quotes field names and separates record entries with commas. +`writeRoot` and `stringify` use the shared serializer's escaping, which differs slightly from the +tree writers: it writes other control bytes as uppercase `\u00XX` and has no `\b` or `\f`. Use the +tree writers when you need `serde_json`-compatible text. diff --git a/docs/web/std/regex.md b/docs/web/std/regex.md new file mode 100644 index 00000000..941a3ba2 --- /dev/null +++ b/docs/web/std/regex.md @@ -0,0 +1,187 @@ +--- +title: Regular expressions +description: Linear-time regex matching with std::regex — syntax, captures, replacement, limits and what is not supported. +section: std +order: 2 +status: stable +--- + +`std::regex` matches regular expressions in the style of RE2. A pattern is parsed, compiled to a +small program and run by a Pike VM, so a search takes time proportional to the text times the +program. It never backtracks, which means a pattern such as `(a*)*b` cannot hang your program. + +```ignis +import Match, Regex from "std::regex"; + +function main(): i32 { + let digits: Regex = Regex::new("\\d+").unwrap(); + let found: Match = digits.find("abc 123").unwrap(); // bytes 4..7 + let number: String = found.textIn("abc 123"); // "123" + + return number.length() as i32; +} +``` + +A pattern is a `str`, so each regex backslash is written `\\` in an Ignis string literal: `"\\d+"` +is the pattern `\d+`. + +## Choosing a method + +| You need | Use | Returns | +| --- | --- | --- | +| Only a yes or no | `isMatch(text)` | `boolean` (cheapest, stops at the first match) | +| The first match | `find(text)` | `Option` | +| Every match | `findAll(text)` | `Vector` | +| The first match with its groups | `captures(text)` | `Option` | +| Every match with its groups | `capturesAll(text)` | `Vector` | +| Replace the first match | `replace(text, replacement)` | `String` | +| Replace every match | `replaceAll(text, replacement)` | `String` | +| Cut the text at the matches | `split(text)` | `Vector` | + +`Regex::new(pattern)` returns `Result`. Compile a pattern once and reuse the +`Regex`; it holds the compiled program and its group names, and every call allocates its own +working state. + +## Matches and offsets + +A `Match` stores byte offsets, never a view of the text: `start()`, `end()`, `length()` and +`isEmpty()`. Offsets are into the UTF-8 bytes and always fall on scalar boundaries. To get the +matched text back, pass the same text to `textIn(haystack)`, which returns a copy. + +The match rules worth knowing: + +- **Leftmost-first.** Of the matches starting at the leftmost position, the one the pattern prefers + wins. Alternatives are tried in order, so `a|ab` on `"ab"` matches `"a"`. Greedy repetition + prefers more, lazy repetition prefers fewer. +- **Unanchored by default.** The search can start anywhere unless the pattern begins with `^`. +- **Non-overlapping.** `findAll` returns matches left to right. After an empty match it resumes one + scalar further on, so `a*` on `"baa"` gives `0..0`, `1..3` and `3..3`. +- **Invalid UTF-8.** An invalid byte is read as U+FFFD and spans one byte. + +## Captures + +`captures` returns a `Captures` with one entry per group. Group 0 is the whole match and group `n` +is the `n`-th `(` in the pattern. + +```ignis +import Captures, Match, Regex from "std::regex"; + +function main(): i32 { + let date: Regex = Regex::new("(?\\d{4})-(\\d\\d)").unwrap(); + let captures: Captures = date.captures("on 2024-05").unwrap(); + let year: Match = captures.name("year").unwrap(); // bytes 3..7 + + return year.length() as i32; +} +``` + +| Method | Description | +| --- | --- | +| `group(index)` | `Option` for group `index`; 0 is the whole match | +| `name(name)` | `Option` for the named group | +| `whole()` | The whole match, group 0 | +| `groupCount()` | Capturing groups, the whole match not included | +| `length()` | Groups including the whole match: `groupCount() + 1` | + +A group that did not take part in the match is `Option::NONE`. For `(a)|(b)` on `"b"`, group 1 is +`Option::NONE` and group 2 is `0..1`. A group inside a repetition holds its last iteration: `(a|b)+` on `"ab"` +leaves group 1 at `1..2`. + +`Regex` also answers questions about its own groups: `groupCount()`, `groupName(index)` and +`groupIndex(name)`. + +## Replacement + +In the replacement text of `replace` and `replaceAll`: + +| Write | Inserts | +| --- | --- | +| `$n` or `${n}` | Group `n`. Digits are read greedily, so `$12` is group 12; use `${1}0` for group 1 followed by `0` | +| `${name}` | The named group. Braces hold `[A-Za-z0-9_]+`: all digits is a number, anything else is a name | +| `$$` | A literal `$` | + +A group that did not take part, or does not exist, inserts nothing. Any other `$` (`$x`, `${}`, +`${a b}`, a trailing `$`) is a literal `$`. A name needs braces: `$name` is the text `$name`, not +the group. + +```ignis +let date: Regex = Regex::new("(?\\d{4})-(\\d\\d)").unwrap(); +let swapped: String = date.replaceAll("on 2024-05", "$2/${year}"); // "on 05/2024" +``` + +`replaceAll` and `split` use the matches `findAll` finds, so an empty match counts: replacing `x*` +with `-` in `"abc"` gives `"-a-b-c-"`. `split` leaves an empty first or last piece when a match +touches the start or end, and returns the whole text when there is no match. + +```ignis +let comma: Regex = Regex::new("\\s*,\\s*").unwrap(); +let parts: Vector = comma.split("a , b,c"); // "a", "b", "c" +``` + +## Syntax + +| Syntax | Meaning | +| --- | --- | +| `x` | The scalar `x`, any UTF-8 scalar | +| `.` | Any scalar except `\n` | +| `\n` `\t` `\r` `\f` `\v` | Control scalars | +| `\.` `\*` `\\` … | Any escaped ASCII punctuation is itself | +| `[abc]` `[a-z]` `[^…]` | Classes, ranges and negation; escapes work inside | +| `\d` `\w` `\s`, `\D` `\W` `\S` | `[0-9]`, `[0-9A-Za-z_]`, `[ \t\n\r\f\v]` and their negations (ASCII) | +| `^` `$` | Start and end of the whole text, not of a line | +| `\b` `\B` | ASCII word boundary and its negation | +| `(x)` `(?:x)` `(?x)` | Capturing, non-capturing and named groups | +| `x\|y` | Alternation, leftmost-first | +| `x*` `x+` `x?` | Zero or more, one or more, zero or one | +| `x{n}` `x{n,}` `x{n,m}` | Counted repetition | +| `x*?` `x+?` `x??` `x{n,m}?` | Lazy forms, preferring fewer repetitions | +| `(?i)` `(?i:x)` | ASCII case-insensitive for the rest of the enclosing group, or inside `x` | + +Group names match `[A-Za-z_][A-Za-z0-9_]*` and must be unique. Capturing groups are numbered from 1 +in the order of their `(`. + +The parser is strict where a pattern would otherwise be ambiguous: + +- `{` always starts a counted repetition, so a literal brace is `\{`. Behind an atom, a `{` that + is not `{n}`, `{n,}` or `{n,m}` is `invalid repetition`; a `{` with no atom before it is + `nothing to repeat`, like any other quantifier. A lone `}` or `]` is a literal. +- A quantifier after a quantifier (`a**`, `a+*`, `a{2}{3}`), or after `^`, `$`, `\b` or `\B`, is + `nothing to repeat`. The `?` of a lazy form is part of its quantifier. +- `[]` and `[^]` are `empty class`. A `]` inside a class is written `\]`. A `-` first or last in a + class is a literal. + +## Errors + +A bad pattern gives a `RegexError` with `message()`, `toString()` and `column()`. The column is +1-based and counted in Unicode scalars, pointing at the part that is wrong. + +The messages are: `unclosed group` (at its `(`), `unmatched )`, `nothing to repeat`, +`invalid range z-a` (at its `-`; when an operand is a class the message is `invalid range` with no +characters, as in `[\d-z]`), `unclosed class` (at its `[`), `empty class`, +`trailing backslash`, `unknown escape \q`, `invalid repetition`, `invalid repetition range`, +`repetition count above 1000`, `invalid group name`, `duplicate group name x`, +`unknown group flag`, `unsupported: backreference` and `unsupported: lookaround`. + +## Limits + +- A count in `{n}`, `{n,}` or `{n,m}` is at most `REGEX_MAX_REPETITION` (1000). +- Counted repetition copies its body, so a compiled program holds at most `REGEX_MAX_PROGRAM` + (100000) instructions. A pattern such as `(a{1000}){1000}` is `pattern too large` at column 1. + +## Performance + +Matching is linear in the text times the program, whatever the pattern. When every match starts +with the same literal scalars (`foo(bar|baz)` starts with `foo`), the search jumps to the next +occurrence of that prefix. A pattern that starts with `^`, a class, an alternation, a repetition +that may be empty, or a case-insensitive letter has no such prefix. Prefer `isMatch` when you only +need a yes or no. + +## Not supported + +- **Backreferences** (`\1`) and **lookaround** (`(?=`, `(?!`, `(?<=`, `(?` | + +`open` runs `PRAGMA journal_mode=WAL` on file databases so readers do not block behind a writer. If +the filesystem cannot support WAL, `open` closes the handle and returns the pragma's error; it does +not fall back to the previous journal mode. `:memory:` databases skip the pragma, and only the +exact path `":memory:"` counts as one. + +## Statements + +`prepare` compiles **only the first statement** of its SQL. Anything after the first semicolon is +silently dropped. Run each statement through its own `prepare`, or hand multi-statement scripts that +need no parameters and return no rows to `exec`. + +**Binding.** Parameter indexes are **1-based**, as in SQLite's C API (`?1` is index 1). + +| Method | Binds | +| --- | --- | +| `bindNull(index)` | `NULL` | +| `bindInt(index, value: i64)` | An integer | +| `bindReal(index, value: f64)` | A floating-point number | +| `bindText(index, text: str)` | Text. SQLite copies the bytes at bind time, so your buffer can go away before `step` | +| `bindBlob(index, &bytes)` | Bytes, copied the same way | + +**Stepping.** `step()` returns `Result`: `Step::ROW` for each row and `Step::DONE` when +the statement has finished. Anything else is an `Sqlite3::Error`. + +**Reading.** Column indexes are **0-based**. + +| Method | Reads | +| --- | --- | +| `columnCount()` | The number of columns | +| `columnIsNull(column)` | Whether the value is `NULL` | +| `columnInt(column)` | An `i64` | +| `columnReal(column)` | An `f64` | +| `columnText(column)` | A `String` | +| `columnBlob(column)` | A `Vector` | + +The getters coerce values the way SQLite does, so `columnInt` on a `TEXT` column parses a number. +Use `columnIsNull` to tell a real `NULL` apart from a coerced `0` or empty string. + +**Reuse.** `reset()` rewinds a statement so it can run again. Bindings survive the reset — nothing +is cleared — so a parameter you do not bind again keeps its previous value; bind every parameter +before stepping. A statement stays compiled, so a query that runs many times is prepared once. +After an error, reset the statement before using it again. + +## Transactions + +`connection.begin()` returns `Result`. Call `commit()` to keep +the changes or `rollback()` to discard them. Both return `Result`. + +If the transaction is dropped without `commit`, it rolls back. An early `return` or an error path +therefore cannot leave a transaction open. That rollback on drop is silent and best effort; code +that needs to know the outcome should call `commit` or `rollback` itself. + +- Calling `commit` or `rollback` a second time is a misuse error, not a panic. +- A failed `commit` leaves the transaction unfinished, so drop still cleans up. +- A transaction does not own its connection. Using it after `close()` gives a misuse error rather + than touching freed memory, but it cannot outlive the `Connection` value itself. Declaring the + connection first handles this, because it then drops last. + +## Errors + +Every fallible operation returns `Result`. `Error.code` is SQLite's extended +result code and `Error.message` is what `sqlite3_errmsg` reports for the connection. + +`isConstraint()` is true for the `SQLITE_CONSTRAINT` family: primary key, unique, not-null, check and +foreign-key violations. It tests the primary part of the code (`code & 0xff`), so every specific +constraint code matches. A service typically turns constraint errors into HTTP 409 or 422 and every +other error into 500. + +## Threads + +A `Connection` holds a raw `sqlite3*`, so it is not `Send`, and a `Mutex` does not +compile. To share one connection between threads, wrap it in `Sqlite3::SharedConnection` and put +that behind a `Mutex`: + +```ignis +import Sqlite3 from "std::sqlite3"; +import Arc, Mutex, MutexGuard, Shared from "std::sync"; + +function insertThroughShared(connection: Sqlite3::Connection): void { + let cell: Sqlite3::SharedConnection = Sqlite3::SharedConnection::new(connection); + let shared: Shared = Arc::new>( + Mutex::new(cell) + ); + + let mut guard: MutexGuard = shared.get().lock(); + guard.get().connection.exec("INSERT INTO t VALUES (1)").unwrap(); +} +``` + +The handle can then move between threads, one at a time. A `Statement` or `Transaction` taken through +the guard must not outlive the guard. + +## Not included + +The binding is blocking and synchronous. There is no asynchronous API and no query builder. diff --git a/std/http/mod.ign b/std/http/mod.ign index ce389035..4a2ca89d 100644 --- a/std/http/mod.ign +++ b/std/http/mod.ign @@ -71,7 +71,11 @@ //! between the parts. The method is a case-sensitive token; methods other //! than the nine standard ones are `Method::OTHER`. The target is kept as //! received and must be visible ASCII. -//! - A version other than `HTTP/1.0` and `HTTP/1.1` is `UNSUPPORTED_VERSION`. +//! - The version is `HTTP/.`, eight characters in all. One +//! spelled that way but other than `HTTP/1.0` and `HTTP/1.1` is +//! `UNSUPPORTED_VERSION` (505); anything else, such as `HTTP/2` or +//! `HTTP/1`, is not a version at all and makes the request line +//! `INVALID_REQUEST_LINE`. //! - A header line is `name: value`. Whitespace between the name and the //! colon, an obsolete line folding (a line starting with a space or a tab) //! and a control byte in the value are `INVALID_HEADER`. Names keep their @@ -122,11 +126,13 @@ //! //! `writeHead` appends `HTTP/1.1 \r\n`, every header field //! and the blank line. `writeResponse` does the same with a `Content-Length` -//! field and appends the body. For a chunked body, add -//! `Transfer-Encoding: chunked` to the head, then call `writeChunk` for each -//! piece and `writeLastChunk` at the end. A header name, header value or -//! reason phrase holding CR or LF could split the response, so it is a -//! `SerializeError` and nothing is appended. +//! field and appends the body, so it refuses a head that already carries +//! `Content-Length` or `Transfer-Encoding` (`FRAMING_HEADER_PRESENT`). For a +//! chunked body, add `Transfer-Encoding: chunked` to the head, write the head +//! with `writeHead`, then call `writeChunk` for each piece and +//! `writeLastChunk` at the end. A header name that is not a token, or a header +//! value or reason phrase holding CR or LF, could split the response, so it is +//! a `SerializeError` and nothing is appended. //! //! Byte inputs are `&Vector`: a slice parameter cannot report its length //! yet. @@ -142,7 +148,7 @@ //! //! @implements(Http::Handler) //! record Greeter { -//! public greeting: str; +//! public greeting: static str; //! //! handle(&self, request: &Http::Request, response: &mut Http::Response): void { //! if (!request.head.target.equals("/")) { @@ -169,9 +175,10 @@ //! connection, serves it to the end and accepts the next, so up to `threads` //! connections are served at once. The handler is shared by all of them, //! which is why it has to be `Send` and `Sync` and `handle` takes `&self`. -//! `run` returns only once every thread's `accept` failed; there is no way -//! to stop a running server yet, so it blocks for as long as the process -//! lives. +//! `run` returns only when a worker's `accept` fails with `EBADF` or +//! `EINVAL`; a recoverable failure such as `EMFILE` or `ENFILE` is retried and +//! does not end the server. There is no way to stop a running server yet, so +//! it blocks for as long as the process lives. //! //! `acceptConnections` is the loop each `run` thread runs: it accepts a //! connection, serves it and accepts the next. Calling it on threads of @@ -195,11 +202,13 @@ //! expires, or the client closes, the connection ends without a response. //! - A malformed request gets an empty response with the parser's status //! and `Connection: close`, then the connection ends. -//! - A response the serializer rejects, a status outside 100 to 999 or a -//! header that holds CR or LF, is replaced by an empty 500. +//! - A response the serializer rejects for any reason — a status outside 100 +//! to 999, a header value with CR or LF, a header name that is not a token +//! — is replaced by an empty 500. //! - Before closing, the server shuts its writing side and discards what -//! the client still sends for up to 2 seconds, so the close does not reset -//! the connection before the client reads the response. +//! the client still sends, for up to 2 seconds or 1048576 bytes, so the +//! close does not reset the connection before the client reads the +//! response. //! //! ## Example //! diff --git a/std/sqlite3/connection.ign b/std/sqlite3/connection.ign index f736b9ba..6f7358ad 100644 --- a/std/sqlite3/connection.ign +++ b/std/sqlite3/connection.ign @@ -13,10 +13,11 @@ //! | `Connection::openInMemory()` | Opens a private `:memory:` database | //! //! Both run `PRAGMA journal_mode=WAL` on a file database so readers do not -//! block behind a writer; SQLite silently keeps the previous journal mode -//! where the filesystem cannot support WAL, and `open` still succeeds. An -//! in-memory database skips the pragma: WAL never applies to `:memory:`, and -//! only the exact path `":memory:"` is recognized as one. +//! block behind a writer; where the filesystem cannot support WAL the pragma +//! fails, and `open` closes the handle and returns that error instead of +//! falling back to the previous journal mode. An in-memory database skips the +//! pragma: WAL never applies to `:memory:`, and only the exact path +//! `":memory:"` is recognized as one. //! //! ## Errors //! diff --git a/std/sqlite3/error.ign b/std/sqlite3/error.ign index 543eb850..86d06518 100644 --- a/std/sqlite3/error.ign +++ b/std/sqlite3/error.ign @@ -2,9 +2,10 @@ //! # Errors //! //! `Sqlite3::Error`, the error type every fallible operation of `std::sqlite3` -//! returns. Nothing in the module panics: a failing SQLite call becomes an -//! `Error` value carrying the extended result code and the message that -//! `sqlite3_errmsg` reports for the connection. +//! returns. A failing SQLite call becomes an `Error` value carrying the +//! extended result code and the message that `sqlite3_errmsg` reports for the +//! connection. Nothing in the module panics except `SharedConnection::new`, +//! which aborts when the linked SQLite was built with `SQLITE_THREADSAFE=0`. //! //! ## Exports //! diff --git a/std/sqlite3/statement.ign b/std/sqlite3/statement.ign index 756b3b6f..db5f6a8c 100644 --- a/std/sqlite3/statement.ign +++ b/std/sqlite3/statement.ign @@ -33,9 +33,10 @@ //! //! ## Reuse //! -//! `reset()` rewinds the statement so it can run again with new bindings; -//! rebinding replaces every bound parameter. The statement stays compiled, so -//! a query run many times prepares once. +//! `reset()` rewinds the statement so it can run again. Bindings survive the +//! reset: nothing is cleared, so a parameter that is not bound again keeps its +//! previous value. The statement stays compiled, so a query run many times +//! prepares once. import Error from "std::sqlite3::error"; import LibC from "std::libc"; diff --git a/std/web/mod.ign b/std/web/mod.ign index bcc4cb88..04873175 100644 --- a/std/web/mod.ign +++ b/std/web/mod.ign @@ -134,7 +134,7 @@ //! //! @implements(Web::App) //! record Users { -//! public greeting: str; +//! public greeting: static str; //! //! build(&self): Web::Router { //! let greeting: str = self.greeting; diff --git a/test_cases/doc/__doc_baselines__/output__std_io_mod.json b/test_cases/doc/__doc_baselines__/output__std_io_mod.json index 80283e16..06802ca2 100644 --- a/test_cases/doc/__doc_baselines__/output__std_io_mod.json +++ b/test_cases/doc/__doc_baselines__/output__std_io_mod.json @@ -86,7 +86,7 @@ }, { "name": "std::http", - "doc": " \n# HTTP \n \nHTTP/1.1 on the server side. The core is sans-IO: a request parser and a \nresponse serializer that never touch a socket. Anything that speaks HTTP \nbut is not a web application (a proxy, a test harness, a server driver) \nbuilds on it. The parser receives bytes and returns what they mean; the \nserializer turns a response into bytes and leaves writing them to the \ncaller. On top of it, `Http::Server` is a blocking driver that accepts \nconnections and calls a handler with a request and a response. \n \n## Exports \n \n| Export | Description | \n|------------------------|----------------------------------------------------------------------| \n| `Http::RequestParser` | `new(limits)`, `feed(&bytes)`, `feedStr(text)`, `next()`, `buffered()` | \n| `Http::ParseEvent` | `NEED_MORE`, `HEAD(RequestHead)`, `BODY_CHUNK(Vector)`, `DONE`, `MALFORMED(ParseError)` | \n| `Http::RequestHead` | `method`, `target`, `version`, `headers`; `keepAlive()` | \n| `Http::Method` | `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTIONS`, `CONNECT`, `TRACE`, `OTHER(String)`; `toString()` | \n| `Http::Version` | `HTTP_1_0`, `HTTP_1_1`; `toStr()` | \n| `Http::Headers` | Ordered fields: `get`, `getAll`, `contains`, `hasToken`, `add`, `set`, `remove`, `length`, `nameAt`, `valueAt`, `fieldAt` | \n| `Http::HeaderField` | One `name` and `value` | \n| `Http::Limits` | `maxRequestLine`, `maxHeaderLine`, `maxHeaders`, `maxBody`; `new()` gives the defaults | \n| `Http::ParseError` | `kind` and the suggested response `status` | \n| `Http::ParseErrorKind` | Why a request is malformed; `name()`, `status()` | \n| `Http::ResponseHead` | `status`, `reason`, `headers`; `create(status)`, `withReason(status, reason)` | \n| `Http::SerializeError` | Why a response head cannot be written | \n| `Http::writeHead` | Appends a response head | \n| `Http::writeResponse` | Appends a head with `Content-Length` and the body | \n| `Http::writeBody` | Appends body bytes unchanged | \n| `Http::writeChunk` | Appends one chunk of a chunked body | \n| `Http::writeLastChunk` | Appends the chunk that ends a chunked body | \n| `Http::reasonPhrase` | The standard reason phrase of a status | \n| `Http::Server` | `bind(&address, config)`, `localAddress()`, `run(handler)` | \n| `Http::ServerConfig` | `threads`, `limits`, `idleTimeout`, `maxRequestsPerConnection`; `new()` gives the defaults | \n| `Http::Handler` | Trait: `handle(&self, &Request, &mut Response)` | \n| `Http::Request` | `head`, `body`; `target()`, `header(name)`, `bodyText()` | \n| `Http::Response` | `status`, `headers`, `body`; `new()`, `setStatus`, `setHeader`, `addHeader`, `write`, `writeStr` | \n| `Http::MediaType` | `mainType`, `subtype`, `parameters`; `parse(text)`, `essence()`, `parameter(name)`, `parameterCount()` | \n| `Http::MediaTypeParameter` | One lowercased `name` and its unescaped `value` | \n| `Http::serveConnection` | Serves one connection with a handler | \n| `Http::acceptConnections` | Accepts and serves connections on the calling thread | \n \n## Parsing \n \n`feed` copies bytes into the parser; `next` reports the next event. Each \nrequest produces `HEAD` once, zero or more `BODY_CHUNK`, then `DONE`. \n`NEED_MORE` means the bytes fed so far are not enough to report anything \nelse. After `DONE` the parser starts on the next request of the same \nconnection, and bytes already fed past the end of a request belong to the \nnext one, so keep-alive and pipelining need nothing special. \n`RequestHead.keepAlive()` tells whether the connection stays open: an \nHTTP/1.1 request keeps it unless `Connection` lists `close`, an HTTP/1.0 \nrequest closes it unless `Connection` lists `keep-alive`. \n \nEvents own their payloads: a `RequestHead` or a body chunk is a copy and \nstays valid after more bytes are fed. \n \n`MALFORMED` is terminal: once the parser reports it, every later `next` \nreports the same error, because the rest of the connection cannot be \nframed. The `ParseError` carries the status a server should answer with \n(400, 413, 414, 431, 501 or 505) before it closes the connection. \nMalformed input never panics. \n \n## Message syntax \n \n- Lines end with CRLF. A bare LF is accepted too, as RFC 9112 section 2.2 \n allows a recipient to; a CR anywhere else is malformed. \n- Empty lines before a request line are skipped. \n- The request line is `method SP target SP HTTP/1.x` with exactly one space \n between the parts. The method is a case-sensitive token; methods other \n than the nine standard ones are `Method::OTHER`. The target is kept as \n received and must be visible ASCII. \n- A version other than `HTTP/1.0` and `HTTP/1.1` is `UNSUPPORTED_VERSION`. \n- A header line is `name: value`. Whitespace between the name and the \n colon, an obsolete line folding (a line starting with a space or a tab) \n and a control byte in the value are `INVALID_HEADER`. Names keep their \n casing; lookups ignore ASCII case. \n \n## Body framing \n \nPer RFC 9112 section 6.3: \n \n| Head | Body | \n|----------------------------------------|------------------------------------------------| \n| `Transfer-Encoding: chunked` | Chunked; reported without the chunk framing | \n| Any other `Transfer-Encoding` | `UNSUPPORTED_TRANSFER_CODING` (501) | \n| `Transfer-Encoding` and `Content-Length` | `CONFLICTING_LENGTH` (400), as request smuggling | \n| `Content-Length: n` | Exactly `n` bytes | \n| `Content-Length` values that disagree | `CONFLICTING_LENGTH` (400) | \n| A `Content-Length` that is not a count | `INVALID_CONTENT_LENGTH` (400) | \n| Neither | No body | \n \nRepeated `Content-Length` fields, or a comma list in one, are accepted when \nevery value is the same. Chunk extensions are ignored. Trailer fields \nafter the last chunk are checked like header fields, counted against \n`maxHeaders`, and discarded. \n \n## Limits \n \n| Limit | Default | Violation | \n|------------------|-----------|-------------------------------------------| \n| `maxRequestLine` | 8192 | `REQUEST_LINE_TOO_LONG` (414) | \n| `maxHeaderLine` | 8192 | `HEADER_TOO_LONG` (431); `INVALID_CHUNK` for a chunk-size line | \n| `maxHeaders` | 100 | `TOO_MANY_HEADERS` (431) | \n| `maxBody` | 1048576 | `BODY_TOO_LARGE` (413) | \n \nLine lengths exclude the line terminator, and a length exactly at its \nlimit is accepted. A line is rejected as soon as it grows past its limit, \nbefore it ends, and a body as soon as its declared size passes `maxBody`, \nso a client cannot make the parser buffer without bound. \n \n## Media types \n \n`MediaType::parse` reads a `Content-Type` value per RFC 9110 section \n8.3.1. The type, subtype and parameter names are lowercased; parameter \nvalues keep their case, and a quoted value loses its quotes and escapes. \nMalformed input gives `NONE`. `essence()` is `type/subtype`, and \n`parameter(\"charset\")` finds a parameter ignoring case. \n \n## Serializing \n \n`writeHead` appends `HTTP/1.1 \\r\\n`, every header field \nand the blank line. `writeResponse` does the same with a `Content-Length` \nfield and appends the body. For a chunked body, add \n`Transfer-Encoding: chunked` to the head, then call `writeChunk` for each \npiece and `writeLastChunk` at the end. A header name, header value or \nreason phrase holding CR or LF could split the response, so it is a \n`SerializeError` and nothing is appended. \n \nByte inputs are `&Vector`: a slice parameter cannot report its length \nyet. \n \n## Serving \n \nA handler is a record that implements `Http::Handler`. Outside the `Http` \nnamespace the trait is reached by its path: `@implements(Http::Handler)`. \n \n```ignis \nimport Http from \"std::http\"; \nimport IpAddress, SocketAddress from \"std::net\"; \n \n@implements(Http::Handler) \nrecord Greeter { \n public greeting: str; \n \n handle(&self, request: &Http::Request, response: &mut Http::Response): void { \n if (!request.head.target.equals(\"/\")) { \n response.setStatus(404); \n return; \n } \n \n response.setHeader(\"Content-Type\", \"text/plain\"); \n response.writeStr(self.greeting); \n } \n} \n \nfunction main(): i32 { \n let address: SocketAddress = SocketAddress::create(IpAddress::v4(127, 0, 0, 1), 8080); \n let Result::OK(server) = Http::Server::bind(&address, Http::ServerConfig::new()) else { \n return 1; \n }; \n \n return server.run(Greeter { greeting: \"hello\" }).isOk() ? 0 : 1; \n} \n``` \n \n`run` starts `ServerConfig.threads` threads (default 8). Each accepts a \nconnection, serves it to the end and accepts the next, so up to `threads` \nconnections are served at once. The handler is shared by all of them, \nwhich is why it has to be `Send` and `Sync` and `handle` takes `&self`. \n`run` returns only once every thread's `accept` failed; there is no way \nto stop a running server yet, so it blocks for as long as the process \nlives. \n \n`acceptConnections` is the loop each `run` thread runs: it accepts a \nconnection, serves it and accepts the next. Calling it on threads of \nyour own gives every thread its own handler, for state that cannot be \nshared; `std::web` builds one router per thread this way. \n \n`serveConnection` serves one accepted connection on the calling thread, \nwhich is what each `run` thread does and what a test calls directly: \n \n- A request reaches the handler once its whole body is in, bounded by \n `Limits.maxBody`. `Expect: 100-continue` is not answered: the client \n sends the body after its own wait. \n- The response always carries `Content-Length`; a `Content-Length` or \n `Transfer-Encoding` the handler set is dropped. A `HEAD` request gets \n the head, with the length the body would have, and no body. \n- The connection stays open unless the request does not keep it alive \n (`RequestHead.keepAlive`), the response lists `Connection: close`, or \n `maxRequestsPerConnection` (0, no limit, by default) is reached. When \n it closes, the response carries `Connection: close`. \n- Every read waits at most `idleTimeout` (default 30 seconds). When it \n expires, or the client closes, the connection ends without a response. \n- A malformed request gets an empty response with the parser's status \n and `Connection: close`, then the connection ends. \n- A response the serializer rejects, a status outside 100 to 999 or a \n header that holds CR or LF, is replaced by an empty 500. \n- Before closing, the server shuts its writing side and discards what \n the client still sends for up to 2 seconds, so the close does not reset \n the connection before the client reads the response. \n \n## Example \n \n```ignis \nimport Http from \"std::http\"; \n \nfunction answer(request: str, out: &mut Vector): i32 { \n let mut parser: Http::RequestParser = Http::RequestParser::new(Http::Limits::new()); \n parser.feedStr(request); \n \n let Http::ParseEvent::HEAD(head) = parser.next() else { \n return 1; \n }; \n \n let mut response: Http::ResponseHead = Http::ResponseHead::create(200); \n response.headers.add(\"Content-Type\", \"text/plain\"); \n let body: Vector = head.target.toBytes(); \n \n return Http::writeResponse(&response, &body, out).isOk() ? 0 : 1; \n} \n```" + "doc": " \n# HTTP \n \nHTTP/1.1 on the server side. The core is sans-IO: a request parser and a \nresponse serializer that never touch a socket. Anything that speaks HTTP \nbut is not a web application (a proxy, a test harness, a server driver) \nbuilds on it. The parser receives bytes and returns what they mean; the \nserializer turns a response into bytes and leaves writing them to the \ncaller. On top of it, `Http::Server` is a blocking driver that accepts \nconnections and calls a handler with a request and a response. \n \n## Exports \n \n| Export | Description | \n|------------------------|----------------------------------------------------------------------| \n| `Http::RequestParser` | `new(limits)`, `feed(&bytes)`, `feedStr(text)`, `next()`, `buffered()` | \n| `Http::ParseEvent` | `NEED_MORE`, `HEAD(RequestHead)`, `BODY_CHUNK(Vector)`, `DONE`, `MALFORMED(ParseError)` | \n| `Http::RequestHead` | `method`, `target`, `version`, `headers`; `keepAlive()` | \n| `Http::Method` | `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `PATCH`, `OPTIONS`, `CONNECT`, `TRACE`, `OTHER(String)`; `toString()` | \n| `Http::Version` | `HTTP_1_0`, `HTTP_1_1`; `toStr()` | \n| `Http::Headers` | Ordered fields: `get`, `getAll`, `contains`, `hasToken`, `add`, `set`, `remove`, `length`, `nameAt`, `valueAt`, `fieldAt` | \n| `Http::HeaderField` | One `name` and `value` | \n| `Http::Limits` | `maxRequestLine`, `maxHeaderLine`, `maxHeaders`, `maxBody`; `new()` gives the defaults | \n| `Http::ParseError` | `kind` and the suggested response `status` | \n| `Http::ParseErrorKind` | Why a request is malformed; `name()`, `status()` | \n| `Http::ResponseHead` | `status`, `reason`, `headers`; `create(status)`, `withReason(status, reason)` | \n| `Http::SerializeError` | Why a response head cannot be written | \n| `Http::writeHead` | Appends a response head | \n| `Http::writeResponse` | Appends a head with `Content-Length` and the body | \n| `Http::writeBody` | Appends body bytes unchanged | \n| `Http::writeChunk` | Appends one chunk of a chunked body | \n| `Http::writeLastChunk` | Appends the chunk that ends a chunked body | \n| `Http::reasonPhrase` | The standard reason phrase of a status | \n| `Http::Server` | `bind(&address, config)`, `localAddress()`, `run(handler)` | \n| `Http::ServerConfig` | `threads`, `limits`, `idleTimeout`, `maxRequestsPerConnection`; `new()` gives the defaults | \n| `Http::Handler` | Trait: `handle(&self, &Request, &mut Response)` | \n| `Http::Request` | `head`, `body`; `target()`, `header(name)`, `bodyText()` | \n| `Http::Response` | `status`, `headers`, `body`; `new()`, `setStatus`, `setHeader`, `addHeader`, `write`, `writeStr` | \n| `Http::MediaType` | `mainType`, `subtype`, `parameters`; `parse(text)`, `essence()`, `parameter(name)`, `parameterCount()` | \n| `Http::MediaTypeParameter` | One lowercased `name` and its unescaped `value` | \n| `Http::serveConnection` | Serves one connection with a handler | \n| `Http::acceptConnections` | Accepts and serves connections on the calling thread | \n \n## Parsing \n \n`feed` copies bytes into the parser; `next` reports the next event. Each \nrequest produces `HEAD` once, zero or more `BODY_CHUNK`, then `DONE`. \n`NEED_MORE` means the bytes fed so far are not enough to report anything \nelse. After `DONE` the parser starts on the next request of the same \nconnection, and bytes already fed past the end of a request belong to the \nnext one, so keep-alive and pipelining need nothing special. \n`RequestHead.keepAlive()` tells whether the connection stays open: an \nHTTP/1.1 request keeps it unless `Connection` lists `close`, an HTTP/1.0 \nrequest closes it unless `Connection` lists `keep-alive`. \n \nEvents own their payloads: a `RequestHead` or a body chunk is a copy and \nstays valid after more bytes are fed. \n \n`MALFORMED` is terminal: once the parser reports it, every later `next` \nreports the same error, because the rest of the connection cannot be \nframed. The `ParseError` carries the status a server should answer with \n(400, 413, 414, 431, 501 or 505) before it closes the connection. \nMalformed input never panics. \n \n## Message syntax \n \n- Lines end with CRLF. A bare LF is accepted too, as RFC 9112 section 2.2 \n allows a recipient to; a CR anywhere else is malformed. \n- Empty lines before a request line are skipped. \n- The request line is `method SP target SP HTTP/1.x` with exactly one space \n between the parts. The method is a case-sensitive token; methods other \n than the nine standard ones are `Method::OTHER`. The target is kept as \n received and must be visible ASCII. \n- The version is `HTTP/.`, eight characters in all. One \n spelled that way but other than `HTTP/1.0` and `HTTP/1.1` is \n `UNSUPPORTED_VERSION` (505); anything else, such as `HTTP/2` or \n `HTTP/1`, is not a version at all and makes the request line \n `INVALID_REQUEST_LINE`. \n- A header line is `name: value`. Whitespace between the name and the \n colon, an obsolete line folding (a line starting with a space or a tab) \n and a control byte in the value are `INVALID_HEADER`. Names keep their \n casing; lookups ignore ASCII case. \n \n## Body framing \n \nPer RFC 9112 section 6.3: \n \n| Head | Body | \n|----------------------------------------|------------------------------------------------| \n| `Transfer-Encoding: chunked` | Chunked; reported without the chunk framing | \n| Any other `Transfer-Encoding` | `UNSUPPORTED_TRANSFER_CODING` (501) | \n| `Transfer-Encoding` and `Content-Length` | `CONFLICTING_LENGTH` (400), as request smuggling | \n| `Content-Length: n` | Exactly `n` bytes | \n| `Content-Length` values that disagree | `CONFLICTING_LENGTH` (400) | \n| A `Content-Length` that is not a count | `INVALID_CONTENT_LENGTH` (400) | \n| Neither | No body | \n \nRepeated `Content-Length` fields, or a comma list in one, are accepted when \nevery value is the same. Chunk extensions are ignored. Trailer fields \nafter the last chunk are checked like header fields, counted against \n`maxHeaders`, and discarded. \n \n## Limits \n \n| Limit | Default | Violation | \n|------------------|-----------|-------------------------------------------| \n| `maxRequestLine` | 8192 | `REQUEST_LINE_TOO_LONG` (414) | \n| `maxHeaderLine` | 8192 | `HEADER_TOO_LONG` (431); `INVALID_CHUNK` for a chunk-size line | \n| `maxHeaders` | 100 | `TOO_MANY_HEADERS` (431) | \n| `maxBody` | 1048576 | `BODY_TOO_LARGE` (413) | \n \nLine lengths exclude the line terminator, and a length exactly at its \nlimit is accepted. A line is rejected as soon as it grows past its limit, \nbefore it ends, and a body as soon as its declared size passes `maxBody`, \nso a client cannot make the parser buffer without bound. \n \n## Media types \n \n`MediaType::parse` reads a `Content-Type` value per RFC 9110 section \n8.3.1. The type, subtype and parameter names are lowercased; parameter \nvalues keep their case, and a quoted value loses its quotes and escapes. \nMalformed input gives `NONE`. `essence()` is `type/subtype`, and \n`parameter(\"charset\")` finds a parameter ignoring case. \n \n## Serializing \n \n`writeHead` appends `HTTP/1.1 \\r\\n`, every header field \nand the blank line. `writeResponse` does the same with a `Content-Length` \nfield and appends the body, so it refuses a head that already carries \n`Content-Length` or `Transfer-Encoding` (`FRAMING_HEADER_PRESENT`). For a \nchunked body, add `Transfer-Encoding: chunked` to the head, write the head \nwith `writeHead`, then call `writeChunk` for each piece and \n`writeLastChunk` at the end. A header name that is not a token, or a header \nvalue or reason phrase holding CR or LF, could split the response, so it is \na `SerializeError` and nothing is appended. \n \nByte inputs are `&Vector`: a slice parameter cannot report its length \nyet. \n \n## Serving \n \nA handler is a record that implements `Http::Handler`. Outside the `Http` \nnamespace the trait is reached by its path: `@implements(Http::Handler)`. \n \n```ignis \nimport Http from \"std::http\"; \nimport IpAddress, SocketAddress from \"std::net\"; \n \n@implements(Http::Handler) \nrecord Greeter { \n public greeting: static str; \n \n handle(&self, request: &Http::Request, response: &mut Http::Response): void { \n if (!request.head.target.equals(\"/\")) { \n response.setStatus(404); \n return; \n } \n \n response.setHeader(\"Content-Type\", \"text/plain\"); \n response.writeStr(self.greeting); \n } \n} \n \nfunction main(): i32 { \n let address: SocketAddress = SocketAddress::create(IpAddress::v4(127, 0, 0, 1), 8080); \n let Result::OK(server) = Http::Server::bind(&address, Http::ServerConfig::new()) else { \n return 1; \n }; \n \n return server.run(Greeter { greeting: \"hello\" }).isOk() ? 0 : 1; \n} \n``` \n \n`run` starts `ServerConfig.threads` threads (default 8). Each accepts a \nconnection, serves it to the end and accepts the next, so up to `threads` \nconnections are served at once. The handler is shared by all of them, \nwhich is why it has to be `Send` and `Sync` and `handle` takes `&self`. \n`run` returns only when a worker's `accept` fails with `EBADF` or \n`EINVAL`; a recoverable failure such as `EMFILE` or `ENFILE` is retried and \ndoes not end the server. There is no way to stop a running server yet, so \nit blocks for as long as the process lives. \n \n`acceptConnections` is the loop each `run` thread runs: it accepts a \nconnection, serves it and accepts the next. Calling it on threads of \nyour own gives every thread its own handler, for state that cannot be \nshared; `std::web` builds one router per thread this way. \n \n`serveConnection` serves one accepted connection on the calling thread, \nwhich is what each `run` thread does and what a test calls directly: \n \n- A request reaches the handler once its whole body is in, bounded by \n `Limits.maxBody`. `Expect: 100-continue` is not answered: the client \n sends the body after its own wait. \n- The response always carries `Content-Length`; a `Content-Length` or \n `Transfer-Encoding` the handler set is dropped. A `HEAD` request gets \n the head, with the length the body would have, and no body. \n- The connection stays open unless the request does not keep it alive \n (`RequestHead.keepAlive`), the response lists `Connection: close`, or \n `maxRequestsPerConnection` (0, no limit, by default) is reached. When \n it closes, the response carries `Connection: close`. \n- Every read waits at most `idleTimeout` (default 30 seconds). When it \n expires, or the client closes, the connection ends without a response. \n- A malformed request gets an empty response with the parser's status \n and `Connection: close`, then the connection ends. \n- A response the serializer rejects for any reason — a status outside 100 \n to 999, a header value with CR or LF, a header name that is not a token \n — is replaced by an empty 500. \n- Before closing, the server shuts its writing side and discards what \n the client still sends, for up to 2 seconds or 1048576 bytes, so the \n close does not reset the connection before the client reads the \n response. \n \n## Example \n \n```ignis \nimport Http from \"std::http\"; \n \nfunction answer(request: str, out: &mut Vector): i32 { \n let mut parser: Http::RequestParser = Http::RequestParser::new(Http::Limits::new()); \n parser.feedStr(request); \n \n let Http::ParseEvent::HEAD(head) = parser.next() else { \n return 1; \n }; \n \n let mut response: Http::ResponseHead = Http::ResponseHead::create(200); \n response.headers.add(\"Content-Type\", \"text/plain\"); \n let body: Vector = head.target.toBytes(); \n \n return Http::writeResponse(&response, &body, out).isOk() ? 0 : 1; \n} \n```" }, { "name": "std::http::headers", @@ -345,15 +345,15 @@ }, { "name": "std::sqlite3::connection", - "doc": " \n# Connection \n \n`Sqlite3::Connection`, one open SQLite database. Owns the `sqlite3*` \nhandle and closes it on drop; `close()` does the same thing early and \nreports the result. \n \n## Construction \n \n| Method | Description | \n|------------------|---------------------------------------------------| \n| `Connection::open(path)` | Opens (or creates) the database file `path` | \n| `Connection::openInMemory()` | Opens a private `:memory:` database | \n \nBoth run `PRAGMA journal_mode=WAL` on a file database so readers do not \nblock behind a writer; SQLite silently keeps the previous journal mode \nwhere the filesystem cannot support WAL, and `open` still succeeds. An \nin-memory database skips the pragma: WAL never applies to `:memory:`, and \nonly the exact path `\":memory:\"` is recognized as one. \n \n## Errors \n \nEvery fallible operation returns `Result`. The error's \n`code` is the extended result code and `message` is what `sqlite3_errmsg` \nreports; see `std::sqlite3::error`. \n \n## Threading \n \nA `Connection` holds a raw `sqlite3*`, so it is not `Send`, and a \n`Mutex` does not compile: `Mutex` requires `Send`. To share one \nconnection between threads, wrap it in `Sqlite3::SharedConnection` and put \nthat behind a `Mutex` (`Shared`): \n \n```ignis \nlet cell: Sqlite3::SharedConnection = Sqlite3::SharedConnection::new(connection); \nlet shared: Shared = Arc::new>(Mutex::new(cell)); \nlet mut guard: MutexGuard = shared.get().lock(); \nguard.get().connection.exec(\"INSERT INTO t VALUES (1)\").unwrap(); \n``` \n \nThe handle may then move between threads, one at a time. A `Statement` or \n`Transaction` taken through the guard must not outlive the guard." + "doc": " \n# Connection \n \n`Sqlite3::Connection`, one open SQLite database. Owns the `sqlite3*` \nhandle and closes it on drop; `close()` does the same thing early and \nreports the result. \n \n## Construction \n \n| Method | Description | \n|------------------|---------------------------------------------------| \n| `Connection::open(path)` | Opens (or creates) the database file `path` | \n| `Connection::openInMemory()` | Opens a private `:memory:` database | \n \nBoth run `PRAGMA journal_mode=WAL` on a file database so readers do not \nblock behind a writer; where the filesystem cannot support WAL the pragma \nfails, and `open` closes the handle and returns that error instead of \nfalling back to the previous journal mode. An in-memory database skips the \npragma: WAL never applies to `:memory:`, and only the exact path \n`\":memory:\"` is recognized as one. \n \n## Errors \n \nEvery fallible operation returns `Result`. The error's \n`code` is the extended result code and `message` is what `sqlite3_errmsg` \nreports; see `std::sqlite3::error`. \n \n## Threading \n \nA `Connection` holds a raw `sqlite3*`, so it is not `Send`, and a \n`Mutex` does not compile: `Mutex` requires `Send`. To share one \nconnection between threads, wrap it in `Sqlite3::SharedConnection` and put \nthat behind a `Mutex` (`Shared`): \n \n```ignis \nlet cell: Sqlite3::SharedConnection = Sqlite3::SharedConnection::new(connection); \nlet shared: Shared = Arc::new>(Mutex::new(cell)); \nlet mut guard: MutexGuard = shared.get().lock(); \nguard.get().connection.exec(\"INSERT INTO t VALUES (1)\").unwrap(); \n``` \n \nThe handle may then move between threads, one at a time. A `Statement` or \n`Transaction` taken through the guard must not outlive the guard." }, { "name": "std::sqlite3::error", - "doc": " \n# Errors \n \n`Sqlite3::Error`, the error type every fallible operation of `std::sqlite3` \nreturns. Nothing in the module panics: a failing SQLite call becomes an \n`Error` value carrying the extended result code and the message that \n`sqlite3_errmsg` reports for the connection. \n \n## Exports \n \n| Export | Description | \n|-----------------|------------------------------------------------| \n| `Sqlite3::Error` | `code` (extended result code) and `message`; `isConstraint()` | \n \n## Constraint violations \n \n`isConstraint()` answers whether the error is one of the `SQLITE_CONSTRAINT` \nfamily (primary-key, unique, not-null, check, foreign-key). A service layer \nturns those into HTTP 409/422; every other code is a 500. The check is on \nthe extended code's primary part (`code & 0xff`), so any specific \nconstraint code the engine reports matches." + "doc": " \n# Errors \n \n`Sqlite3::Error`, the error type every fallible operation of `std::sqlite3` \nreturns. A failing SQLite call becomes an `Error` value carrying the \nextended result code and the message that `sqlite3_errmsg` reports for the \nconnection. Nothing in the module panics except `SharedConnection::new`, \nwhich aborts when the linked SQLite was built with `SQLITE_THREADSAFE=0`. \n \n## Exports \n \n| Export | Description | \n|-----------------|------------------------------------------------| \n| `Sqlite3::Error` | `code` (extended result code) and `message`; `isConstraint()` | \n \n## Constraint violations \n \n`isConstraint()` answers whether the error is one of the `SQLITE_CONSTRAINT` \nfamily (primary-key, unique, not-null, check, foreign-key). A service layer \nturns those into HTTP 409/422; every other code is a 500. The check is on \nthe extended code's primary part (`code & 0xff`), so any specific \nconstraint code the engine reports matches." }, { "name": "std::sqlite3::statement", - "doc": " \n# Statement \n \n`Sqlite3::Statement`, one compiled SQL statement. Wraps the `sqlite3_stmt*` \nthat `Connection::prepare` produces, binds parameters, steps through rows \nand reads columns; finalizes on drop. \n \n## Exports \n \n| Export | Description | \n|-----------------|------------------------------------------------------| \n| `Sqlite3::Statement` | `bindNull`, `bindInt`, `bindReal`, `bindText`, `bindBlob`, `step`, `columnCount`, `columnIsNull`, `columnInt`, `columnReal`, `columnText`, `columnBlob`, `reset` | \n| `Sqlite3::Step` | `ROW` or `DONE`, what `step` reports | \n \n## Binding and reading \n \nParameter indexes are 1-based, the way SQLite itself counts them in the C \nAPI (`?1` is index 1). Column indexes are 0-based. `bindText` and \n`bindBlob` pass `SQLITE_TRANSIENT` to SQLite, so the bound bytes are \ncopied at bind time and the caller's buffer can go away before `step`. \n`SQLITE_TRANSIENT` is SQLite's own documented sentinel — the \n`sqlite3_bind_text` docs define it as \"a special destructor (...) which \nmakes SQLite copy the bytes\" — spelled here as the pointer value `-1` \nbecause the C header defines it as a cast of -1 to the destructor's \nfunction-pointer type. \n \n`step()` returns `Result::OK(Step::ROW)` for each row and \n`Result::OK(Step::DONE)` when the statement is finished; anything else is \nan `Sqlite3::Error`. Column getters coerce the value the way SQLite does \n(`columnInt` on a TEXT column parses a number); `columnIsNull` tells the \ntwo cases apart that a coercion would blur. After an error the statement \nis reset before reuse. \n \n## Reuse \n \n`reset()` rewinds the statement so it can run again with new bindings; \nrebinding replaces every bound parameter. The statement stays compiled, so \na query run many times prepares once." + "doc": " \n# Statement \n \n`Sqlite3::Statement`, one compiled SQL statement. Wraps the `sqlite3_stmt*` \nthat `Connection::prepare` produces, binds parameters, steps through rows \nand reads columns; finalizes on drop. \n \n## Exports \n \n| Export | Description | \n|-----------------|------------------------------------------------------| \n| `Sqlite3::Statement` | `bindNull`, `bindInt`, `bindReal`, `bindText`, `bindBlob`, `step`, `columnCount`, `columnIsNull`, `columnInt`, `columnReal`, `columnText`, `columnBlob`, `reset` | \n| `Sqlite3::Step` | `ROW` or `DONE`, what `step` reports | \n \n## Binding and reading \n \nParameter indexes are 1-based, the way SQLite itself counts them in the C \nAPI (`?1` is index 1). Column indexes are 0-based. `bindText` and \n`bindBlob` pass `SQLITE_TRANSIENT` to SQLite, so the bound bytes are \ncopied at bind time and the caller's buffer can go away before `step`. \n`SQLITE_TRANSIENT` is SQLite's own documented sentinel — the \n`sqlite3_bind_text` docs define it as \"a special destructor (...) which \nmakes SQLite copy the bytes\" — spelled here as the pointer value `-1` \nbecause the C header defines it as a cast of -1 to the destructor's \nfunction-pointer type. \n \n`step()` returns `Result::OK(Step::ROW)` for each row and \n`Result::OK(Step::DONE)` when the statement is finished; anything else is \nan `Sqlite3::Error`. Column getters coerce the value the way SQLite does \n(`columnInt` on a TEXT column parses a number); `columnIsNull` tells the \ntwo cases apart that a coercion would blur. After an error the statement \nis reset before reuse. \n \n## Reuse \n \n`reset()` rewinds the statement so it can run again. Bindings survive the \nreset: nothing is cleared, so a parameter that is not bound again keeps its \nprevious value. The statement stays compiled, so a query run many times \nprepares once." }, { "name": "std::sqlite3::transaction", @@ -441,7 +441,7 @@ }, { "name": "std::web", - "doc": " \n# Web \n \nA minimally opinionated web framework in the spirit of Express, built on \n`std::http`. Middleware and routes take the request, the response and the \nnext function, and return `Result`; an error that \nreaches the router becomes a response with its status. \n \n## Exports \n \n| Export | Description | \n|---------------------|---------------------------------------------------------------------| \n| `Web::Router` | `new()`, `use`, `get`, `post`, `put`, `patch`, `delete`, `any`, `route`, `dispatch`; implements `Http::Handler` | \n| `Web::App` | Trait: `build(&self): Web::Router`, called once per server thread | \n| `Web::listen` | Parses `\"127.0.0.1:8080\"` and serves an app with the default configuration | \n| `Web::listenOn` | Serves an app from a host and a port | \n| `Web::listenWith` | Serves an app from an address and a `Web::Config` | \n| `Web::parseAddress` | Parses `\":\"`; `\":8080\"` and `\"*:8080\"` are every interface | \n| `Web::Config` | `threads`; `new()`, `toServerConfig()` | \n| `Web::ListenError` | A failed start; `message()` renders what was expected or the bind failure | \n| `Web::serve` | The layer below: binds a `SocketAddress` and serves an app on `ServerConfig.threads` threads | \n| `Web::serveListener` | The layer below: serves an app on a listener already bound | \n| `Web::Middleware` | `(&mut Request, &mut Response, Next) -> Result` | \n| `Web::Next` | `(&mut Request, &mut Response) -> Result` | \n| `Web::Request` | `http`; `create(&http)`, `method()`, `target()`, `path()`, `header(name)`, `body()`, `bodyText()`, `param(name)`, `query(name)` | \n| `Web::Response` | `status`, `headers`, `body`; `new()`, `setStatus`, `header`, `setHeader`, `addHeader`, `write`, `writeStr`, `text`, `json`, `finish` | \n| `Web::Error` | `status`, `message`; `new(message)` (500), `withStatus(status, message)` | \n| `Web::Param` | One route parameter: `name` and decoded `value` | \n \n## Starting a server \n \n`Web::listen` parses an address string, binds it and serves the app: \n`\"127.0.0.1:8080\"` binds that interface, and `\":8080\"` or `\"*:8080\"` \nbinds every interface, `0.0.0.0`. `Web::listenOn` takes a host and a \nport, `Web::listenWith` a `Web::Config` (the thread count), and \n`Web::parseAddress` parses without serving. A malformed address is a \n`Web::ListenError` whose message names what was expected and what was \ngiven; names are not resolved. `Web::serve` and `Web::serveListener` \nare the layer below: they take the `std::net::SocketAddress` and the \n`std::http::ServerConfig` directly. \n \n## Middleware and routes \n \nBoth have the `Web::Middleware` shape. A middleware added with `use` \nruns for every request, in the order it was added, before the routes. \nCalling `next` runs the rest of the chain and returns once it finished, \nso code after `next` runs on the way back out (the onion model), and an \nerror from `next` propagates with `!` like any other. `next` takes the \nrequest and the response back as arguments: a closure holding them would \nkeep them borrowed for as long as it lives. \n \nA middleware that does not call `next` ends the chain; returning an \nerror does too. A route that calls `next` passes the request to the next \nroute that matches it; when there is none, the answer is 404. \n \n## Routing \n \nA route matches by method and path. `get` also answers `HEAD` (the \nserver sends the head without the body); `any` answers every method; \n`route` takes any method name as written on the request line. \n \nThe path is compared segment by segment, before any `?` and without \ndecoding. A segment `:name` matches any non-empty segment and makes its \npercent-decoded value available as `request.param(\"name\")`; any other \nsegment matches only itself. Every segment counts, so a trailing slash \nis significant: `/users/:id` matches `/users/7` but not `/users/7/`, and \n`/users/` does not match `/users`. A parameter that is not valid \npercent-encoded UTF-8 is answered with 400. \n \nWhen no route matches, the answer is 404. When some route matches the \npath but none its method, the answer is 405 with an `Allow` header \nlisting the methods that would match. Both run through the middleware \nas errors, so a logger sees them. \n \n`request.query(\"name\")` decodes the first query parameter with that \nname: `+` is a space, `%XX` an escaped byte, and a parameter written \nwithout `=` has an empty value. A value that is not valid \npercent-encoded UTF-8 is `NONE`. \n \n## Errors \n \n`Web::Error` carries a status (500 by default) and a message. The router \nanswers an error with that status, `Content-Type: text/plain; \ncharset=utf-8` and the message as the body, keeping header fields that \nwere already set. Client input never makes the router panic. \n \n## Threads \n \nFunction values are neither `Send` nor `Sync`, so a router cannot be \nshared between threads. An application is a record implementing \n`Web::App`; `Web::serve` shares it among `ServerConfig.threads` threads, \neach of which calls `build` once and serves its connections with its own \nrouter through `Http::acceptConnections`. State shared by every thread \nlives in the app record and has to be `Send` and `Sync`, behind an `Arc`, \na `Mutex` or an atomic. \n \nA router is also an `Http::Handler`, so `Http::serveConnection` serves \none connection with it, which is how a test drives it. \n \n## Example \n \n```ignis \nimport Io from \"std::io\"; \nimport Web from \"std::web\"; \n \nfunction logger( \n request: &mut Web::Request, \n response: &mut Web::Response, \n next: Web::Next \n): Result { \n let result: Result = next(request, response); \n Io::println(`${request.method().toString()} ${request.path()} ${response.status}`); \n return result; \n} \n \nfunction showUser( \n request: &mut Web::Request, \n response: &mut Web::Response, \n next: Web::Next \n): Result { \n let Option::SOME(id) = request.param(\"id\") else { \n return Result::ERROR(Web::Error::withStatus(400, \"missing id\")); \n }; \n \n let text: String = String::create(id); \n \n if (text.equals(\"0\")) { \n return Result::ERROR(Web::Error::withStatus(404, \"no such user\")); \n } \n \n response.text(`user ${id}`); \n return Result::OK(()); \n} \n \n@implements(Web::App) \nrecord Users { \n public greeting: str; \n \n build(&self): Web::Router { \n let greeting: str = self.greeting; \n let mut router: Web::Router = Web::Router::new(); \n router.use(logger); \n router.get( \n \"/\", \n (request: &mut Web::Request, response: &mut Web::Response, next: Web::Next): Result -> { \n response.text(greeting); \n return Result::OK(()); \n }, \n ); \n router.get(\"/users/:id\", showUser); \n return router; \n } \n} \n \nfunction main(): i32 { \n let app: Users = Users { greeting: \"hello\" }; \n \n return Web::listen(\"127.0.0.1:8080\", app).isOk() ? 0 : 1; \n} \n```" + "doc": " \n# Web \n \nA minimally opinionated web framework in the spirit of Express, built on \n`std::http`. Middleware and routes take the request, the response and the \nnext function, and return `Result`; an error that \nreaches the router becomes a response with its status. \n \n## Exports \n \n| Export | Description | \n|---------------------|---------------------------------------------------------------------| \n| `Web::Router` | `new()`, `use`, `get`, `post`, `put`, `patch`, `delete`, `any`, `route`, `dispatch`; implements `Http::Handler` | \n| `Web::App` | Trait: `build(&self): Web::Router`, called once per server thread | \n| `Web::listen` | Parses `\"127.0.0.1:8080\"` and serves an app with the default configuration | \n| `Web::listenOn` | Serves an app from a host and a port | \n| `Web::listenWith` | Serves an app from an address and a `Web::Config` | \n| `Web::parseAddress` | Parses `\":\"`; `\":8080\"` and `\"*:8080\"` are every interface | \n| `Web::Config` | `threads`; `new()`, `toServerConfig()` | \n| `Web::ListenError` | A failed start; `message()` renders what was expected or the bind failure | \n| `Web::serve` | The layer below: binds a `SocketAddress` and serves an app on `ServerConfig.threads` threads | \n| `Web::serveListener` | The layer below: serves an app on a listener already bound | \n| `Web::Middleware` | `(&mut Request, &mut Response, Next) -> Result` | \n| `Web::Next` | `(&mut Request, &mut Response) -> Result` | \n| `Web::Request` | `http`; `create(&http)`, `method()`, `target()`, `path()`, `header(name)`, `body()`, `bodyText()`, `param(name)`, `query(name)` | \n| `Web::Response` | `status`, `headers`, `body`; `new()`, `setStatus`, `header`, `setHeader`, `addHeader`, `write`, `writeStr`, `text`, `json`, `finish` | \n| `Web::Error` | `status`, `message`; `new(message)` (500), `withStatus(status, message)` | \n| `Web::Param` | One route parameter: `name` and decoded `value` | \n \n## Starting a server \n \n`Web::listen` parses an address string, binds it and serves the app: \n`\"127.0.0.1:8080\"` binds that interface, and `\":8080\"` or `\"*:8080\"` \nbinds every interface, `0.0.0.0`. `Web::listenOn` takes a host and a \nport, `Web::listenWith` a `Web::Config` (the thread count), and \n`Web::parseAddress` parses without serving. A malformed address is a \n`Web::ListenError` whose message names what was expected and what was \ngiven; names are not resolved. `Web::serve` and `Web::serveListener` \nare the layer below: they take the `std::net::SocketAddress` and the \n`std::http::ServerConfig` directly. \n \n## Middleware and routes \n \nBoth have the `Web::Middleware` shape. A middleware added with `use` \nruns for every request, in the order it was added, before the routes. \nCalling `next` runs the rest of the chain and returns once it finished, \nso code after `next` runs on the way back out (the onion model), and an \nerror from `next` propagates with `!` like any other. `next` takes the \nrequest and the response back as arguments: a closure holding them would \nkeep them borrowed for as long as it lives. \n \nA middleware that does not call `next` ends the chain; returning an \nerror does too. A route that calls `next` passes the request to the next \nroute that matches it; when there is none, the answer is 404. \n \n## Routing \n \nA route matches by method and path. `get` also answers `HEAD` (the \nserver sends the head without the body); `any` answers every method; \n`route` takes any method name as written on the request line. \n \nThe path is compared segment by segment, before any `?` and without \ndecoding. A segment `:name` matches any non-empty segment and makes its \npercent-decoded value available as `request.param(\"name\")`; any other \nsegment matches only itself. Every segment counts, so a trailing slash \nis significant: `/users/:id` matches `/users/7` but not `/users/7/`, and \n`/users/` does not match `/users`. A parameter that is not valid \npercent-encoded UTF-8 is answered with 400. \n \nWhen no route matches, the answer is 404. When some route matches the \npath but none its method, the answer is 405 with an `Allow` header \nlisting the methods that would match. Both run through the middleware \nas errors, so a logger sees them. \n \n`request.query(\"name\")` decodes the first query parameter with that \nname: `+` is a space, `%XX` an escaped byte, and a parameter written \nwithout `=` has an empty value. A value that is not valid \npercent-encoded UTF-8 is `NONE`. \n \n## Errors \n \n`Web::Error` carries a status (500 by default) and a message. The router \nanswers an error with that status, `Content-Type: text/plain; \ncharset=utf-8` and the message as the body, keeping header fields that \nwere already set. Client input never makes the router panic. \n \n## Threads \n \nFunction values are neither `Send` nor `Sync`, so a router cannot be \nshared between threads. An application is a record implementing \n`Web::App`; `Web::serve` shares it among `ServerConfig.threads` threads, \neach of which calls `build` once and serves its connections with its own \nrouter through `Http::acceptConnections`. State shared by every thread \nlives in the app record and has to be `Send` and `Sync`, behind an `Arc`, \na `Mutex` or an atomic. \n \nA router is also an `Http::Handler`, so `Http::serveConnection` serves \none connection with it, which is how a test drives it. \n \n## Example \n \n```ignis \nimport Io from \"std::io\"; \nimport Web from \"std::web\"; \n \nfunction logger( \n request: &mut Web::Request, \n response: &mut Web::Response, \n next: Web::Next \n): Result { \n let result: Result = next(request, response); \n Io::println(`${request.method().toString()} ${request.path()} ${response.status}`); \n return result; \n} \n \nfunction showUser( \n request: &mut Web::Request, \n response: &mut Web::Response, \n next: Web::Next \n): Result { \n let Option::SOME(id) = request.param(\"id\") else { \n return Result::ERROR(Web::Error::withStatus(400, \"missing id\")); \n }; \n \n let text: String = String::create(id); \n \n if (text.equals(\"0\")) { \n return Result::ERROR(Web::Error::withStatus(404, \"no such user\")); \n } \n \n response.text(`user ${id}`); \n return Result::OK(()); \n} \n \n@implements(Web::App) \nrecord Users { \n public greeting: static str; \n \n build(&self): Web::Router { \n let greeting: str = self.greeting; \n let mut router: Web::Router = Web::Router::new(); \n router.use(logger); \n router.get( \n \"/\", \n (request: &mut Web::Request, response: &mut Web::Response, next: Web::Next): Result -> { \n response.text(greeting); \n return Result::OK(()); \n }, \n ); \n router.get(\"/users/:id\", showUser); \n return router; \n } \n} \n \nfunction main(): i32 { \n let app: Users = Users { greeting: \"hello\" }; \n \n return Web::listen(\"127.0.0.1:8080\", app).isOk() ? 0 : 1; \n} \n```" }, { "name": "std::web::listen",