Package 'zugrpc'

Title: Client for 'gRPC' Remote Procedure Calls over HTTP/2
Description: A client for 'gRPC' remote procedure calls, written in 'R' on top of the HTTP/2 requests that 'zuhttp' makes. Implements the 'gRPC' wire protocol: length-prefixed messages, request headers and metadata, deadlines, cancellation, and the call status carried in HTTP trailers, with error details decoded into structured conditions. Supports unary and server-streaming calls, with streamed responses read one message at a time. Messages are encoded and decoded by the caller, for example with 'zuproto'.
Authors: Pedro Baltazar [aut, cre, cph], Google LLC [cph] (google/rpc protocol definitions in inst/descriptors)
Maintainer: Pedro Baltazar <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0
Built: 2026-12-05 18:19:15 UTC
Source: https://github.com/pedrobtz/zugrpc

Help Index


Call credentials

Description

Credentials authenticate a channel's calls without becoming part of the channel. The secret stays in this R session: printing, saving or sending a channel or a credentials object to another process carries only a key, and a copy that reaches another process refuses every call with zugrpc_error_argument until it is created again there.

Usage

grpc_bearer_token(token)

grpc_call_credentials(provider)

Arguments

token

The token, one non-empty string of printable ASCII.

provider

A function of one argument, the method being called (as "/package.Service/Method"). It returns the metadata to send: a named character vector or a named list, as metadata in grpc_call(). A provider that raises an error fails the call with zugrpc_error_unavailable, the error kept as parent, and nothing is sent.

Details

grpc_bearer_token() sends a fixed token as ⁠authorization: Bearer <token>⁠. grpc_call_credentials() calls provider before every call, so a token that expires can be refreshed. Its result is sent and never stored.

Credentials need TLS: grpc_channel() accepts them for an ⁠https://⁠ URL, or for an ⁠http://⁠ URL whose host is localhost, a ⁠127.x.x.x⁠ address or ⁠[::1]⁠.

Value

A zugrpc_credentials, for credentials in grpc_channel().

See Also

grpc_channel().

Examples

creds <- grpc_bearer_token("my-token")
creds
ch <- grpc_channel("https://grpc.example.org:443", credentials = creds)
ch
grpc_close(ch)

# A token read when each call is made, for one that expires:
refresh <- grpc_call_credentials(function(method) {
  c(authorization = paste("Bearer", Sys.getenv("MY_TOKEN")))
})

Make a unary gRPC call

Description

Sends one request message to a method and returns the one response message, with the server's initial and trailing metadata. The request is already encoded, for example by zuproto::proto_encode(); zugrpc only frames it. A call that ends with a status other than OK raises a condition instead of returning.

Usage

grpc_call(channel, method, request, metadata = NULL, deadline = NULL)

Arguments

channel

A channel from grpc_channel().

method

The full method name, "/package.Service/Method".

request

The encoded request message, a raw vector.

metadata

Request metadata: a named character vector, or a named list whose -bin entries are raw vectors. Names are lower-cased. Names starting with ⁠grpc-⁠ or : are reserved, and so are te, content-type, content-length, accept-encoding, host and the connection headers HTTP/2 forbids, such as connection. Each name may be given once. A user-agent is sent before zugrpc's own.

deadline

Seconds from now, or an absolute POSIXct, by which the call must finish. It is sent to the server as grpc-timeout and also bounds the request locally. NULL sets no deadline.

Value

A list with elements message (raw, the response message), headers and trailers (named lists of the initial and trailing metadata, with -bin values as raw vectors) and status ("OK"). A -bin value holding several, joined by commas, gives one entry each. One that is not base64 is dropped with a zugrpc_warning_metadata warning.

Errors

A non-OK status raises zugrpc_error_status, whose class also carries the status as ⁠zugrpc_error_<name>⁠, for example zugrpc_error_unavailable. Its fields are grpc_status, grpc_code, grpc_message, details, http_status, method, headers and trailers. details is the decoded google.rpc.Status from the grpc-status-details-bin trailer, or NULL when there is none: a list of code, message and details. Its details are the decoded error details, named by type, such as ErrorInfo with its reason, domain and metadata. Two details of one type share its name, so d[names(d) == "BadRequest"] selects them all. A trailer that does not decode gives a zugrpc_warning_details warning, and details is NULL.

