Go · Serving

Serving

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

Ask your coding agent about this page, or add the docs server to it

curl -s 'https://www.unum.cloud/docs/ucall/go/serving.md' | claude -p "How would this fit my code?"

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.
server.go:1001 ↗
type BatchEndpointStatistics struct {
    Batches        uint64
    Requests       uint64
    FilledBatches  uint64
    ReadyBatches   uint64
    ExpiredBatches uint64
}
EventLoopStatisticsEventLoopStatistics are the counters of one event loop since the server started; divided by Requests, they price one call.
server.go:421 ↗
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.
server.go:693 ↗
type Log struct {
    Callback func(level LogLevel, line []byte)
    Format   LogFormat
    Level    LogLevel
}
LogFormatLogFormat is the shape of each log line.
server.go:681 ↗
type LogFormat int32

Values

LogHumanLogHuman writes readable lines with normalized units.
LogJSONLogJSON writes one JSON document per line.
LogLevelLogLevel is the severity of a log line, from the most verbose up.
server.go:664 ↗
type LogLevel int32

Values

LogDebugLogDebug is detail for debugging.
LogInfoLogInfo is a normal lifecycle event.
LogWarningLogWarning is something unexpected the library recovered from.
LogErrorLogError is a failed operation.
LogFatalLogFatal 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.
server.go:120 ↗
type Metrics struct {
    Address string
    SampleRate float32
    Prefix string
    Tags []string
    Interval time.Duration
}

Fields

AddressstringAddress is the endpoint in "host:port" form.
SampleRatefloat32SampleRate is the fraction of finished requests whose latency is reported; zero means all.
PrefixstringPrefix starts every metric name; empty means "ucall".
Tags[]stringTags go on every metric, each "key:value".
Intervaltime.DurationInterval 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.
server.go:134 ↗
type ServerOptions struct {
    Backend Backend
    CPUClassCeiling CPUClass
    Log *Log
    Metrics *Metrics
}

Fields

BackendBackendBackend is the requested I/O backend, failing rather than substituting when unavailable.
CPUClassCeilingCPUClassCPUClassCeiling caps the CPU class; CPUClassUnknown sets no ceiling.
Log*LogLog is where log lines go; nil keeps the server silent.
Metrics*MetricsMetrics is where StatsD datagrams go; nil sends none.
VerbVerb is an HTTP method a route takes or a request carries.
server.go:492 ↗
type Verb int32

Values

VerbUnknownVerbUnknown is a method the parser did not recognize.
VerbGetVerbGet retrieves a resource.
VerbPostVerbPost creates a resource.
VerbPutVerbPut replaces a resource.
VerbDeleteVerbDelete removes a resource.
VerbPatchVerbPatch updates part of a resource.
VerbHeadVerbHead retrieves the headers alone.
VerbOptionsVerbOptions asks which methods a resource takes.
VerbAnyVerbAny matches every method, when registering a route only.
EnumBackendBackend is a concrete I/O implementation; BackendAutomatic picks the fastest one available.2
types.go:382 ↗
type Backend int32

Values

BackendAutomaticBackendAutomatic picks the fastest backend the machine and its limits allow.
BackendPOSIXBackendPOSIX polls blocking sockets and files with poll, on any POSIX system.
BackendLinuxEpollAIOBackendLinuxEpollAIO runs epoll for sockets and Linux AIO for files.
BackendLinuxUring612BackendLinuxUring612 runs io_uring as Linux 6.12 provides it.
BackendLinuxUring618BackendLinuxUring618 runs io_uring as Linux 6.18 provides it, with multishot receives.
BackendBSDKqueueBackendBSDKqueue runs kqueue on FreeBSD and macOS.
BackendWindowsIOCPBackendWindowsIOCP runs I/O completion ports on Windows.
BackendWindowsRIOBackendWindowsRIO runs Registered I/O for stream sockets on Windows.
BackendFromNameBackendFromName reads a backend back from its stable name, "automatic" included.
types.go:410 ↗
func BackendFromName(name string) (Backend, error)
StringString renders the backend's stable name, such as "linux-uring618".
types.go:405 ↗
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
server.go:78 ↗
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

