# Calling

> A Client submits calls without driving the network, and polls to drive them and collect what finished.

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