A failure below gRPC, such as a refused connection or a TLS error, raises zugrpc_error_transport, which is also zugrpc_error_unavailable. The zuhttp condition is its parent. A local timeout is DEADLINE_EXCEEDED, and an interrupt raises zugrpc_error_interrupt. A response that is not gRPC, or breaks its framing, raises zugrpc_error_protocol. See grpc_status_codes().

Examples

# A test server, from zuhttp's mock transport: it answers every call with
# an empty message and status OK.
fake <- zuhttp::zu_mock_transport(function(req) {
  zuhttp::zu_response(
    200L,
    headers = c("content-type" = "application/grpc+proto"),
    body = as.raw(c(0, 0, 0, 0, 0)),
    trailers = c("grpc-status" = "0")
  )
})
ch <- grpc_channel(
  "http://localhost:50051",
  client = zuhttp::zu_client(transport = fake)
)
res <- grpc_call(ch, "/grpc.testing.TestService/EmptyCall", raw())
res$status
res$message

Open a gRPC channel

Description

A channel holds what every call to one server shares: the server's address, the headers sent on every call, the message size limit, and the zuhttp client whose connection pool carries the calls. An ⁠http://⁠ URL speaks cleartext HTTP/2 with prior knowledge (h2c), for a local server. An ⁠https://⁠ URL negotiates HTTP/2 over TLS. gRPC has no HTTP/1.1 fallback, so the channel's client always requires HTTP/2.

Usage

grpc_channel(
  url,
  headers = NULL,
  credentials = NULL,
  tls = NULL,
  keepalive = grpc_keepalive(),
  max_message = 128 * 1024^2,
  client = NULL
)

Arguments

url

The server, as ⁠http://host:port⁠ or ⁠https://host:port⁠. The host is a name, an IPv4 address or a bracketed IPv6 address, and the port is from 1 to 65535. No path, query or user information.

headers

Metadata sent on every call: a named character vector or a named list, as metadata in grpc_call(), with the same reserved names. A call's own metadata replaces a channel header of the same name. Headers are part of the channel, and go wherever it is saved or sent, so authorization is refused here: pass a token as credentials.

credentials

Call credentials from grpc_bearer_token() or grpc_call_credentials(), or NULL for none. They need an ⁠https://⁠ URL, or an ⁠http://⁠ one to a loopback host. Their metadata may not share a name with headers or with a call's metadata.

tls

Certificate trust settings from zuhttp::zu_tls(), for an ⁠https://⁠ URL.

keepalive

HTTP/2 keepalive from grpc_keepalive(), or NULL for none. The default sends a PING on a connection idle for 60 seconds and replaces it if no answer comes within 20, as Spark Connect's Python client does.

max_message

The largest response message accepted, in bytes. The default, 128 MiB, is Spark Connect's. A larger message fails the call with RESOURCE_EXHAUSTED.

client

A zuhttp::zu_client() to build on, so that proxies, TLS pins, middleware and test transports come from zuhttp unchanged. The channel derives its own client from it, with HTTP/2 required, no HTTP content coding and no query. Its headers may not use a name reserved for metadata (see metadata in grpc_call()), nor authorization. The channel holds the client and everything in it, such as a proxy URL with a password or middleware that captures a token, so keep secrets out of it and pass a token as credentials. NULL builds a fresh one.

Value

A zugrpc_channel.

See Also

grpc_call() to make a call, grpc_close() to close it.

Examples

ch <- grpc_channel("http://localhost:50051")
ch
grpc_close(ch)

Close a gRPC channel

Description

Cancels the channel's open streams and closes its idle connections. A call on a closed channel raises zugrpc_error_argument, and a cancelled stream raises zugrpc_error_cancelled when it is next read. Closing a channel twice does nothing.

Usage

grpc_close(channel)

Arguments

channel

A channel from grpc_channel().

Value

channel, invisibly.

Examples

ch <- grpc_channel("http://localhost:50051")
grpc_close(ch)

HTTP/2 keepalive settings

Description

A channel's connection can sit idle between calls, and a server or a middlebox may drop it without saying so. With keepalive, a connection idle for time seconds is sent an HTTP/2 PING before its next call, and replaced by a new one if no answer comes within timeout seconds.

