| @@ -0,0 +1,89 @@ |
| 1 | +# ADR 0012: Bytes, builders and HTTP connections |
| 2 | + |
| 3 | +**Status:** Proposed — 2026-10-09 (issue #36). Runtime and library architecture: awaits engineering review. |
| 4 | + |
| 5 | +## Context |
| 6 | +- `Bytes` was declared in the prelude, and the ABI reserved `TL_TAG_BYTES`, but there were no operations. Binary data went through `String`: network reads replaced invalid UTF-8, so HTTP could neither receive nor send binary bodies. |
| 7 | +- `std/http` served one request per connection and closed it (`Connection: close`). Request bodies needed `Content-Length`; chunked bodies were not understood. |
| 8 | +- `string.join` appended each part to its accumulator, copying it every time. `html.render` joins its parts, so rendering was quadratic: a 30,000-row page took over a minute. |
| 9 | + |
| 10 | +## Decision |
| 11 | + |
| 12 | +### `Bytes`: an immutable byte string, copied when sliced |
| 13 | +- **Representation:** a `TL_TAG_BYTES` block, as the ABI already defined: an `i64` length, then the bytes. Strings have the same layout plus a NUL, so the runtime reads both through one accessor. Converting between them copies; `bytes.to_string` validates UTF-8. |
| 14 | +- **No views.** `slice` copies. A view would need another block kind (a scanned parent field and an offset) and would keep a large buffer alive for a small slice. Code that walks a buffer passes offsets instead (as `std/http` does). |
| 15 | +- **Sending:** large `Bytes` are shared, not copied, when the sender keeps them. `send.rs` already promoted strings and byte strings above 4 KiB; a unit scenario now checks it for `Bytes`, and `tests/run/bytes.til` sends large and small `Bytes` on both backends. |
| 16 | + |
| 17 | +**API (`std/bytes`):** |
| 18 | + |
| 19 | +| Function | Behaviour | |
| 20 | +|---|---| |
| 21 | +| `empty`, `length`, `concat`, `concat_all` | `concat_all` allocates once | |
| 22 | +| `get(b, i) -> Option<Int>` | `None` out of range | |
| 23 | +| `slice(b, start, end)` | both bounds clamped to `0..length`; empty when `end <= start` | |
| 24 | +| `from_string`, `to_string -> Result<String, String>`, `to_string_lossy` | UTF-8; the error names the first invalid byte | |
| 25 | +| `from_list`, `to_list` | `List<Int>`; `from_list` panics on an Int outside `0..=255` | |
| 26 | +| `builder`, `append`, `append_string`, `append_byte`, `build` | see below | |
| 27 | + |
| 28 | +The prelude gives `Bytes` `Eq`, `Ord` (lexicographic: a prefix is smaller), `Hash` (the strings' FNV-1a) and `Debug` (`b"..."`: printable ASCII as is, other bytes escaped). The interpreter implements the same functions, so programs print the same on both backends. |
| 29 | + |
| 30 | +### The builder is persistent; appends never copy earlier pieces |
| 31 | +- **Representation:** `Builder(parts)`, the pieces appended so far, most recent first. `append` conses a piece; `build` sizes the result once and copies every piece exactly once. Building is linear in the total size. |
| 32 | +- **Semantics:** a builder is an ordinary immutable value. Appending to the same builder twice gives two independent builders. |
| 33 | +- **Why not append in place when the builder is unique.** That is the usual Perceus approach (FBIP), but externs *borrow* their arguments (ABI Revision 1). A borrowed argument with `rc == 1` may still be used by the caller after the call, so the runtime cannot tell a last use from a borrow; mutating it would break immutability. In-place appends need an extern parameter that Perceus passes *owned*, which is a Perceus change. The builder's functions do not expose its representation, so it can move to an in-place buffer later without changing callers. |
| 34 | +- **Cost today:** each append allocates a list cell and a builder cell; `append_string` and `append_byte` also copy the piece into new `Bytes`. |
| 35 | + |
| 36 | +**Strings:** `string.join` is a runtime function that sizes its result once (`string.concat` joins without a separator). `html.render` collects its parts in reverse and concatenates them once, so rendering is linear. The html benchmark now renders 200,000 rows. |
| 37 | + |
| 38 | +### Network IO is `Bytes` |
| 39 | +- `net.read` returns `Bytes`, and `net.write` sends `Bytes`. `net.write_string` sends text without a conversion. |
| 40 | +- There is no `read_string`: a read may end inside a UTF-8 character. Callers decode once the data is complete. |
| 41 | + |
| 42 | +### HTTP connections |
| 43 | +**One actor per connection** reads a request, runs the handler, writes the response, and loops (keep-alive). Requests on one connection are handled one at a time; pipelined requests are answered in order, from the same buffer. |
| 44 | + |
| 45 | +**When the connection stays open:** |
| 46 | +- HTTP/1.1: unless the request or the response has `Connection: close`; |
| 47 | +- HTTP/1.0: only if the request has `Connection: keep-alive`; |
| 48 | +- never after a malformed request: it gets an error response, then the connection closes; |
| 49 | +- when the peer closes the connection or a read fails, the actor stops silently. |
| 50 | + |
| 51 | +The server sets `Content-Length` and `Connection` on every response, and replaces those headers if the handler set them. |
| 52 | + |
| 53 | +**Framing (request smuggling):** |
| 54 | +- A body is sized by `Content-Length` or by chunks (`Transfer-Encoding: chunked`, with chunk extensions and trailers, which are ignored). |
| 55 | +- These requests are rejected, because a misread length would make the server read part of a body as the next request: |
| 56 | + - both headers at once (400); |
| 57 | + - a `Content-Length` that is not a decimal number, or two that differ (400); |
| 58 | + - another transfer coding (501). |
| 59 | +- The runtime parses heads and chunk-size lines with httparse. Both parsers take a buffer and an offset and return offsets, so a buffer holding many pipelined requests or small chunks is not copied per item. Large bodies are accumulated with a builder. |
| 60 | +- `Expect: 100-continue` gets an interim `100 Continue` before the body is read. HEAD responses have no body. |
| 61 | + |
| 62 | +**Idle timeout:** |
| 63 | +- A connection that waits longer than the idle timeout for a request, or for more of one, is closed. The default is 5 s; `http.serve_with(server, Settings(connections, idle_timeout), handler)` changes it. |
| 64 | +- The handler and the response are not timed. |
| 65 | +- **How:** each connection actor starts a *watchdog* actor, which monitors it. Before each read, the connection actor sends the watchdog `Reading`; before running the handler, it sends `Handling`. The watchdog `select`s on these messages and on the monitor's `Down`, with the idle timeout while the connection is reading. On timeout, it shuts the socket down; the parked read then returns the end of the stream, and the connection actor stops normally. On `Down`, which also arrives when the handler crashed, the watchdog stops and releases its reference to the socket. |
| 66 | +- While an actor waits on a socket, the scheduler's clock follows real time, so the timeout is a real one. |
| 67 | + |
| 68 | +**Limits:** |
| 69 | +- a request head or chunk-size line over 64 KiB is rejected (431 / 400); |
| 70 | +- bodies have no size limit yet. |
| 71 | + |
| 72 | +## Consequences |
| 73 | +- **Breaking changes:** |
| 74 | + - `Request.body` and `Response.body` are `Bytes`. `http.text`, `http.html` and the new `http.response(status, content_type, body)` build responses; `http.body_text` and `http.form_body` decode requests. |
| 75 | + - `net.read` and `net.write` use `Bytes`. |
| 76 | + - `http.serve_some` is replaced by `http.serve_with` and `Settings`. |
| 77 | + |
| 78 | + The demo and its tests were updated. Clients that read a reply to the end of the stream must now send `Connection: close`. |
| 79 | +- **Cost per connection:** two actors. Per request, two messages to the watchdog, plus one for each additional read. |
| 80 | +- **Not timed:** a client that stops reading a response is not timed out, because writes are not timed. |
| 81 | +- **Restarts:** connections accepted before the listener's actor was restarted keep serving with the handler they started with. In the demo, a kept-alive browser connection after `/admin/restart` still talks to the old store, which is gone. |
| 82 | +- **Header values** that are not UTF-8 have the invalid bytes replaced. |
| 83 | +- **C bindings** have no `tl_bytes_*` accessors yet. `tl_string_ptr` and `tl_string_len` happen to work on `Bytes`, because the layouts agree, but that is not a documented contract. |
| 84 | + |
| 85 | +## Alternatives considered |
| 86 | +- **Socket deadlines in the scheduler:** a parked IO wait with a deadline, and a `net.read` with a timeout. This needs one actor less per connection and no message per read. It was deferred because it changes the scheduler, which is being reworked; it should replace the watchdog then. |
| 87 | +- **Killing the connection actor on timeout**, instead of closing its socket. The timeout can race with the `Handling` message, so a kill could interrupt a handler that just started. Closing the socket can at worst fail the response. |
| 88 | +- **Views for slices:** see above. |
| 89 | +- **Text request bodies, with a separate `Text | Binary` body type for responses.** A `Text` response would avoid copying a rendered page into `Bytes`. One body type is simpler, and the copy is small next to the rendering. |