# UCall for Go

> Clients and servers behind one C ABI, with Noise instead of TLS, io_uring to IOCP and server-side batching, from Go

`go get github.com/unum-cloud/ucall/golang@main` 1.0.0-rc.1 · b7577426

## Installation

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

Fetch the module, which serves and calls HTTP, in plaintext or over Noise, from Go:

```sh
go get github.com/unum-cloud/ucall/golang@main
```

The package binds the C interface in `c/ucall/` through cgo and links the `ucall_static` archive, so building needs Go 1.24 or newer with cgo enabled and a C toolchain. Building the archive takes CMake 4.3 and a C++23 compiler: GCC 15, Clang 22 with libstdc++ 15 or libc++ 22, Xcode 26 or VS 2026. Build it from a checkout and point cgo at it for the current shell, or install it where the linker looks:

```sh
cmake -B build_release -D CMAKE_BUILD_TYPE=Release
cmake --build build_release --target ucall_static
export CGO_LDFLAGS="-L$PWD/build_release"
```

On Linux the archive’s io_uring backends also link the `liburing` archive the same build leaves beside it. Pin a branch or a commit, as in `@main` or `@<commit>`, which `go.sum` records as a pseudo-version. The library picks its I/O backend and CPU kernels when a server or client starts, so one build adapts to the kernel and CPU it runs on.

### API

#### Functions

##### `Version`

Version reports the version of the linked library, a release-candidate suffix included.

