# Serving

> server_t::make takes the interfaces to answer on, as an array whose size the compiler knows, and optionally server_options_t: the backend, a CPU class ceiling that caps the picked class rather than demanding one the machine lacks, a log_t sink and a StatsD endpoint.

`#include <ucall/server.hpp>``#include <ucall/types.hpp>` 1.0.0-rc.1 · b7577426

`server_t::make` takes the interfaces to answer on, as an array whose size the compiler knows, and optionally `server_options_t`: the backend, a CPU class ceiling that caps the picked class rather than demanding one the machine lacks, a `log_t` sink and a StatsD endpoint. It fails rather than substituting when the backend is unavailable or the CPU does not run the class. An `interface_t` is an address, optionally pinned to a Linux device, with its own security and admission limits, so one server answers plaintext on loopback and Noise on the wire at once. `server_t::memory_domain` reports the NUMA node the kernel ties an interface’s device to, or -1, so the application inits and polls from threads there; UCall places nothing by it. It admits 1024 connections by default, reads one request per connection at a time unless `max_pipelined_requests` allows more, and replies still leave in request order. Once an interface holds its whole `max_concurrent_connections` budget, a new peer evicts the idle keep-alive connection that progressed least recently. A connection that has not yet carried a request is never idle in this sense, so it is never evicted: its peer may have sent that request already. `max_request_bytes` caps a request’s head and buffered body, answering 413 past it, and `reply_directories` names the directories path replies resolve beneath. `listen_descriptor` accepts on a listener another owner opened instead of binding an address, and never closes it. Port zero binds a free port, which `server_t::address` reports.

```cpp
void list_files(uc::request_t request) noexcept {
    auto [user, user_status] = request.path_parameter("user");
    auto [path, path_status] = request.path_parameter("path");
    ucall_reply_part_t const parts[] {uc::bytes_part(user), uc::bytes_part(":"), uc::bytes_part(path)};
    uc::deferred<> sent;
    [[maybe_unused]] uc::status_t const replied =
        std::move(request).reply_parts(ucall_http_status_ok_k, {}, parts, sent);
}

void not_served(uc::request_t request) noexcept {
    [[maybe_unused]] uc::status_t const replied =
        std::move(request).reply_error(ucall_http_status_not_implemented_k, "This method is not served");
}

auto log_line = [](ucall_log_level_t level, std::string_view line) noexcept {
    std::fprintf(stderr, "%d %.*s\n", int(level), int(line.size()), line.data());
};
uc::interface_t const interfaces[] {
    {.address = "0.0.0.0:8545", .event_loops = 4, .max_concurrent_connections = 16'384, .max_pipelined_requests = 16},
    {.address = "127.0.0.1:8546", .max_concurrent_connections = 4},
};
uc::server_options_t const options {
    .log = {log_line, ucall_log_format_human_k, ucall_log_level_warning_k},
    .metrics_address = "127.0.0.1:8125",
    .metrics_prefix = "myapp",
    .cpu_class_ceiling = ucall_cpu_class_serial_k,
};
auto [server, server_status] = uc::server_t::make(interfaces, options);
std::printf("%zu event loops on %.*s\n", server.event_loops(), int(uc::io_backend_name(server.backend()).size()),
            uc::io_backend_name(server.backend()).data());

uc::status_t const listed = server.get<list_files>("/users/{user}/files/{*path}");
uc::status_t const fallback = server.route<not_served>("/anything", ucall_verb_any_k);
```

Routes register before any loop is polled, with `route` taking any verb and `get`, `post`, `put`, `delete_` and `patch` naming one; `delete_` carries an underscore, as `delete` is a keyword. A handler is a `noexcept` function taking `request_t` by value, named as a template argument, as in `server.get<greet>(path)`; a member function named the same way with its object, as in `server.post<&service_t::echo>(path, service)`; or a callable with state, such as a lambda with captures, passed as an argument. The server refers to a member’s object or a callable, which the caller keeps until the server is destroyed, and keeps no record of a route; log sinks and peer authorizers are callables the caller keeps alike. Every polling loop may run a route at once, so a callable, a log sink and a peer authorizer are called through a const call operator, and a member’s object must be safe to call from several threads, like an internally synchronized store. Templates capture `{name}` segments and a greedy `{*name}` tail, literal segments match before captures, and registering one template and verb twice fails with `status_code_t::already_exists_k`. Routing is exact: an empty segment is a segment, so `/users` and `/users/` are different paths. A path no route matches answers 404, one whose routes take other verbs answers 405 with an `allow` header, a GET route also serves HEAD, and `OPTIONS` answers 204 with the same `allow` list.

