hcs — HTTP server & client

Build OCaml HTTP services with hcs using HTTP/1.1, HTTP/2, WebSocket, Server-Sent Events, typed routes and Eio.

API reference

hcs is an HTTP server and client for OCaml. As a server, it listens for incoming web requests and sends back responses. As a client, it lets a program make outgoing HTTP calls. It runs on Eio, the I/O runtime for OCaml 5. Programs use it to serve a website or API, open a WebSocket, or fetch data from another service.

The shape of an hcs application

hcs represents its main pieces as ordinary values. A handler is a function from a request to a response. A plug wraps a handler to add behavior. A pipeline is a list of plugs. A router maps paths to handlers. An endpoint combines a router and global plugs into one handler, and Hcs.Server.run serves that handler. The main function builds these values and passes them to the server.

hcs runs on Eio, the effect-based I/O runtime for OCaml 5. In Eio, capabilities such as the network and the clock are values taken from the environment and passed where they are needed. Programs in this guide start with Eio_main.run and a switch. The modules described below (Server, Client, Router, Plug, Pipeline, Endpoint, Request, Response, Websocket, Sse, Pubsub, Channel, Multipart, Assigns, Log and Tls_config) are reachable under Hcs.

Your first server

The first server has three pieces: a view, a handler and a boot function. Each piece is a value that can be tested on its own.

The view

examples/hcs_hello/main.ml
let hello_page =
  let open Tyxml.Html in
  html
    (head (title (txt "Hello from araara")) [])
    (body [ h1 [ txt "Hello, araara!" ] ])

The handler

examples/hcs_hello/main.ml
let hello _params _req =
  Hcs.Server.respond_html (Format.asprintf "%a" (Tyxml.Html.pp ()) hello_page)

A handler takes the router's captured parameters and the request, and returns a response. respond_html sets the content type and renders the node tree to a string.

Starting the server

examples/hcs_hello/main.ml
let () =
  Eio_main.run @@ fun env ->
  Eio.Switch.run @@ fun sw ->
  let routes =
    Hcs.Router.(compile_scopes [ scope "/" [ Route.get "/" hello ] ])
  in
  let handler =
    Hcs.Endpoint.(
      create default_config |> Fun.flip router routes |> to_handler)
  in
  Hcs.Server.run ~sw
    ~net:(Eio.Stdenv.net env)
    ~clock:(Eio.Stdenv.clock env)
    handler

Eio_main.run starts the runtime. Eio.Switch.run opens the scope that owns the fibers the server starts. compile_scopes builds the router, the endpoint turns it into a handler, and Server.run serves it on port 8080 with HTTP/1.1 and a built-in health check at /_health by default.

$ dune exec examples/hcs_hello/main.exe
$ curl localhost:8080/

Routing

The router is a radix trie, a tree that shares common path prefixes. Lookup follows the segments of the request path through the trie. Routes are declared inside scopes, each scope runs its routes through a pipeline, and captured path segments arrive already typed. There is a route constructor for each method (get, post, put, patch, delete, head and options), plus any for a catch-all. A route can also carry its own per-route plug.

Typed bidirectional routes

A route is a typed value built from small combinators. s "items" is a literal segment. int and str each capture one segment, and / joins pieces together. The value is bidirectional: the same value matches an incoming URL and builds an outgoing one.

Register it with Route.get or Route.post and the handler receives the captures as typed arguments. Handlers do not look up or parse parameters themselves. A request whose segment does not parse (for example /items/abc for an int) receives a 404 response without calling the handler.

Build a URL with Route.link against the same route. The compiler checks that the call passes the right number of captures, each at the right type. If the route's captures change, the link call must change before the program compiles again. Routes still compile to the radix trie, so scopes and pipelines work as described above.

examples/hcs_routing/main.ml
(* A route is a typed value. [int] and [str] capture path segments, and
   the handler receives them as typed arguments, without a [params]
   lookup. A bad capture (/items/abc) is a 404, and the handler is not
   called. The same value builds URLs through [Route.link], so links are
   built from the route definition. Routes are thunks because each is
   polymorphic in its result: a response when registered, a string when
   linked. *)
let hello () = Route.(s "hello" / str)
let item () = Route.(s "items" / int)

let greet name _req = Hcs.Server.respond (Printf.sprintf "Hello, %s!\n" name)
let item_view id _req = Hcs.Server.respond (Printf.sprintf "item #%d\n" id)

(* link is the reverse direction, type-checked against the same route: *)
let _self = Route.link (item ()) 42 (* "/items/42" *)

A route value is polymorphic in its result (a response when registered, a string when linked), so each route is written as a thunk and called where it is used.

Pipelines and scopes

examples/hcs_routing/main.ml
(* Pipelines: cross-cutting concerns compose as plugs. A scope routes
   every request in it through its pipeline before the handler. *)
