tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

306 lignes · 27327 octetsBrut · Historique

ADR 0012: Bytes, builders and HTTP connections

Status: Accepted by the project owner on 2026-10-09 (PRs #54–#59); proposed 2026-10-09 (issue #36); needs engineering review (#44), including the breaking API changes.

Context

  • 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.
  • std/http served one request per connection and closed it (Connection: close). Request bodies needed Content-Length; chunked bodies were not understood.
  • 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.

Decision

Bytes: an immutable byte string, copied when sliced

  • 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.
  • 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).
  • 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.lse sends large and small Bytes on both backends.

API (std/bytes):

FunctionBehaviour
empty, length, concat, concat_allconcat_all allocates once
get(b, i) -> Option<Int>None out of range
slice(b, start, end)both bounds clamped to 0..length; empty when end <= start
from_string, to_string -> Result<String, String>, to_string_lossyUTF-8; the error names the first invalid byte
to_string_range(b, off, len)to_string of slice(b, off, off + len) without the intermediate copy
read_u8, read_u16be, read_u32be, read_u64bebig-endian reads in place, for cursor decoders (the "passes offsets" case); -1 out of range
from_list, to_listList<Int>; from_list panics on an Int outside 0..=255
builder, append, append_string, append_byte, buildsee below

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.

The builder is persistent; appends never copy earlier pieces

  • 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.
  • Semantics: a builder is an ordinary immutable value. Appending to the same builder twice gives two independent builders.
  • 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.
  • Cost today: each append allocates a list cell and a builder cell; append_string and append_byte also copy the piece into new Bytes.

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. (Until issue #129 it didn't: it gathered the parts into a vector, joined them into a buffer, then copied that. Now it sums the lengths, then copies each part into the string once; <>, bytes.concat and bytes.concat_all do the same.)

Network IO is Bytes

  • net.read returns Bytes, and net.write sends Bytes. net.write_string sends text without a conversion.
  • There is no read_string: a read may end inside a UTF-8 character. Callers decode once the data is complete.

HTTP connections

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.

When the connection stays open:

  • HTTP/1.1: unless the request or the response has Connection: close;
  • HTTP/1.0: only if the request has Connection: keep-alive;
  • never after a malformed request: it gets an error response, then the connection closes;
  • when the peer closes the connection or a read fails, the actor stops silently.

The server sets Content-Length and Connection on every response, and replaces those headers if the handler set them.

Framing (request smuggling):

  • A body is sized by Content-Length or by chunks (Transfer-Encoding: chunked, with chunk extensions and trailers, which are ignored).
  • These requests are rejected, because a misread length would make the server read part of a body as the next request:
    • both headers at once (400);
    • a Content-Length that is not a decimal number, or two that differ (400);
    • another transfer coding (501).
  • 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.
  • Expect: 100-continue gets an interim 100 Continue before the body is read. HEAD responses have no body.

Idle timeout:

  • 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.
  • The handler and the response are not timed.
  • 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 selects 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.
  • Once a program opens a socket, the scheduler's clock follows real time, even while every thread is busy (ADR 0004, Revision 3), so the timeout is a real one under load too.

Limits:

  • a request head or chunk-size line over 64 KiB is rejected (431 / 400);
  • bodies have no size limit yet.

Consequences

  • Breaking changes:

    • 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.
    • net.read and net.write use Bytes.
    • http.serve_some is replaced by http.serve_with and Settings.

    The demo and its tests were updated. Clients that read a reply to the end of the stream must now send Connection: close.

  • Cost per connection: two actors. Per request, two messages to the watchdog, plus one for each additional read.

  • Not timed: a client that stops reading a response is not timed out, because writes are not timed.

  • 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.

  • Header values that are not UTF-8 have the invalid bytes replaced.

  • 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.

Alternatives considered

  • 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.
  • 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.
  • Views for slices: see above.
  • 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.

Revision 1 — 2026-10-09: write timeouts, a body limit, in-place builders

Status: Accepted by the project owner on 2026-10-12; needs engineering review (#44). Issue #47.

Context

This ADR left three follow-ups: writes were not timed, so a client that stops reading a response pinned its connection actor (and its socket) forever; request bodies had no size limit; and builder appends allocated a list cell and a builder cell each, because externs borrow their arguments. ADR 0014 adds owned externs, which make in-place appends possible.

Decision

Write timeouts.

  • The connection actor sends its watchdog a third message, Writing, before it writes a response (error responses too). The watchdog then waits write_timeout milliseconds; on timeout it closes the socket, as for the idle timeout. The parked write fails, and the actor stops.
  • The timeout covers the whole response, not each write: the actor makes one net.write per response, and Louise code cannot see its progress. The default is 30 s, so a client that reads slowly but steadily can still download a few hundred megabytes; long downloads need a larger setting.

A request body limit.

  • max_body bytes (1 MiB by default, the usual default of nginx; negative for no limit).
  • A Content-Length over the limit is answered with 413 (Content Too Large) before the body is read, and before 100 Continue, so a client that waits for it does not send the body.
  • Chunked bodies are counted as their chunks arrive: the first chunk that crosses the limit gets the 413, without being read.
  • As with every malformed request, the connection is then closed: the unread body cannot be told apart from the next request.

Settings. Settings(connections, idle_timeout, write_timeout, max_body). Callers start from http.defaults() with a record update, Settings(..http.defaults(), idle_timeout: 200), so further fields do not break them.

Builders append in place.

  • A Builder is a runtime block (TL_TAG_BUILDER): an i64 length, an i64 capacity, then the bytes.
  • append, append_string, append_byte and build are owned externs (ADR 0014). A unique builder grows in place (capacity doubling, realloc); a shared one is copied first, so appending twice to the same builder still gives two independent builders.
  • build turns a unique builder into the Bytes in place: it moves the bytes over the capacity word, changes the tag and shrinks the block, without copying them elsewhere. builder_with_capacity(n) reserves room up front.
  • append_byte panics on an Int that is not a byte (bytes.append_byte: 256 is not a byte); it used to fail inside bytes.from_list.
  • The interpreter keeps a builder as its contents and copies them on each append: same results, different cost.

Consequences

  • Breaking: Settings has two more fields; Settings(n, t) no longer compiles. The demo and the test fixtures use the record update.
  • Cost per request: one more message to the watchdog (Writing).
  • Still not timed: the handler itself. A handler that never returns pins its connection, as before.
  • A large response to a slow client is cut after write_timeout, even if the client is still reading. A per-write deadline in the runtime (the alternative this ADR already prefers to the watchdog) would time progress instead.
  • The demo stops after MAX_CONNECTIONS connections when it is set, so a load test can read the leak oracle at exit (crates/louise/tests/demo.rs, the_demo_under_load, ignored by default).

Verification

  • http_body_limit_and_write_timeout (crates/louise/tests/cli.rs): 413 for a Content-Length and for chunks over the limit, no 100 Continue, a body at the limit accepted, and a client that does not read a 32 MiB response disconnected after 300 ms. The test fails with the write timeout disabled. The leak oracle reads 0 at exit.
  • Unit scenarios in louise_rt/src/builder.rs: appends in place, growth, copies of shared builders, build in place.
  • The load test: 64 keep-alive connections × 500 requests to the demo, release builds. 30,800 requests/s on one scheduler thread and 121,000 on eight (a loaded 22-core machine), every response checked, the leak oracle at 0 after each run.

Revision 2 — 2026-10-15: slow and greedy clients, and name resolution

Status: Proposed; needs engineering review (#44). Issues #220 and #222.

Context

A review of std/http and std/net (issues #220, #222) found ways a few clients can hold a server, or a scheduler thread, with very little traffic:

  • The idle timeout restarts on every read. The connection actor sends Reading before each read, and the watchdog restarts idle_timeout on each one, so a client that sends one byte every few seconds keeps its connection, and its actor, forever ("slowloris").
  • Nothing limits open connections. connections counts accepts in all, and is unlimited by default; each connection is an actor and a socket.
  • A request head is copied and parsed again on every read. receive_more concatenates the unread buffer with what arrives, and parse_head starts over from its beginning: quadratic in the head's size, up to the 64 KiB limit — which is also checked only on a partial head, before the read that may add 64 KiB more.
  • A failing accept loops at once. Out of descriptors (EMFILE), serve_with prints and accepts again, spinning a scheduler thread.
  • Repeated Transfer-Encoding headers are not refused. The first one is read; a proxy that reads the last one frames the request differently (request smuggling, RFC 9112 §6.1 and §6.3).
  • Name resolution runs on a scheduler thread. net.connect and net.listen resolve their host (getaddrinfo) inside the extern, which is not blocking: a slow resolver stalls the thread and every actor queued on it. And the port is truncated to 16 bits (as u16): 65616 is port 80.

Decision

A deadline per request head. Settings gains head_timeout (10 s by default). Once a head has begun — its first bytes read, but not its end — the whole head must arrive within it. The connection actor tells its watchdog once (Activity gains HeadStarted) and then sends nothing more until the head is read, so the watchdog's wait of head_timeout is not restarted by the reads: no clock is needed. idle_timeout keeps timing the wait for a request to start (keep-alive), and each read of a body.

A limit on open connections. Settings gains max_open (512 by default: under the usual descriptor limit of 1024, so the limit is reached before accept fails). serve_with counts the connections it has started and that have not ended: the watchdog, which already learns when its connection's actor stops, tells the acceptor — on that Stopped and also when it closes the connection itself on a timeout. At the limit, serve_with waits for one to end before accepting again; below it, it reads the notices without waiting. connections keeps its meaning: how many to accept in all.

A head is scanned once. Arriving bytes go into a Builder (appended in place, Revision 1). A new extern, tl_http_parse_head_end(bytes, from) -> Int, finds the empty line that ends a head (lines ending in CRLF or a bare LF, as httparse reads them), or -1; each read scans only what it brought, plus the three bytes before it. When the end is found, the head is built once and parse_head runs once. The limit is checked against the head's size after each read and on the parsed head, so 64 KiB means 64 KiB, and a head that arrives whole is checked too. A head whose end is found but which httparse still finds incomplete — empty lines before the request line — gets 400: restarting it would let a client restart head_timeout with empty lines. Bodies and chunks keep their current path.

accept backs off. After a failed accept, serve_with sleeps, from 10 ms doubling to 1 s while it keeps failing, and starts again from 10 ms after a success.

One Transfer-Encoding. parse_head refuses a request with more than one Transfer-Encoding header, as it refuses differing Content-Length values: Invalid, answered with 400 and a closed connection.

Resolution off the scheduler. A new blocking extern (ADR 0005), tl_net_resolve(host, port) -> Result<List<String>, String>, resolves on the blocking pool and returns the addresses as text. connect and listen become Louise functions: they check the port (0 to 65535, else an Error), resolve, then try each address with the existing externs, which resolve an IP literal without a lookup, and return the last error if none works. A literal still takes the round trip to the pool; listen and connect are rare next to reads and writes.

Consequences

  • Breaking: Settings has two more fields. Callers that start from http.defaults() with a record update, as every one in the repository does, are unaffected.
  • A server under a burst of connections waits at max_open instead of failing accept; clients queue in the kernel's listen backlog.
  • A slow client has head_timeout for its whole head, however it trickles it.
  • Cost per request: one more watchdog message when a head starts; no copy of the head per read.
  • Runtime ABI: two new externs (tl_net_resolve, tl_http_parse_head_end); no layout or calling-convention change, so TL_ABI_VERSION stays.
  • Still not timed: the handler, as before. A body trickled slowly is still timed by idle_timeout per read: a body deadline, or a minimum rate, is left for when it is needed (bodies are capped by max_body, 1 MiB by default).
  • Empty lines before a request line are still skipped when the request arrives with them, but give 400 when they arrive alone first (above).

Verification

  • crates/louise/tests/cli.rs, with fixtures in tests/fixtures/http: http_slow_and_greedy_clients — a head trickled a byte every 100 ms closed at the 300 ms head_timeout (the old server kept it as long as the client trickled), a kept-alive connection idle longer than head_timeout but under idle_timeout still served, and with max_open connections held open the next one served only once their watchdogs close them; http_rejects_malformed_requests — a repeated Transfer-Encoding answered 400, a 70 KB head arriving whole and a 64 KiB + 1 head arriving in two reads answered 431. The leak oracle reads 0 at exit.
  • Unit tests of the head's end and of the repeated Transfer-Encoding in louise_rt/src/http.rs; names_resolve_off_the_scheduler_and_ports_are_checked (cli.rs) for resolve and out-of-range ports.
  • The demo under load (the_demo_under_load), with the leak oracle at 0.

Revision 3 — 2026-10-23: kept-alive clients cannot starve waiting ones

Status: Accepted (owner); needs engineering review (#44). Issue #304.

Context

Revision 2's max_open waits for a connection to end before accepting another, but a kept-alive client that keeps sending requests never ends its connection. Under load (toki2's stress test: 800 users against the default 512), the clients beyond max_open were never let in while the others stayed busy, and timed out.

Decision

  • Drain on demand. At max_open, the acceptor still accepts the next client, which proves one is waiting, and holds it (one socket over the limit). It then asks the oldest open connection it has not asked yet to close, and admits the held client when any connection ends. The watchdog closes the asked connection at once if it waits for a request (a new Idle activity, distinct from reading more of a body); otherwise its actor answers the current request with Connection: close. A waiting client gets in within about one response time.
  • max_requests (default 1,000, nginx's keepalive_requests): a connection's last request is answered with Connection: close. It bounds what one connection's actor can accumulate.
  • The acceptor learns of connections from their watchdogs (Opened, with the two subjects that ask it to close, then Ended), and keeps the ones it may ask in a Dict by id: ids grow, so dict.first (new, O(log n)) is the oldest.

Consequences

  • Closing an idle connection races with a request just sent on it, as the idle timeout already did. Clients that retry an idempotent request on a new connection (RFC 9112, section 9.3.1: browsers, k6, Go) see nothing; a bare client sees the connection reset.
  • When more clients want connections than max_open allows, connections rotate instead of some clients starving: the issue's repro (2 places, 3 clients sending every 100 ms) serves all three throughout, each reconnecting about four times a second.
  • A streamed response (ADR 0053), Server-Sent Events included, is not cut: its connection closes when the stream ends. An oldest connection that streams for long therefore delays the held client until another connection ends.

Verification

http_keep_alive_limits (cli.rs, fixture tests/fixtures/http/ keepalive.lse): the third request of a connection answered with Connection: close; at max_open, a client served once the oldest, busy connection ends its response with Connection: close, the younger idle one left open. http_slow_and_greedy_clients now sees the next client served at once, the oldest idle connection closed for it. The leak oracle reads 0 at exit in both.

Revision 4 — 2026-10-23: the client's address

Status: Proposed; needs engineering review (#44). Issue #308.

Context

Request is Request(method, path, headers, body): a handler could not tell which client sent a request, and std/net had no way to ask a connection for its peer. Per-client rate limits, connection caps, access logs and abuse detection all need it; toki2 had to drop a per-client login bucket.

Decision

  • std/net: peer(conn) -> Result<SocketAddress, String>, with SocketAddress(host, port); the host is an IP address as text. The runtime records the peer when it accepts or makes the connection (tl_net_peer), so a connection reset since still answers.
  • std/http: the server reads the peer once per connection and puts it first among every request's headers as the pseudo-header :peer ("127.0.0.1:52144", "[::1]:52144"); http.peer(req) reads it back, None for a request built by hand. A client cannot send it: a header name is a token, which cannot contain : (httparse answers 400; a test pins it).
    • Why not a field: Request(..., peer: Option<SocketAddress>) would be the plainest, but every request built by hand (tests, examples/http_demo, users' handlers' tests) would change. The pseudo-header keeps Request as it is.
    • The cost: it shows in req.headers. http.wire_headers(req) is the headers the client sent, without it: what to forward or log.
  • Proxies: http.client_address(req, trusted): the peer, unless it is one of trusted (exact addresses), in which case the right-most X-Forwarded-For entry that is not trusted (each proxy appends the address it got the request from; the left-most one if all are trusted; the peer if there are none). From an untrusted peer, X-Forwarded-For is ignored: anyone can send it. Address ranges (CIDR) are left for later.

Verification

http_peer.rs (fixture tests/fixtures/http/peer.lse): a handler sees 127.0.0.1 and the client's ephemeral port; client_address through trusted proxies, and ignoring a spoofed X-Forwarded-For; wire_headers without :peer; a client's :peer header refused with 400. tests/run/http_client_address.lse covers client_address's cases on requests built by hand, in both back ends. The tutorial builds a per-client rate limit on it.

Revision 5 — 2026-11-07: larger body limits under some paths

Status: Proposed; needs engineering review (#44): a larger limit is more memory per request, as bodies are read whole.

Context

max_body is one limit for the whole server (1 MiB by default). An app that takes uploads (toki2's attachments, ADR 0080) needs tens of MiB on its upload routes, and raising max_body would raise it on every route, login and search included.

Decision

  • Settings.large_bodies: List<(String, Int)>, [] by default: path prefixes with their own body limits. As Revision 1 intended, a new field does not break callers that start from http.defaults() with a record update; a caller that wrote every field positionally must add this one.
  • Matching: the first entry whose prefix matches the request's path (the target before ?) on whole segments sets the limit: /uploads matches /uploads and /uploads/a, not /uploadsx; a prefix written with its slash (/files/) matches only below it. No match: max_body. List order decides, not length.
  • Matched as written: the path is not percent-decoded, so a client that spells a prefix another way (/upl%6Fads) gets max_body, the smaller limit in any sane setting. An app routes on the decoded path (http.segments); it should not rely on large_bodies for anything but memory.
  • Where: the limit is chosen in request_of, from the parsed head, before read_body. So, as before, a Content-Length over the limit is answered 413 before any byte of the body is read and before 100 Continue, and chunked bodies are counted as their chunks arrive.
  • http.body_limit settings target gives the limit a target gets, for apps and tests.

Verification

  • tests/run/http_body_limit.lse (both back ends): whole-segment matching, the first match winning, a prefix with its slash, the query ignored, an escaped spelling getting max_body.
  • http_body_limit_and_write_timeout (crates/louise/tests/cli.rs, fixture http/limits.lse, now with large_bodies: [("/upload", 64)]): 40 bytes accepted under /upload, 65 bytes refused with 413 and no 100 Continue, and /uploadx kept to max_body.