type ClientCall struct {
Verb Verb
URL string
Headers []string
Body []byte
Options ClientCallOptions
} 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.
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:
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
ClientCallClientCall is one call to submit; the client pins its URL, header lines and body until it completes.
ClientCallOptionsClientCallOptions is one call's time budget, retries, redirects, security and body delivery, each zero field taking its default.
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. |
ClientOptionsClientOptions is what a client may hold open at once, how long it waits, and who it is under Noise.
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. |
CompletedCompleted is one finished call: the context it was submitted with, and its response, whatever its HTTP status, or why none arrived.
type Completed struct {
Context uint64
Response *Response
Err error
} StructClientClient is an HTTP client used by one goroutine at a time.10
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.
NewClientNewClient starts a client, which holds no connection until its first call is polled.
func NewClient(config *ClientOptions) (*Client, error) CallCall submits request and polls until it finishes, leaving the completions of other calls queued for TakeCompleted.
func (client *Client) Call(request ClientCall) (*Response, error) The response arrives whatever its HTTP status; a failed exchange answers its error.
CloseClose cancels the calls in flight, discards completions not yet taken, and frees the client; responses already taken stay readable.
DeleteDelete deletes url and polls until the response arrives.
func (client *Client) Delete(url string) (*Response, error) GetGet fetches url and polls until the response arrives.
func (client *Client) Get(url string) (*Response, error) PatchPatch patches url with body and polls until the response arrives.
func (client *Client) Patch(
url string,
body []byte,
) (*Response, error) PostPost posts body to url and polls until the response arrives.
func (client *Client) Post(
url string,
body []byte,
) (*Response, error) PutPut puts body at url and polls until the response arrives.
func (client *Client) Put(
url string,
body []byte,
) (*Response, error) SubmitSubmit admits call without driving the network; its one completion carries context.
func (client *Client) Submit(
call ClientCall,
context uint64,
) error A full client refuses with StatusContended until completions are taken.
TakeCompletedTakeCompleted 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.
func (client *Client) TakeCompleted(
completed []Completed,
timeout time.Duration,
) ([]Completed, error) StructResponseResponse is a received HTTP response, whatever its status.6
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.
BodyBody 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.
func (response *Response) Body() ([]byte, error) BodyChunkBodyChunk pulls the body bytes of a streamed call decoded since the last pull, valid until the next pull, empty once the body ended.
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.
CloseClose frees the response, ending every slice viewing it.
FieldsFields yields every header field line in arrival order, as Request.Fields does.
func (response *Response) Fields() iter.Seq2[[]byte, []byte] HeaderHeader is the value of header name, matched case-insensitively, failing with StatusNotFound without one.
func (response *Response) Header(name string) ([]byte, error) StatusCodeStatusCode is the status code the server sent.
func (response *Response) StatusCode() HTTPStatus