let browser =
  Hcs.Pipeline.create
    [
      Hcs.Plug.Logger.create ~clock (Hcs.Log.stdout ());
      Hcs.Plug.Recover.create ();
    ]
in
let api =
  Hcs.Pipeline.compose browser
    (Hcs.Pipeline.create
       [ Hcs.Plug.Request_id.create (); Hcs.Plug.Cors.create () ])
in
examples/hcs_routing/main.ml
(* Route.get/post take a typed route and a handler expecting its captures.
   The string router underneath is unchanged, and scopes and pipelines
   work as before. *)
let routes =
  Hcs.Router.compile_scopes
    [
      Hcs.Router.scope "/" ~through:browser
        [
          Route.get (Route.s "") home;
          Route.get (hello ()) greet;
          Route.get (item ()) item_view;
        ];
      Hcs.Router.scope "/api" ~through:api
        [ Route.get (Route.s "status") api_status ];
    ]
in

A pipeline composes plugs in order. A scope prefixes its routes and runs them through a pipeline, so the plugs that apply to a route are listed with its scope. Matching prefers a literal segment over a :param, and a :param over a * wildcard. A wildcard route can serve a styled 404 page.

Server configuration

examples/hcs_routing/main.ml
(* Server settings are a plain record; override the fields to change. *)
let port =
  Option.value ~default:8080
    (Option.bind (Sys.getenv_opt "PORT") int_of_string_opt)
in
let config = { Hcs.Server.default_config with port } in
Hcs.Server.run ~sw ~net:(Eio.Stdenv.net env) ~clock ~config handler

The config record covers binding (host, port, backlog), protocol selection, timeouts (read, write, idle, request), body-size limits, socket options, GC tuning, and domain_count for multi-core serving with Server.run_parallel.

$ dune exec examples/hcs_routing/main.exe
$ curl localhost:8080/hello/ada
$ curl -i localhost:8080/api/status

Reading the request

Hcs.Request parses lazily. The method, target and version are read up front. The query string, headers, cookies, body and form fields are read on demand through accessor functions.

Query parameters and headers

examples/hcs_request/main.ml
(* Query parameters are read by key; typed and defaulting variants save
   the caller from juggling [option]s. *)
let page = Hcs.Request.query_int req "page" in
let sort = Hcs.Request.query_or ~default:"asc" req "sort" in
let raw = Hcs.Request.query req "q" in
examples/hcs_request/main.ml
(* [header] is case-insensitive and returns an [option]. *)
let agent =
  match Hcs.Request.header req "x-demo" with
  | Some v -> v
  | None -> "(none)"
in

query returns a string option; query_int parses; query_or supplies a default; query_all returns every value for a repeated key. Headers come through header / header_multi / has_header, with named shortcuts such as content_type, host, authorization and accept, and predicates accepts_json / accepts_html. Method predicates (is_get, is_post, is_safe, is_idempotent) are also available.

Body and form fields

examples/hcs_request/main.ml
(* [body] materializes the request body; [form_data]/[form_field] decode
   an [application/x-www-form-urlencoded] payload into an assoc list. *)
let raw = Hcs.Request.body req in
let email =
  match Hcs.Request.form_field req "email" with Some e -> e | None -> "(none)"
in
let fields = Hcs.Request.form_data req in

body reads the whole body as a string. body_stream streams the body, which suits large uploads. form_data decodes an application/x-www-form-urlencoded body into an assoc list; form_field, form_int and related functions return a single field. For multipart bodies, see the uploads section below.

$ dune exec examples/hcs_request/main.exe

Building the response

Hcs.Response has a builder per content type and a status helper per common code, plus combinators that add headers, cookies, caching and CORS.

Content and status

examples/hcs_response/main.ml
(* The content-type helpers set the right header and wrap the body. Each
   returns a [Hcs.Response.t] that a route hands straight back. *)
let as_text _params _req = Hcs.Response.text "plain words\n"
let as_html _params _req = Hcs.Response.html "<h1>hi</h1>\n"
let as_json _params _req = Hcs.Response.json {|{"ok":true}|}

text, html, json, xml, stream and bigstring set the content type; each takes an optional ?status. Named status helpers (ok, created, no_content, bad_request, unauthorized, forbidden, not_found, unprocessable_entity, too_many_requests, internal_error and others) provide an alternative to numeric codes at the call site.

Redirects

examples/hcs_response/main.ml
(* A redirect carries the Location header and an empty body; [found] is a
   302, [redirect ~permanent:true] a 301. *)
let go_home _params _req = Hcs.Response.found "/"

redirect, found, see_other, moved_permanently and temporary_redirect set the Location header and the corresponding 3xx status.

Headers, cookies and caching

examples/hcs_response/main.ml
(* Combinators thread modifications through a base response. [with_header]
   adds an arbitrary header; [with_cookie] appends a Set-Cookie. *)
let session _params _req =
  Hcs.Response.text "session set\n"
  |> Hcs.Response.with_header "X-Request-Source" "example"
  |> Hcs.Response.with_cookie ~max_age:3600 "sid" "abc123"