[ucall.go:379 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/ucall.go#L379)

```go
func Version() string
```

## Quickstart

1.0.0-rc.1 · b7577426

A server answers on one or more interfaces, and a client calls it; neither starts a goroutine.

```go
package main

import (
	"fmt"
	"log"

	ucall "github.com/unum-cloud/ucall/golang"
)

func main() {
	server, err := ucall.NewServer([]ucall.Interface{ucall.NewInterface("127.0.0.1:0")}, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer server.Close()
	err = server.Get("/hello/{name}", func(request *ucall.Request) {
		name, _ := request.PathParameter("name")
		greeting := append([]byte("Hello, "), name...)
		_ = request.Reply(ucall.HTTPStatusOK, []string{"content-type: text/plain"}, greeting)
	})
	if err != nil {
		log.Fatal(err)
	}
	address, _ := server.Address(0)
	polled := make(chan error)
	go func() { polled <- server.TakeCalls(0) }()

	client, err := ucall.NewClient(&ucall.ClientOptions{Connections: 1})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	response, err := client.Get("http://" + address + "/hello/world")
	server.Stop()
	if err := <-polled; err != nil {
		log.Fatal(err)
	}
	if err != nil {
		log.Fatal(err)
	}
	defer response.Close()
	body, err := response.Body()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(body))
}
```

The polling goroutine runs the handler, the client blocks in `Get` until its response arrives, and `Stop` releases the polling goroutine. `golang/example_test.go` compiles and runs this Quickstart.

## Serving

`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
```

## Requests

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

A handler receives each `*Request`. Its reads view the received bytes until the reply: `Verb`, `Path`, `QueryString`, `PathParameter`, `Query`, `Header` and `Body`, with `Peer` naming the interface it arrived on, the client’s authenticated Noise key and its `PeerAddress`. Every read that can fail answers its value beside an error, so a missing header or parameter reports `StatusNotFound` and a body read on a streamed route `StatusInvalidArgument`. The path and query values stay percent-encoded as sent, which `ucall.DecodePercent` decodes, header names match case-insensitively, and the body arrives whole, decoded from chunked framing if it was sent that way. `Fields` yields every header field in arrival order as a name and a value, names lowercased and values trimmed, as a proxy forwards a head. `PathSegmentsCount` and `PathSegment` read the path component by component, and `PartsCount` and `Part` read a `multipart/form-data` body as `RequestPart` s.

```go
err = server.Post("/orders/{order}", func(request *ucall.Request) {
	token, err := request.Header("authorization")
	if err != nil {
		_ = request.ReplyError(ucall.HTTPStatusUnauthorized, "sign in first")
		return
	}
	order, _ := request.PathParameter("order")
	receipt := append(append(append([]byte{}, order...), " by "...), token...)
	headers := []string{"content-type: text/plain", "cache-control: no-store"}
	_ = request.Reply(ucall.HTTPStatusCreated, headers, receipt)
})
```

`Reply` and `ReplyError` take the request, so a request is answered at most once, and Content-Length, Date and Server are generated. A reply copies what it sends before it returns, so a body may view the request’s bytes. A handler that neither replies nor detaches its request answers 500 once it returns, and a handler that panics crashes the process, as a panic cannot unwind through the library. The library clears the request’s handle once a reply took it, a closed connection included, which reports `StatusConnectionClosed`; a reply it refused keeps the handle, and the handler’s return then answers 500.

### API

#### Types

##### `AddressFamily`

AddressFamily is the family of a peer's socket address.

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

```go
type AddressFamily uint8
```

##### Values

| `AddressUnknown` | | AddressUnknown means no address was read. |
| - | - | - |
| `AddressIPv4` | | AddressIPv4 is an IPv4 peer. |
| `AddressIPv6` | | AddressIPv6 is an IPv6 peer. |
| `AddressUnix` | | AddressUnix is a local socket peer. |

##### `HTTPStatus`

HTTPStatus is an HTTP status code, named or not.

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

```go
type HTTPStatus uint32
```

##### Values

| `HTTPStatusOK` | | |
| - | - | - |
| `HTTPStatusCreated` | | |
| `HTTPStatusNoContent` | | |
| `HTTPStatusPartialContent` | | |
| `HTTPStatusMovedPermanently` | | |
| `HTTPStatusFound` | | |
| `HTTPStatusNotModified` | | |
| `HTTPStatusBadRequest` | | |
| `HTTPStatusUnauthorized` | | |
| `HTTPStatusForbidden` | | |
| `HTTPStatusNotFound` | | |
| `HTTPStatusMethodNotAllowed` | | |
| `HTTPStatusTimeout` | | |
| `HTTPStatusConflict` | | |
| `HTTPStatusPreconditionFailed` | | |
| `HTTPStatusPayloadTooLarge` | | |
| `HTTPStatusRangeNotSatisfiable` | | |
| `HTTPStatusTooManyRequests` | | |
| `HTTPStatusInternalError` | | |
| `HTTPStatusNotImplemented` | | |
| `HTTPStatusBadGateway` | | |
| `HTTPStatusServiceUnavailable` | | |
| `HTTPStatusGatewayTimeout` | | |
| `HTTPStatusVersionNotSupported` | | |

##### `Peer`

Peer is who sent a request: the interface it arrived on, the client's authenticated static key, zeroed in plaintext, and its socket address.

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

```go
type Peer struct {
    NetworkInterfaceIndex uint
    StaticKey             NoiseKey
    Address               PeerAddress
}
```

##### `PeerAddress`

PeerAddress is a socket address: IPv4 in the first 4 bytes, IPv6 in all 16, both in network order, with the port and the IPv6 scope; a local socket carries only its family.

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

```go
type PeerAddress struct {
    Bytes  [16]byte
    Scope  uint32
    Port   uint16
    Family AddressFamily
    // contains filtered or unexported fields
}
```

##### `PercentMode`

PercentMode says whether a '+' decodes as itself, in a path, or as a space, in a query.

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

```go
type PercentMode int32
```

##### Values

| `PercentPath` | | PercentPath decodes a path, where '+' stays itself. |
| - | - | - |
| `PercentQuery` | | PercentQuery decodes a query value, where '+' is a space. |

##### `RequestPart`

RequestPart is one part of a multipart/form-data body, viewing the received bytes.

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

```go
type RequestPart struct {
    Name        []byte
    ContentType []byte
    Data        []byte
}
```

##### Struct `BodyChunk`

BodyChunk is the body bytes a pull answered, valid until the next pull.1

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

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

###### `Bytes`

Bytes are the pulled bytes, empty once the body ended.

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

```go
func (chunk BodyChunk) Bytes() []byte
```

##### Struct `Deferred`

Deferred is a submitted call, which holds its outcome and inputs until it is final, owned by the one goroutine that polls or waits on it.3

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

```go
type Deferred[Result any] struct {
    // contains filtered or unexported fields
}
```

Status polls without blocking, Wait blocks until the call is final and hands back its result, and Close waits the same way and drops it. A Deferred dropped without Wait or Close is released by the collector once the call is final, never blocking on it: until then every later collection checks it again.

###### `Close`

Close blocks until the call is final, releases its pins, and reports the call's failure.

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

```go
func (deferred *Deferred[Result]) Close() error
```

It is idempotent and safe after Wait.

###### `Status`

Status reports StatusDeferred until the call is final, then its final status, without blocking.

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

```go
func (deferred *Deferred[Result]) Status() Status
```

###### `Wait`

Wait blocks until the call is final, releases its pins, then hands back its result, the same every time it is asked.

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

```go
func (deferred *Deferred[Result]) Wait() (Result, error)
```

##### Struct `DetachedRequest`

DetachedRequest is a request taken off its polling goroutine, and the only owner of the verbs that may finish later: ReplyParts, ReplyStream and BodyChunk.20

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

```go
type DetachedRequest struct {
    Request
}
```

Close answers 500 for one never replied to.

###### `BodyChunk`

BodyChunk pulls the body bytes decoded since the last pull, final once they arrive and empty once the body ended; on a buffered route the first pull is the whole body.

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

```go
func (detached *DetachedRequest) BodyChunk() (*Deferred[BodyChunk], error)
```

A pull on the polling goroutine finding nothing fails with StatusWouldBlock instead.

###### `Close`

Close answers 500 if the request was never replied to.

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

```go
func (detached *DetachedRequest) Close() error
```

It is idempotent.

###### `ReplyParts`

ReplyParts answers with status, header lines and parts concatenated into the body, its length measured from the files, and consumes the request.

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

```go
func (detached *DetachedRequest) ReplyParts(
    status HTTPStatus,
    headers []string,
    parts []ReplyPart,
) (*Deferred[struct{}], error)
```

It is final at once for bytes alone, and with a file or path part stays deferred until every part is sent; a part failing before the head left replaces the reply with 404, 416 or 500, and the Deferred reports the cause.

###### `ReplyStream`

ReplyStream sends the status line and header lines and opens a body appended part by part, which is chunked unless a Content-Length line declares its length.

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

```go
func (detached *DetachedRequest) ReplyStream(
    status HTTPStatus,
    headers []string,
) (*ReplyStream, error)
```

###### `*Body`

× 2 Body is the body, decoded from chunked framing if it arrived that way; a streamed route refuses it, as DetachedRequest.BodyChunk pulls its body.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Body() ([]byte, error)
```

###### `*Detach`

× 2 Detach hands the request to a goroutine that may wait, where it gains the replies that may finish later; the polling goroutine itself must never wait on them.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Detach() *DetachedRequest
```

###### `*Fields`

× 2 Fields yields every header field line in arrival order, repeated names apart, each name lowercased as the parser keeps it and its value trimmed.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Fields() iter.Seq2[[]byte, []byte]
```

###### `*Header`

× 2 Header is the value of header name, matched case-insensitively, failing with StatusNotFound without one.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Header(
    name string,
) ([]byte, error)
```

###### `*Part`

× 2 Part is part index of a multipart/form-data body, its payload undecoded.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Part(
    index uint,
) (RequestPart, error)
```

###### `Parts*PartsCount`

× 2 PartsCount is how many parts a multipart/form-data body has, zero for any other body.

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

Inherited from `Request`

```go
func (request *DetachedRequest) PartsPartsCount() uint
```

###### `*Path`

× 2 Path is the path as sent, still percent-encoded, without the query.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Path() ([]byte, error)
```

###### `Path*PathParameter`

× 2 PathParameter is the value the route's template captured under name, case-sensitive, failing with StatusNotFound without one.

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

Inherited from `Request`

```go
func (request *DetachedRequest) PathPathParameter(
    name string,
) ([]byte, error)
```

###### `Path*PathSegment`

× 2 PathSegment is path component index, counting from zero, failing with StatusNotFound past the last one.

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

Inherited from `Request`

```go
func (request *DetachedRequest) PathPathSegment(
    index uint,
) ([]byte, error)
```

###### `PathSegments*PathSegmentsCount`

× 2 PathSegmentsCount is how many path components the request has, as sent.

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

Inherited from `Request`

```go
func (request *DetachedRequest) PathSegmentsPathSegmentsCount() uint
```

###### `*Peer`

× 2 Peer is the interface the request arrived on, the client's key and its address, readable after its connection closed.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Peer() (Peer, error)
```

###### `*Query`

× 2 Query is the value of query parameter name, case-sensitive and still percent-encoded, failing with StatusNotFound without one.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Query(name string) ([]byte, error)
```

###### `Query*QueryString`

× 2 QueryString is the query after the first '?', still percent-encoded, or empty without one.

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

Inherited from `Request`

```go
func (request *DetachedRequest) QueryQueryString() ([]byte, error)
```

###### `*Reply`

× 2 Reply answers with status, full header lines like "content-type: text/plain" and body, and consumes the request; the length, date and server lines are generated.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Reply(
    status HTTPStatus,
    headers []string,
    body []byte,
) error
```

###### `Reply*ReplyError`

× 2 ReplyError answers with an error status, 400 or above, and a plain-text message, and consumes the request.

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

Inherited from `Request`

```go
func (request *DetachedRequest) ReplyReplyError(
    status HTTPStatus,
    message string,
) error
```

###### `*Verb`

× 2 Verb is the HTTP method, which tells apart the requests of a VerbAny route.

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

Inherited from `Request`

```go
func (request *DetachedRequest) Verb() Verb
```

##### Struct `ReplyPart`

ReplyPart is one part of a reply body: bytes in memory, a range of the caller's unbuffered descriptor, or a range of a file beneath one of the interface's reply directories.3

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

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

###### `BytesPart`

BytesPart is bytes in memory, copied before the reply returns.

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

```go
func BytesPart(bytes []byte) ReplyPart
```

###### `FilePart`

FilePart is a range of a regular file the event loop reads unbuffered after the call returns.

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

```go
func FilePart(file FileRange) ReplyPart
```

###### `PathPart`

PathPart is a range of a file the event loop opens beneath a reply directory and closes once sent.

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

```go
func PathPart(path PathRange) ReplyPart
```

##### Struct `Request`

Request is one received request, answered at most once.

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

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

Its reads view the received bytes until the reply, which consumes it; a handler that neither replies nor detaches it answers 500.

#### Functions

##### `DecodePercent`

DecodePercent decodes the percent escapes of a path or a query value, which requests hold still encoded, into a new slice.

[ucall.go:476 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/ucall.go#L476)

```go
func DecodePercent(
    encoded []byte,
    mode PercentMode,
) ([]byte, error)
```

## Files and Streams

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

Handlers run on the polling goroutine, so a reply or a pull that finishes later runs on a worker: `Request.Detach` hands the request over as a `*DetachedRequest`, which reads and replies like a `Request` and alone has the verbs below.

| Verb | Returns | Final when |
| - | - | - |
| `ReplyParts(status, headers, parts)` | `*Deferred[struct{}]` | every part is sent |
| `ReplyStream(status, headers)` | `*ReplyStream` with `Append` and `End` | `End` answers a `*Deferred` |
| `BodyChunk()` | `*Deferred[BodyChunk]` | the next bytes arrived |

#### Serving a File

Reply with a file beneath a served directory from a worker goroutine, while the event loop opens and sends it:

```go
handed := make(chan *ucall.DetachedRequest, 16)
videos := ucall.NewInterface("0.0.0.0:8080")
videos.ReplyDirectories = []string{"/srv/videos"}
server, err := ucall.NewServer([]ucall.Interface{videos}, nil)
if err != nil {
	return err
}
err = server.Get("/videos/{name}", func(request *ucall.Request) { handed <- request.Detach() })
go server.TakeCalls(0)
for detached := range handed {
	name, _ := detached.PathParameter("name")
	parts := []ucall.ReplyPart{ucall.PathPart(ucall.PathRange{Directory: 0, Path: string(name)})}
	if sent, err := detached.ReplyParts(ucall.HTTPStatusOK, nil, parts); err == nil {
		_, _ = sent.Wait()
	}
}
```

`ReplyParts` concatenates `BytesPart`, `MemoryPart`, `PathPart` and `FilePart` parts into one body whose Content-Length is measured from the files. A path part resolves beneath the interface’s `ReplyDirectories`, refusing absolute paths, `..` and links leading out, and a file part names the caller’s unbuffered descriptor until the reply is final, while bytes and paths are copied before the call returns. A memory part is sent in place, so its bytes stay pinned and unchanged until the reply is final, and a stream holding one must reach `End` or `Close`. A missing, unreadable or too short file replaces the reply with 404, 416 or 500 before its head leaves, and the `Deferred` reports the cause. `Deferred.Status` polls, `Deferred.Wait` parks the goroutine in the library until the call is final, `Deferred.Close` waits and drops it, and a `Deferred` dropped without either is released by the collector once final. A refusal comes back as the error beside a nil `Deferred`, before anything is submitted.

#### Streaming a Reply

Send a reply of unknown length row by row, as a chunked stream:

```go
func sendRows(detached *ucall.DetachedRequest, rows []string) error {
	stream, err := detached.ReplyStream(ucall.HTTPStatusOK, []string{"content-type: text/csv"})
	if err != nil {
		return err
	}
	for _, row := range rows {
		if err := stream.Append([]ucall.ReplyPart{ucall.BytesPart([]byte(row))}); err != nil {
			return err
		}
	}
	ended, err := stream.End()
	if err != nil {
		return err
	}
	_, err = ended.Wait()
	return err
}
```

The stream is chunked unless a Content-Length header declares the length, `Append` refuses with `StatusWouldBlock`, queueing nothing, while the peer lags behind, and `ReplyStream.Close` ends a stream not yet ended.

#### Streaming an Upload

Take a large upload chunk by chunk as it arrives, rather than buffered whole, here only counting its bytes:

```go
func store(detached *ucall.DetachedRequest) error {
	receivedBytes := 0
	for {
		pulled, err := detached.BodyChunk()
		if err != nil {
			return err
		}
		chunk, err := pulled.Wait()
		if err != nil {
			return err
		}
		if len(chunk.Bytes()) == 0 {
			break
		}
		receivedBytes += len(chunk.Bytes())
	}
	return detached.Reply(ucall.HTTPStatusOK, nil, []byte(strconv.Itoa(receivedBytes)))
}
```

A route registered through `Server.RouteWith` with `BodyStreamed` runs its handler once the headers arrive and hands `request.Detach()` to a worker, whose pulls wait for the next bytes, each valid until the next pull. On the polling goroutine a pull with nothing decoded fails with `StatusWouldBlock` instead, as nothing arrives while it runs.

### API

#### Types

##### `FileRange`

FileRange is a range of the caller's unbuffered descriptor, open until the reply is final.

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

```go
type FileRange struct {
    Descriptor int
    Offset     uint64
    Length uint64
}
```

##### Fields

| `Length` | `uint64` | Length is the range's byte count; zero sends through the end of the file. |
| - | - | - |

##### `PathRange`

PathRange is a range of a file beneath one of the interface's reply directories.

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

```go
type PathRange struct {
    Directory uint
    Path      string
    Offset    uint64
    Length uint64
}
```

##### Fields

| `Length` | `uint64` | Length is the range's byte count; zero sends through the end of the file. |
| - | - | - |

##### Struct `ReplyStream`

ReplyStream is a reply whose head left and whose body is appended part by part until End.3

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

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

###### `Append`

Append queues parts on the body together, or none of them, failing with StatusWouldBlock while the peer lags behind the parts already queued.

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

```go
func (stream *ReplyStream) Append(parts []ReplyPart) error
```

###### `Close`

Close ends a stream not yet ended and waits for its file parts.

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

```go
func (stream *ReplyStream) Close() error
```

It is idempotent.

###### `End`

End ends the body, final once its file parts are sent.

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

```go
func (stream *ReplyStream) End() (*Deferred[struct{}], error)
```

## Batches

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

A pooled batch endpoint gathers matching requests from every event loop into one queue and hands them to its handler in batches, which suits work that is cheaper per request in bulk, like GPU inference.

```go
network := ucall.NewInterface("127.0.0.1:0")
network.PipelinedRequests = 8
server, err := ucall.NewServer([]ucall.Interface{network}, nil)
if err != nil {
	return err
}
batching := ucall.Batching{MinSize: 16, MaxSize: 64, MaxLatency: 2 * time.Millisecond}
infer, err := server.PooledBatch("/infer", ucall.VerbPost, batching, func(batch ucall.Batch) {
	for index := range batch.Len() {
		request := batch.Take(index)
		body, err := request.Body()
		if err != nil {
			_ = request.ReplyError(ucall.HTTPStatusBadRequest, err.Error())
			continue
		}
		_ = request.Reply(ucall.HTTPStatusOK, nil, []byte(strconv.Itoa(len(body))))
	}
})
if err != nil {
	return err
}
go server.TakeCalls(0)
go infer.TakeBatches()
```

`Batching` dispatches as soon as `MinSize` requests wait, never more than `MaxSize` at once, and a smaller batch once its oldest request waited `MaxLatency`; zero fields mean 1, 32 and 10 milliseconds. The handler runs on the goroutine polling the endpoint through `TakeBatch` or `TakeBatches`, never on an event loop, so a slow batch never stalls the network. A `Batch` holds its requests in arrival order, and `Take` hands one over, to be replied to then or later from any goroutine; a request never taken stays unanswered until the server closes. The queue holds as many requests as the interfaces admit at once, connections times pipelined requests, and refuses more with 503. `PooledBatchEndpoint.Statistics` counts batches and requests, and whether each was dispatched on reaching `MaxSize`, on reaching `MinSize`, or once `MaxLatency` passed. `Server.LocalBatch` takes the same handler and `Batching`, but each event loop fires its own batches inside `TakeCall` or `TakeCalls`, so no goroutine drains them and the handler may reply there; its `LocalBatchEndpoint` offers only `Statistics`.

### API

#### Types

##### `Batching`

Batching says when a batch endpoint dispatches; zero fields take 1, 32 and 10 milliseconds.

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

```go
type Batching struct {
    MinSize uint
    MaxSize uint
    MaxLatency time.Duration
}
```

##### Fields

| `MinSize` | `uint` | MinSize is how many waiting requests dispatch a batch at once. |
| - | - | - |
| `MaxSize` | `uint` | MaxSize is how many requests one batch holds at most. |
| `MaxLatency` | `time.Duration` | MaxLatency is how long the oldest request of a smaller batch waits before it dispatches. |

##### `BodyDelivery`

BodyDelivery says when a body is handed over: once buffered, or at headers time with the body pulled chunk by chunk.

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

```go
type BodyDelivery int32
```

##### Values

| `BodyBuffered` | | BodyBuffered hands the body over once it is whole. |
| - | - | - |
| `BodyStreamed` | | BodyStreamed hands the request or response over once the head arrived. |

##### Struct `Batch`

Batch holds the requests one batch callback received, in arrival order, each taken once.2

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

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

A request never taken stays unanswered until the server is closed.

###### `Len`

Len is how many requests the batch holds.

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

```go
func (batch Batch) Len() int
```

###### `Take`

Take hands over request index, which its taker replies to.

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

```go
func (batch Batch) Take(index int) *Request
```

## Calling

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

A `Client` submits calls without driving the network, and polls to drive them and collect what finished. It holds up to `Connections` connections, reusing them across calls, and carries up to `PipelinedCalls` calls on each.

```go
client, err := ucall.NewClient(&ucall.ClientOptions{Connections: 4, PipelinedCalls: 16})
if err != nil {
	return err
}
defer client.Close()
for index := range uint64(64) {
	call := ucall.ClientCall{Verb: ucall.VerbPost, URL: "http://127.0.0.1:8545/infer", Body: []byte{byte(index)}}
	if err := client.Submit(call, index); err != nil {
		return err
	}
}
completed := make([]ucall.Completed, 16)
for remaining := 64; remaining != 0; {
	finished, err := client.TakeCompleted(completed, time.Second)
	if err != nil {
		return err
	}
	for _, done := range finished {
		if done.Err != nil {
			fmt.Println("call", done.Context, "failed:", done.Err)
			continue
		}
		fmt.Println("call", done.Context, "answered", done.Response.StatusCode())
		_ = done.Response.Close()
	}
	remaining -= len(finished)
}

health, err := client.Get("http://127.0.0.1:8545/health")
if err != nil {
	return err
}
defer health.Close()
cacheControl, _ := health.Header("cache-control")
```

`Submit` takes a `ClientCall`, whose URL, header lines and body the client pins until the call completes, and tags it with a `uint64` context. A call admitted once completes exactly once, and a client already holding `Calls` unretrieved calls refuses more with `StatusContended`. `TakeCompleted` drives every admitted call and fills a caller-provided slice with finished ones, waiting up to its timeout for the first, and a zero timeout performs one nonblocking round. `Get`, `Post`, `Put`, `Delete`, `Patch` and `Call` submit one call and poll until it finishes, while the library keeps the completions of other calls queued for the next `TakeCompleted`. `ClientCall.Options` carries the call’s own `ClientCallOptions`: a timeout in place of the client’s, retries, redirect hops, security, and the client and server keys.

Every received response is a `*Response`, whatever its HTTP status, and only a failed exchange is an error. A `Response` owns its received bytes, stays readable after its `Client` is closed and may move to another goroutine; `Close` frees it, and the collector frees one dropped. Closing the client cancels the calls still in flight and discards completions not yet retrieved.

#### Streamed Response Bodies

Download a body larger than the client buffers by pulling it chunk by chunk as it lands:

```go
call := ucall.ClientCall{Verb: ucall.VerbGet, URL: "http://127.0.0.1:8545/dataset.bin"}
call.Options.BodyDelivery = ucall.BodyStreamed
response, err := client.Call(call)
if err != nil {
	return err
}
defer response.Close()
receivedBytes := 0
for {
	chunk, err := response.BodyChunk()
	if errors.Is(err, ucall.StatusWouldBlock) {
		_, _ = client.TakeCompleted(nil, time.Millisecond)
		continue
	}
	if err != nil {
		return err
	}
	if len(chunk) == 0 {
		break
	}
	receivedBytes += len(chunk)
}
```

A call whose `BodyDelivery` is `BodyStreamed` completes once its head arrived, so a download larger than `MaxResponseBytes` is pulled through `Response.BodyChunk` as it lands, while `Response.Body` reads empty. A pull never waits: with nothing decoded yet it fails with `StatusWouldBlock`, and an empty `TakeCompleted` advances the client, moving the next bytes in. Every streamed response is pulled to its end or closed, as its connection carries no other call meanwhile; closing it early closes that connection and fails the calls pipelined behind it.

### API

#### Types

##### `ClientCall`

ClientCall is one call to submit; the client pins its URL, header lines and body until it completes.

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

```go
type ClientCall struct {
    Verb    Verb
    URL     string
    Headers []string
    Body    []byte
    Options ClientCallOptions
}
```

##### `ClientCallOptions`

ClientCallOptions is one call's time budget, retries, redirects, security and body delivery, each zero field taking its default.

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

```go
type ClientCallOptions struct {
    Timeout time.Duration
    MaxRetries uint
    MaxRedirects uint
    Security Security
    NoisePrivateKey *NoiseKey
    NoisePeerKey *NoiseKey
    NoisePreSharedKey *NoiseKey
    KeyExchange KeyExchange
    BodyDelivery BodyDelivery
}
```

##### Fields

| `Timeout` | `time.Duration` | Timeout bounds the call, queueing and redirects included; zero takes the client's. |
| - | - | - |
| `MaxRetries` | `uint` | MaxRetries are additional connection attempts; zero means 3. |
| `MaxRedirects` | `uint` | MaxRedirects are the redirect hops followed; zero means 5. |
| `Security` | `Security` | Security is the transport the call runs over. |
| `NoisePrivateKey` | `*NoiseKey` | NoisePrivateKey is the client's identity, needed by Noise KK. |
| `NoisePeerKey` | `*NoiseKey` | NoisePeerKey is the server's expected key, needed by Noise IK and KK. |
| `NoisePreSharedKey` | `*NoiseKey` | NoisePreSharedKey is the secret the server's interface also holds, mixed first into the handshake; refused on a plaintext call. |
| `KeyExchange` | `KeyExchange` | KeyExchange is the key exchange of the handshake, which the server must match. |
| `BodyDelivery` | `BodyDelivery` | BodyDelivery completes the call once the body is buffered, or once the head arrived. |

##### `ClientOptions`

ClientOptions is what a client may hold open at once, how long it waits, and who it is under Noise.

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

```go
type ClientOptions struct {
    Connections uint
    PipelinedCalls uint
    Calls uint
    ConnectTimeout time.Duration
    CallTimeout time.Duration
    NoisePrivateKey *NoiseKey
    PeerAuthorizer PeerAuthorizer
    Backend Backend
    CPUClassCeiling CPUClass
    Log *Log
    MaxResponseBytes uint
    Server *Server
    EventLoop uint
}
```

Connections is required; every other zero field takes its documented default.

##### Fields

| `Connections` | `uint` | Connections open at once; zero fails with StatusInvalidArgument. |
| - | - | - |
| `PipelinedCalls` | `uint` | PipelinedCalls one connection may carry at once; zero means one. |
| `Calls` | `uint` | Calls admitted at once, unretrieved completions included; zero means Connections times PipelinedCalls. |
| `ConnectTimeout` | `time.Duration` | ConnectTimeout bounds establishing a connection; zero means 5 seconds. |
| `CallTimeout` | `time.Duration` | CallTimeout bounds a full exchange, queueing and redirects included; zero means 30 seconds. |
| `NoisePrivateKey` | `*NoiseKey` | NoisePrivateKey is the client identity for Noise handshakes. |
| `PeerAuthorizer` | `PeerAuthorizer` | PeerAuthorizer vets each server's authenticated static key; Noise XX calls need one. |
| `Backend` | `Backend` | Backend is the requested I/O backend. |
| `CPUClassCeiling` | `CPUClass` | CPUClassCeiling caps the CPU class; CPUClassUnknown sets no ceiling. |
| `Log` | `*Log` | Log is where log lines go; nil keeps the client silent. |
| `MaxResponseBytes` | `uint` | MaxResponseBytes caps what a call buffers, failing it with StatusOverflow past the cap; zero takes the largest receive buffer the kernel grants a socket. |
| `Server` | `*Server` | Server, when set, drives this client through one of its event loops, polled on that loop's goroutine only; the client must be closed before the server. |
| `EventLoop` | `uint` | EventLoop is which of Server's event loops. |

##### `Completed`

Completed is one finished call: the context it was submitted with, and its response, whatever its HTTP status, or why none arrived.

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

```go
type Completed struct {
    Context  uint64
    Response *Response
    Err      error
}
```

##### Struct `Client`

Client is an HTTP client used by one goroutine at a time.10

[client.go:138 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L138)

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

It submits calls without driving the network, and polls to drive them and take what finished.

Its call slots, which pin each call's inputs, and its completion table are sized by its call budget when it starts; a blocking call takes its own completion out of the library, leaving the others queued there for TakeCompleted.

###### `NewClient`

NewClient starts a client, which holds no connection until its first call is polled.

[client.go:154 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L154)

```go
func NewClient(config *ClientOptions) (*Client, error)
```

###### `Call`

Call submits request and polls until it finishes, leaving the completions of other calls queued for TakeCompleted.

[client.go:334 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L334)

```go
func (client *Client) Call(request ClientCall) (*Response, error)
```

The response arrives whatever its HTTP status; a failed exchange answers its error.

###### `Close`

Close cancels the calls in flight, discards completions not yet taken, and frees the client; responses already taken stay readable.

[client.go:215 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L215)

```go
func (client *Client) Close() error
```

It is idempotent.

###### `Delete`

Delete deletes url and polls until the response arrives.

[client.go:368 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L368)

```go
func (client *Client) Delete(url string) (*Response, error)
```

###### `Get`

Get fetches url and polls until the response arrives.

[client.go:353 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L353)

```go
func (client *Client) Get(url string) (*Response, error)
```

###### `Patch`

Patch patches url with body and polls until the response arrives.

[client.go:373 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L373)

```go
func (client *Client) Patch(
    url string,
    body []byte,
) (*Response, error)
```

###### `Post`

Post posts body to url and polls until the response arrives.

[client.go:358 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L358)

```go
func (client *Client) Post(
    url string,
    body []byte,
) (*Response, error)
```

###### `Put`

Put puts body at url and polls until the response arrives.

[client.go:363 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L363)

```go
func (client *Client) Put(
    url string,
    body []byte,
) (*Response, error)
```

###### `Submit`

Submit admits call without driving the network; its one completion carries context.

[client.go:280 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L280)

```go
func (client *Client) Submit(
    call ClientCall,
    context uint64,
) error
```

A full client refuses with StatusContended until completions are taken.

###### `TakeCompleted`

TakeCompleted drives every admitted call on this goroutine and fills the front of completed with finished ones, waiting up to timeout for the first; zero performs one nonblocking round, and an empty completed only advances the network.

[client.go:320 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L320)

```go
func (client *Client) TakeCompleted(
    completed []Completed,
    timeout time.Duration,
) ([]Completed, error)
```

##### Struct `Response`

Response is a received HTTP response, whatever its status.6

[client.go:383 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L383)

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

It owns its received bytes, so it stays readable after its client is closed; Close frees it, and the collector frees one dropped.

###### `Body`

Body is the body, decoded from chunked framing if it arrived that way, valid until Close; a streamed call refuses it, as BodyChunk pulls its body.

[client.go:415 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L415)

```go
func (response *Response) Body() ([]byte, error)
```

###### `BodyChunk`

BodyChunk pulls the body bytes of a streamed call decoded since the last pull, valid until the next pull, empty once the body ended.

[client.go:459 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L459)

```go
func (response *Response) BodyChunk() ([]byte, error)
```

Pulls never wait: with nothing decoded yet it fails with StatusWouldBlock, and polling the client with TakeCompleted moves the next bytes in.

###### `Close`

Close frees the response, ending every slice viewing it.

[client.go:398 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L398)

```go
func (response *Response) Close() error
```

It is idempotent.

###### `Fields`

Fields yields every header field line in arrival order, as Request.Fields does.

[client.go:438 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L438)

```go
func (response *Response) Fields() iter.Seq2[[]byte, []byte]
```

###### `Header`

Header is the value of header name, matched case-insensitively, failing with StatusNotFound without one.

[client.go:427 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L427)

```go
func (response *Response) Header(name string) ([]byte, error)
```

###### `StatusCode`

StatusCode is the status code the server sent.

[client.go:409 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/client.go#L409)

```go
func (response *Response) StatusCode() HTTPStatus
```

## Noise Keys

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

Interfaces and calls can run over the Noise protocol instead of plain TCP, authenticating both sides by 32-byte Curve25519 static keys.

```go
serverPrivateKey, serverPublicKey, err := ucall.GenerateNoiseKeypair()
if err != nil {
	return err
}
clientPrivateKey, _, err := ucall.GenerateNoiseKeypair()
if err != nil {
	return err
}
clientPublicKey, err := ucall.DeriveNoisePublicKey(clientPrivateKey)
if err != nil {
	return err
}

sealed := ucall.NewInterface("0.0.0.0:8546")
sealed.Security, sealed.NoisePrivateKey = ucall.SecurityNoiseXX, &serverPrivateKey
sealed.PeerAuthorizer = func(key ucall.NoiseKey) bool { return key == clientPublicKey }
server, err := ucall.NewServer([]ucall.Interface{sealed}, nil)
if err != nil {
	return err
}

client, err := ucall.NewClient(&ucall.ClientOptions{
	Connections:     1,
	NoisePrivateKey: &clientPrivateKey,
	PeerAuthorizer:  func(key ucall.NoiseKey) bool { return key == serverPublicKey },
})
```

`GenerateNoiseKeypair` draws from the operating system’s entropy and fails with `StatusIO` when it is refused. `DeriveNoisePublicKey` recovers the public half of a stored private key, which peers compare in their authorizers. Under Noise XX both sides learn each other’s key during the handshake, so both need an authorizer; Noise IK has the client name the server’s key in advance through `ClientCallOptions.NoisePeerKey`. Noise KK has both sides know each other in advance: the interface admits the one key `Interface.NoisePeerKey` names, and the call presents `ClientCallOptions.NoisePrivateKey` or the client’s own key. Both sides may also hold a 32-byte `NoisePreSharedKey`, and must match their `KeyExchange`, whose zero value is the post-quantum `KeyExchangeX25519MLKEM768`. An `http+noise://` URL implies Noise XX, and a handler reads the client’s authenticated key through `Request.Peer`.

### API

#### Types

##### `PeerAuthorizer`

PeerAuthorizer decides whether a peer presenting an authenticated static key may proceed.

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

```go
type PeerAuthorizer func(key NoiseKey) bool
```

It runs on the polling goroutine completing the handshake and must not panic.

##### `Security`

Security is the transport an interface or a call runs over.

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

```go
type Security int32
```

##### Values

| `SecurityNone` | | SecurityNone is plain TCP. |
| - | - | - |
| `SecurityNoiseXX` | | SecurityNoiseXX authenticates both sides during the handshake. |
| `SecurityNoiseIK` | | SecurityNoiseIK has the client know the server's key in advance. |
| `SecurityNoiseKK` | | SecurityNoiseKK has both sides know each other's key in advance. |

##### Enum `KeyExchange`

KeyExchange is the key exchange of a Noise handshake, which both sides must match.2

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

```go
type KeyExchange int32
```

##### Values

| `KeyExchangeX25519MLKEM768` | | KeyExchangeX25519MLKEM768 runs X25519 and ML-KEM-768 together: recorded traffic stays private unless both break. |
| - | - | - |
| `KeyExchangeX25519` | | KeyExchangeX25519 runs X25519 alone, for standard Noise peers: recorded traffic falls to a quantum computer. |

###### `KeyExchangeFromName`

KeyExchangeFromName reads a key exchange back from its stable name.

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

```go
func KeyExchangeFromName(name string) (KeyExchange, error)
```

###### `String`

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

```go
func (exchange KeyExchange) String() string
```

##### Type `NoiseKey`

NoiseKey is a 32-byte Curve25519 key.1

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

```go
type NoiseKey [32]byte
```

###### `DeriveNoisePublicKey`

DeriveNoisePublicKey recovers the public half of a stored private key, which peers compare in their authorizers.

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

```go
func DeriveNoisePublicKey(privateKey NoiseKey) (NoiseKey, error)
```

#### Functions

##### `GenerateNoiseKeypair`

GenerateNoiseKeypair draws a fresh private key and its public key from the operating system's entropy.

[ucall.go:609 ↗](https://github.com/unum-cloud/UCall/blob/b75774266a108d8a1b1a6db1489f8a7141c556df/ucall.go#L609)

```go
func GenerateNoiseKeypair() (NoiseKey, NoiseKey, error)
```

## Errors

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

Every fallible call answers an `error`, an `*ucall.Error` carrying the `Status` the library reported and its static message, which `errors.Is` matches against a bare `Status`. A mistake the binding catches before calling the library, like a client closed before a call, reports the status the library would have used. `Status` prints its stable spelling, such as “connection-failed”.

```go
client, err := ucall.NewClient(&ucall.ClientOptions{Connections: 1})
if err != nil {
	return err
}
defer client.Close()
response, err := client.Get("http://127.0.0.1:1/")
switch {
case errors.Is(err, ucall.StatusConnectionFailed):
	fmt.Println("nobody listens:", err)
case err != nil:
	return err
default:
	defer response.Close()
	fmt.Println("answered", response.StatusCode())
}
```

A submitted call that fails completes with `Completed.Err`: `StatusConnectionFailed`, `StatusConnectionClosed`, `StatusTimeout`, `StatusHandshakeFailed` or `StatusPeerRejected`. A request or response lookup that finds nothing fails with `StatusNotFound` beside an empty value, and HTTP error statuses are ordinary responses. `Backend`, `CPUClass` and `Status` print their stable names, like “linux-uring618” and “intel-icelake”, and `BackendFromName`, `CPUClassFromName` and `StatusFromName` parse them back, failing with `StatusInvalidArgument` on a name no value has. `ucall.Version()` spells the linked library’s version, candidate suffix included, and `ucall.DecodePercent` decodes a path or a query value, which requests hold still percent-encoded.

### API

#### Struct `Error`

Error is one failed call: a status every caller can branch on, and the detail the status cannot carry.2

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

```go
type Error struct {
    Status  Status
    Message string
}
```

Reach the status with errors.Is or errors.As.

##### `Error`

Error implements the error interface.

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

```go
func (failure *Error) Error() string
```

##### `Unwrap`

Unwrap exposes the status, which is what errors.Is compares.

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

```go
func (failure *Error) Unwrap() error
```

#### Enum `Status`

Status names what went wrong, in a vocabulary shared by the library and by this binding.3

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

```go
type Status int32
```

Validation performed here before a call crosses reports the status the library would have reported for the same fault.

A Status is an error, so errors.Is(err, ucall.StatusConnectionFailed) matches any failure carrying it.

##### Values

| `StatusSuccess` | | StatusSuccess means the call completed and carries no message. |
| - | - | - |
| `StatusDeferred` | | StatusDeferred means a submitted call is not final yet. |
| `StatusOutOfMemory` | | StatusOutOfMemory means an allocation or reservation could not be satisfied. |
| `StatusIO` | | StatusIO means a socket or file could not be opened, read, written or closed. |
| `StatusMalformed` | | StatusMalformed means the peer sent bytes that do not decode as the expected protocol. |
| `StatusInternal` | | StatusInternal means the library violated its contract, which points at a defect. |
| `StatusOverflow` | | StatusOverflow means a size exceeds the representable range. |
| `StatusUninitialized` | | StatusUninitialized means the call needs a handle that was never made or is closed. |
| `StatusContended` | | StatusContended means the call was refused rather than waited for. |
| `StatusUnsupported` | | StatusUnsupported means the build, backend or machine lacks the feature. |
| `StatusInvalidArgument` | | StatusInvalidArgument means an argument is missing, out of range or contradicts another. |
| `StatusNotFound` | | StatusNotFound means the endpoint, header or parameter does not exist. |
| `StatusAlreadyExists` | | StatusAlreadyExists means an endpoint of the same template and verb is registered, or a request was already answered. |
| `StatusConnectionFailed` | | StatusConnectionFailed means a lookup or a connection attempt failed. |
| `StatusConnectionClosed` | | StatusConnectionClosed means the connection closed before the exchange completed. |
| `StatusTimeout` | | StatusTimeout means the operation exceeded its time budget. |
| `StatusHandshakeFailed` | | StatusHandshakeFailed means the Noise handshake failed to authenticate or agree on keys. |
| `StatusPeerRejected` | | StatusPeerRejected means the peer authorizer declined the authenticated static key. |
| `StatusWouldBlock` | | StatusWouldBlock means a nonblocking poll or pull had no progress to report. |

###### `StatusFromName`

StatusFromName reads a status back from the spelling String gives it.

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

```go
func StatusFromName(name string) (Status, error)
```

###### `Error`

Error implements the error interface, so a bare Status is an errors.Is target.

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

```go
func (status Status) Error() string
```

###### `String`

String renders the status as the library spells it, such as "connection-failed".

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

```go
func (status Status) String() string
```

## Threads and Polling

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

The package starts no goroutines: every callback runs on a goroutine the application gave to a polling call, which stays on one thread for that call.

- A route handler runs on the goroutine inside `TakeCall` or `TakeCalls` for the event loop that received the request.
- A `PooledBatch` handler runs on the goroutine inside `TakeBatch` or `TakeBatches` for its endpoint, never on an event loop, while a `LocalBatch` handler runs inside `TakeCall` or `TakeCalls` for the loop whose requests it holds.
- A server’s peer authorizer runs on the polling goroutine completing the handshake, and a client’s on the goroutine inside `TakeCompleted` or a blocking call.

Each event loop and each batch endpoint has one polling owner at a time. `TakeCalls` and `TakeBatches` run until `Server.Stop`, while `TakeCall` and `TakeBatch` return after one round, waiting up to their timeout, so a loop of them interleaves polling with other work; `TakeCall` answers `PollingRetired` once the loop drained after a stop. `Server.Stop` works from any goroutine, handlers included, and wakes every polling goroutine; `Server.Close` frees the server once they returned. The first stop drains, answering every request already held before its connection closes, and a second one cuts the replies still in flight. A `Request` and a `Response` move between goroutines, while a `Client` is used by one goroutine at a time. Every thread that polls, replies or reads must run on a CPU supporting the CPU class the server or client resolved at start, so `CPUClassSerial` is the safe choice on machines mixing CPU generations.

### API

#### Types

##### `Polling`

Polling is what Server.TakeCall found of its event loop.

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

```go
type Polling int
```

##### Values

| `PollingServing` | `iota` | PollingServing means the loop serves, or drains what it holds after a stop. |
| - | - | - |
| `PollingRetired` | | PollingRetired means the loop drained or cut everything after Server.Stop. |

##### Enum `CPUClass`

CPUClass is a bundle of CPU kernels; CPUClassUnknown sets no ceiling.2

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

```go
type CPUClass int32
```

##### Values

| `CPUClassUnknown` | | CPUClassUnknown sets no ceiling, picking the newest class the machine runs. |
| - | - | - |
| `CPUClassSerial` | | CPUClassSerial runs portable kernels with no SIMD on every machine. |
| `CPUClassMonoversioned` | | CPUClassMonoversioned is the one class a monoversioned build compiles. |
| `CPUClassIntelHaswell` | | CPUClassIntelHaswell runs AVX2 kernels. |
| `CPUClassIntelSkylake` | | CPUClassIntelSkylake adds AVX-512 kernels. |
| `CPUClassIntelIcelake` | | CPUClassIntelIcelake adds Ice Lake's AVX-512 extensions and SHA. |
| `CPUClassIntelAlder` | | CPUClassIntelAlder runs AVX2 kernels with SHA and no AVX-512. |
| `CPUClassAWSG2` | | CPUClassAWSG2 runs NEON kernels with the AES and SHA extensions. |
| `CPUClassAppleM4` | | CPUClassAppleM4 adds timed waits to the Graviton5 kernels. |
| `CPUClassAWSG5` | | CPUClassAWSG5 runs the Graviton2 kernels with newer atomics. |
| `CPUClassAlibabaC930` | | CPUClassAlibabaC930 runs RVV kernels with Zawrs waits and Zacas compare-and-swap. |
| `CPUClassIBMPower10` | | CPUClassIBMPower10 runs VSX kernels with short pauses and store atomics. |

###### `CPUClassFromName`

CPUClassFromName reads a class back from its stable name, "unknown" included.

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

```go
func CPUClassFromName(name string) (CPUClass, error)
```

###### `String`

String renders the class's stable name, such as "intel-icelake".

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

```go
func (class CPUClass) String() string
```

## Design

1.0.0-rc.1 · b7577426

The package is a thin layer over UCall’s native library, and every rule below follows from that.

- **Verbs share one name across languages.** `TakeCall`, `TakeCalls`, `TakeBatch`, `TakeBatches`, `Submit` and `TakeCompleted` name the same calls as `take_call` and its siblings in C++, Python and Rust.
- **Blocking stays simple, deferring stays symmetric.** A reply that is final on return answers an `error`, and one that may finish later answers `(*Deferred[T], error)`, as Rust’s `Deferring::answer` hands back its refusal before submitting anything.
- **Ownership is a type, not a flag.** A reply takes its `Request`, which the library clears once taken, only a `DetachedRequest` hands back a `Deferred`, and a `Response` is freed by `Close` or the collector.
- **Callbacks cross as handles.** Routes, batch endpoints, log sinks and authorizers reach C as `cgo.Handle` s the server or client deletes when closed, never as Go pointers; a route’s handle holds its handler alone, as each callback receives its server from the library.
- **One pinned frame per call.** Each call pins one allocation holding its outcome, its argument structure and its result, polls included, and a refusal the binding catches allocates only its `Error`, before anything is pinned.
- **No life of its own.** The package starts no goroutines, keeps no locks or counters, and recovers no panics, so it drops into any concurrency model.

| Path | Go | Rust |
| - | - | - |
| Blocking call | 1 frame | 0 |
| Refusal before the call | 1 `Error` | 1 error |
| Deferred submit and wait | 4: frame, `Deferred`, 2 in `AddCleanup` | 0 |
| Each callback | 1 `Request` | 0 |

A completion `TakeCompleted` lifts adds its `Response` and that response’s cleanup, and header lines or reply parts add the one array they cross as. `TestCallsAllocateOnlyTheirFrames` holds the first three rows.
