# Serving

> NewServer takes the interfaces to answer on and optional ServerOptions: the Backend, a CPUClass ceiling that caps the picked class rather than demanding one the machine lacks, a Log sink and a StatsD endpoint in Metrics.

`import "github.com/unum-cloud/ucall"` 1.0.0-rc.1 · b7577426

`NewServer` takes the interfaces to answer on and optional `ServerOptions`: the `Backend`, a `CPUClass` ceiling that caps the picked class rather than demanding one the machine lacks, a `Log` sink and a StatsD endpoint in `Metrics`. It fails rather than substituting when the backend is unavailable or the CPU does not run the class. An `Interface` 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.MemoryDomain` reports the NUMA node the kernel ties an interface’s device to, or -1, so the application inits and polls from goroutines locked to threads there; UCall places nothing by it. `NewInterface` admits 1024 connections, reads one request per connection at a time unless `PipelinedRequests` allows more, and replies still leave in request order. Once an interface holds its whole `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. `MaxRequestBytes` caps a request’s head and buffered body, answering 413 past it, and `ReplyDirectories` names the directories path replies resolve beneath. `SendPolicy` picks how replies of a page or more leave: `SendPolicyAutomatic` copies to peers on this host and pins for the rest, `SendPolicyZeroCopy` pins for every peer and `SendPolicyCopying` copies for every peer. `ListenDescriptor` accepts on a listener another owner opened instead of binding an address, and never closes it. Port zero binds a free port, which `Server.Address` reports.

```go
public := ucall.NewInterface("0.0.0.0:8545")
public.EventLoops, public.Connections, public.PipelinedRequests = 4, 16_384, 16
health := ucall.NewInterface("127.0.0.1:8546")
health.Connections = 4
sink := &ucall.Log{
	Callback: func(level ucall.LogLevel, line []byte) { fmt.Fprintf(os.Stderr, "%d %s\n", level, line) },
	Format:   ucall.LogHuman,
	Level:    ucall.LogWarning,
}
options := &ucall.ServerOptions{
	CPUClassCeiling: ucall.CPUClassSerial,
	Log:             sink,
	Metrics:         &ucall.Metrics{Address: "127.0.0.1:8125", Prefix: "myapp"},
}
server, err := ucall.NewServer([]ucall.Interface{public, health}, options)
if err != nil {
	return err
}
fmt.Println(server.EventLoops(), "event loops on", server.Backend(), "with", server.CPUClassCeiling(), "kernels")

err = server.Get("/users/{user}/files/{*path}", func(request *ucall.Request) {
	user, _ := request.PathParameter("user")
	path, _ := request.PathParameter("path")
	_ = request.Reply(ucall.HTTPStatusOK, nil, append(append(user, ':'), path...))
})
err = server.Route("/anything", ucall.VerbAny, func(request *ucall.Request) {
	_ = request.ReplyError(ucall.HTTPStatusNotImplemented, "This method is not served")
})
```

Routes register before any loop is polled, with `Route` taking any `Verb` and `Get`, `Post`, `Put`, `Delete` and `Patch` naming one, while `RouteWith` also names the `BodyDelivery`. Templates capture `{name}` segments and a greedy `{*name}` tail, literal segments match before captures, and registering one template and verb twice fails with `StatusAlreadyExists`. 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 callback on whichever goroutine produced them, and StatsD datagrams carry each loop’s counters and sampled request latencies, every second unless `Metrics.Interval` says otherwise. `Server.EventLoopStatistics` copies one loop’s counters, from any goroutine while the loop runs; divided by `Requests`, they price one call.

## API

### Types

#### `BatchEndpointStatistics`

BatchEndpointStatistics count a batch endpoint's batches and requests, and why each batch dispatched: on reaching the maximum size, the minimum size, or the latency.

[server.go:1001 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L1001)

```go
type BatchEndpointStatistics struct {
    Batches        uint64
    Requests       uint64
    FilledBatches  uint64
    ReadyBatches   uint64
    ExpiredBatches uint64
}
```