Responses are immutable values. with_header, with_cookie (path, max_age, http_only, secure, same_site), clear_cookie, with_cache_control, with_no_cache and with_cors each return a new response, so calls can be chained.

$ dune exec examples/hcs_response/main.exe

Plugs and pipelines

A plug is a wrapper around a handler. It receives the inner handler and the request, and it can change the request before calling the handler, change the response afterwards, or return a response without calling the handler. Its type is Hcs.Plug.t = (request -> response) -> request -> response. Plugs compose into pipelines. Cross-cutting tasks such as logging, authentication and compression are implemented as plugs, so handlers do not repeat that code.

Writing a custom plug

examples/hcs_plug/main.ml
(* A plug has type [(request -> response) -> request -> response]: it wraps
   the inner handler. To pass the request through, call [handler req]. To
   halt, return a response without calling [handler]. The inner handler
   (and everything after this plug) does not run for that request. *)
let require_header name : Hcs.Plug.t =
 fun handler req ->
  match Hcs.Request.header req name with
  | Some _ -> handler req
  | None ->
      Hcs.Server.respond ~status:`Forbidden
        (Printf.sprintf "missing %s header\n" name)

The plug receives the downstream handler and the request and returns a response. It can run code before calling the handler, after the handler returns, or at both points.

Halting the chain

examples/hcs_plug/main.ml
Hcs.Server.respond ~status:`Forbidden
  (Printf.sprintf "missing %s header\n" name)

Returning a response without calling the handler stops the request at that plug. The authentication, rate limiting and CSRF plugs use this to reject a request before it reaches the handler.

Composing a pipeline

examples/hcs_plug/main.ml
(* Built-in plugs and our custom plug compose left-to-right into a
   pipeline; the scope runs every request through it before the handler. *)
let pipeline =
  Hcs.Pipeline.create
    [
      Hcs.Plug.Logger.create ~clock (Hcs.Log.stdout ());
      Hcs.Plug.Recover.create ();
      require_header "x-api-key";
    ]
in
let routes =
  Hcs.Router.(
    compile_scopes [ scope "/" ~through:pipeline [ Route.get "/hello" hello ] ])
in

Pipeline.create takes plugs in order (outermost first). Pipeline.compose combines one pipeline with another, and Plug.(@>) composes plugs inline. A scope runs its routes through the pipeline given to it.

$ dune exec examples/hcs_plug/main.exe

The built-in plug catalog

hcs includes plugs for common cross-cutting tasks under Hcs.Plug.

Observability and safety: Logger.create ~clock (a Log.logger) logs each request and response; Request_id.create adds a correlation id; Recover.create ?on_error turns an uncaught exception into a 500 response; Timeout.create ~clock seconds bounds handler time; Head.create answers HEAD by running the GET handler and dropping the body.

Traffic control: Cors.create ~config adds CORS headers and answers preflight requests; Rate_limit.create ~clock ~key ~requests ~per is a token bucket keyed by a function of the request (client IP, API key, and similar values); Circuit_breaker.create and Retry.create ~clock handle calls to downstream services that fail.

Representation: Compress.create gzips eligible responses; Etag.create adds ETags and answers conditional requests with 304; Cache_control.create sets Cache-Control; Negotiate.create ~formats picks a representation from the Accept header. Sessions, CSRF and authentication are described in the next section.

Sessions, CSRF and authentication

In araara, authentication and session state are handled by pipeline plugs. The pipeline assigned to a route shows which checks run before its handler. A handler runs after those plugs have accepted the request.

HTTP Basic auth

examples/hcs_auth/main.ml
(* A pipeline fronted by Basic auth: requests without valid credentials
   get an automatic 401 before reaching the handler. *)
let admin =
  Hcs.Pipeline.create
    [
      Hcs.Plug.Basic_auth.create_static ~realm:"admin" ~username:"root"
        ~password:"hunter2";
    ]
in

Basic_auth.create_static guards a scope with a fixed credential; create ~validate checks credentials with a supplied function, and create_with_map checks them against a table. An unauthorized request receives a 401 response that includes the realm. Token-based API keys use Hcs.Plug.Token, which signs and verifies HMAC tokens.

Sessions

examples/hcs_auth/main.ml
(* An encrypted cookie store keeps session state on the client; the plug
   decodes it on the way in and re-encodes it on the way out. [~secure:false]
   lets the cookie travel over plain HTTP for this local demo (use the
   default in production). CSRF protection would be added with
   [Hcs.Plug.Csrf.create ()]; safe methods (GET/HEAD) bypass it. *)
let store =
  Hcs.Plug.Session.Cookie_store.create ~secret:"a-32-byte-demo-secret-value!!" ()
in
let sessions =
  Hcs.Pipeline.create [ Hcs.Plug.Session.create ~store ~secure:false () ]
