type BatchEndpointStatistics struct {
Batches uint64
Requests uint64
FilledBatches uint64
ReadyBatches uint64
ExpiredBatches uint64
} 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.
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
BatchEndpointStatisticsBatchEndpointStatistics count a batch endpoint's batches and requests, and why each batch dispatched: on reaching the maximum size, the minimum size, or the latency.
EventLoopStatisticsEventLoopStatistics are the counters of one event loop since the server started; divided by Requests, they price one call.
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
} LogLog 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.
type Log struct {
Callback func(level LogLevel, line []byte)
Format LogFormat
Level LogLevel
} LogFormatLogFormat is the shape of each log line.
type LogFormat int32 Values
LogHuman | LogHuman writes readable lines with normalized units. | |
|---|---|---|
LogJSON | LogJSON writes one JSON document per line. |
LogLevelLogLevel is the severity of a log line, from the most verbose up.
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. |
MetricsMetrics is the StatsD endpoint a server sends each event loop's counters and sampled request latencies to.
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. |
ServerOptionsServerOptions is what a server runs on and reports through, beside its interfaces.
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. |
VerbVerb is an HTTP method a route takes or a request carries.
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. |
EnumBackendBackend is a concrete I/O implementation; BackendAutomatic picks the fastest one available.2
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. |
BackendFromNameBackendFromName reads a backend back from its stable name, "automatic" included.
func BackendFromName(name string) (Backend, error) StringString renders the backend's stable name, such as "linux-uring618".
func (backend Backend) String() string StructInterfaceInterface 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
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. |
NewInterfaceNewInterface listens on address, admitting 1024 connections at once.
func NewInterface(address string) Interface StructLocalBatchEndpointLocalBatchEndpoint 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
type LocalBatchEndpoint struct {
// contains filtered or unexported fields
} StatisticsStatistics copies the endpoint's counters, from any goroutine while its loops run.
func (endpoint *LocalBatchEndpoint) Statistics() (BatchEndpointStatistics, error) StructPooledBatchEndpointPooledBatchEndpoint is one pooled batch endpoint, drained by one goroutine at a time until its server closes.3
type PooledBatchEndpoint struct {
// contains filtered or unexported fields
} StatisticsStatistics copies the endpoint's counters, from any goroutine while it is polled.
func (endpoint *PooledBatchEndpoint) Statistics() (BatchEndpointStatistics, error) TakeBatchTakeBatch runs the handler on this goroutine if a batch is due, waiting up to timeout for one; zero performs one nonblocking round.
func (endpoint *PooledBatchEndpoint) TakeBatch(
timeout time.Duration,
) error TakeBatchesTakeBatches runs the handler on this goroutine for every due batch until the server stops.
func (endpoint *PooledBatchEndpoint) TakeBatches() error StructServerServer is an HTTP server over one or more interfaces, polled by application goroutines.20
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.
NewServerNewServer starts a server answering on interfaces, with the backend, CPU class, log sink and StatsD endpoint options name; nil options take every default.
func NewServer(
interfaces []Interface,
config *ServerOptions,
) (*Server, error) AddressAddress is the numeric address interface index listens on, with the port it bound, and false past the last interface.
func (server *Server) Address(index uint) (string, bool) BackendBackend is the I/O backend the server resolved to.
func (server *Server) Backend() Backend CPUClassCeilingCPUClassCeiling is the CPU class the server resolved to under its ceiling.
func (server *Server) CPUClassCeiling() CPUClass CloseClose frees the server once its polling goroutines returned and its bound clients are closed.
DeleteDelete routes DELETE requests on path to handler.
func (server *Server) Delete(
path string,
handler func(request *Request),
) error EventLoopStatisticsEventLoopStatistics copies one loop's counters, from any goroutine while it is polled.
func (server *Server) EventLoopStatistics(
eventLoop uint,
) (EventLoopStatistics, error) EventLoopsEventLoops is how many event loops the server runs, each polled by one goroutine at a time.
func (server *Server) EventLoops() uint GetGet routes GET requests on path to handler.
func (server *Server) Get(
path string,
handler func(request *Request),
) error LocalBatchLocalBatch 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.
func (server *Server) LocalBatch(
path string,
verb Verb,
options Batching,
handler func(batch Batch),
) (*LocalBatchEndpoint, error) Every polling loop may run it at once.
MemoryDomainMemoryDomain 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.
func (server *Server) MemoryDomain(index uint) (int32, bool) PatchPatch routes PATCH requests on path to handler.
func (server *Server) Patch(
path string,
handler func(request *Request),
) error PooledBatchPooledBatch 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.
func (server *Server) PooledBatch(
path string,
verb Verb,
options Batching,
handler func(batch Batch),
) (*PooledBatchEndpoint, error) PostPost routes POST requests on path to handler.
func (server *Server) Post(
path string,
handler func(request *Request),
) error PutPut routes PUT requests on path to handler.
func (server *Server) Put(
path string,
handler func(request *Request),
) error RouteRoute sends requests matching path and verb to handler, which runs on the polling goroutine.
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.
RouteWithRouteWith 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.
func (server *Server) RouteWith(
path string,
verb Verb,
delivery BodyDelivery,
handler func(request *Request),
) error StopStop 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.
func (server *Server) Stop() TakeCallTakeCall 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.
func (server *Server) TakeCall(
eventLoop uint,
timeout time.Duration,
) (Polling, error) TakeCallsTakeCalls drives one event loop on this goroutine until Server.Stop or an I/O failure.
func (server *Server) TakeCalls(eventLoop uint) error