#### `EventLoopStatistics`

EventLoopStatistics are the counters of one event loop since the server started; divided by Requests, they price one call.

[server.go:421 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L421)

```go
type EventLoopStatistics struct {
    Polls                  uint64
    EmptyPolls             uint64
    KernelEnters           uint64
    Submissions            uint64
    Completions            uint64
    KernelEntries          uint64
    Cancellations          uint64
    Accepts                uint64
    Requests               uint64
    ReceiveRearms          uint64
    BytesReceived          uint64
    BytesSent              uint64
    BytesCopied            uint64
    ZeroCopySends          uint64
    ZeroCopyFallbacks      uint64
    CopyingSends           uint64
    FileReadsAsynchronous  uint64
    FileReadsBlocking      uint64
    BytesRead              uint64
    FileWindowOverlaps     uint64
    LingerResets           uint64
    ReadyPasses            uint64
    ReplicaDequeues        uint64
    RefusedRequests        uint64
    HandshakeFailures      uint64
    AuthorizerRefusals     uint64
    ShedConnections        uint64
    WindowsUnpinned        uint64
    ReceiveSlicesRefused   uint64
    ReceivePoolBuffers     uint64
    ReceivePoolBufferBytes uint64
}
```

#### `Log`

Log is the single sink of a server or a client: every line at or above Level, in Format, reaches Callback on whichever goroutine produced it, valid only during the call.

[server.go:693 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L693)

```go
type Log struct {
    Callback func(level LogLevel, line []byte)
    Format   LogFormat
    Level    LogLevel
}
```

#### `LogFormat`

LogFormat is the shape of each log line.

[server.go:681 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L681)

```go
type LogFormat int32
```

#### Values

| `LogHuman` | | LogHuman writes readable lines with normalized units. |
| - | - | - |
| `LogJSON` | | LogJSON writes one JSON document per line. |

#### `LogLevel`

LogLevel is the severity of a log line, from the most verbose up.

[server.go:664 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L664)

```go
type LogLevel int32
```

#### Values

| `LogDebug` | | LogDebug is detail for debugging. |
| - | - | - |
| `LogInfo` | | LogInfo is a normal lifecycle event. |
| `LogWarning` | | LogWarning is something unexpected the library recovered from. |
| `LogError` | | LogError is a failed operation. |
| `LogFatal` | | LogFatal means the server or client cannot continue. |

#### `Metrics`

Metrics is the StatsD endpoint a server sends each event loop's counters and sampled request latencies to.

[server.go:120 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L120)

```go
type Metrics struct {
    Address string
    SampleRate float32
    Prefix string
    Tags []string
    Interval time.Duration
}
```

#### Fields

| `Address` | `string` | Address is the endpoint in "host:port" form. |
| - | - | - |
| `SampleRate` | `float32` | SampleRate is the fraction of finished requests whose latency is reported; zero means all. |
| `Prefix` | `string` | Prefix starts every metric name; empty means "ucall". |
| `Tags` | `[]string` | Tags go on every metric, each "key:value". |
| `Interval` | `time.Duration` | Interval is the time between one event loop's datagrams; zero means one second. |

#### `ServerOptions`

ServerOptions is what a server runs on and reports through, beside its interfaces.

[server.go:134 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L134)

```go
type ServerOptions struct {
    Backend Backend
    CPUClassCeiling CPUClass
    Log *Log
    Metrics *Metrics
}
```

#### Fields

| `Backend` | `Backend` | Backend is the requested I/O backend, failing rather than substituting when unavailable. |
| - | - | - |
| `CPUClassCeiling` | `CPUClass` | CPUClassCeiling caps the CPU class; CPUClassUnknown sets no ceiling. |
| `Log` | `*Log` | Log is where log lines go; nil keeps the server silent. |
| `Metrics` | `*Metrics` | Metrics is where StatsD datagrams go; nil sends none. |