Usage

grpc_keepalive(time = 60, timeout = 20)

Arguments

time

Seconds of idleness before a PING, from 0.001 (1 ms) to 2147483.647 (about 24.8 days).

timeout

Seconds to wait for the answer, in the same range.

Value

A zugrpc_keepalive, for grpc_channel().

Examples

grpc_keepalive()
grpc_keepalive(time = 30, timeout = 10)

gRPC status codes

Description

The 17 status codes a gRPC call can end with, as the gRPC specification defines them. A failed call raises a condition of class ⁠zugrpc_error_<name>⁠ in lower case, for example zugrpc_error_unavailable.

Usage

grpc_status_codes()

Value

A data frame with one row per code and columns code (integer), name and description (character).

Examples

grpc_status_codes()

Make a server-streaming gRPC call

Description

Sends one request message and returns a stream that yields the response messages one at a time, as they arrive. The server sends only as far ahead as you read, so a stream you stop reading holds the server back rather than filling memory.

Usage

grpc_stream(channel, method, request, metadata = NULL, deadline = NULL)

Arguments

channel

A channel from grpc_channel().

method

The full method name, "/package.Service/Method".

request

The encoded request message, a raw vector.

metadata

Request metadata: a named character vector, or a named list whose -bin entries are raw vectors. Names are lower-cased. Names starting with ⁠grpc-⁠ or : are reserved, and so are te, content-type, content-length, accept-encoding, host and the connection headers HTTP/2 forbids, such as connection. Each name may be given once. A user-agent is sent before zugrpc's own.

deadline

Seconds from now, or an absolute POSIXct, by which the whole stream must end. It is sent as grpc-timeout. Locally it is checked before each read, and each wait for more data is bounded by the time the deadline allowed when the call began, so a stall can overrun a deadline that is already partly used. NULL sets no deadline.

Details

The stream is an object with five methods:

  • ⁠$headers()⁠ returns the initial metadata, a named list.

  • ⁠$next_message()⁠ returns the next message as a raw vector, or NULL at the end of the stream. It raises a condition, as grpc_call() does, when the call ends with a status other than OK. A stream that fails any other way, such as a lost connection, a passed deadline or a broken message, raises the same condition again on every later call. The complete messages that arrived before a broken one are returned first.

  • ⁠$trailers()⁠ returns the trailing metadata once ⁠$next_message()⁠ has returned NULL, and NULL before.

  • ⁠$status()⁠ returns the final status name once the stream has ended, and NULL before: "OK", the server's status, or the status the stream failed with, such as "CANCELLED" or "DEADLINE_EXCEEDED". A stream that failed without a status, on a protocol error, stays NULL.

  • ⁠$cancel()⁠ stops the call. The connection stays open for other calls. A second ⁠$cancel()⁠ does nothing. A later ⁠$next_message()⁠ raises zugrpc_error_cancelled.

A stream that is no longer referenced is cancelled when it is garbage-collected, and grpc_close() cancels every open stream of its channel.

Value

A zugrpc_stream.

Examples

# A test server, from zuhttp's mock transport: it streams two messages
# and ends with status OK.
fake <- zuhttp::zu_mock_transport(function(req) {
  zuhttp::zu_response(
    200L,
    headers = c("content-type" = "application/grpc+proto"),
    body = as.raw(c(0, 0, 0, 0, 1, 0x61, 0, 0, 0, 0, 1, 0x62)),
    trailers = c("grpc-status" = "0")
  )
})
ch <- grpc_channel(
  "http://localhost:50051",
  client = zuhttp::zu_client(transport = fake)
)
st <- grpc_stream(ch, "/grpc.testing.TestService/StreamingOutputCall", raw())
while (!is.null(m <- st$next_message())) print(rawToChar(m))
st$status()

What this installation of zugrpc can do

Description

Reports the zuhttp that carries zugrpc's calls: its version, whether it speaks HTTP/2, which gRPC requires, and its TLS backend.

Usage

zugrpc_info()

Value

A list with elements version (zugrpc's, a string), zuhttp (its version, a string), http2 (logical), tls_backend (a string) and tls_capabilities (character), printed as a short report.

See Also

zuhttp::zu_info() for the full transport report.

Examples

zugrpc_info()