Skip to content

std/tcp

std/tcp — HTTP/1.1 accept loop + handler-friendly env helper. tcp_serve(port, handler) runs an HTTP/1.1 accept loop on port, calling handler(req, plat) once per accepted connection. The plat: Platform capability bag is the seam where future host-side effects (fetch / kv / secrets / log / now) will be plumbed per docs/PLATFORM-RESEARCH.md Rec §1; for Phase 1 it carries a single version: i32 placeholder and handler code typically ignores it. Returns -errno when the listener can’t be bound (e.g. EADDRINUSE); on success the loop runs indefinitely until the host kills the process (no clean-shutdown channel exposed yet). Per-connection lifecycle: 1. tcp_recv up to 8192 bytes (matches http_parse_request’s header-size cap) plus body bytes via a follow-up recv loop driven by Content-Length. 2. http_parse_request — return None ⇒ close the socket without a response (HTTP/1.1 §10 explicitly allows server-side reset on malformed input). 3. handler(req) returns the HttpResponse. 4. http_serialize_response → tcp_send → tcp_close. arm64 wires this through real Linux sockets via the existing fern_tcp* syscall helpers. The wasm side gates tcp* on wasi:sockets at module instantiation; CLI-mode programs that call tcp_serve need a host-pre-opened socket (wasmtime run -S tcp=y). __port_from_env(name, fallback) is the convenience helper the auto-main-from-handle() synthesis uses so handler- shaped programs can be tuned via PORT=N ./bin without a manual main(). Migrated from the auto-injected prelude per docs/PRELUDE-TO-MODULES.md.

pub function tcp_serve(port: i32, handler: (HttpRequest, Platform) => HttpResponse): i32