in
examples/hcs_auth/main.ml
(* Inside a handler running under the Session plug, the session is read and
   written with plain string keys/values. [put] marks it modified, so the
   plug serializes it into a Set-Cookie on the way out. *)
let login _params _req =
  Hcs.Plug.Session.put "user" "ada";
  Hcs.Server.respond "logged in\n"

let whoami _params _req =
  match Hcs.Plug.Session.get "user" with
  | Some user -> Hcs.Server.respond (Printf.sprintf "you are %s\n" user)
  | None -> Hcs.Server.respond ~status:`Unauthorized "no session\n"

A session store is either Cookie_store.create ~secret (signed and stored in the cookie) or Memory_store.create (stored on the server). The Session.create plug makes Session.get / Session.put / Session.delete available inside handlers. The Csrf.create plug provides CSRF protection: safe methods pass through, and unsafe methods must present a matching token.

$ dune exec examples/hcs_auth/main.exe

Typed request context (Assigns)

When a plug computes a value that a handler needs (the authenticated account, a parsed locale or a request-scoped id), it stores the value in the request's typed context. Hcs.Assigns is a heterogeneous map keyed by typed keys, so the handler reads the value back at the type recorded in the key.

A typed key

examples/hcs_assigns/main.ml
(* A key carries the type of the value it stores. [create_key] creates a
   new key; the phantom type parameter ties [add] and [find] together so
   reads come back at the key's type, without a cast at the use site. *)
let current_user : string Hcs.Assigns.key = Hcs.Assigns.create_key ()

A plug that assigns

examples/hcs_assigns/main.ml
(* This plug derives a user id from a header and attaches it to the request's
   assigns. Assigns are immutable, so we build a new request carrying the
   extended map and pass that to the handler. *)
let identify : Hcs.Plug.t =
 fun handler req ->
  let user =
    match Hcs.Request.header req "x-api-key" with
    | Some "secret" -> "ada"
    | _ -> "anonymous"
  in
  let assigns = Hcs.Assigns.add current_user user (Hcs.Request.assigns req) in
  handler { req with Hcs.Server.assigns }

The plug adds a binding to Request.assigns and puts the updated request back on the chain.

A handler that reads it

examples/hcs_assigns/main.ml
(* The handler recovers the value by key; [find] returns it at the key's
   type ([string] here), so no downcast is needed. *)
let greet _params req =
  match Hcs.Assigns.find current_user (Hcs.Request.assigns req) with
  | Some user -> Hcs.Server.respond (Printf.sprintf "hello, %s\n" user)
  | None -> Hcs.Server.respond ~status:`Internal_server_error "no user\n"

Assigns.find returns an option at the key's type. A missing key returns None. The key carries a phantom type that ties the stored value to that type.

$ dune exec examples/hcs_assigns/main.exe

Serving static files

Plug.Static serves a directory, with index files, ETags and content types based on the file. Mount it on the endpoint, ahead of the router. It answers asset requests and passes other requests through.

Mounting the plug

