ecosystem::web is an HTTP server framework with GoML routing, typed extraction, middleware, response construction and server-sent events. HTTP parsing, TCP transport, body streams, deadlines and server shutdown use std::net and std::context. TLS listeners use the public std::net::tls API. The repository contains only GoML implementation and test sources, with no Go adapter or native module configuration.
The design takes inspiration from Axum. It adapts the handler model to GoML closures and garbage collection, rather than reproducing Rust ownership or async futures. The transport supports HTTP/1.1 keepalive, chunked bodies, pipelined requests and 100 Continue.
Chunk-size lines validate extension names, values and quoted escapes before ignoring extension metadata, including extensions on the final zero chunk. Malformed extensions return 400; permitted space/tab around their separators is accepted. Chunk lines remain bounded to 8192 bytes.
Host fields validate the authority syntax before dispatch, including IP-literal brackets, percent escapes and decimal ports. Invalid fields return 400 and close the connection. Accepted host spelling is preserved for handlers; HTTP/1.0 requests can still omit Host.
GoML 0.1.62 or newer is required. This release provides the public std::net::tls pending-accept, explicit-handshake, stream-address and abort APIs used by the server.
Declare an unversioned registry dependency:
[dependencies]
"ecosystem::web" = trueConsumers need only a GoML manifest; no go.mod or native dependency declaration is required. The independent GoML fixture under testdata/downstream/native exercises the registry dependency boundary.
use ecosystem::web::{Router, Response};
use std::time::{Duration};
let router = Router::new().get("/hello/{name}", |request| {
Result::Ok(Response::text(200, "Hello " + request.params().required("name")?))
}).layer(|request, next| {
Result::Ok(next.run(request)?.header("x-service", "example"))
});
let server = router.serve("127.0.0.1:0")?;
println(server.address()?);
server.shutdown(Duration::from_seconds(3))?;
serve binds before returning. Port zero requests an ephemeral port. Keep the application alive until its own shutdown signal, then call shutdown with a positive bound. The example above deliberately shuts down immediately; the downstream fixture's --serve mode waits for standard input to close.
get,post,put,patch,deleteandroute(method, path, handler)create new routers; previous router values retain their routes and layers. Registration errors are retained and returned byvalidate,dispatchorserve.- Patterns support complete
{name}path segments and a final{*path}wildcard. Wildcards require a nonempty remaining path. Repeated capture names, duplicate methods on the same pattern and different capture names for the same route shape are rejected. - Matching prefers literals over parameters over wildcards, independently of registration order. Method selection happens after finding the most specific matching path. A less specific route does not receive a request merely because its method matches.
- Matching splits the escaped path before percent decoding. An encoded slash stays within one capture;
+is literal in paths. Query/form decoding converts+to space. Invalid UTF-8 and malformed percent escapes are recoverable errors. - Paths are case sensitive and preserve repeated or trailing slashes. There is no implicit redirect, slash merging or dot-segment normalization. Route patterns are unescaped absolute paths and reject
%,?,#and malformed braces.Request::pathexposes the escaped path. - GET supplies HEAD unless an explicit HEAD handler exists. HEAD executes the selected handler and middleware, suppresses response bodies and skips stream producers. Known paths supply OPTIONS with
Allow; other unsupported methods return 405. Explicit OPTIONS overrides the automatic response. nestmounts child routes beneath a static prefix without a trailing slash. It wraps their child middleware. The parent's limits and fallback govern the combined router; child limits and fallback are not imported.- Layers execute in registration order, first outermost, including fallback and method-error responses. A
Nextcan be called explicitly; middleware can short circuit, change string attributes, inspect errors, or transform responses. Request-body aliases share one stream cursor. - Application state is captured by handler closures. Use
Channel, atomic types or another synchronized state container for concurrent mutation. Capturing an ordinary mutableRefdoes not make it thread safe.
Request exposes method, escaped path, raw query, headers, path parameters, remote address, host, body, cancellation checks and cancellation-aware waits. Request::scheme() reports http or https from the inbound transport, independent of forwarding headers; dispatch/recording uses http. Headers is an immutable builder with case-insensitive names, duplicate preservation, injection validation and copied entry snapshots.
json[T: Deserialize] accepts application/json and application/*+json with optional parameters. Missing or incompatible content type produces 415; invalid typed data produces 422. JSON output uses Response::json[T: Serialize]. Binary bytes, text, HTML, redirects, custom status and repeated response headers are also supported. HTML output accepts already prepared HTML and does not perform template escaping.
query and form return ordered Pairs, preserving repeated and empty fields. query_as, form_as and Pairs::decode use a GoML Serde deserializer. They support flat derived structs with string, character, boolean, signed/unsigned integer, float, present optional, and repeated vector fields. Numeric conversions retain width/range checks; string values such as 0001 stay strings. Scalar duplicates fail instead of silently taking a first/last value. Vector fields accept one or more occurrences. Unknown fields follow the normal Serde derive behavior; missing fields, including missing optional fields, follow the existing GoML derive's required-field policy. Nested objects, bracket-index conventions, enum fields and arbitrary map roots are not supported by this form format.
Error records a kind and message. Extractor errors become HTTP responses; internal/configuration/transport errors expose a generic message. Middleware can implement a different error response policy. Errors after response headers have been sent abort that stream and connection; they cannot change its HTTP status.
Body::read(maximum) reads up to 1–65536 bytes and returns an empty buffer at EOF. collect(limit) is explicitly bounded. Body implements std::io::Read and Close; StreamWriter implements std::io::Write. io::copy(request.body(), writer) therefore supports a true streaming echo or transform without buffering the whole body.
A transport, framing or request-body-limit failure is terminal for the shared
body stream: subsequent reads return the original error, and the connection
cannot process further requests. Failures known before response headers are
sent also set Connection: close. Invalid read sizes and extraction limits do
not invalidate the transport stream.
Response::stream(status, content_type, producer) invokes the producer while the response is active. StreamWriter::write buffers through the HTTP transport, send writes and flushes, text sends UTF-8, and event sends an SSE event. Each bespoke write/send/text/event call accepts at most 65536 encoded bytes and returns a configuration error above that bound. The standard io::Write implementation uses partial writes of at most 65536 bytes, so write_all/copy handle larger input.
Streaming sends headers before invoking the producer, including when the producer has not yet emitted an event. Writes execute synchronously against the TCP stream; a slow receiver blocks the producer instead of growing a background output queue. Request bodies remain readable while streaming a response. The input reader uses 16 KiB reads and one queued chunk, and the operating system retains its own bounded buffers. HTTP/1.1 streams use chunked framing; HTTP/1.0 streams finish by closing the connection.
SSE supports event name, ID, retry milliseconds and multiline UTF-8 data. CRLF/CR data is normalized into separate data: lines. Event names and IDs reject newline/NUL injection. Response::sse supplies the event-stream content type and cache/proxy buffering headers. Reconnect storage, replay, heartbeat scheduling and application event queues are the application's responsibility.
A request remains active until its response producer finishes. Body/request/writer aliases become invalid after dispatch ends, and late operations return Closed. Request-body reads and response writes are serialized internally. A client disconnect cancels Request::wait, subsequent body operations and writes. Finite streams and cancellation-aware loops should finish their own work before returning; the framework does not join arbitrary goroutines spawned by application code.
request.multipart(ecosystem::mime::multipart::Limits::standard()) opens a bounded, incremental form-data reader. Call next_field() for each field; its public metadata includes name, optional filename, optional content_type, and headers. field.read(maximum) reads at most 65536 bytes, while field.collect(limit) explicitly buffers a bounded field. Moving to the next field drains unread data under the same limits and invalidates the previous handle. Handles also expire when the request ends. Filenames are metadata; applications choose their own storage names and paths.
Declare ecosystem::mime as a direct dependency when configuring multipart limits. Part count, header sizes, individual part bytes and total bytes have independent limits in addition to the router's request-body limit. Invalid dispositions and transfer encodings return 400; exceeded multipart limits return 413. The reader does not write temporary files.
Request-body framing errors retain 400 and the router's body limit retains 413
while reading multipart headers, reading a field or discarding an unread field.
let files = StaticFiles::new("public", 8 * 1024 * 1024)?;
let router = Router::new().get("/assets/{*path}", files.handler("path"))
.layer(Cors::new(Vec::from_array(["https://example.com"]))
.allow_methods(Vec::from_array(["GET", "POST"]))
.allow_headers(Vec::from_array(["content-type"]))
.layer()?)
.layer(compression(1024 * 1024)?);
Import StaticFiles, Cors and compression from ecosystem::web. Close the
static root with files.close() after the server has shut down. Files are read
under the configured byte bound, with MIME types, SHA-256 ETags, conditional
GET/HEAD and a single GET byte range. If-Match uses strong ETag comparison
(or *) and returns 412 on failure before evaluating If-None-Match or ranges.
If-None-Match accepts weak ETags and returns 304 on a match. Commas inside
quoted opaque tags remain part of the tag; * is a wildcard only as the entire
field value. HEAD ignores Range
and reports the full representation length without a body. These checks follow
HTTP conditional and range semantics;
date validators and multipart ranges are not supported. Range units are
case-insensitive; unknown units are ignored and receive the full 200 response.
Byte positions use overflow-safe decimal parsing: oversized last positions
clamp to the last byte, oversized suffix lengths select the whole file, and
oversized first positions are unsatisfiable. Leading zeroes are accepted;
nondigits, reversed ranges, zero suffix lengths, integer ranges on empty files
and multiple byte ranges receive 416. A valid nonzero suffix range on an empty
file is ignored and receives an empty 200 response. Numeric overflow never makes a valid suffix
or last position fail (RFC 9110, byte ranges).
There is no directory listing or implicit index file. Descriptor-relative opening rejects symlinks, dotfiles and traversal components, including decoded route captures; only regular files are served. The implementation uses the existing Linux file-descriptor API.
Cors validates explicit origins, methods and headers, handles preflight requests, and maintains Vary: Origin. Builders also configure exposed headers, credentials and preflight cache age. Credentialed requests require explicit origins; a wildcard origin cannot enable credentials. Disallowed origins, methods and requested headers receive 403.
compression(max_bytes) negotiates gzip and identity using Accept-Encoding
quality values. Coding names and the q parameter name are case-insensitive,
as required by RFC 9110 section 12.4.2.
It compresses buffered responses within the bound, preserves Vary, weakens
representation ETags, and removes Content-MD5, Digest, Content-Digest and
Repr-Digest after transforming the body. The latter two fields depend on the
encoded bytes (RFC 9530); responses
that are not transformed keep their digest fields. Existing encodings, range
responses, upgrades, streams/SSE and Cache-Control: no-transform remain outside
compression. If no available representation is acceptable it returns 406.
Statuses 204, 205 and 304 keep empty bodies regardless of encoding preferences;
response validation rejects buffered content and stream producers for these
statuses. A 205 response retains ordinary Content-Length: 0 framing.
Streaming responses retain their existing bounded transport behavior.
When combined with StaticFiles, compression selects the complete response's
encoding before evaluating If-Match, If-None-Match and ranges. A gzip 304
keeps the same weak ETag as its corresponding 200; an identity response retains
its strong ETag. This lets caches refresh the representation under
RFC 9111 section 4.3.4.
An unacceptable encoding produces 406 before conditional checks. For otherwise
unencoded static responses, supported byte ranges select identity, which must
still be acceptable; an unusable If-Range ignores the range and allows the full
response to use gzip. HEAD uses the corresponding full GET representation's
encoding and validator; 304 has neither body bytes nor Content-Length.
Inner middleware sees the complete static response before these checks, so its
ETag, encoding and no-transform changes participate in selection. Replacing
that response with a new response or stream transfers responsibility for
conditional handling to the replacement. Nested compression layers finalize
static conditions only after the outermost layer has selected the response.
When conditions remove or slice content, stale Content-Digest and
Content-MD5 fields are removed. A 206 or 304 retains the complete selected
representation's Repr-Digest and legacy Digest; empty 412/416 errors discard
those representation digests too. Middleware that supplies Content-Digest
for HEAD must calculate it over empty content, while Repr-Digest can describe
the corresponding full GET representation.
Custom handlers that directly return 304 remain responsible for evaluating
conditions against their final representation; compression cannot infer an
absent representation's size or encoding from a 304 alone.
These facilities are opt-in router layers. Session and limiter state is shared
by copies of the same store and serialized internally. They use GoML code and
std::crypto::rand operating-system entropy, without additional dependencies.
use ecosystem::web::{Router, Response, SessionStore, SessionOptions, Csrf};
use ecosystem::web::{RateLimiter, RateLimitOptions};
let sessions = SessionStore::new(SessionOptions::new())?;
let limiter = RateLimiter::new(RateLimitOptions::new())?;
let router = Router::new()
.get("/csrf", |request| {
Result::Ok(Response::text(200, request.session()?.csrf_token()?))
})
.post("/preference", |request| {
request.session()?.insert("theme", request.text()?)?;
Result::Ok(Response::new(204))
})
.layer(limiter.layer())
.layer(sessions.layer())
.layer(Csrf::new(Vec::from_array(["https://app.example"])).layer()?);
Layers run in registration order: rate limiting first prevents rejected traffic
from allocating sessions; sessions must precede CSRF. Serve this configuration
through HTTPS. Fetch the token response using the session cookie, then send it
in X-CSRF-Token with the browser's Origin on every state-changing request.
Tokens belong in response bodies and request headers, never URLs or logs.
Request::session() exposes get, insert, remove, csrf_token, rotate
and logout. Values are strings stored only on the server. IDs and CSRF tokens
are independently generated 256-bit random values encoded as lowercase hex.
The cookie carries only the opaque session ID. Unknown, malformed, expired or
revoked IDs receive a fresh anonymous session with a newly generated ID;
client-supplied IDs are never adopted. Duplicate named cookies and whitespace
before the named cookie's = return 400.
This follows the strict session lifecycle described in the
OWASP session guidance.
After successfully authenticating credentials or changing privileges, call
rotate() before saving the new authentication state. Rotation preserves data
and the absolute expiry, changes both ID and CSRF token, and immediately
invalidates the old ID. Previously opened handles for the old ID cannot restore
it. logout() removes server state and expires the cookie. SessionStore::clear
revokes every stored session. Neither method supplies authentication or
application authorization; handlers must implement those checks.
SessionOptions::new() limits the store to 4096 sessions, 64 fields and 16384
combined key/value bytes per session. Idle timeout is 1800 seconds and absolute
lifetime is 86400 seconds; accepted requests refresh only the idle timestamp.
The store never evicts active sessions to admit new ones: exhausted capacity
returns 503. Expiration is checked on access; a capacity-pressure scan and
len() also reclaim expired records. There is no background cleanup task.
Fields exceeding configured bounds return BodyLimit without changing data.
Individual operations are synchronized; a separate get followed by insert
is not an atomic read-modify-write transaction.
The default cookie is __Host-goml_session, Secure, HttpOnly, Path=/,
SameSite=Lax, with no Domain and a Max-Age equal to the remaining absolute
lifetime rounded up to seconds. Server-side expiry remains exact even during
that final fraction of a second. SessionCookie builders configure name, path, domain, Secure and
SameSite::{Strict,Lax,None}. Prefix invariants are validated and SameSite=None
requires Secure; HttpOnly is always set. Local HTTP development requires both
an ordinary cookie name and explicit with_secure(false). Domain sharing
expands trust to sibling hosts, so retain the default host-only policy when
possible. Session responses use Cache-Control: no-store.
Make session changes before the handler returns. Handles are sealed before response streaming and become unusable after a response, so a stream producer cannot rotate a cookie after headers have been decided. A handler error or panic can leave a newly allocated session without a delivered cookie until expiry, within the fixed capacity. Records and tokens live in process memory; there is no persistent/distributed backend or cross-process revocation.
Csrf::new(origins).layer() implements a
synchronizer token
check using the session token. Only GET, HEAD and OPTIONS bypass the check;
these handlers must avoid state-changing application actions. Every other
method requires exactly one Origin matching an explicitly configured HTTP(S)
origin and exactly one valid token header. Missing Origin, null, wildcards,
duplicate headers and token mismatches fail with 403. Origin comparisons are
exact; configure the browser's serialized origin, without a trailing slash,
credentials, query or fragment. Host, Referer and forwarding headers never
establish trust. with_header changes the token header name.
Verification compares all 64 bytes for equal-length tokens using
std::crypto::digest_equal; GoML does not promise compiler-enforced constant
time. There is no form-body token extraction, Referer fallback, Fetch Metadata
policy or automatic CORS registration. Credentialed cross-origin frontends
must configure the separate CORS layer consistently. Session rotation requires
clients to fetch or receive the new token.
RateLimitOptions::new() permits a burst of 60 requests per key and replenishes
one token each 1000 milliseconds. It retains at most 4096 keys, each at most
256 bytes; idle records are eligible for removal after 60000 milliseconds.
idle_milliseconds must be at least burst * refill_milliseconds, ensuring
that eviction cannot restore tokens sooner than a full refill. At capacity,
unexpired keys are retained and new keys receive 503; an exhausted existing
bucket receives 429. Both include a positive, rounded-up Retry-After value
(the capacity response uses one second as a retry hint).
layer() groups requests by the actual socket peer IP, excluding the ephemeral
port, and ignores Forwarded and X-Forwarded-For. layer_by supplies a custom
request-to-key function; use it after verified identity middleware for account
limits, or with an explicitly authenticated proxy policy. For dispatch tests
without a socket peer, use layer_by. check(key) exposes the same atomic
bucket decision without HTTP, including remaining tokens and capacity status.
len() reports allocated buckets, including idle buckets until a later
capacity-pressure scan.
Both stores offer with_clock(options, () -> i64) for deterministic millisecond
clocks; defaults use elapsed monotonic time. Regressions clamp to the last
observed value. Clock callbacks run under the store lock and must be fast and
must not reenter that store. These are per-process limits, not distributed
quotas or a replacement for ingress connection/body limits.
Limits::new sets a 1 MiB request body limit, 1 MiB extraction limit, 1024 query/form fields, 4 MiB captured response limit, 30-second total request timeout, 5-second header timeout, 32 KiB header limit and 256 concurrent requests. header_bytes is an exact bound including the request line, CRLF delimiters and final empty line; trailers have a separate bound of the same size. Both known-length and chunked bodies are checked. Ambiguous Content-Length/Transfer-Encoding framing, duplicate framing headers, invalid header names and control-byte injection are rejected. Concurrent admission rejects excess requests with 503 without building an unbounded wait queue. Idle keepalive connections do not occupy request slots; accepted connections have a separate cap of concurrent_requests + 256. Idle connections expire after 60 seconds.
The total request context and connection deadlines bound body reads, writes and cooperative work. Request::check and wait are suitable for application loops and external cancellation-aware operations. Arbitrary CPU loops, sleeps and foreign calls that ignore cancellation cannot be forcibly preempted. They continue to occupy an admitted slot. Expired connections are closed instead of reusing a cancelled HTTP connection context.
Shutdown first stops accepting connections, closes idle connections and waits for active requests. On timeout it forcibly closes connections and cancels their request contexts, returning Timeout. Concurrent shutdown calls share the first result and each caller has its own bound while waiting. Repeated shutdown is safe. Forced shutdown cannot terminate an uncooperative application function; it releases transport resources and relies on that function to observe cancellation.
Handlers, middleware, fallbacks and stream producers run inside std::panic::catch boundaries. Callback panics unwind their deferred cleanup and become an Internal error without exposing the panic payload. Before response headers are sent, the server returns a generic 500 and closes that connection. After headers are sent, including when a stream producer panics before its first write, the server aborts the stream and closes the connection without changing its status or writing a successful terminal chunk. The request's admission slot and transport resources are released, and other requests continue normally. Ordinary Result::Err values and cancellation retain their existing behavior. A panic propagated by a handler-owned task::scope is caught when it reaches that handler; detached application goroutines need their own recovery boundaries.
dispatch(method, target, headers, bytes) runs the same GoML routing and body/stream machinery against an in-process response recorder. It does not open a socket. Handler-produced error responses remain ordinary captured responses; callback panics, transport body-limit, timeout and capture-limit failures return Err. A panic returns a generic Internal error, and request/writer aliases expire before dispatch returns. Targets must use origin form (/path?query). Captured responses copy their bytes on access.
ecosystem::web::testing adds a reusable dispatch recorder with exchange
history, a loopback HTTP test-server wrapper, and scripted fault dispatches.
The child package reuses this router and server implementation; see its
testing/README.md for the bounded behavior and failure modes.
ecosystem::web::proxy adds a bounded reverse-proxy handler using the existing
request client. It strips hop-by-hop and untrusted forwarding headers on both
legs, retains duplicate end-to-end headers, passes backend redirects through,
and propagates the incoming cancellation context. See proxy/README.md
for body limits, response mapping and unsupported upgrade/streaming cases.
The listener serves HTTP/1.1 and HTTP/1.0 over TCP or TLS. Responses with status
200 and above receive a current UTC Date field when no explicit Date was
supplied, including responses that reject a request before routing. The IMF-fixdate formatter reuses
ecosystem::datetime calendar conversion and preserves forwarded origin dates.
HTTP/2 and HTTP/3 remain unsupported. WebSocket upgrade is an explicit response operation; arbitrary connection hijacking is not exposed. Multipart, static files, CORS and buffered gzip compression have the bounds described above.
Run from this library repository:
(cd ../workflows && just ecosystem-test --goml ../../goml/stage2/bin/goml web)GoML black-box tests, independent downstream tests and cached rebuild checks cover
routing, typed payloads, request/body limits and lifecycle.
The downstream fixture sends 120 generated Unicode query/form requests through
ecosystem::request, exercises concurrent requests and checks real HTTP status
codes and duplicate headers. GoML std::process invokes curl as an independent
HTTP client for a 200 KiB chunked binary upload and a timed SSE disconnect; it then
asserts producer cleanup. Streaming events, shared counters and deadline responses
are tested over actual loopback connections. GoML TCP tests cover early stream
arrival, backpressure, admission, idle keepalive, graceful/forced shutdown,
request framing, panic isolation, deferred cleanup and transport failures. The shared verifier runs generated tests
under the race detector.
Router::serve_tls(address, TlsConfig::new(certificate_pem, private_key_pem)) starts an HTTPS listener with the same routing, streaming responses, limits and graceful shutdown behavior as serve. PEM inputs are std::bytes::Bytes; invalid certificates and keys fail before a listener is published. with_minimum_version(tls::Version::Tls13) raises the default TLS 1.2 minimum. with_handshake_timeout(Duration) controls each connection's positive handshake deadline (default ten seconds). Handshakes run per connection, so a stalled client does not block acceptance of other clients. ALPN advertises http/1.1.
The transport uses std::net::tls::{ServerConfig, TlsListener, TlsStream}. Pending accepts keep handshakes independent, and peer addresses remain available to handlers and rate limiting. Cancelling a context during a TLS read or write closes that connection and interrupts blocked transport work. Shutdown uses the stream’s explicit abort() operation to interrupt sockets immediately. GoML TLS integration tests cover certificate validation, TLS 1.3, ALPN, peer addresses, stalled and failed handshakes, cancellation and graceful/forced shutdown. Fixed PEM fixtures in testdata/tls replace runtime certificate generation. The same tests run under the race detector; no test Go module or Go FFI is needed.
Use Response::websocket(request, selected_protocol, websocket::Limits::standard(), handler) in a route. It validates an HTTP/1.1 GET handshake and returns a 101 response. selected_protocol is an optional offered subprotocol. Applications can inspect request.websocket(limit) to authorize the target, origin and proposed protocols before accepting the upgrade.
use ecosystem::web;
use ecosystem::websocket;
fn routes() -> web::Router {
web::Router::new().get("/socket", |request| {
web::Response::websocket(
request,
Option::None,
websocket::Limits::standard(),
|connection, context| {
let message = connection.receive(context).map_err(
|error| web::Error::new(web::ErrorKind::Transport, error.message),
)?;
connection.send(message, context).map_err(
|error| web::Error::new(web::ErrorKind::Transport, error.message),
)
},
)
})
}
The handler receives the existing WebSocket connection API and a request context. Frames already buffered after HTTP headers are preserved. The handler runs within the configured request timeout, participates in graceful shutdown, and its connection closes when it returns or panics. Choose a suitable Limits.request_timeout for long sessions. Both TCP and TLS listeners support upgrades. HTTP dispatch/recording without a live connection rejects an upgrade, and upgrade responses cannot carry ordinary response bodies. WebSocket extensions are not negotiated.
Use GoML 0.1.62 or newer. The independent GoML fixture is in testdata/downstream/native/; it retains a separate manifest and resolves the library through the isolated registry. From the library root, run:
(cd ../workflows && just ecosystem-test --goml ../../goml/stage2/bin/goml web)The ecosystem verifier builds and tests the fixture against an isolated registry snapshot and runs the library-specific smoke and compatibility checks.