Case: Building a Http server app
A station client sends its name to a report service. The service validates the request and acknowledges it. Follow the server and the client that connects to it. For individual client capabilities, start with HttpClient and HTTP.
| Step | Client | Server |
|---|---|---|
| Prepare | Build a report containing the station name Café |
Listen on loopback and accept an exchange |
| Submit | POST JSON to /reports with application/json content |
Parse the body and require a string-valued station |
| Acknowledge | Check the status and read the acknowledgement | Return 201 with {"accepted":true} |
| Reject bad input | Handle the error status explicitly | Return 400 for invalid JSON/report data, or 404 for an unknown route |
| Finish | Report the result to the caller | Complete the response and close the exchange |
This case acknowledges a report; it does not save it. The downloadable project contains the client, server, shared JSON/error code and an interoperability verifier. Use the setup guide for the matching runtime and compiler.
Start web applications with Serve
Use HttpServer.Serve(handler) for application hosting with a matching development
toolchain after Preview 16. The canonical callback receives an HttpContext and
returns Task<Result<unit, HttpError>>. Configure context.Response or use
context.Respond / context.RespondText, then return success. The server sends
the response and owns completion and cleanup; do not call Complete inside the
callback. Route selection, JSON parsing and acknowledgement logic belong there.
async func Handle(context: HttpContext) -> Task<Result<unit, HttpError>> {
context.RespondText(HttpStatusCode.OK, "Hello from neoCLR")
return Ok(())
}
Start the listener and await its lifetime in async Main:
async func Main() -> Task<()> {
let Ok(server) = HttpServer.Listen("127.0.0.1", 8080, 64) else {
Panic("Could not listen")
}
let result = await server.Serve(Handle)
server.Close()
if let Failure(error) = result {
Panic(error.ToString())
}
}
Download the context callback sample. The server supervises up to 16 concurrent exchanges.
A normal application's shutdown signal can be different. Awaiting Serve's lifetime
task is correct and does not serialize callbacks; retain the task only when you
need to coordinate other work before awaiting it. Handle its Result. Close closes
connections, then the lifetime task joins all started handlers. It does not drain
in-flight responses successfully or forcibly cancel arbitrary callback work.
Async handlers can suspend while other requests advance. Neither calling a task without awaiting it nor the cooperative dispatcher guarantees execution on another thread. Blocking synchronous code can stall other requests. See the Serve contract.
Lower-level example: accept requests in a loop
The downloadable JSON interoperability samples below retain explicit context
ownership and a bounded sequential loop so their verifiers can finish. They
demonstrate request/response operations, not the recommended hosting pattern for
concurrent web applications. ServeOne similarly handles only one exchange.
The listener and the application model are separate. This sample calls
HttpServer.Listen("127.0.0.1", 0, 4) once, then repeatedly awaits Accept().
Each successful accept gives the application one HttpContext. Configure
chooses the response; Complete sends it and ends the exchange.
The loop below is extracted from the downloadable server:
async func Serve(server: HttpServer, count: int) -> Task<Result<unit, AppError>> {
var index = 0
while index < count {
let accepted = await server.Accept()
if let Failure(reason) = accepted {
// Accept already closes the rejected connection and releases its slot.
// Count rejected attempts too, so the sample has a bounded lifetime.
if reason is HttpError.Protocol(_) || reason is HttpError.LimitExceeded(_) || reason is HttpError.Unsupported(_) {
index += 1
continue
}
return Failure(AppError.Http(reason))
}
let Ok(context) = accepted else {
return Failure(AppError.Body("Missing accepted request"))
}
// Close the owned exchange before propagating a configuration failure.
let configured = await Configure(context)
if let Failure(error) = configured {
context.Close()
return Failure(error)
}
let sent = await context.Complete()
if let Failure(sendError) = sent {
return Failure(AppError.Http(sendError))
}
index += 1
}
return Ok(())
}
This example handles exchanges sequentially and stops after a configured number of attempts so the verifier can finish. Rejected protocol, limit and unsupported requests count toward that limit and leave the server listening. Other failures end the sample. Accept cleans up rejected exchanges; configuration failures close the acquired context explicitly, and Complete closes it after sending or failure. The program's completion callback closes the listener.
Configure is where this application chooses its model. The later routing and
attribute-mapper examples change dispatch inside the handler; they do not require
a different listening model in these fixtures. With Serve, use a context callback returning Task<Result<unit, HttpError>>
and leave response completion to the server. With manual
acceptance, await context acquisition, then supervise bounded processing tasks if
concurrency is needed; simply ignoring them loses error and lifetime observation.
A long-running application also needs an explicit
shutdown policy. Accept(token) supports cancellation, while server.Close()
stops the listener and closes its owned exchanges; it does not drain handlers.
See exchange ownership and limits.
Server: validate and acknowledge
async func Configure(context: HttpContext) -> Task<Result<unit, AppError>> {
let request = context.Request
if request.Method.Method == "GET" && request.Target == "/report" {
let report = CreateReport()?
let content = JsonContent(report)?
context.Respond(HttpStatusCode.OK, content)
} else if request.Method.Method == "POST" && request.Target == "/reports" {
let body = await HttpStringContent.Read(request.Content)
// This boundary handles invalid input as an HTTP response, rather than propagating it.
if let Ok(text) = body {
if let Ok(reply) = Acknowledge(text) {
if let Ok(content) = JsonContent(reply) {
context.Respond(HttpStatusCode.Created, content)
return Ok(())
}
}
}
context.Respond(HttpStatusCode.BadRequest, ErrorContent("{\"error\":\"Invalid report\"}"))
} else {
context.Respond(HttpStatusCode.NotFound, ErrorContent("{\"error\":\"Not found\"}"))
}
return Ok(())
}
Client: connect and send the report
class ReportClient {
async func SubmitReport(client: HttpClient) -> Task<Result<string, AppError>> {
let content = PrepareReport()?
let response = await client.Post("reports", content)?
return await ReadReply(response)
}
}
The client program connects to the server URL supplied as its command-line argument:
async func Main(arguments: string[]) -> Task<()> {
if arguments.Length != 1 {
Panic("Supply the server base URL, for example http://localhost:8080/")
return ()
}
let client = HttpClient()
client.BaseUri = Some(arguments[0])
let result = await ReportClient().SubmitReport(client)
if let Ok(reply) = result {
Console.WriteLine(reply)
} else if let Failure(error) = result {
Panic(error.ToString())
}
}
For example, pass http://localhost:8080/ if the server reports port 8080. The server binds a free loopback port,
prints it, accepts the request and completes the response. The verifier connects
these two programs using that port; no public service is required.
The application sample constructs a report with the public System.Data.Json DOM and POSTs it to a neoCLR server. The server uses HttpContext to parse the body and return a JSON acknowledgement with status 201. Bad JSON or report shapes return 400; unknown routes return 404.
Application-owned converters project HttpError and JsonError into AppError while
retaining the original causes through helpers and async methods. Async Main awaits the submission and converts errors to display text at its
reporting boundary. Ordinary steps use propagation. The
server handles invalid input explicitly where it chooses the HTTP response.
Download the client/server sample. It uses the runtime
library's JSON parser and includes checks against independent Python HTTP peers.
Serialization is synchronous; HTTP bodies are currently buffered. The provisional
DOM limits are 1,024 UTF-8 bytes, four container levels and 32 values. The
sample has an opt-in variant using the provisional object serializer overloads.
It maps both report and acknowledgement models through checked runtime reflection:
constructors, getters and setters execute normally. Flat public string, int and
bool properties are supported, using exact property names. Writable properties
must be present; extra JSON fields are ignored. Nested models and typed arrays
are supported as shown below; null mapping and naming policies remain deferred. The sample's property names match its lowercase
wire names explicitly. Both mapped peers are checked against independent peers and each other.
Latency under load is not characterized.
The downloadable demo defaults to direct DOM mapping; its verifier selects this
experiment with --mapped.
Run the client and server
Download and extract the projects. From that directory, run with the matching runtime and SDK:
python3 http-json/verify.py \
--toolchain-root /absolute/path/to/runtime \
--sdk /absolute/path/to/matching/raven-sdk \
--runner /absolute/path/to/runtime/tools/http-runner \
--case all
The verifier builds the two .rvnproj projects, starts the server, reads its chosen
port and passes that URL to the client. It also tests each side against Python.
The client prints {"accepted":true}; the server prints Reports served after
completion. The default case uses DOM conversion and one POST in the paired run.
Use --mapped for the flat typed-model variant, which fetches then submits a report.
Development case: a report with a nested station
The report
exchange carries a station name and a description of where the sensor is
installed and why staff use it, plus a readings array of integer measurements. The client first fetches
this model from GET /report, then submits it to POST /reports. The server
reads the nested station and returns the same 201 acknowledgement. This is still
an explicit HttpServer application. The routing case below uses a
route parser inside the handler, with named parameters and typed parsing;
WebApplication infrastructure remains deferred.
Shared models
public class Station {
init() { }
var name: string { get; set; } = ""
var description: string { get; set; } = ""
}
public class ReportPayload {
init() { }
var station: Station { get; set; } = Station()
var readings: int[] { get; set; } = [21, 22]
}
Client: fetch and submit the model
class ReportClient {
async func SubmitReport(client: HttpClient) -> Task<Result<string, AppError>> {
let fetched = await client.GetFromJson<ReportPayload>("report")
let report = AdaptClientResult(fetched)?
let response = await client.PostAsJson("reports", report)
return ReadReply(response)
}
}
ReadReply checks the status and reads the acknowledgement. The shared
application error union retains both HTTP and JSON causes.
Server: read the nested request
func Acknowledge(content: HttpContent) -> Task<Result<Acknowledgement, JsonError>> {
_ = await content.ReadFromJson<ReportPayload>()?
let reply = Acknowledgement()
reply.accepted = true
return Ok(reply)
}
The server callback calls this operation, serializes the acknowledgement with
JsonContent.Create, and completes the response. Invalid nested values such as
{"station":{"name":12}}, a missing name, or null produce 400; unknown paths
produce 404. In the development sample, protocol, limit and unsupported-request
errors close the rejected connection and leave the server available for the next
request. Rejected attempts count toward its configured request count. Header
rejection occurs before a context exists, so this path does not send a 400/431
response. See the complete server.
Run the paired case
Download the complete client/server projects, extract them, and run from the extracted directory. Set these paths to a matching matching runtime bundle and Raven SDK.
python3 http-json/verify.py \
--toolchain-root /absolute/path/to/development/runtime \
--sdk /absolute/path/to/matching/raven-sdk \
--runner /absolute/path/to/development/runtime/tools/http-runner \
--nested --case all
The verifier builds both projects, starts the server on a free loopback port,
checks it with Python requests, runs the neoCLR client/server pair, and checks the
client against a Python server. Expect 19 server cases, successful JSON client and
server reports, and a final Public JSON DOM + HTTP checks passed: all line with
an iteration count. The client response is {"accepted":true}. Individual server
or client checks can be selected with --case server or --case client.
Nested mapping allows 1,024 UTF-8 bytes per document, matching the buffered HTTP body limit, and permits four object levels including the root, counting arrays as containers. Typed arrays preserve order and empty values; each array allows up to 31 items within the shared 32-value document limit. Nulls, generic lists and polymorphic property/element values remain unsupported. Shared child references are serialized as repeated objects; cycles fail at the depth limit. See JSON mapping rules for construction, error and stream ownership contracts.
Development case: routing with typed parameters
A station is
addressed by ID: GET /stations/42/reports reads its report and POST to the same
path submits it. Station 42 is the small case's known sensor. The shared nested
JSON models above are unchanged.
Compile RoutePattern.Parse("/stations/{stationId}/reports") once. The fundamental
API matches a target and exposes named values; no route union is required:
func ReadStationId(pattern: RoutePattern, target: string) -> Result<Optional<int>, string> {
let matched = pattern.Match(target)?
let Some(parameters) = matched else {
return Ok(None())
}
let id = parameters.GetInt32("stationId")?
return Ok(Some(id))
}
An application-defined union is an optional convenience for dispatch. These cases carry already parsed parameters; the fallback carries the original target:
union StationRoute {
case ReadReports(stationId: int)
case SubmitReport(stationId: int)
case Unmatched(target: string)
}
Ordinary application code converts a match into its chosen route variant:
func ParseStationRoute(pattern: RoutePattern, method: string, target: string) -> Result<StationRoute, string> {
let matched = pattern.Match(target)?
let Some(parameters) = matched else {
return Ok(StationRoute.Unmatched(target))
}
let id = parameters.GetInt32("stationId")?
if method == "GET" {
return Ok(StationRoute.ReadReports(id))
}
if method == "POST" {
return Ok(StationRoute.SubmitReport(id))
}
return Ok(StationRoute.Unmatched(target))
}
Server dispatch
The handler uses match to choose its own logic. Invalid parameters become 400;
unmatched paths, unknown stations and unsupported methods become 404 in this case.
The existing HttpContext completion and cleanup remain in the surrounding server.
async func Configure(context: HttpContext) -> Task<Result<unit, AppError>> {
let request = context.Request
let Ok(route) = ParseStationRoute(pattern, request.Method.Method, request.Target) else {
context.Respond(HttpStatusCode.BadRequest, ErrorContent("{\"error\":\"Invalid route parameter\"}"))
return Ok(())
}
// Domain lookup and dispatch remain application-owned.
match route {
StationRoute.Unmatched(_) => {
context.Respond(HttpStatusCode.NotFound, ErrorContent("{\"error\":\"Not found\"}"))
}
StationRoute.ReadReports(let id) => {
if id != 42 {
context.Respond(HttpStatusCode.NotFound, ErrorContent("{\"error\":\"Unknown station\"}"))
return Ok(())
}
let report = CreateReport()?
let content = JsonContent.Create(report)?
context.Respond(HttpStatusCode.OK, content)
}
StationRoute.SubmitReport(let id) => {
if id != 42 {
context.Respond(HttpStatusCode.NotFound, ErrorContent("{\"error\":\"Unknown station\"}"))
return Ok(())
}
let acknowledged = await Acknowledge(request.Content)
if let Ok(reply) = acknowledged {
let content = JsonContent.Create(reply)?
context.Respond(HttpStatusCode.Created, content)
} else {
context.Respond(HttpStatusCode.BadRequest, ErrorContent("{\"error\":\"Invalid report\"}"))
}
}
}
return Ok(())
}
Connecting client
The client reads the report and submits it back using the same station path:
class ReportClient {
async func SubmitReport(client: HttpClient) -> Task<Result<string, AppError>> {
let received = await client.GetFromJson<ReportPayload>("stations/42/reports")
let report = AdaptClientResult(received)?
let response = await client.PostAsJson("stations/42/reports", report)
return ReadReply(response)
}
}
Matching is case-sensitive; trailing slashes matter. Query text is ignored. Segment
values are decoded once as UTF-8, while encoded separators and malformed escapes
are rejected. Each target/pattern allows at most 1,024 UTF-8 bytes and 16 segments.
GetInt32 checks spelling and bounds; other types can use Get and their own parser.
See the route API guide for the complete contract.
The project download includes http-routing, the shared
model source and verifier. From the downloaded projects, select the matching runtime and SDK:
python3 http-json/verify.py --routed --case all \
--toolchain-root /path/to/runtime --sdk /path/to/raven-sdk \
--runner /path/to/runtime/tools/http-runner
The HTTP checks cover route parsing and union dispatch, 29 independent server requests,
the neoCLR client/server pair and the client against an independent server. The
client prints {"accepted":true}. The examples are packaged sample source; they do not introduce a hosting framework.
Case: attributed item routes
A small catalog API can declare its routes on the union returned to the handler:
public union AppRoutes {
[RoutePattern("/items")]
case ListItems
[RoutePattern("/items/{id}")]
case GetItem(id: int)
}
AppRoutesParser.Create() inspects these attributes once before the server starts.
It validates the schema and retains compiled patterns, capture conversions and
constructors:
let Ok(routes) = AppRoutesParser.Create() else {
Panic("Invalid route configuration")
return
}
Parse(target) returns Result<AppRoutes, RouteMappingError>.
NoMatch is separate from InvalidTarget, InvalidParameter and ConstructionFailed;
no fallback union case or unmatched attribute is needed. The handler owns method
selection, item lookup and response policy:
func Configure(context: HttpContext) {
var status = HttpStatusCode.NotFound
var body = "{\"error\":\"Not found\"}"
// Method policy and item lookup belong to the application.
if context.Request.Method.Method == "GET" {
let parsed = routes.Parse(context.Request.Target)
if let Ok(route) = parsed {
match route {
AppRoutes.ListItems => {
status = HttpStatusCode.OK
body = "[{\"id\":42,\"name\":\"Desk lamp\"}]"
}
AppRoutes.GetItem(let id) => {
if id == 42 {
status = HttpStatusCode.OK
body = "{\"id\":42,\"name\":\"Desk lamp\"}"
}
}
}
} else if parsed is Failure(RouteMappingError.ConstructionFailed(_)) {
status = HttpStatusCode.InternalServerError
body = "{\"error\":\"Route construction failed\"}"
} else if !(parsed is Failure(RouteMappingError.NoMatch)) {
status = HttpStatusCode.BadRequest
body = "{\"error\":\"Invalid route\"}"
}
}
context.Respond(status, HttpStringContent(body, "application/json; charset=utf-8"))
}
The connecting client lists the catalog and reads item 42:
async func Main(arguments: string[]) -> Task<Result<unit, HttpError>> {
let client = HttpClient()
client.BaseUri = Some(arguments[0])
Console.WriteLine(await client.GetString("items")?)
Console.WriteLine(await client.GetString("items/42")?)
return Ok(())
}
The server returns 404 for unmatched routes or missing items, 400 for invalid route input and 500 for construction errors. This small in-memory case uses fixed JSON responses; the station case above demonstrates typed JSON.
The source download includes runtime-route-mapper, its
three projects, reusable mapper, typed application facade and verifier. With a
matching runtime and SDK, run:
python3 runtime-route-mapper/verify.py --toolchain-root /path/to/runtime \
--sdk /path/to/raven-sdk --runner /path/to/runtime/tools/http-runner
Application-owned sample code; not installed as an SDK mapper. One public nongeneric union, up to 16 cases and String/Int32 payloads are supported. Startup rejects invalid schemas and structurally overlapping patterns. Overlap checks conservatively ignore typed conversion domains and the total target byte limit. Requests still decode targets, allocate arguments and perform checked constructor invocation. Attribute constructors never execute. Source generation remains a possible future alternative. The ordinary route primitives remain independently usable.
Request-processing benchmarks
The HTTP benchmark matrix separates plain-text responses, JSON serialization and JSON with database access across interpreter, JIT and AOT. It distinguishes measured development baselines from workloads still awaiting measurement, and keeps startup separate from request processing.
A source-only development experiment runs 1–4 isolated HTTP application workers against one listening socket. Heaps, statics and async state remain per worker; shared-object GC qualification is a separate gate before shared-heap parallelism. This provides server primitives, with no new application framework or change to the default host. Experimental contract and evidence.