examples/hcs_static/main.ml
(* [Plug.Static.create] takes an Eio directory capability; it serves
   regular files under that root and falls through to the next handler
   (here the endpoint's 404) when nothing matches. *)
let root = Eio.Path.(fs / dir) in
let static = Hcs.Plug.Static.create ~with_etag:true root in
let handler =
  Hcs.Endpoint.(create default_config |> with_plug static |> to_handler)
in

The root is an Eio.Path.t, and the plug reads only inside that root. Requests that would escape the root through path traversal or a symlink are refused. ?index sets the directory index; ?with_etag toggles conditional requests.

Fetching an asset

examples/hcs_static/main.ml
match Hcs.Client.get client url with
| Ok { Hcs.Client.status; body; _ } ->
    Printf.printf "%s -> %d %S\n" path status (String.trim body)
| Error _ ->
    prerr_endline "request failed";
    exit 1
$ dune exec examples/hcs_static/main.exe

The HTTP client

hcs includes an HTTP client as well as the server described above. The example starts a server and queries it from the same process, so the exchange runs in the test suite.

A server fiber

examples/hcs_client/main.ml
let echo params _req =
  match Hcs.Router.param "word" params with
  | Some word -> Hcs.Server.respond (String.uppercase_ascii word)
  | None -> Hcs.Server.respond ~status:`Bad_request "missing word"

let start_server ~sw ~net ~clock =
  let routes =
    Hcs.Router.(compile_scopes [ scope "/" [ Route.get "/echo/:word" echo ] ])
  in
  let handler =
    Hcs.Endpoint.(
      create default_config |> Fun.flip router routes |> to_handler)
  in
  let config = { Hcs.Server.default_config with port; host = "127.0.0.1" } in
  Eio.Fiber.fork ~sw (fun () -> Hcs.Server.run ~sw ~net ~clock ~config handler)

The client value

examples/hcs_client/main.ml
(* A client is a value: connection pooling and protocol selection live
   inside it. [get] returns a result, so errors are returned as values. *)
let fetch ~sw ~net ~clock url =
  let client = Hcs.Client.create ~sw ~net ~clock () in
  match Hcs.Client.get client url with
  | Ok { Hcs.Client.status; body; _ } ->
      Printf.printf "GET %s -> %d %s\n" (Uri.to_string url) status body
  | Error _ ->
      prerr_endline "request failed";
      exit 1

Client.create returns a value holding a connection pool and protocol negotiation settings. get, post and request return a result. Connection failures, timeouts and oversized bodies are reported as variants in that result. Configuration functions return an updated config: with_timeout, with_redirects / without_redirects, with_http2, with_tls and with_default_header. Methods are the Hcs.Http constructors (Hcs.Http.GET, POST, and so on).

$ dune exec examples/hcs_client/main.exe

WebSocket

hcs implements WebSocket (RFC 6455) for servers and clients. The server runs in Auto_websocket mode and passes each upgraded connection to a handler. The client connects and exchanges frames. The example runs server and client in one process.

The connection handler

examples/hcs_websocket/main.ml
(* A WebSocket handler is [Websocket.t -> unit]: it owns the connection for its
   lifetime. This one echoes text frames back until the peer closes (at which
   point [recv_message] returns an error and the loop ends). [recv_message]
   reassembles fragmented frames and returns the opcode plus the payload. *)
let echo_handler ws =
  let rec loop () =
    match Hcs.Websocket.recv_message ws with
    | Ok (Hcs.Websocket.Opcode.Text, msg) -> (
        match Hcs.Websocket.send_text ws msg with
        | Ok () -> loop ()
        | Error _ -> ())
    | Ok _ -> loop () (* ignore non-text messages *)
    | Error _ -> () (* connection closed or errored: stop *)
  in
  loop ()

A ws_handler is Websocket.t -> unit. recv_message returns the opcode and payload; send_text / send_binary write frames; send_ping / send_pong and close handle control frames; is_open tests the connection.

Wiring the server

examples/hcs_websocket/main.ml
(* WebSocket support is opt-in: run the server in [Auto_websocket] protocol mode
   and register the handler on the endpoint. [Endpoint.ws_handler] then supplies
   it to [Server.run] via [?ws_handler]. *)
let start_server ~sw ~net ~clock =
  let ep =
    Hcs.Endpoint.(create default_config |> Fun.flip websocket echo_handler)
  in
  let config =
    {
      Hcs.Server.default_config with
      port;
      host = "127.0.0.1";
      protocol = Hcs.Server.Auto_websocket;
    }
  in
  Eio.Fiber.fork ~sw (fun () ->
      Hcs.Server.run ~sw ~net ~clock ~config
        ?ws_handler:(Hcs.Endpoint.ws_handler ep)
        (Hcs.Endpoint.to_handler ep))

Endpoint.websocket attaches the handler; Server.run takes it via ?ws_handler with protocol Auto_websocket, so the same port serves HTTP and upgrades WebSocket requests.

The client

examples/hcs_websocket/main.ml
(* [connect] performs the HTTP/1.1 upgrade handshake and returns a connection
   (or an error). Send a text message, read the echo, then close. *)
let exchange ~sw ~net url =
  match Hcs.Websocket.connect ~sw ~net url with
  | Error _ ->
      prerr_endline "connect failed";
      1
  | Ok ws -> (
      match Hcs.Websocket.send_text ws "hello" with
      | Error _ ->
          prerr_endline "send failed";
          1
      | Ok () -> (
          match Hcs.Websocket.recv_message ws with
          | Ok (_, reply) ->
              Printf.printf "echo: %s\n" reply;
              Hcs.Websocket.close ws;
              if reply = "hello" then 0 else 1
          | Error _ ->
              prerr_endline "recv failed";
              1))

Websocket.connect performs the handshake and returns a Websocket.t. The same send and receive functions used on the server operate on this value. To broadcast one message to many subscribed sockets or SSE streams, use hive's pubsub, documented on the hive page. hcs provides the WebSocket transport.

$ dune exec examples/hcs_websocket/main.exe

Server-Sent Events

With SSE, the server streams HTML fragments to the browser, where htmx inserts them into the page. hive's pubsub distributes one broadcast to each subscribed connection (see the hive page). An SSE handler subscribes when a client connects and sends each message it receives.

An SSE stream

examples/hcs_sse/main.ml
(* An SSE response is driven by a generator: hcs calls it each time it
   wants the next event; returning None closes the stream. *)
let ticks ~clock _params _req =
  let count = Atomic.make 0 in
  Hcs.Sse.respond (fun () ->
      Eio.Time.sleep clock 1.0;
      let n = Atomic.fetch_and_add count 1 in
      if n >= 5 then None
      else
        Some
          (Hcs.Sse.make ~event_type:"tick" ~id:(string_of_int n)
             (Printf.sprintf "tick %d at %.0f" n (Eio.Time.now clock))))
examples/hcs_sse/main.ml
let routes =
  Hcs.Router.(
    compile_scopes
      [
        scope "/"
          [ Route.get "/" home; Route.get "/events" (ticks ~clock) ];
      ])
in

An SSE response is pull-based. hcs calls the generator when the connection can take the next event; Some sends an event and None closes the stream. Events carry an optional type and id. A reconnecting client can use the id to resume. respond_with_heartbeat sends heartbeat events on idle connections, including connections that pass through proxies. Sse_client and Event_source (which reconnects automatically) read SSE streams.

$ dune exec examples/hcs_sse/main.exe
$ curl -N localhost:8080/events

Multipart uploads

File uploads arrive as multipart/form-data. Hcs.Multipart parses the body into parts (text fields and files). It can parse the body at once or stream it for large payloads.

Parsing on the server

examples/hcs_multipart/main.ml
(* On the server, [Multipart.parse] turns the request body into parts.
   [find_part] looks up a field by name; [find_file] finds a file part (one
   that carries a filename). A parse error is answered with a 400. *)
let upload _params req =
  match Hcs.Multipart.parse req with
  | Error e ->
      Hcs.Server.respond ~status:`Bad_request (Hcs.Multipart.error_to_string e)
  | Ok parts -> (
      let caption =
        match Hcs.Multipart.find_part "caption" parts with
        | Some p -> p.Hcs.Multipart.data
        | None -> "(none)"
      in
      match Hcs.Multipart.find_file "upload" parts with
      | None -> Hcs.Server.respond ~status:`Bad_request "no file part"
      | Some file ->
          let name = Option.value ~default:"(unnamed)" file.filename in
          Hcs.Server.respond
            (Printf.sprintf "caption=%s file=%s size=%d" caption name
               (String.length file.data)))

is_multipart checks the request; parse returns the parts as a result; find_part returns a text field and find_file returns a file (name, filename, content_type, data). For large uploads, create_parser with iter_parts / next_part streams parts without buffering the whole body.

Posting a file

examples/hcs_multipart/main.ml
(* The client posts the assembled body with a multipart Content-Type whose
   [boundary] parameter matches the one used to frame the parts. *)
let post_upload ~sw ~net ~clock url =
  let body =
    build_multipart_body ~field:"a tiny upload" ~filename:"hello.txt"
      ~file_contents:"file body bytes"
  in
  let headers =
    [ ("Content-Type", Printf.sprintf "multipart/form-data; boundary=%s" boundary) ]
  in
  let client = Hcs.Client.create ~sw ~net ~clock () in
  match Hcs.Client.post client url ~headers ~body with
  | Ok { Hcs.Client.status; body; _ } ->
      Printf.printf "POST %s -> %d %s\n" (Uri.to_string url) status body;
      if status = 200 then 0 else 1
  | Error _ ->
      prerr_endline "request failed";
      1
$ dune exec examples/hcs_multipart/main.exe

Assembling the endpoint

The endpoint combines the global plugs that each request passes through, the router and an optional WebSocket handler into one value. The first server example used the minimal form (create |> router |> to_handler). This section describes the builder functions.

The builder

examples/hcs_endpoint/main.ml
(* An endpoint is built by a chain: start from a config, attach
   cross-cutting plugs and pipelines, mount a router, then close it
   into a handler. [health_check = true] makes the endpoint answer
   GET /_health and /health on its own. *)
let config =
  { Hcs.Endpoint.secret_key_base = "change-me-in-production";
    health_check = true }
in
let pipeline =
  Hcs.Pipeline.create
    [
      Hcs.Plug.Logger.create ~clock (Hcs.Log.stdout ());
      Hcs.Plug.Recover.create ();
    ]
in
let routes =
  Hcs.Router.(compile_scopes [ scope "/" [ Route.get "/" home ] ])
in
let handler =
  Hcs.Endpoint.create config
  |> Hcs.Endpoint.with_plug security_headers
  |> Hcs.Endpoint.with_pipeline pipeline
  |> Fun.flip Hcs.Endpoint.router routes
  |> Hcs.Endpoint.to_handler
in

Endpoint.create takes a config record { secret_key_base; health_check }. secret_key_base is the signing key used for cookie sessions and CSRF tokens. Set it from configuration in production and do not commit it. The builder functions then update the endpoint: with_plug adds one global plug (static files, security headers), with_pipeline (or the @>> operator) composes a pipeline of plugs, router attaches the compiled routes, websocket attaches a Websocket.t -> unit handler, and to_handler produces the request -> response function that Server.run serves.

Order matters. The global plugs wrap the static plug, the health check and the not-found handler as well as the router. A logger or security-headers plug at the endpoint level therefore applies to static, health check and not-found responses too. Per-scope pipelines (from the routing section) apply to the routes inside their scope, inside the global plugs.

The health check

examples/hcs_endpoint/main.ml
(* The endpoint answers its own health check with 200 "ok". *)
fetch ~sw ~net ~clock ~label:"health"
  (Uri.of_string (Printf.sprintf "http://127.0.0.1:%d/_health" port));

With health_check enabled (the default), the endpoint answers GET /_health and GET /health with a 200 and the body "ok", before the router runs. Load balancers and container orchestrators can use these paths as a liveness probe without an application route. This site's Docker image uses the health check. The config can turn it off if the application should handle those paths itself.

$ dune exec examples/hcs_endpoint/main.exe

Protocols, HTTP/2 and multiple cores

The protocol field of the server config selects how connections are handled:

examples/hcs_endpoint/main.ml
(* The server config selects the protocol. Http1_only is the default;
   Http2_only, Auto and Auto_websocket are the other options. *)
let config =
  {
    Hcs.Server.default_config with
    port;
    host = "127.0.0.1";
    protocol = Hcs.Server.Http1_only;
  }
in

Http1_only: HTTP/1.1 only. This is the default. It is suitable behind a proxy that terminates HTTP/2.

Http2_only: HTTP/2 cleartext (h2c), for an internal connection that uses HTTP/2.

Auto: both protocols. With TLS, ALPN negotiates h2 or http/1.1 per connection. Without TLS, the server uses HTTP/1.1 with an h2c upgrade.

Auto_websocket: Auto plus the WebSocket upgrade path. The WebSocket section uses this mode.

Server.run uses a single accept loop. For multi-core serving, Server.run_parallel takes a domain manager and runs accept loops across domain_count domains (set in the config). Handlers remain direct-style Eio code. The config also sets backlog, max_connections, the read / write / idle / request timeouts, max_header_size, max_body_size, TCP_NODELAY / SO_REUSEPORT and GC parameters.

TLS

TLS is configured through Hcs.Tls_config, which wraps OpenSSL through eio-ssl. The example generates a self-signed certificate at runtime, writes it to short-lived PEM files and makes an HTTPS request and response in one process. A deployment can load its own certificate with Tls_config.Server.of_pem.

A certificate

examples/hcs_tls/main.ml
(* Build a key and a self-signed certificate entirely in memory. Both the
   key generation and the signing draw on the process-wide RNG, so this
   must run after the RNG is seeded. Each step returns a result; we thread
   them with [let*] so any failure surfaces as a clear message. *)
let ( let* ) = Result.bind

let self_signed () =
  let key = X509.Private_key.generate `ED25519 in
  let dn = [ Dn.Relative_distinguished_name.singleton (Dn.CN "localhost") ] in
  let* csr =
    Result.map_error
      (fun (`Msg m) -> "csr: " ^ m)
      (X509.Signing_request.create dn key)
  in
  (* Validity window: now .. now + 1 day, expressed as Ptime.t. *)
  let now = Ptime_clock.now () in
  let valid_until =
    match Ptime.add_span now (Ptime.Span.of_int_s 86_400) with
    | Some t -> t
    | None -> now
  in
  let* cert =
    Result.map_error
      (fun e -> Format.asprintf "sign: %a" X509.Validation.pp_signature_error e)
      (X509.Signing_request.sign csr ~valid_from:now ~valid_until key dn)
  in
  Ok (cert, key)

In this example, X509 generates an ED25519 key and self-signs a certificate for development. In production, Tls_config.Server.of_pem ~cert_file ~key_file loads the chain and key issued by a CA.

The server

examples/hcs_tls/main.ml
(* The server TLS config points at a certificate and private key stored as
   PEM files, plus the ALPN protocols to advertise. We encode the in-memory
   self-signed pair to PEM and write it to two temp files, then hand hcs
   their paths. We advertise only HTTP/1.1 so the in-process client
   negotiates cleanly. *)
let start_server ~sw ~net ~clock cert key =
  let write_pem suffix data =
    let path = Filename.temp_file "hcs_tls_" suffix in
    let oc = open_out_bin path in
    output_string oc data;
    close_out oc;
    path
  in
  let cert_file = write_pem "_cert.pem" (X509.Certificate.encode_pem cert) in
  let key_file = write_pem "_key.pem" (X509.Private_key.encode_pem key) in
  let server_tls =
    {
      Hcs.Tls_config.Server.cert_file;
      key_file;
      alpn_protocols = Some [ Hcs.Tls_config.alpn_http11 ];
    }
  in
  let hello _params _req = Hcs.Server.respond "secure hello\n" in
  let routes = Hcs.Router.(compile_scopes [ scope "/" [ Route.get "/" hello ] ]) in
  let handler =
    Hcs.Endpoint.(create default_config |> Fun.flip router routes |> to_handler)
  in
  let config =
    {
      Hcs.Server.default_config with
      port;
      host = "127.0.0.1";
      protocol = Hcs.Server.Auto;
      tls = Some server_tls;
    }
  in
  Eio.Fiber.fork ~sw (fun () -> Hcs.Server.run ~sw ~net ~clock ~config handler)

A Tls_config.Server.t pairs the certificate and key files with the ALPN protocols to advertise. Put it in the server config's tls field. In Auto mode, ALPN offers h2 and http/1.1, and HTTP/2 is negotiated when the client supports it. The helpers h1_only / h2_only / h2_or_http11 set the protocol list.

The client

examples/hcs_tls/main.ml
(* A self-signed cert won't chain to any system CA, so the client uses
   [with_insecure_tls], which skips verification. This suits a local dev
   cert; do not use it in production. The URL scheme is https; everything
   else is the ordinary client API. *)
let fetch ~sw ~net ~clock url =
  let config = Hcs.Client.with_insecure_tls Hcs.Client.default_config in
  let client = Hcs.Client.create ~sw ~net ~clock ~config () in
  match Hcs.Client.get client url with
  | Ok { Hcs.Client.status; body; _ } ->
      Printf.printf "GET %s -> %d %s" (Uri.to_string url) status body
  | Error _ ->
      prerr_endline "request failed";
      exit 1

Tls_config.Client has a default verifying configuration and an insecure variant for local self-signed certificates. The client takes a configuration with with_insecure_tls / with_tls, and Tls_config exposes the negotiated protocol after the handshake. An application can terminate TLS at a reverse proxy and run Http1_only behind it. Built-in TLS is available when the application terminates TLS itself.

$ dune exec examples/hcs_tls/main.exe

Logging

Request logging uses the Plug.Logger.create ~clock plug from the catalog. The plug takes a Hcs.Log.logger, a sink for structured request and response events.

A log sink

examples/hcs_logging/main.ml
(* A logger is [level -> event -> unit]. [Hcs.Log.custom] hands us each
   event pre-formatted as a string, so here we collect the lines.
   ([Hcs.Log.stdout ~json:true ()] can be passed instead to emit JSON
   to stdout; the plug is unchanged.) *)
let captured : string list ref = ref []

let capture_sink : Hcs.Log.logger =
  Hcs.Log.custom (fun level msg ->
      let line =
        Printf.sprintf "[%s] %s" (Hcs.Log.level_to_string level) msg
      in
      captured := line :: !captured)

The Log module builds sinks: stdout and stderr (each with ?min_level and a ?json toggle for line-delimited JSON), custom and custom_json to send formatted lines to another logging system, combine to send one event stream to several sinks, with_min_level to filter, and null to discard events.

Installing it

examples/hcs_logging/main.ml
(* Plug.Logger turns request lifecycle events into log events and feeds
   them to whichever sink we pass it. *)
let pipeline =
  Hcs.Pipeline.create
    [
      Hcs.Plug.Logger.create ~clock capture_sink;
      Hcs.Plug.Recover.create ();
    ]
in

The plug takes the logger as a value, so a program can pass a human-readable logger in development and Hcs.Log.stdout ~json:true () in production. Log events carry the request id from Plug.Request_id for correlation.

$ dune exec examples/hcs_logging/main.exe

Streaming bodies

A body may be too large to hold in memory. Hcs.Stream provides synchronous and asynchronous streams, and the request and response sides both use them.

Streaming a response

examples/hcs_streaming/main.ml
(* [Response.stream] takes a generator [unit -> Cstruct.t option]: each call
   yields the next chunk, [None] ends the body. The chunks are sent as they
   are produced rather than buffered into one string. *)
let counter _params _req =
  let remaining = ref [ "one "; "two "; "three" ] in
  let next () =
    match !remaining with
    | [] -> None
    | chunk :: rest ->
        remaining := rest;
        Some (Cstruct.of_string chunk)
  in
  Hcs.Response.stream next

Response.stream (and bigstring / cstruct) sends a body produced incrementally. The generator returns the next chunk until it returns None. The SSE generator and the multipart streaming parser use the same incremental form.

Consuming a request body in chunks

examples/hcs_streaming/main.ml
(* On the request side, [Request.body_stream] pulls the incoming body in
   chunks the same way. This suits large uploads that should not be held
   in memory all at once. Here we count the bytes as they arrive. *)
let upload _params req =
  let stream = Hcs.Request.body_stream req in
  let total = ref 0 in
  let rec drain () =
    match stream () with
    | None -> ()
    | Some chunk ->
        total := !total + Cstruct.length chunk;
        drain ()
  in
  drain ();
  Hcs.Server.respond (Printf.sprintf "received %d bytes\n" !total)

Request.body_stream returns the body as chunks rather than as one string. The server's request_body_buffer_limit caps how much of the body is held in memory. An endpoint that counts or forwards a large upload can process the chunks without buffering the whole body.

$ dune exec examples/hcs_streaming/main.exe

In a full application

In a full application, the endpoint and pipelines are defined in lib/_web. Handlers are controllers that call contexts, and the conventions page describes the layering around them. The API reference linked above documents the modules and functions.