#### `Verb`

Verb is an HTTP method a route takes or a request carries.

[server.go:492 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L492)

```go
type Verb int32
```

#### Values

| `VerbUnknown` | | VerbUnknown is a method the parser did not recognize. |
| - | - | - |
| `VerbGet` | | VerbGet retrieves a resource. |
| `VerbPost` | | VerbPost creates a resource. |
| `VerbPut` | | VerbPut replaces a resource. |
| `VerbDelete` | | VerbDelete removes a resource. |
| `VerbPatch` | | VerbPatch updates part of a resource. |
| `VerbHead` | | VerbHead retrieves the headers alone. |
| `VerbOptions` | | VerbOptions asks which methods a resource takes. |
| `VerbAny` | | VerbAny matches every method, when registering a route only. |

#### Enum `Backend`

Backend is a concrete I/O implementation; BackendAutomatic picks the fastest one available.2

[types.go:382 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/types.go#L382)

```go
type Backend int32
```

#### Values

| `BackendAutomatic` | | BackendAutomatic picks the fastest backend the machine and its limits allow. |
| - | - | - |
| `BackendPOSIX` | | BackendPOSIX polls blocking sockets and files with poll, on any POSIX system. |
| `BackendLinuxEpollAIO` | | BackendLinuxEpollAIO runs epoll for sockets and Linux AIO for files. |
| `BackendLinuxUring612` | | BackendLinuxUring612 runs io_uring as Linux 6.12 provides it. |
| `BackendLinuxUring618` | | BackendLinuxUring618 runs io_uring as Linux 6.18 provides it, with multishot receives. |
| `BackendBSDKqueue` | | BackendBSDKqueue runs kqueue on FreeBSD and macOS. |
| `BackendWindowsIOCP` | | BackendWindowsIOCP runs I/O completion ports on Windows. |
| `BackendWindowsRIO` | | BackendWindowsRIO runs Registered I/O for stream sockets on Windows. |

##### `BackendFromName`

BackendFromName reads a backend back from its stable name, "automatic" included.

[types.go:410 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/types.go#L410)

```go
func BackendFromName(name string) (Backend, error)
```

##### `String`

String renders the backend's stable name, such as "linux-uring618".

[types.go:405 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/types.go#L405)

```go
func (backend Backend) String() string
```

#### Struct `Interface`

Interface is one address a server answers on, with the security and admission limits of the connections arriving there, so one server answers plaintext on loopback and Noise on the wire.1

[server.go:78 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L78)

```go
type Interface struct {
    Address string
    ListenDescriptor *uintptr
    DeviceName string
    Security Security
    NoisePrivateKey *NoiseKey
    NoisePeerKey *NoiseKey
    NoisePreSharedKey *NoiseKey
    KeyExchange KeyExchange
    PeerAuthorizer PeerAuthorizer
    EventLoops uint
    Connections uint
    PipelinedRequests uint
    MaxRequestBytes uint
    ReplyDirectories []string
}
```

#### Fields

| `Address` | `string` | Address is the listening address in "host:port" form; port zero binds a free one, which Server.Address reports. |
| - | - | - |
| `ListenDescriptor` | `*uintptr` | ListenDescriptor is a listening stream socket another owner opened, accepted on instead of Address and never closed. |
| `DeviceName` | `string` | DeviceName pins the interface to a physical device, like "eth0", on Linux only. |
| `Security` | `Security` | Security is the transport connections accepted here run over. |
| `NoisePrivateKey` | `*NoiseKey` | NoisePrivateKey is the server identity every Noise mode needs. |
| `NoisePeerKey` | `*NoiseKey` | NoisePeerKey is the one initiator's static public key Noise KK admits. |
| `NoisePreSharedKey` | `*NoiseKey` | NoisePreSharedKey is a secret every client also holds, mixed first into every handshake; refused on a plaintext interface. |
| `KeyExchange` | `KeyExchange` | KeyExchange is the key exchange of Noise handshakes, which clients must match. |
| `PeerAuthorizer` | `PeerAuthorizer` | PeerAuthorizer vets each client's authenticated static key; Noise XX needs one. |
| `EventLoops` | `uint` | EventLoops accepting here; zero means one, or a named device's receive queues. |
| `Connections` | `uint` | Connections open at once across this interface's loops; zero is refused. |
| `PipelinedRequests` | `uint` | PipelinedRequests one connection may have in flight; zero means one. |
| `MaxRequestBytes` | `uint` | MaxRequestBytes caps a request head and buffered body, answering 413 past it; zero takes the largest receive buffer the kernel grants a socket. |
| `ReplyDirectories` | `[]string` | ReplyDirectories are the directories path parts of replies resolve beneath, by position. |

##### `NewInterface`

NewInterface listens on address, admitting 1024 connections at once.

[server.go:114 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L114)

```go
func NewInterface(address string) Interface
```

#### Struct `LocalBatchEndpoint`

LocalBatchEndpoint is one local batch endpoint whose event loops each fire their own batches, so nothing drains it; it answers statistics until its server closes.1

[server.go:1022 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L1022)

```go
type LocalBatchEndpoint struct {
    // contains filtered or unexported fields
}
```

##### `Statistics`

Statistics copies the endpoint's counters, from any goroutine while its loops run.

[server.go:1062 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L1062)

```go
func (endpoint *LocalBatchEndpoint) Statistics() (BatchEndpointStatistics, error)
```

#### Struct `PooledBatchEndpoint`

PooledBatchEndpoint is one pooled batch endpoint, drained by one goroutine at a time until its server closes.3

[server.go:937 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L937)

```go
type PooledBatchEndpoint struct {
    // contains filtered or unexported fields
}
```

##### `Statistics`

Statistics copies the endpoint's counters, from any goroutine while it is polled.

[server.go:1010 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L1010)

```go
func (endpoint *PooledBatchEndpoint) Statistics() (BatchEndpointStatistics, error)
```

##### `TakeBatch`

TakeBatch runs the handler on this goroutine if a batch is due, waiting up to timeout for one; zero performs one nonblocking round.

[server.go:977 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L977)

```go
func (endpoint *PooledBatchEndpoint) TakeBatch(
    timeout time.Duration,
) error
```

##### `TakeBatches`

TakeBatches runs the handler on this goroutine for every due batch until the server stops.

[server.go:989 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L989)

```go
func (endpoint *PooledBatchEndpoint) TakeBatches() error
```

#### Struct `Server`

Server is an HTTP server over one or more interfaces, polled by application goroutines.20

[server.go:153 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L153)

```go
type Server struct {
    // contains filtered or unexported fields
}
```

Register every route before any loop is polled, then poll each event loop from one goroutine at a time, as `go server.TakeCalls(0)` does. Close it once its polling goroutines returned.

##### `NewServer`

NewServer starts a server answering on interfaces, with the backend, CPU class, log sink and StatsD endpoint options name; nil options take every default.

[server.go:168 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L168)

```go
func NewServer(
    interfaces []Interface,
    config *ServerOptions,
) (*Server, error)
```

##### `Address`

Address is the numeric address interface index listens on, with the port it bound, and false past the last interface.

[server.go:282 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L282)

```go
func (server *Server) Address(index uint) (string, bool)
```

##### `Backend`

Backend is the I/O backend the server resolved to.

[server.go:275 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L275)

```go
func (server *Server) Backend() Backend
```

##### `CPUClassCeiling`

CPUClassCeiling is the CPU class the server resolved to under its ceiling.

[server.go:278 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L278)

```go
func (server *Server) CPUClassCeiling() CPUClass
```

##### `Close`

Close frees the server once its polling goroutines returned and its bound clients are closed.

[server.go:247 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L247)

```go
func (server *Server) Close() error
```

It is idempotent.

##### `Delete`

Delete routes DELETE requests on path to handler.

[server.go:362 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L362)

```go
func (server *Server) Delete(
    path string,
    handler func(request *Request),
) error
```

##### `EventLoopStatistics`

EventLoopStatistics copies one loop's counters, from any goroutine while it is polled.

[server.go:456 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L456)

```go
func (server *Server) EventLoopStatistics(
    eventLoop uint,
) (EventLoopStatistics, error)
```

##### `EventLoops`

EventLoops is how many event loops the server runs, each polled by one goroutine at a time.

[server.go:266 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L266)

```go
func (server *Server) EventLoops() uint
```

##### `Get`

Get routes GET requests on path to handler.

[server.go:347 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L347)

```go
func (server *Server) Get(
    path string,
    handler func(request *Request),
) error
```

##### `LocalBatch`

LocalBatch batches requests matching path and verb per event loop into handler, which each loop runs on its own requests inside TakeCall or TakeCalls, where it may reply; it must not take calls itself.

[server.go:1030 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L1030)

```go
func (server *Server) LocalBatch(
    path string,
    verb Verb,
    options Batching,
    handler func(batch Batch),
) (*LocalBatchEndpoint, error)
```

Every polling loop may run it at once.

##### `MemoryDomain`

MemoryDomain is the NUMA node the kernel ties interface index's device to, or -1, and false past the last interface; init and poll from goroutines locked to threads there.

[server.go:292 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L292)

```go
func (server *Server) MemoryDomain(index uint) (int32, bool)
```

##### `Patch`

Patch routes PATCH requests on path to handler.

[server.go:367 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L367)

```go
func (server *Server) Patch(
    path string,
    handler func(request *Request),
) error
```

##### `PooledBatch`

PooledBatch collects requests matching path and verb from every event loop into one queue, which the returned endpoint drains into handler on whichever goroutine polls it.

[server.go:944 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L944)

```go
func (server *Server) PooledBatch(
    path string,
    verb Verb,
    options Batching,
    handler func(batch Batch),
) (*PooledBatchEndpoint, error)
```

##### `Post`

Post routes POST requests on path to handler.

[server.go:352 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L352)

```go
func (server *Server) Post(
    path string,
    handler func(request *Request),
) error
```

##### `Put`

Put routes PUT requests on path to handler.

[server.go:357 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L357)

```go
func (server *Server) Put(
    path string,
    handler func(request *Request),
) error
```

##### `Route`

Route sends requests matching path and verb to handler, which runs on the polling goroutine.

[server.go:312 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L312)

```go
func (server *Server) Route(
    path string,
    verb Verb,
    handler func(request *Request),
) error
```

Templates capture {name} segments and a greedy {\*name} tail, read back through Request.PathParameter; literal segments match before captures. A handler that neither replies nor detaches its request answers 500, and one that panics crashes the process.

##### `RouteWith`

RouteWith routes like Server.Route, running handler once the body is buffered, or with BodyStreamed as soon as the headers arrived, the body still to be pulled through DetachedRequest.BodyChunk.

[server.go:319 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L319)

```go
func (server *Server) RouteWith(
    path string,
    verb Verb,
    delivery BodyDelivery,
    handler func(request *Request),
) error
```

##### `Stop`

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

[server.go:417 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L417)

```go
func (server *Server) Stop()
```

##### `TakeCall`

TakeCall advances one event loop, running the handlers of the requests it completes on this goroutine, and waits up to timeout for progress; zero performs one nonblocking round.

[server.go:384 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L384)

```go
func (server *Server) TakeCall(
    eventLoop uint,
    timeout time.Duration,
) (Polling, error)
```

##### `TakeCalls`

TakeCalls drives one event loop on this goroutine until Server.Stop or an I/O failure.

[server.go:402 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/server.go#L402)

```go
func (server *Server) TakeCalls(eventLoop uint) error
```
