Skip to main content

core.net.weft

Weft (from the weaver's weft — the cross-thread that binds the warp into fabric) is the Verum server framework. It is designed to be ergonomic like axum, performant like Pingora, resilient like an OTP-supervised Cowboy — and verifiable: refinement-typed routes, effect-checked middleware, dependent-typed protocol state machines, structurally concurrent connection nurseries.

Listener and shutdown coverage

Focused interpreter and native controls preserve the stored values through Shared<AtomicBool> and Shared<AtomicInt>. These atomic checks do not establish a complete listener, cancellation or shutdown lifecycle.

Interpreter HTTP controls cover binary responses, header deadlines and cancellation before reading. Mutex guard lifetime remains incomplete, and native cancellation propagation and end-to-end serving require separate validation. Treat the APIs below as contracts subject to those limits; see async backend coverage and guard lifetime.

This page is the framework's navigational reference. Every section maps a feature area to the actual core/net/weft/*.vr module that implements it and its conformance status.

Architectural pyramid​

+-------------------------------------------------------------+
| L6 APPLICATION user code: handlers, DI, business |
+-------------------------------------------------------------+
| L5 HANDLER / EXTRACT async fn(...) using [...] + extractors|
+-------------------------------------------------------------+
| L4 SERVICE Service<Req, Resp> + Layer |
+-------------------------------------------------------------+
| L3 PROTOCOL HTTP/1.1 / HTTP/2 / HTTP/3 / WS / RPC |
+-------------------------------------------------------------+
| L2 CONNECTION nursery wrapping Transport + FSM |
+-------------------------------------------------------------+
| L1 TRANSPORT TcpStream / TlsStream / QuicStream |
+-------------------------------------------------------------+
| L0 REACTOR IoEngine: io_uring / kqueue / IOCP |
+-------------------------------------------------------------+
| S SUPERVISION supervisor-tree wraps L0..L5 |
+-------------------------------------------------------------+

Layer S is not another stratum but an orthogonal axis: any node from L0 (reactor) to L6 (business) can be a supervised child of an OTP tree. The tree is described declaratively in the root fn main() and validated by types at compile time.

Module map​

ModuleFilePurpose
servicecore/net/weft/service.vrService<Req,Resp> + Layer<Inner> + ServiceBuilder<S> + Identity layer.
errorcore/net/weft/error.vrIntoResponse protocol, WeftError taxonomy, WeftErrorCategory, ExtractRejection.
response_extcore/net/weft/response_ext.vrResponse builders: resp_status, resp_text, resp_with_header, resp_with_body_text, resp_ok.
handlercore/net/weft/handler.vrWeftRequest, Handler protocol, extractors (PathParam<T>, QueryParam<T>, BodyBytes, BodyText), ClosureHandler.
json_extractorcore/net/weft/json_extractor.vrJson<T> extractor with five gates (content-type / size cap / UTF-8 / parse / materialise) plus JsonDeserialize<T> protocol.
routercore/net/weft/router.vrRadix-tree router: route(), get(), post(), put(), delete(), patch(), nest(), fallback().
transportcore/net/weft/transport.vrWeftTransport byte-duplex protocol with blanket TcpStream impl.
connectioncore/net/weft/connection.vrPer-connection HTTP/1.1 pipeline (keep-alive, chunked, drain, serve_http1).
listenercore/net/weft/listener.vrServer<H> plus accept loop, ConnectionRunner protocol, PlainHttp1Runner, SO_REUSEPORT, two-phase shutdown.
appcore/net/weft/app.vrWeftApp.new(handler).bind(addr).serve() plus child_spec() for supervisor integration.
tlscore/net/weft/tls.vrTlsTransport + TlsHttp1Runner + Server<H>.serve_tls(cfg), zero crypto duplicated.
http2core/net/weft/http2.vrHttp2Limits (Rapid-Reset hard defaults), Http2cRunner, Server.serve_h2c().
http3core/net/weft/http3.vrWeftQuicConfig, Http3WeftServer<H>, post-quantum hybrid TLS defaults.
h3core/net/weft/h3.vrWebTransport / Datagrams / Multipath QUIC server adapter.
h3_prioritycore/net/weft/h3_priority.vrRFC 9218 Extensible Priorities — urgency 0..7 + incremental flag.
zero_rtt_gatecore/net/weft/zero_rtt_gate.vr0-RTT replay-safe handler annotation enforcement (@allow_0rtt(idempotent_only=true)).
websocketcore/net/weft/websocket.vrRFC 6455 full handshake, CONT re-assembly, auto-PONG, Close-echo, WsServer<H>.
rpccore/net/weft/rpc.vrConnect-RPC (wire-compatible with gRPC) — 17 status codes plus HTTP mapping plus Router.rpc_unary().
arena_poolcore/net/weft/arena_pool.vrPer-request arena lease with RAII reset-on-drop; CBGR-backed O(1) generational invalidation.
bufpoolcore/net/weft/bufpool.vrBuffer pool shaped for io_uring registered-buffer optimisation (runtime intrinsic is a follow-up).
backpressurecore/net/weft/backpressure.vrConcurrencyLimitLayer, RateLimitLayer, LoadShedLayer, CoDelLayer (sojourn-time admission), tenant-fair WFQ.
adaptivecore/net/weft/adaptive.vrAdaptiveConcurrencyLayer — Vegas algorithm port.
timeoutcore/net/weft/timeout.vrTimeoutLayer.ms(N) per-request deadline propagation.
tracingcore/net/weft/tracing.vrW3C Trace Context propagation, TracingLayer.
metricscore/net/weft/metrics.vrPrometheus-text registry, standard RPS / latency-histogram / connection-count metrics.
metrics_otlpcore/net/weft/metrics_otlp.vrOTLP/gRPC + OTLP/HTTP+JSON push exporter, tail-based sampling hooks, exemplar attach.
healthcore/net/weft/health.vr/_health/live + /_health/ready plus supervisor-state probe and dep-readiness aggregator.
refined_routescore/net/weft/refined_routes.vrPathRefinement<T> plus factories (int_between, text_one_of, slug); bridge to the language refinement system.
spiffecore/net/weft/spiffe.vrPrincipal, SpiffeAuthLayer<P> (JWT / mTLS), TrustBundleProvider.
dstcore/net/weft/dst.vrDeterministic Simulation Testing primitives — TestClock, SeededRng, SimNetworkConfig, TaskSchedule, WeftSimulator.
wasm_filtercore/net/weft/wasm_filter.vrProxy-Wasm 0.2.1 sandbox plus WasmCapabilities plus CPU / memory / instruction caps.

Total: 32 weft modules, plus core/net/proxy/ — the L7 reverse-proxy kit (see below).

core.net.proxy — L7 reverse-proxy kit​

FilePurpose
core/net/proxy/upstream_pool.vrConnection-reuse pool with retire policy.
core/net/proxy/health_check.vrActive and passive probing through HEAD /healthz.
core/net/proxy/loadbalancer.vrRound-robin / Random / Weighted Least-Conn.
core/net/proxy/circuit_breaker.vrThree-state Hystrix-style breaker.
core/net/proxy/retry.vrBounded retry with budget.
core/net/proxy/rate_limit.vrTenant-aware token bucket.

Hello world in 20 lines​

note
Response.ok(...) was not a thing — and nothing in the library was using it either

checked: Response.ok does not exist anywhere in core/, and neither does any construction of the type at all:

grep -rl 'Response\.ok' core/ --include='*.vr' | wc -l # 0
grep -rl 'Response\.new(' core/ --include='*.vr' | wc -l # 0

core/net/http.vr declares Response as a builder — new(status), .status(), .body(List<Byte>), .header() — and Response.new(StatusCode.ok()) compiles.

Worth saying WHY the drift went unnoticed: nothing in core/ constructs an http.Response at all. The type is declared, the weft handlers pass it around in their signatures, and no code path builds one — so no compile ever disagreed with the page. core/net/weft/app.vr carries the same mistake in its own doc comment, with a third spelling (Response.text(...), also absent).

@runtime(work_stealing)
mount core.net.weft.{Router, Method, WeftApp, WeftRequest};
mount core.net.http.{Request, Response, StatusCode};

async fn hello() -> Response {
// NOT `Response.ok(body)` — that constructor does not exist. The type
// is a builder: `new(status)`, then `.status()`, `.body(List<Byte>)`
// and `.header(name, value)`. `StatusCode.ok()` is the 200.
Response.new(StatusCode.ok())
}

// A path parameter is read from the request, not destructured in the
// signature: a pattern like `PathParam(name): PathParam<Text>` is an axum-style
// extractor and does not parse in Verum — a parameter takes an
// identifier, not a tuple-variant pattern. `WeftRequest` carries the
// captures and offers `path_param` / `path_param_int` / `query_param`.
async fn echo_name(req: WeftRequest) -> Response {
match req.path_param(&"name") {
Maybe.Some(name) =>
Response.new(StatusCode.ok()).body(f"Hello, {name}!".into_bytes()),
Maybe.None =>
Response.new(StatusCode.ok()).body("no name".into_bytes()),
}
}

async fn main() {
let app = Router.new()
.route("/", Method.Get, hello)
.route("/hello/:name", Method.Get, echo_name);

// `bind` hands back `Result<Server<_>, Text>` — an address already
// in use is an ordinary error here, not a panic — so it is unwrapped
// before `serve`, which lives on `Server` and not on the `Result`.
// Two fallible steps, and both errors are `Text`: `bind` can fail on
// an address already in use, `serve` on the accept loop.
let outcome = match WeftApp.new(app).bind("0.0.0.0:8080") {
Result.Ok(server) => server.serve().await,
Result.Err(e) => Result.Err(e),
};
if let Result.Err(e) = outcome {
eprintln(&f"server stopped: {e}");
}
}
note
Which Response a weft handler returns

Not weft's own — core/net/weft/mod.vr re-exports it:

public mount core.net.http.{Response, StatusCode, Method, Headers, Version};

So the builders are core/net/http.vr's: new(status), status(code), body(bytes), header(name, value), with StatusCode.ok() for the 200. There is no ok(body) and no text(body) — core/net/weft/app.vr reaches for the latter in its own doc comment and it is not defined either. A 200 with a text body is

Response.new(StatusCode.ok()).body(text.into_bytes())

Do not confuse this with H3Response.ok(body) on the HTTP/3 pages, which is real (core/net/h3/request.vr:139) and takes List<Byte>. Same word, different type, and only one of them has the shortcut.

REST API with DI, validation, errors​

@runtime(work_stealing)
mount core.net.weft.*;
mount core.runtime.{SupervisorHandle, ChildSpec};
// `SupervisorConfig` is the parameter type of `SupervisorHandle.root`, and
// `core/runtime/mod.vr` does not re-export it — the file submodule is the
// only path that resolves.
mount core.runtime.supervisor.{SupervisorConfig};
mount core.database.postgres.{PgAdapter, PgConfig};

type UserId is Int where |n| { n >= 1 };

context Database {
async fn find(id: UserId) -> Maybe<User>;
async fn save(user: User) -> Result<UserId, DbError>;
}

type ApiError is
| NotFound | Validation(Text) | Internal(Text) | Unauthorized;

implement IntoResponse for ApiError {
fn into_response(self) -> Response {
match self {
ApiError.NotFound => resp_not_found(),
// `resp_bad_request()` takes no arguments — the body is
// attached with `resp_with_body_text`.
ApiError.Validation(m) => resp_with_body_text(resp_bad_request(), m),
_ => resp_internal_error(),
}
}
}

async fn get_user(PathParam(id): PathParam<UserId>)
-> Result<Json<User>, ApiError>
using [Database]
{
// `find_user` is your own helper over the narrow `Database`
// context (query / execute / begin / commit / rollback /
// is_connected) — domain queries are not part of it.
let user = find_user(id)
.map_err(|e| ApiError.Internal(f"{e}"))?;
match user {
Some(u) => Ok(Json { inner: u }),
None => Err(ApiError.NotFound),
}
}

async fn main() using [Config] {
// `layer` belongs to `ServiceBuilder`, not to `Router`: the router is
// the innermost service and the builder wraps it. See
// `core/net/weft/service.vr` and the example in `timeout.vr`.
let router = Router.new()
.route("/users/:id", Method.Get, get_user);

let app = ServiceBuilder.new(router)
.layer(TracingLayer.new())
.layer(TimeoutLayer.ms(5000))
.layer(RateLimitLayer.new(1000, 100)) // rps, burst — two Ints
.layer(SpiffeAuthLayer.jwt(Config.get_or("jwt.secret", "")))
.build();

// `Supervisor` is a PROTOCOL and nothing implements it —
// `SupervisorHandle` is the concrete one. `root` for the top of the
// tree, `new` for a subtree.
let root = SupervisorHandle.root(SupervisorConfig.one_for_one("api"));

// The start function belongs to `supervise`, not to the spec: a
// ChildSpec carries restart policy, timeouts and priority, and the
// factory is the other half of the call.
root.supervise(
|| PgAdapter.connect(&PgConfig.new(
Config.get_or("db.host", "localhost"),
5432,
Config.get_or("db.user", "app"),
Config.get_or("db.password", ""),
Config.get_or("db.name", "app"),
)),
ChildSpec.permanent("db"),
).await?;
root.supervise(
// `bind` returns `Result<Server<H>, Text>` and `serve` is the
// SERVER's, so the result is unwrapped first — in a `let`, not
// with `?.`: that is the OPTIONAL-CHAINING operator, which
// resolves through `Maybe` and is a no-op on a `Result`.
|| {
let server = WeftApp.new(app).bind("0.0.0.0:8080")?;
server.serve()
},
ChildSpec.permanent("http"),
).await?;

root.shutdown().await
}

Five distinguishing capabilities​

These five architectural pillars exist individually in other ecosystems; their intersection exists nowhere else.

1. Refinement-typed routes​

type ValidApiVersion is Text where |s| { s == "v1" || s == "v2" || s == "v3" };
type UserId is Int where |n| { n >= 1 && n <= 1_000_000_000 };

async fn get_user(
PathParam(version): PathParam<ValidApiVersion>,
PathParam(id): PathParam<UserId>,
) -> Json<User> {
// The SMT solver has already proved version is one of v1/v2/v3
// and id is in [1, 10^9]. Defensive checks become provably
// unnecessary; unwrap()-style panics become structurally impossible.
}

If anyone forgets to extend ValidApiVersion to include a new version, an old endpoint /api/v4/... breaks at compile time, not as a 4xx in production.

2. Effect-typed middleware​

Computational properties (Pure, IO, Async, Fallible, Mutates, Spawns, FFI) are inferred by the compiler. TracingLayer must be Pure in its composition logic — silently performing a DB call inside wrap leaks into the effect set and is rejected at compile time.

3. CBGR arena as the request-path standard​

core.net.weft.arena_pool simultaneously provides:

  • Zero-allocation request path (Netty class).
  • Memory safety (Rust class).
  • Runtime diagnostics through CBGR — using a stale reference is a controlled error, not undefined behaviour.
  • O(1) destruction through generation bump.

This is not an optimisation; it is a semantic. The user writes handlers in the style of "allocate freely, do not think about it".

4. Supervision tree as the root architecture​

core.runtime.supervisor ships full OTP strategies (OneForOne / OneForAll / RestForOne) with type-safe ChildSpec API. Outside the BEAM ecosystem, no other server framework provides this — Tokio / Hyper / Seastar / Netty rely on Tokio's JoinError::Panic plus manual handling. (Rust spelling, and deliberately so — this sentence is about another ecosystem's API, not Verum's. Verum's own variant is JoinError.Panicked.)