Log lines reach the handler on whichever thread produced them, and StatsD datagrams carry each loop’s counters and sampled request latencies, every second unless `metrics_interval` says otherwise. `server_t::event_loop_statistics` copies one loop’s counters, from any thread while the loop runs; divided by `requests`, they price one call.

## API

### Types

#### `local_batch_endpoint_t`

One local batch endpoint, whose event loops each fire their own batches, so nothing drains it; valid until its server is freed.

[server.hpp:544 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L544)

```cpp
class local_batch_endpoint_t
```

#### `interface_t`

One address a server answers on, with the security and admission limits of the connections arriving there.

[server.hpp:570 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L570)

```cpp
struct interface_t
```

#### Fields

| `address` | `std::string_view` | The listening address in "host:port" form; port zero picks a free one. |
| - | - | - |
| `listen_descriptor` | `std::intptr_t const *` | A listening stream socket another owner opened, accepted on instead of [`address`](#address). |
| `device_name` | `std::string_view` | A physical device to pin the interface to, like "eth0", on Linux only. |
| `security` | `ucall_security_t` | Encryption for connections accepted here. |
| `noise_private_key` | `ucall_noise_key_t const *` | The server identity for handshakes, needed by every Noise mode. |
| `noise_peer_key` | `ucall_noise_key_t const *` | The one initiator's static public key Noise KK admits. |
| `noise_pre_shared_key` | `ucall_noise_key_t const *` | A secret every client also holds, mixed first into every handshake; refused on plaintext. |
| `key_exchange` | `ucall_key_exchange_t` | The key exchange of Noise handshakes, which clients must match. |
| `peer_authorizer` | `peer_authorizer_t` | Vets each client's authenticated key, needed by Noise XX. |
| `event_loops` | `std::size_t` | Event loops accepting here; zero means one, or a named device's receive queues. |
| `max_concurrent_connections` | `std::size_t` | Connections open at once across this interface's loops. |
| `max_pipelined_requests` | `std::size_t` | Requests one connection may have in flight; zero means one. |
| `max_request_bytes` | `std::size_t` | The largest request head and buffered body; zero takes the largest receive buffer. |
| `reply_directories` | `std::span<ucall_bytes_view_t const>` | Directories that path parts of replies resolve beneath, by position. |
| `send_policy` | `ucall_send_policy_t` | How replies of a page or more leave: copied to peers on this host, pinned for the rest. |

#### `server_options_t`

What a server runs on and reports through, beside its interfaces.

[server.hpp:639 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L639)

```cpp
struct server_options_t
```

#### Fields

| `log` | `log_t` | Where log lines go; empty keeps the server silent. |
| - | - | - |
| `metrics_address` | `std::string_view` | The StatsD endpoint in "host:port" form; empty sends nothing. |
| `metrics_sample_rate` | `float` | The fraction of finished requests whose latency is reported; zero means all. |
| `metrics_prefix` | `std::string_view` | The metric name prefix; empty means "ucall". |
| `metrics_tags` | `std::span<ucall_bytes_view_t const>` | Tags on every metric, each "key:value". |
| `metrics_interval` | `std::chrono::microseconds` | The time between one event loop's datagrams; zero means one second. |
| `backend` | `ucall_io_backend_t` | The requested I/O backend, failing rather than substituting when it is unavailable. |
| `cpu_class_ceiling` | `ucall_cpu_class_t` | A ceiling on the CPU class; unknown sets none. |

#### `log_t`

The log sink of a server or a client: a handler the caller keeps for its lifetime, the line format, and the least severe level formatted; empty logs nothing.

[types.hpp:448 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/types.hpp#L448)

```cpp
class log_t
```

#### Class `pooled_batch_endpoint_t`

One pooled batch endpoint, whose one queue gathers every event loop's requests and is drained by one thread at a time; valid until its server is freed.4

[server.hpp:497 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L497)

```cpp
class pooled_batch_endpoint_t
```

##### `pooled_batch_endpoint_t`

[server.hpp:502 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L502)

```cpp
pooled_batch_endpoint_t() noexcept=default;
```

```cpp
pooled_batch_endpoint_t(
    ucall_server_t server,
    ucall_http_batch_endpoint_t endpoint) noexcept;
```

##### `take_batch`

Runs the handler on this thread if a batch is due, waiting up to `timeout` for one; zero performs one nonblocking round.

[server.hpp:508 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L508)

```cpp
status_t take_batch(std::chrono::microseconds timeout) const noexcept;
```

##### `take_batches`

Runs the handler on this thread for every due batch until the server stops.

[server.hpp:519 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L519)

```cpp
status_t take_batches() const noexcept;
```

##### `statistics`

A snapshot of the endpoint's counters, readable from any thread while it is polled.

[server.hpp:528 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L528)

```cpp
expected<batch_endpoint_statistics_t> statistics() const noexcept;
```

#### Class `server_t`

An HTTP server over one or more interfaces, polled by application threads.17

[server.hpp:674 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L674)

```cpp
class server_t
```

Register every route before any loop is polled, then poll each event loop from one thread at a time. Destroying it frees the server, which the bound clients must not outlive. A route keeps nothing here: its handler is a template argument, and a member's object or a callable is the context the library hands back.

##### `make`

Starts a server answering on `interfaces`, whose callbacks it calls until it is freed.

[server.hpp:753 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L753)

```cpp
template <std::size_t count_>
expected<server_t> make(
    interface_t const (&) interfaces,
    server_options_t const & options = {}) noexcept;
```

##### `event_loops`

Event loops the server runs, each polled by one thread at a time.

[server.hpp:784 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L784)

```cpp
std::size_t event_loops() const noexcept;
```

##### `backend`

The I/O backend the server resolved to.

[server.hpp:792 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L792)

```cpp
ucall_io_backend_t backend() const noexcept;
```

##### `cpu_class_ceiling`

The CPU class the server resolved to under its ceiling.

[server.hpp:795 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L795)

```cpp
ucall_cpu_class_t cpu_class_ceiling() const noexcept;
```

##### `address`

The numeric address interface `index` listens on, with the port it bound.

[server.hpp:798 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L798)

```cpp
expected<std::string_view> address(std::size_t index) const noexcept;
```

##### `memory_domain`

The NUMA node the kernel ties interface `index's` device to, or -1; init and poll from threads there.

[server.hpp:807 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L807)

```cpp
expected<std::int32_t> memory_domain(std::size_t index) const noexcept;
```

##### `route`

Routes requests matching [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) and [`verb`](https://www.unum.cloud/docs/ucall/cpp/requests.md#verb) to the plain function `function_`, which runs on the polling thread.

[server.hpp:823 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L823)

```cpp
template <request_function_t function_>
status_t route(
    std::string_view path,
    ucall_verb_t verb,
    ucall_body_delivery_t delivery = ucall_body_delivery_buffered_k) noexcept;
```

```cpp
template <auto member_, typename object_type_>
requires a_request_handling_member<member_, object_type_>
status_t route(
    std::string_view path,
    ucall_verb_t verb,
    object_type_ & object,
    ucall_body_delivery_t delivery = ucall_body_delivery_buffered_k) noexcept;
```

Routes like the function overload to the member function `member_` of `object`, which the caller keeps until the server is freed.

```cpp
template <a_request_handler handler_type_>
status_t route(
    std::string_view path,
    ucall_verb_t verb,
    handler_type_ & handler,
    ucall_body_delivery_t delivery = ucall_body_delivery_buffered_k) noexcept;
```

Routes like the function overload to a `handler` with state, which the caller keeps until the server is freed.

Templates capture `{name}` segments and a greedy `{*name}` tail; literal segments match before captures. A streamed `delivery` runs the handler once the headers arrive, the body still to be pulled through `request_t::body_chunk`.

##### `get`

Routes GET requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to the function or member `handler_`, the member's object following the path.

[server.hpp:849 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L849)

```cpp
template <auto handler_, typename... object_types_>
status_t get(std::string_view path, object_types_ &... object) noexcept;
```

```cpp
template <a_request_handler handler_type_>
status_t get(std::string_view path, handler_type_ & handler) noexcept;
```

Routes GET requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to a `handler` the caller keeps.

##### `post`

Routes POST requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to the function or member `handler_`.

[server.hpp:861 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L861)

```cpp
template <auto handler_, typename... object_types_>
status_t post(
    std::string_view path,
    object_types_ &... object) noexcept;
```

```cpp
template <a_request_handler handler_type_>
status_t post(std::string_view path, handler_type_ & handler) noexcept;
```

Routes POST requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to a `handler` the caller keeps.

##### `put`

Routes PUT requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to the function or member `handler_`.

[server.hpp:873 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L873)

```cpp
template <auto handler_, typename... object_types_>
status_t put(std::string_view path, object_types_ &... object) noexcept;
```

```cpp
template <a_request_handler handler_type_>
status_t put(std::string_view path, handler_type_ & handler) noexcept;
```

Routes PUT requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to a `handler` the caller keeps.

##### `patch`

Routes PATCH requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to the function or member `handler_`.

[server.hpp:898 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L898)

```cpp
template <auto handler_, typename... object_types_>
status_t patch(
    std::string_view path,
    object_types_ &... object) noexcept;
```

```cpp
template <a_request_handler handler_type_>
status_t patch(std::string_view path, handler_type_ & handler) noexcept;
```

Routes PATCH requests on [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) to a `handler` the caller keeps.

##### `pooled_batch`

Collects requests matching [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) and [`verb`](https://www.unum.cloud/docs/ucall/cpp/requests.md#verb) from every event loop into one queue, which the returned endpoint drains into the plain function `function_` on its polling thread.

[server.hpp:911 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L911)

```cpp
template <batch_function_t function_>
expected<pooled_batch_endpoint_t> pooled_batch(
    std::string_view path,
    ucall_verb_t verb,
    batching_t const & batching) noexcept;
```

```cpp
template <auto member_, typename object_type_>
requires a_batch_handling_member<member_, object_type_>
expected<pooled_batch_endpoint_t> pooled_batch(
    std::string_view path,
    ucall_verb_t verb,
    batching_t const & batching,
    object_type_ & object) noexcept;
```

Batches like the function overload into the member function `member_` of `object`, which the caller keeps until the server is freed.

```cpp
template <a_batch_handler handler_type_>
expected<pooled_batch_endpoint_t> pooled_batch(
    std::string_view path,
    ucall_verb_t verb,
    batching_t const & batching,
    handler_type_ & handler) noexcept;
```

Batches like the function overload into a `handler` with state, which the caller keeps until the server is freed.

##### `local_batch`

Batches requests matching [`path`](https://www.unum.cloud/docs/ucall/cpp/requests.md#path) and [`verb`](https://www.unum.cloud/docs/ucall/cpp/requests.md#verb) per event loop into the plain function `function_`, which each loop runs on its own requests inside [`take_call`](#take_call) or [`take_calls`](#take_calls), where it may reply; it must not take calls itself.

[server.hpp:943 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L943)

```cpp
template <batch_function_t function_>
expected<local_batch_endpoint_t> local_batch(
    std::string_view path,
    ucall_verb_t verb,
    batching_t const & batching) noexcept;
```

```cpp
template <auto member_, typename object_type_>
requires a_batch_handling_member<member_, object_type_>
expected<local_batch_endpoint_t> local_batch(
    std::string_view path,
    ucall_verb_t verb,
    batching_t const & batching,
    object_type_ & object) noexcept;
```

Batches locally like the function overload into the member function `member_` of `object`, which the caller keeps until the server is freed.

```cpp
template <typename handler_type_>
requires a_batch_handler<handler_type_ const>
expected<local_batch_endpoint_t> local_batch(
    std::string_view path,
    ucall_verb_t verb,
    batching_t const & batching,
    handler_type_ & handler) noexcept;
```

Batches locally like the function overload into a `handler` the caller keeps until the server is freed, called through a const call operator, as every polling loop may run it at the same time.

Every polling loop may run it at once, so the object must be safe to call from several threads.

##### `take_call`

Advances one event loop, running the handlers of the requests it completes on this thread, and waits up to `timeout`; [`status_code_t::connection_closed_k`](https://www.unum.cloud/docs/ucall/cpp/errors.md#connection_closed_k) means the loop retired after [`stop`](#stop).

[server.hpp:974 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L974)

```cpp
status_t take_call(
    std::size_t event_loop,
    std::chrono::microseconds timeout) const noexcept;
```

##### `take_calls`

Drives one event loop on this thread until [`stop`](#stop) or an I/O failure.

[server.hpp:985 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L985)

```cpp
status_t take_calls(std::size_t event_loop) const noexcept;
```

##### `stop`

Requests shutdown from any thread, handlers included: the first call drains, answering the requests already held, and a second one cuts the replies still in flight.

[server.hpp:995 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L995)

```cpp
void stop() const noexcept;
```

##### `event_loop_statistics`

A snapshot of one event loop's counters, readable from any thread while it is polled.

[server.hpp:998 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/server.hpp#L998)

```cpp
expected<event_loop_statistics_t> event_loop_statistics(
    std::size_t event_loop) const noexcept;
```

### Functions

#### `io_backend_name`

The stable name of an I/O backend, such as "linux-uring618".

[types.hpp:313 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/types.hpp#L313)

```cpp
std::string_view io_backend_name(ucall_io_backend_t backend) noexcept;
```

#### `io_backend_from_name`

Reads an I/O backend back from its stable name, "automatic" included.

[types.hpp:316 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/cpp/ucall/types.hpp#L316)

```cpp
expected<ucall_io_backend_t> io_backend_from_name(
    std::string_view name) noexcept;
```