AddressstringAddress is the listening address in "host:port" form; port zero binds a free one, which Server.Address reports.
ListenDescriptor*uintptrListenDescriptor is a listening stream socket another owner opened, accepted on instead of Address and never closed.
DeviceNamestringDeviceName pins the interface to a physical device, like "eth0", on Linux only.
SecuritySecuritySecurity is the transport connections accepted here run over.
NoisePrivateKey*NoiseKeyNoisePrivateKey is the server identity every Noise mode needs.
NoisePeerKey*NoiseKeyNoisePeerKey is the one initiator's static public key Noise KK admits.
NoisePreSharedKey*NoiseKeyNoisePreSharedKey is a secret every client also holds, mixed first into every handshake; refused on a plaintext interface.
KeyExchangeKeyExchangeKeyExchange is the key exchange of Noise handshakes, which clients must match.
PeerAuthorizerPeerAuthorizerPeerAuthorizer vets each client's authenticated static key; Noise XX needs one.
EventLoopsuintEventLoops accepting here; zero means one, or a named device's receive queues.
ConnectionsuintConnections open at once across this interface's loops; zero is refused.
PipelinedRequestsuintPipelinedRequests one connection may have in flight; zero means one.
MaxRequestBytesuintMaxRequestBytes caps a request head and buffered body, answering 413 past it; zero takes the largest receive buffer the kernel grants a socket.
ReplyDirectories[]stringReplyDirectories are the directories path parts of replies resolve beneath, by position.
NewInterfaceNewInterface listens on address, admitting 1024 connections at once.
server.go:114 ↗
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
server.go:1022 ↗
type LocalBatchEndpoint struct {
    // contains filtered or unexported fields
}
StatisticsStatistics copies the endpoint's counters, from any goroutine while its loops run.
server.go:1062 ↗
func (endpoint *LocalBatchEndpoint) Statistics() (BatchEndpointStatistics, error)
StructPooledBatchEndpointPooledBatchEndpoint is one pooled batch endpoint, drained by one goroutine at a time until its server closes.3
server.go:937 ↗
type PooledBatchEndpoint struct {
    // contains filtered or unexported fields
}
StatisticsStatistics copies the endpoint's counters, from any goroutine while it is polled.
server.go:1010 ↗
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.
server.go:977 ↗
func (endpoint *PooledBatchEndpoint) TakeBatch(
    timeout time.Duration,
) error
TakeBatchesTakeBatches runs the handler on this goroutine for every due batch until the server stops.
server.go:989 ↗
func (endpoint *PooledBatchEndpoint) TakeBatches() error
StructServerServer is an HTTP server over one or more interfaces, polled by application goroutines.20
server.go:153 ↗
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.
server.go:168 ↗
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.
server.go:282 ↗
func (server *Server) Address(index uint) (string, bool)
BackendBackend is the I/O backend the server resolved to.
server.go:275 ↗
func (server *Server) Backend() Backend
CPUClassCeilingCPUClassCeiling is the CPU class the server resolved to under its ceiling.
server.go:278 ↗
func (server *Server) CPUClassCeiling() CPUClass
CloseClose frees the server once its polling goroutines returned and its bound clients are closed.
server.go:247 ↗
func (server *Server) Close() error

It is idempotent.

DeleteDelete routes DELETE requests on path to handler.
server.go:362 ↗
func (server *Server) Delete(
    path string,
    handler func(request *Request),
) error
EventLoopStatisticsEventLoopStatistics copies one loop's counters, from any goroutine while it is polled.
server.go:456 ↗
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.
server.go:266 ↗
func (server *Server) EventLoops() uint
GetGet routes GET requests on path to handler.
server.go:347 ↗
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.
server.go:1030 ↗
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.
server.go:292 ↗
func (server *Server) MemoryDomain(index uint) (int32, bool)
PatchPatch routes PATCH requests on path to handler.
server.go:367 ↗
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.
server.go:944 ↗
func (server *Server) PooledBatch(
    path string,
    verb Verb,
    options Batching,
    handler func(batch Batch),
) (*PooledBatchEndpoint, error)
PostPost routes POST requests on path to handler.
server.go:352 ↗
func (server *Server) Post(
    path string,
    handler func(request *Request),
) error
PutPut routes PUT requests on path to handler.
server.go:357 ↗
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.
server.go:312 ↗
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.
server.go:319 ↗
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.
server.go:417 ↗
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.
server.go:384 ↗
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.
server.go:402 ↗
func (server *Server) TakeCalls(eventLoop uint) error