5. Nursery-scoped connections​

A connection is a core.async.nursery. All related tasks (reader, writer, heartbeat, multiplex per stream) are its children. The cancellation tree guarantees: no detached tasks can outlive the connection by construction.

Performance targets​

WorkloadTarget
Plaintext RPS (1 core, 1 conn)>= 180k RPS
Plaintext RPS (56 core, 5000 conn)>= 20 M RPS
Echo TCP latency p50 / p99<= 20 us / <= 80 us
TLS 1.3 handshake (cold)<= 2.5 ms
TLS 1.3 resumption (0-RTT)<= 500 us
HTTP/2 multiplex (1000 streams)>= 1.5 M req/s
WebSocket fan-out (100k subs, 1 msg/sec)<= 50 ms p99 end-to-end
Memory per idle connection<= 8 KB
Graceful restart under 1M req/s0 dropped

Conformance status​

Coverage is recorded by API and backend in the networking verification guide and the conformance inventory. Weft, QUIC, TLS and HTTP protocol suites have different open paths; a single framework pass percentage would conceal those differences. Use the listener and shutdown limits above when assessing the examples on this page.

Tier-0 interpreter networking​

The interpreter implements __tcp_*_raw and __udp_*_raw with OS sockets stored in a thread-local synthetic-fd registry. A script can bind a port and serve traffic through these intrinsics:

mount core.intrinsics.runtime.os.{
__tcp_listen_raw, __tcp_accept_raw,
__tcp_recv_raw, __tcp_send_raw, __tcp_close_raw,
};

fn main() {
let listen_fd = __tcp_listen_raw(7878);
let conn_fd = __tcp_accept_raw(listen_fd);
let req = __tcp_recv_raw(conn_fd, 4096);
let _ = __tcp_send_raw(conn_fd, "HTTP/1.0 200 OK\r\n\r\nhello");
__tcp_close_raw(conn_fd);
__tcp_close_raw(listen_fd);
}

The full Weft stack — through core/net/tcp.vr plus the io-engine async layer — currently goes through AOT only; Tier-0 syscall emulation (accept4, read, write through syscall_raw) is on the roadmap.