grpc API reference Changelog View on GitHub

API reference

gRPC in Zig: a client and a server over HTTP/2, with no code generation.

The primitive layer is message: one length-prefixed frame, no allocator, and no stream. A caller that already has HTTP/2 and its own message type needs nothing above it.

pub const Header = http.Header

src

The header field and field list that server, Call, and the client use.

pub const Headers = http.Headers

src

pub const OptionalDuration = time.OptionalDuration

src

The compact optional durations and timestamps that carry deadlines.

pub const OptionalTimestamp = time.OptionalTimestamp

src

struct Client

src
pub const Client = @import("client.zig").Client

The client: one connection across calls. unary and unaryIo send one call and return, ServerStream pulls a server-streaming response one message at a time, and open and step run several calls at once. The io value carries the concurrency model: a call blocks the calling thread under Io.Threaded and suspends under an evented Io such as zio.

Fields

io: Io
allocator: Allocator
socket: ?Io.net.Stream = null

Owned and closed by deinit when this client opened it.

transport_reader: Io.net.Stream.Reader = undefined
transport_writer: Io.net.Stream.Writer = undefined
reader: *Io.Reader = undefined

The bytes this client reads and writes. A socket client points these at its own transport pair; a caller with a TLS transport points them at whatever that transport exposes as plaintext.

writer: *Io.Writer = undefined
fd: OptionalFd = .none

The socket behind reader and writer, when there is one to poll for a deadline. A transport that decrypts in memory has none.

deadline_by: DeadlineBy = .fd

Whether the deadline is enforced by polling the fd or by the reader.

read_deadline: ?Driver.ReadDeadline = null
read_buffer: [read_capacity]u8 = undefined
write_buffer: [write_capacity]u8 = undefined
frame: []u8 = &.{}
conn: h2.client.Connection
driver: Driver
keepalive: KeepAliveState = .{}

Functions

pub fn init( self: *Client, allocator: Allocator, io: Io, socket: Io.net.Stream, ) !void

src

On success, the client owns the socket and deinit closes it. On failure, the caller retains the socket.

pub fn initIo( self: *Client, allocator: Allocator, io: Io, reader: *Io.Reader, writer: *Io.Writer, options: IoOptions, ) !void

src

pub fn setKeepAlive(self: *Client, policy: KeepAlive) !void

src

Configure HTTP/2 PING keepalive on this connection.

pub fn deinit(self: *Client) void

src

pub fn connectionError(self: *const Client) ?h2.frame.ErrorCode

src

The HTTP/2 error code the session reported for this connection, if it failed. Null means the connection has not failed.

pub fn isPoisoned(self: *const Client) bool

src

pub fn stream(self: *Client, call: *Call, calls: []Call) Stream

src

Lend a call the byte-stream facade shared with readiness sessions. The stream borrows this client, call, and calls; it owns neither the client nor its socket. calls must contain every live call, including this one, because each Stream.advance is exactly Client.step(calls). Stream.deinit deinitializes call, not the client. Keep every entry in the shared calls slice initialized until no stream will advance that group again; entry removal remains the caller's scheduling job.

pub fn open(self: *Client, request: Request) !Call

src

Open a call without waiting for its status. The call borrows this client's connection, so it must be dropped before the client.

pub fn step(self: *Client, calls: []Call) !bool

src

Drive every call one step: flush output, pump each request, hand each queued event to each call, and read when the connection wants input.

False means no call can make progress right now. An event for a stream that is not in calls is dropped, so the slice must hold every call the connection carries.

pub fn stepUntil( self: *Client, calls: []Call, wait_deadline: time.OptionalTimestamp, ) !bool

src

Like step, but returns true without expiring calls if wait_deadline elapses while waiting for peer bytes. The caller must check its own clock to distinguish a deadline wake from protocol progress.

pub fn send(self: *Client, calls: []Call) !void

src

Write everything queued, and each call's request, without reading. It is the send half of step, for a caller that has to do something between sending and waiting, such as cancelling after a delay.

pub fn unary(self: *Client, request: UnaryRequest, reply: []u8) !Response

src

Send one serialized message and return one response on this connection. No other call can remain active. Use open and step for concurrent calls.

pub fn unaryCaptured(self: *Client, request: UnaryRequest, reply: []u8) !Captured

src

unary, keeping the response headers, trailers, and error details. The message and status text go in reply; the metadata goes in the result's arena, so the caller must deinit it.

Types

struct IoOptions

src

A client over any byte pair, such as a TLS transport's plaintext side. The caller owns the reader and the writer, and nothing here closes them.

Fields

fd: OptionalFd = .none

The raw socket for every read in .fd mode. The driver consumes prefetched bytes before the next socket read. A decrypting reader requires .reader mode.

deadline_by: DeadlineBy = .fd

Who enforces a deadline. fd is right when the reader hands over the socket's own bytes. reader is required when it decrypts, because reading the fd would feed ciphertext to the connection and the parser reads the first three bytes as a frame length.

read_deadline: ?Driver.ReadDeadline = null

The plaintext reader owner's deadline operations. The context must outlive this client. Required for reader-enforced call deadlines.

keepalive: KeepAlive = .{}

Optional HTTP/2 PING keepalive policy for this connection.

enum DeadlineBy

src

Fields

fd fd
reader reader

struct KeepAlive

src
pub const KeepAlive = @import("client.zig").KeepAlive

Connection-level HTTP/2 PING keepalive policy.

more

When idle_time is set, the client sends an HTTP/2 PING frame whenever no inbound connection event has been observed for that long while calls are running. If no matching PING ACK (or other inbound peer event) arrives within timeout, the connection is treated as dead and open calls fail with UNAVAILABLE.

Fields

idle_time: time.OptionalDuration = .none

How long the connection may sit silently before sending a PING. .none disables keepalive pings.

timeout: time.Duration = .fromSecondsComptime(10)

How long to wait for the peer to answer a PING before failing the connection. Ignored when idle_time is .none.

struct ServerStream

src
pub const ServerStream = @import("client.zig").ServerStream

A server-streaming call in progress: the connection, the call, and the socket, so the caller pulls one message at a time.

init takes a pointer because the h2 stream inside the call points at the connection, and a moved struct would break that pointer. The caller keeps it in place and calls deinit.

Fields

io: Io
allocator: Allocator
socket: Io.net.Stream
transport_reader: Io.net.Stream.Reader
transport_writer: Io.net.Stream.Writer
read_buffer: [read_capacity]u8 = undefined
write_buffer: [write_capacity]u8 = undefined
frame_buffer: []u8 = &.{}
conn: h2.client.Connection
driver: Driver
call: Call

Functions

pub fn init( self: *ServerStream, allocator: Allocator, io: Io, socket: Io.net.Stream, request: Request, ) !void

src

On success, the stream owns the socket and deinit closes it. If initialization fails, the caller retains the socket.

pub fn deinit(self: *ServerStream) void

src

pub fn next(self: *ServerStream) !?message.Message

src

The next message, or null when the stream ended. Read status after null: it is the answer, and it is UNIMPLEMENTED when the peer sent a compressed message this layer cannot read.

The message borrows the call's buffer and is valid until the next next call.

pub fn status(self: *const ServerStream) ?Status

src

The answer, or null while messages are still arriving.

struct Captured

src
pub const Captured = @import("client.zig").Captured

A unary response that keeps the metadata Response drops.

more

The status text, the message bytes, and nothing else live in the caller's reply buffer. The status text is truncated to the space left after the message; for the whole text give the reply buffer room for it, or read the untruncated grpc-message field from headers or trailers. Those, and the error details, are copies in this capture's own arena, so they stay valid until deinit and not past it. Copy anything that must outlive the capture.

Fields

arena: std.heap.ArenaAllocator
status: Status

The first status the peer sent, or the local transport status. status.message borrows the reply buffer after message, truncated to the space left there. status.code is never altered.

message: []const u8

The response message with its prefix removed, a prefix of the reply buffer. Empty when the call carried no message.

headers: ?http.Headers

The response head's fields, or null when no head arrived. A trailers-only answer keeps its grpc-status and custom fields here and has no trailers.

trailers: ?http.Headers

The trailing fields, or null when the peer sent none.

error_details: []const u8

The decoded grpc-status-details-bin value: a serialized google.rpc.Status, or empty. Parsing it is the caller's codec's job.

Functions

pub fn deinit(self: *Captured) void

src

struct Request

src
pub const Request = @import("client.zig").Request

Fields

authority: []const u8

:authority, as in host:port.

service: []const u8
method: []const u8
body: []const u8 = &.{}

Framed request messages, from message.write.

scheme: http.client.Scheme = .http

.https when the transport under the reader and writer is TLS.

streaming: bool = false

The caller writes the request messages itself with Call.writeMessage and finishes with Call.closeSend, so the send side stays open. When false, body is the complete framed request.

encoding_codec: ?*const compression.Codec = null

Compress each request message with this codec: the frame flag is set, and grpc-encoding names the codec. body and the streaming writes go through Call.writeMessage, which applies it; a caller with pre-compressed bytes leaves this null and writes through writeMessageFlagged itself, with encoding naming what it sent.

encoding: []const u8 = "identity"

grpc-encoding, when this call compresses its messages. Derived from encoding_codec when both would apply.

accept_encoding: []const u8 = "identity," ++ compression.accept_all

grpc-accept-encoding: every encoding this client can read. The default advertises the whole registry, because the library decodes every member of it.

message_limit: ?u32 = null

The largest response message this call accepts, before decompression. Null uses the message frame's default.

timeout: time.OptionalDuration = .none

Relative call timeout. .none leaves the call without a deadline.

metadata: []const http.Header = &.{}

struct UnaryRequest

src
pub const UnaryRequest = @import("client.zig").UnaryRequest

One request message for the unary helpers. The codec supplies the bytes.

Fields

authority: []const u8
service: []const u8
method: []const u8
message: []const u8 = &.{}

Serialized message bytes without the five-byte gRPC prefix. The helper copies these bytes before its first transport write.

compressed: bool = false

The message already uses encoding. The helper does not compress it.

scheme: http.client.Scheme = .http
encoding_codec: ?*const compression.Codec = null

Compress the request message with this codec; the helper frames and flags it. Without one, message is delivered as the caller's bytes through the raw primitive.

encoding: []const u8 = "identity"
accept_encoding: []const u8 = "identity," ++ compression.accept_all
message_limit: ?u32 = null

The largest response message this call accepts, before decompression.

timeout: time.OptionalDuration = .none

Relative call timeout. .none leaves the call without a deadline.

metadata: []const http.Header = &.{}

struct Config

src
pub const Config = @import("client.zig").Config

Fields

allocator: Allocator
message: []u8

Destination for the response: the message first, then the status text. Both Response.message and Response.status.message borrow it. A message that does not fit is error.MessageTooLarge; the message is never truncated. The status text takes only the space left after the message and is cut to fit, possibly to empty, while status.code is always the peer's. Size it for the message plus the longest status text you need whole.

struct Response

src
pub const Response = @import("client.zig").Response

Fields

status: Status
message: []const u8

The response message with the length prefix removed, a prefix of Config.message. Empty when the call carried no message.

pub fn unary(io: Io, stream: Io.net.Stream, request: UnaryRequest, config: Config) !Response

src

Send one request and read one response over a caller-owned stream.

pub fn unaryIo( reader: *Io.Reader, writer: *Io.Writer, request: UnaryRequest, config: Config, ) !Response

src

The same call over plaintext reader and writer interfaces. A TLS adapter calls this after its handshake, which is why this takes no stream.

module Call

src

One gRPC call over one HTTP/2 stream.

more

The call owns the request bytes going out, the reassembly of the message frames coming back, and the status the stream ends with. It does not own the connection: h2.client.Stream is the write handle, and the driver hands every event to handle. Events for another stream are ignored, so a driver may hand every event to every live call.

A call is finished when result returns a status. The status is the answer, whatever the HTTP layer did, so a reset, a GOAWAY, and a clean trailer all end the same way.

Constants

pub const Error = …

src
value
error{
    /// `writeMessage` after `closeSend`.
    SendClosed,
} || Allocator.Error

Functions

pub fn init( allocator: Allocator, stream: h2.client.Stream, request: []const u8, options: Options, ) Error!Call

src

A call starts with request as its first bytes, and closes the send side after them. A streaming caller appends with writeMessage and closes with closeSend instead.

pub fn deinit(self: *Call) void

src

Free the call. A call that never got a status resets its stream first, so the peer stops working for a caller that has gone. The reset is best effort: nothing is left to report an error to.

pub fn result(self: *const Call) ?Result

src

The answer, or null while the call is still running.

pub fn errorDetails(self: *const Call) []const u8

src

The raw error details the peer attached, decoded from base64. Empty when there are none, or when the value was not base64.

pub fn responseHeaders(self: *const Call) ?Headers

src

The response header fields, or null before a head arrived. The view is a copy in this call's arena, valid until deinit.

pub fn responseTrailers(self: *const Call) ?Headers

src

The trailing fields, or null when the peer sent none. A copy in this call's arena, like responseHeaders.

pub fn abandon(self: *Call, code: status.Code, text: []const u8) void

src

Finish the call locally when the transport ends before the peer answers. A truncation is not the peer's status, so it gets the code the specification gives an interrupted call.

pub fn httpStatus(self: *const Call) u16

src

The HTTP status the response head carried, or 0 before a head arrived.

pub fn streamId(self: *const Call) u31

src

pub fn requestSent(self: *const Call) bool

src

True when every request byte is on the wire and END_STREAM was sent.

pub fn pendingBytes(self: *const Call) usize

src

Framed request bytes in this call's queue that HTTP/2 has not accepted yet. This excludes bytes already accepted by the connection, including any that its own output buffers still hold. Callers can bound their lending to this queue without inspecting its fields.

pub fn writeMessage(self: *Call, msg: []const u8) Error!void

src

Frame one message and queue it behind whatever is still unsent. A call configured with an encoding_codec compresses through this: the bytes are encoded, the frame's compressed flag is set, and the request head already names the codec in grpc-encoding. The convenience writes through writeMessageFlagged, the same primitive a caller with its own bytes uses.

pub fn writeMessageFlagged(self: *Call, bytes: []const u8, compressed: bool) Error!void

src

The same, with the compressed flag the caller's codec decided.

pub fn closeSend(self: *Call) void

src

Finish the request: the next pump sends END_STREAM behind the queued bytes.

pub fn messageLimit(self: *const Call) u32

src

The largest message this call accepts, before decompression.

pub fn pump(self: *Call) !bool

src

Write the request until h2 takes no more. False means backpressure: call again after a .writable event or after the connection drains.

pub fn nextMessage(self: *Call) Error!?message.Message

src

The next complete response message, or null when more bytes are needed.

more

The returned bytes borrow the reassembly buffer and are valid until the next handle or nextMessage; a decoded message borrows the call's decode scratch under the same rule. A compressed message whose encoding the call accepted decodes here. One that did not resolves the call as INTERNAL, unless allow_compressed hands the bytes up raw.

pub fn cancel(self: *Call) !void

src

Abort the call. The peer sees RST_STREAM with CANCEL, and the call ends CANCELLED. Calling this on a finished call does nothing, and a second call queues no second reset. The send side is finished with it: the reset is already queued, so a later closeSend has nothing to send. A failed reset returns its error and leaves the call as it was, so it may be tried again.

pub fn expire(self: *Call) void

src

Finish the call locally because its deadline passed, and tell the peer. The first status wins: a call that already ended keeps its answer and queues nothing.

pub fn handle(self: *Call, event: h2.client.Event) Error!void

src

Take one event. An event for another stream is ignored, so a driver that owns several calls may hand every event to every call.

Types

struct Result

src
pub const Result = status.Status

A finished call's answer. message borrows the call's arena and is valid until deinit.

Fields

code: Code
message: []const u8 = ""

struct Options

src

Fields

encoding_codec: ?*const compression.Codec = null

Compress each writeMessage with this codec, flag the frame, and name the codec in the request head's grpc-encoding. writeMessageFlagged stays the raw primitive: a caller with its own bytes writes those and this stays null.

allow_compressed: bool = false

Return a compressed message with its flag set instead of decoding or ending the call with INTERNAL. The layer above owns the bytes, so this is how it takes delivery — when the response's grpc-encoding names a registry codec this call accepts, nextMessage decodes first and this flag never matters.

accepted_encodings: []const u8 = "identity," ++ compression.accept_all

The encodings named in grpc-accept-encoding, comma separated. A response that names a registry codec outside this list cannot be decoded here; anything outside the registry entirely cannot be read at all.

send_closed: bool = true

Close the send side once request is on the wire. A streaming caller sets this false and closes with closeSend.

message_limit: u32 = message.default_limit

The largest message this call accepts, excluding the five prefix bytes.

Under compression this is the plaintext budget, not the length on the wire: with the flag set the prefix counts gzip bytes, and a small body can decode past any multiple of itself. A decoder target is sized from this number, and a decode that overflows it is RESOURCE_EXHAUSTED.

module Stream

src

The byte-oriented client stream shared by the blocking and readiness drivers.

A stream borrows its Call and its client or session. It adds no socket or scheduling policy: advance runs the driver that made it. Request and response bytes still belong to the call, and the raw call remains available for operations this small facade does not carry.

Functions

pub fn init(call: *Call, driver: Driver) Stream

src

Build a borrowed stream over a call and its driver. The call, driver context, and every call in driver.calls must stay in place until deinit. This is the adapter used by the two client implementations.

pub fn deinit(self: *Stream) void

src

Release the call through the client that owns it. This does not close the client, session, or socket. The stream must not be used again.

pub fn advance(self: *Stream) !bool

src

Drive the owning client: Client.step, or Session.wait on the readiness client. False has that driver's existing meaning.

pub fn advanceUntil(self: *Stream, deadline: time.OptionalTimestamp) !bool

src

Drive the owning client without blocking past deadline. Waking on deadline leaves the call alive and returns true; the caller must inspect its own clock to distinguish a deadline wake from protocol progress.

pub fn send(self: *Stream, bytes: []const u8) Call.Error!bool

src

Frame and queue one message if the previous queued message has drained. False queues nothing and means backpressure: keep the bytes, call advance, and retry. At most one message frame is lent to the call's writer queue at a time. The call still owns the frame after this returns.

pub fn pendingBytes(self: *const Stream) usize

src

Bytes in the call's framed request queue that HTTP/2 has not accepted yet.

pub fn closeSend(self: *Stream) void

src

Close the send side behind queued request bytes. The next advance sends END_STREAM once the bytes drain.

pub fn requestSent(self: *const Stream) bool

src

True when every request byte is on the wire and END_STREAM was sent.

pub fn nextMessage(self: *Stream) Call.Error!?message.Message

src

The next complete response message, without advancing the connection. Its bytes borrow the call and are valid until the next event or message read. Call advance when this is null and result is still null.

pub fn result(self: *const Stream) ?Call.Result

src

The final status, or null while the call is still running.

pub fn responseHeaders(self: *const Stream) ?http.Headers

src

Response headers copied into the call, valid until the stream is released.

pub fn responseTrailers(self: *const Stream) ?http.Headers

src

Response trailers copied into the call, valid until the stream is released.

pub fn errorDetails(self: *const Stream) []const u8

src

Decoded binary error details owned by the call.

pub fn cancel(self: *Stream) !void

src

Ask the transport to cancel this call.

pub fn raw(self: *Stream) *Call

src

The sans-I/O call, for callers that need a field or operation outside this facade. Its lifetime and receive-buffer borrowing rules are unchanged.

Types

struct Driver

src

The operations a client supplies when it lends out one of its calls. Applications normally get these from Client.stream or readiness.Session.stream instead of constructing them directly.

Fields

context: *anyopaque
calls: []Call = &.{}

Every live call on a blocking client. Unused by a readiness session, whose own slots already describe the complete set.

advance: *const fn (*anyopaque, []Call) anyerror!bool
advance_until: ?*const fn (*anyopaque, []Call, time.OptionalTimestamp) anyerror!bool = null

Optional deadline-bounded step. When set, advanceUntil wakes at deadline without expiring the call.

close: *const fn (*anyopaque, *Call) void

module head

src

The request head for one call: the :path, the gRPC fields, and the caller's metadata.

h2 writes the pseudo-fields from its own request struct, so this module produces regular fields only, in wire order. A key or value that cannot go on the wire is refused here rather than becoming a connection error three layers down.

Constants

pub const content_type = "application/grpc+proto"

src

pub const accept_encoding = "identity"

src

The one encoding this layer reads. A server that answers with anything else gets UNIMPLEMENTED until a codec is wired above the call.

pub const Error = …

src
value
error{
    /// The destination cannot hold the path or the field list.
    NoSpace,
    InvalidService,
    InvalidMethod,
    InvalidName,
    InvalidValue,
    /// A key beginning with `grpc-`, which the specification reserves.
    ReservedName,
}

Functions

pub fn path(out: []u8, request: Request) Error![]const u8

src

Write /<service>/<method> and return the slice used.

pub fn isBinary(name: []const u8) bool

src

A metadata key whose value is raw bytes on the wire. gRPC marks those with a -bin suffix and base64-encodes the value.

pub fn binaryEncodedLen(raw: []const u8) usize

src

The base64 length of raw, padding included.

pub fn encodeBinary(out: []u8, raw: []const u8) Error![]const u8

src

Base64-encode a binary metadata value into out.

pub fn binaryDecodedLen(encoded: []const u8) Error!usize

src

The length decodeBinary writes for this value.

pub fn decodeBinary(out: []u8, encoded: []const u8) Error![]const u8

src

Base64-decode a binary metadata value into out.

pub fn fieldCount(request: Request) usize

src

How many regular fields fields writes for this request.

pub fn fields( out: []Header, scratch: []u8, timeout_buf: *[timeout.max_digits + 1]u8, request: Request, ) Error![]Header

src

Fill out with every regular field, in wire order, and return the slice used.

timeout_buf holds the encoded deadline, and scratch holds each lowered key and the base64 of every binary value, because the fields borrow both. Size scratch as the sum of every key length and binaryEncodedLen over the -bin values.

pub fn validateName(name: []const u8) Error!void

src

A metadata key: ASCII letters, digits, -, _, and .. An upper-case key is legal input and goes on the wire lower-cased, which fields does.

pub fn validateValue(value: []const u8) Error!void

src

A metadata value: printable ASCII and spaces, with no control bytes. Binary metadata arrives base64-encoded, so it passes this check too.

Types

struct Request

src

Fields

service: []const u8

A dotted service name, as the generated stubs spell it: helloworld.Greeter.

method: []const u8

The RPC name: SayHello.

encoding: []const u8 = "identity"

The encoding this call sends messages in. identity writes no grpc-encoding field, which is the same thing on the wire.

accept_encoding: []const u8 = "identity"

The encodings this client can read, sent as grpc-accept-encoding.

timeout: time.OptionalDuration = .none

Sent as grpc-timeout when set, and enforced as a deadline when the client runs.

metadata: []const Header = &.{}

Regular fields the caller adds. Names are lowercase.

module message

src

The gRPC message frame: a compressed flag, a big-endian length, and a body.

One message is five header bytes and a body: a flag byte that is 0 or 1, a big-endian u32 length, then that many bytes of encoded message. Nothing here reads the body. The codec above decides what the bytes mean; grpc counts them and hands them over unchanged.

Constants

pub const prefix_len = 5

src

pub const default_limit: u32 = 4 * 1024 * 1024

src

The receive limit every gRPC implementation starts from: 4 MiB.

pub const max_length: u32 = std.math.maxInt(u32)

src

The largest value a length can hold.

pub const Error = …

src
value
error{
    /// The buffer ends before the header, or before the body the header promised.
    Truncated,
    /// The length is above the limit the caller set.
    TooLarge,
    /// The flag byte was neither 0 nor 1. The flag is a boolean on the wire.
    InvalidFlag,
    /// The destination slice cannot hold the frame.
    NoSpace,
}

Functions

pub fn parseHeader(bytes: []const u8) Error!Header

src

Read the frame header at the start of bytes. Five bytes is enough.

pub fn writeHeader(out: *[prefix_len]u8, compressed: bool, length: u32) void

src

Write the five header bytes for a body of length.

pub fn write(out: []u8, body: []const u8, compressed: bool) Error![]u8

src

A whole frame in one slice. A message above 4 GiB has no gRPC encoding.

Types

struct Header

src

Fields

compressed: bool
length: u32

struct Message

src

One decoded message. bytes borrows from the buffer it was read out of.

Fields

compressed: bool
bytes: []const u8

struct Iterator

src

Walk complete messages out of one contiguous buffer.

The buffer has to hold a whole message: gRPC messages outlive the DATA frame they arrived in, so the caller concatenates first and reads second. The iterator reports Truncated rather than buffering, because buffering is a policy and this layer holds no allocator.

Fields

bytes: []const u8
offset: usize = 0
limit: u32 = default_limit

Functions

pub fn init(bytes: []const u8) Iterator

src

pub fn next(self: *Iterator) Error!?Message

src

The next complete message, or null at the end of the buffer.

module readiness

src

A readiness client: one connection, several calls in flight, no threads.

more

Experimental: this surface will be removed. grpc.Client runs the same calls on any std.Io implementation, and an evented Io such as zio multiplexes without a thread per call.

A session owns the call slots and dispatches HTTP events to each call. The shared HTTP connection driver handles socket reads, frame writes, and deadline waits. Each call keeps its own absolute deadline.

Constants

pub const Error = …

src
value
error{
    /// Every call slot is in use.
    TooManyCalls,
    /// The peer ended the connection with calls still open.
    ConnectionClosed,
    /// The connection will not take more bytes from this driver.
    InputFull,
}

Types

struct Options

src

Fields

allocator: Allocator
max_calls: usize = 16

Calls this session can carry at once.

message_limit: u32 = message.default_limit

The largest message each call accepts, before decompression.

struct Session

src

Fields

io: Io
allocator: Allocator
socket: Io.net.Stream
transport_reader: Io.net.Stream.Reader
transport_writer: Io.net.Stream.Writer
read_buffer: [read_capacity]u8 = undefined
frame: []u8 = &.{}
conn: h2.client.Connection
driver: Driver
calls: []Call = &.{}
used: []bool = &.{}
opened: bool = false
keepalive: client.KeepAliveState = .{}

Functions

pub fn init( self: *Session, options: Options, io: Io, socket: Io.net.Stream, ) !void

src

On success, the session owns the socket and deinit closes it. On failure, the caller retains the socket.

pub fn deinit(self: *Session) void

src

pub fn setKeepAlive(self: *Session, policy: client.KeepAlive) !void

src

Configure HTTP/2 PING keepalive on this session.

pub fn stream(self: *Session, call: *Call) Stream

src

Lend a session-owned call the byte-stream facade shared with blocking clients. The stream borrows this session and owns neither it nor its socket. Each Stream.advance is exactly Session.wait. Stream.deinit returns this call's slot to the session, not the session itself.

pub fn open(self: *Session, request: client.Request) !*Call

src

Open a call on this connection. The call belongs to the session until close is called on its slot.

pub fn close(self: *Session, call: *Call) void

src

Hand a slot back. Its call is finished or abandoned.

pub fn running(self: *const Session) usize

src

Calls still waiting for a status.

pub fn wait(self: *Session) !bool

src

Advance every call and return after output or event progress. Otherwise, wait for input until the nearest call deadline.

False means no call is still waiting for a status.

pub fn waitUntil(self: *Session, wait_deadline: time.OptionalTimestamp) !bool

src

Like wait, but returns true without expiring calls if wait_deadline elapses while waiting for input. The caller must check its own clock to distinguish a deadline wake from protocol progress.

module compression

src

The gRPC compression codecs, over baskingspot/compress.

more

gRPC compression is wire format, not caller policy: the protocol's registry is closed (identity, gzip, deflate, snappy, zstd), the message frame carries one flag bit, and the grpc-encoding and grpc-accept-encoding fields negotiate which side may use what. So the library ships the registry, backed by the org's codecs, and a caller who wants different bytes still has the raw primitive underneath: Call.writeMessageFlagged writes a compressed-flagged frame untouched, and allow_compressed hands a compressed response message back whole.

The layering rule holds: every convenience here writes through the primitives, and the test pins its bytes to the hand-composed form.

Constants

pub const EncodeError = error{BufferTooSmall}

src

pub const DecodeError = error{ BufferTooSmall, DecodeFailed }

src

A decode ran out of target space, or the bytes were not what the codec's name promised. The gRPC mapping is the caller's: an unknown grpc-encoding is UNIMPLEMENTED, and bytes that fail their named codec are INTERNAL.

pub const gzip: Codec = …

src
value
.{
    .name = "gzip",
    .maxEncodedLen = compress.gzip.encode.maxCompressedLength,
    .encode = encodeGzip,
    .decode = decodeGzip,
}

The registry's built-in members, in the order the accept-encoding field lists them.

pub const deflate: Codec = …

src
value
.{
    .name = "deflate",
    .maxEncodedLen = compress.zlib.encode.maxCompressedLength,
    .encode = encodeDeflate,
    .decode = decodeDeflate,
}

pub const snappy: Codec = …

src
value
.{
    .name = "snappy",
    .maxEncodedLen = maxEncodedLenSnappy,
    .encode = encodeSnappy,
    .decode = decodeSnappy,
}

pub const zstd: Codec = …

src
value
.{
    .name = "zstd",
    .maxEncodedLen = compress.zstd.encode.maxCompressedLength,
    .encode = encodeZstd,
    .decode = decodeZstd,
}

pub const all = [_]*const Codec{ &gzip, &deflate, &snappy, &zstd }

src

Every built-in codec, identity excluded: identity is not a codec here, it is the absence of one, and the call paths treat it that way.

pub const accept_all = "gzip,deflate,snappy,zstd"

src

The grpc-accept-encoding value that names every built-in: what a side configured with all of them advertises.

Functions

pub fn byName(name: []const u8) ?*const Codec

src

The codec a grpc-encoding token names, or null for anything else — including identity, which no codec answers to.

Types

struct Codec

src

One codec from the protocol's registry. The functions are pointers so a Codec value can be a vtable a caller replaces or extends; the built-ins below are the registry's members.

Fields

name: []const u8

The grpc-encoding token this codec answers to.

maxEncodedLen: *const fn (input_len: usize) usize

The worst-case encoded size of input_len plaintext bytes: the size to allocate before encode.

encode: *const fn (source: []const u8, target: []u8) EncodeError!usize

Encode source into target, which holds at least maxEncodedLen(source.len). Returns the encoded byte count.

decode: *const fn (source: []const u8, target: []u8) DecodeError!usize

Decode source into target, which is bounded by the message receive limit, because that limit applies to the plaintext. Returns the plaintext byte count.

module server

src

gRPC handlers on HTTP/2 engines.

more

Stream reads messages and writes framed bytes as they arrive. Handler is the buffered convenience: every request message in, every response out. Both adapters use the same status trailers and support caller-owned TLS.

The status travels in the trailing HEADERS section, never in :status. A call that fails is still HTTP 200 with grpc-status set, which is the one thing a gRPC server cannot share with an ordinary request/response handler.

Functions

pub fn serve( io: Io, listener: *Io.net.Server, handler: Handler, options: Options, ) Io.net.Server.AcceptError!void

src

Accept connections until an unrecoverable accept error, serving each one on the Io executor with buffered handlers.

The group is awaited once the loop ends; until then every accepted connection is one concurrent task. An implementation without concurrency falls back to serving the connection inline, which is what the previous version did for every connection.

pub fn serveStreaming( io: Io, listener: *Io.net.Server, handler: StreamingHandler, options: Options, ) Io.net.Server.AcceptError!void

src

The same loop with streaming handlers: next reads one request message, and the handler writes through Stream.begin, write, and finish, all inside its own connection task, so it may block freely.

pub fn serveConnection( io: Io, stream: Io.net.Stream, handler: Handler, options: Options, ) !void

src

Serve one connection until the peer closes it.

Types

module Stream

src

A gRPC stream on an HTTP/2 exchange, with no socket or proto codec.

more

next reassembles one message across body chunks and decodes it when the request head named a compression codec from the protocol's registry. write accepts framed bytes and returns the accepted prefix. The caller retains the unsent tail. send frames one message into stream-owned storage and flush drives it through write. begin and finish write the response head and the gRPC status trailers.

Functions

pub fn init(io: Io, exchange: *Exchange) time.Timestamp.Error!Stream

src

pub fn initLimited(io: Io, exchange: *Exchange, message_limit: u32) time.Timestamp.Error!Stream

src

The same, with the message limit the server was configured for. The streaming adapter builds its streams this way so a serveStreaming options limit reaches the framing and decode checks.

pub fn next(self: *Stream) !?message.Message

src

A message borrows this stream until the next next. A decoded message borrows the exchange arena the same way. Pending reads retain incomplete prefixes and bodies. A clean end returns null. A framing or compression error is terminal and repeats on later reads.

pub fn begin(self: *Stream, headers: []const http.Header) !void

src

pub fn write(self: *Stream, bytes: []const u8) !usize

src

Write already-framed gRPC bytes. Zero means backpressure, not completion. This is the raw byte sink: the caller keeps the unaccepted tail and no message state is involved. Do not interleave it with a message that unsent reports as incomplete, or the frames corrupt each other.

pub fn send(self: *Stream, bytes: []const u8, compressed: bool) !void

src

Frame bytes and queue the message, then try to write it. The framed copy lives in stream-owned storage, so bytes may change once this returns.

more

A previous message that is still unsent is flushed first. If it cannot finish, this returns error.Pending and bytes is not accepted: return the error from the handler and call send again on the next turn. After a successful return a rest that the transport has not taken stays queued; see unsent and flush. error.TooLarge rejects a body above send_limit. Any other error is a transport failure and ends the stream.

pub fn flush(self: *Stream) !void

src

Write the queued message through write until it is complete. Zero accepted bytes returns error.Pending; the cursor keeps every accepted byte, and the next call continues from it. With nothing queued this succeeds.

pub fn unsent(self: *const Stream) usize

src

Bytes of the queued message the transport has not accepted.

pub fn finish( self: *Stream, result: status.Status, metadata: []const http.Header, details: []const u8, ) !void

src

Send the final status, once. A call after completion returns without effect. Retry on WouldBlock, which also reports a queued message that is still unsent: the trailers follow only after its last byte. The first call that reaches the trailers fixes them, and a retry sends those exactly.

more

An expired RPC deadline ends a message that cannot finish. If no byte of it was sent, it is dropped and the status becomes DEADLINE_EXCEEDED unless result already is an error. If part was sent, the stream is reset with CANCEL and no trailers follow a truncated message. Before expiry the message is waited for, so a clean finish never drops accepted output. A blocked, expired final status waits for output credit instead of another immediate deadline wake.

pub fn park(self: *Stream, wake: time.OptionalTimestamp) time.Timestamp.Error!void

src

Yield until input, output credit, or the earlier of this wake and the RPC deadline. A null wake waits only for progress or the RPC deadline.

pub fn now(self: *const Stream) time.Timestamp.Error!time.Timestamp

src

pub fn expired(self: *const Stream) time.Timestamp.Error!bool

src

pub fn trailers( arena: Allocator, result: status.Status, metadata: []const http.Header, details: []const u8, ) ![]const http.Header

src

Serialize the status identically for buffered and incremental responses.

struct StreamingHandler

src

A nonblocking callback on an accepted gRPC call. Stream.context retains application state between invocations. Pending reads and writes yield to the engine. The adapter owns Exchange.context.

Fields

ptr: *anyopaque
call: *const fn (ptr: *anyopaque, stream: *Stream) anyerror!void
complete: ?*const fn (ptr: *anyopaque, stream: *Stream) void = null

Runs once when the call closes, including reset. The call arena remains readable during this callback. It is freed after the callback returns.

Functions

pub fn init( ptr: anytype, comptime function: fn (@TypeOf(ptr), *Stream) anyerror!void, ) StreamingHandler

src

struct Request

src

Fields

path: []const u8

The :path as it arrived: /helloworld.Greeter/SayHello.

messages: []const Message

Every request message, in wire order, with the length prefix removed. Borrows the request body, so it is valid for the length of the handler call. A unary RPC sees one; a client stream sees as many as the client sent before it closed, up to the engine's body limit.

metadata: http.Headers

The regular fields of the request head.

deadline: time.OptionalTimestamp = .none

When the client's grpc-timeout runs out, read once as the request arrived, on the awake clock. .none when the field is absent or malformed. A handler cannot be interrupted by it: check expired.

arena: Allocator

Per-stream storage that lives until the response is complete. Allocate the response message here: the server reads it after the handler returns, so a handler's stack buffer would already be gone.

Functions

pub fn expired(self: Request, io: Io) time.Timestamp.Error!bool

src

Whether Request.deadline has passed. io must read the awake clock the deadline was taken on, as std's threaded Io does on Linux and macOS; this is not checked for other backends.

struct Message

src

One message with its framing removed.

Fields

compressed: bool
bytes: []const u8

struct Response

src

Fields

messages: []const []const u8 = &.{}

Every response message, in wire order. They must outlive the handler call, so allocate from Request.arena or point at static bytes. The server adds each length prefix and sends them in one body.

status: status.Status = .{ .code = .ok }
headers: []const http.Header = &.{}

Header fields to send before the body. Borrowed until the response is complete.

metadata: []const http.Header = &.{}

Trailing fields to add beside grpc-status. Borrowed the same way.

details: []const u8 = &.{}

A serialized google.rpc.Status for grpc-status-details-bin. The server base64-encodes it; an empty value sends no such trailer.

struct Handler

src

What the server calls for each request.

Fields

ptr: *anyopaque
call: *const fn (ptr: *anyopaque, request: Request, response: *Response) anyerror!void

Functions

pub fn init( ptr: anytype, comptime function: fn (@TypeOf(ptr), Request, *Response) anyerror!void, ) Handler

src

struct Options

src

Fields

allocator: Allocator
body_bytes: usize = 64 * 1024

The largest request body the engine buffers. A longer request is refused by the engine before the handler sees it.

max_streams: u16 = 64
message_limit: u32 = message.default_limit

The largest one request message may decode to. The wire body cap in body_bytes bounds the compressed bytes; this bounds the plaintext a compressed message may expand to, and a message that decodes past it answers RESOURCE_EXHAUSTED. The default matches the message frame's.

struct Adapter

src

What a caller that owns its own transport loop hands to http's engines. The TLS readiness engines in http_tls take an engine handler, so a TLS gRPC server is this adapter plus their loop; serve below is the plaintext one.

The adapter holds no allocation of its own: keep it in the server's state and call engine once, the way http's own examples keep their handler.

Fields

handler: union(enum) { buffered: struct { io: Io, Handler }, streaming: struct { io: Io, StreamingHandler }, }
message_limit: u32 = message.default_limit

The per-message plaintext bound from Options. dispatch decodes compressed request messages against it.

Functions

pub fn init(io: Io, handler_value: Handler) Adapter

src

pub fn initLimited(io: Io, handler_value: Handler, message_limit: u32) Adapter

src

init with the server's per-message plaintext bound.

pub fn initStreaming(io: Io, handler_value: StreamingHandler) Adapter

src

pub fn initStreamingLimited( io: Io, handler_value: StreamingHandler, message_limit: u32, ) Adapter

src

initStreaming with the server's per-message plaintext bound.

pub fn engine(self: *Adapter) h2_engine.Handler

src

struct Errors

src

The fixed answers for a request this server cannot route.

Constants

pub const unsupported_media_type: status.Status = …

src
value
.{
        .code = .internal,
        .message = "content-type is not application/grpc",
    }

The request had no content-type: application/grpc....

pub const not_unary: status.Status = …

src
value
.{
        .code = .internal,
        .message = "this server answers one message per call",
    }

The body was not exactly one framed message.

pub const malformed: status.Status = …

src
value
.{
        .code = .internal,
        .message = "malformed request message",
    }

struct ReadinessOptions

src

Fields

allocator: Allocator
max_connections: usize = 128

Slots, and the connections they can carry at once.

max_streams: u16 = 64
body_bytes: usize = 64 * 1024

Maximum unread request bytes in streaming mode, including prefixes. Buffered mode applies this limit to the complete request body.

message_limit: u32 = message.default_limit

The largest one request message may decode to, as in Options.

read_buffer_bytes: usize = 16 * 1024
write_buffer_bytes: usize = 16 * 1024
idle_timeout: Io.Duration = .zero

Zero disables each of these. The engine applies them per connection.

head_timeout: Io.Duration = .zero
body_timeout: Io.Duration = .zero
total_timeout: Io.Duration = .zero

struct ReadinessServer

src

A gRPC server on the readiness engine: many connections on one thread, with the engine's deadlines, accepting on the address given.

more

Experimental: this surface will be removed. The same handlers run on serve with any std.Io implementation, and an evented Io such as zio gives one-thread multiplexing to that path. The readiness engines stay in baskingspot/http.

init takes a pointer because the engine holds the address of the adapter below it, and a moved struct would break that pointer.

Fields

adapter: Adapter
inner: Backend.Server
listening: bool = false

Functions

pub fn init( self: *ReadinessServer, io: Io, bind: Io.net.IpAddress, handler: Handler, options: ReadinessOptions, ) !void

src

pub fn initStreaming( self: *ReadinessServer, io: Io, bind: Io.net.IpAddress, handler: StreamingHandler, options: ReadinessOptions, ) !void

src

Keep self at a stable address until deinit. Each callback must yield on Pending or WouldBlock and retain its unsent bytes in per-call state. body_bytes caps unread input. The HTTP engine reuses body buffers. Stream.message_limit bounds assembly. The caller controls application storage.

pub fn deinit(self: *ReadinessServer) void

src

pub fn address(self: *const ReadinessServer) Io.net.IpAddress

src

The address the kernel gave, which is how a caller finds the port when it asked for zero.

pub fn run(self: *ReadinessServer) !void

src

Serve until the engine stops or a wait fails.

pub fn requestStop(self: *ReadinessServer) void

src

Ask run to finish: it stops accepting, drains the open connections, and returns.

module status

src

gRPC status codes and the trailer field that carries them.

A call ends with one code. The code travels in grpc-status when the server answered, and in the HTTP/2 error when it did not, so this module is a plain mapping from the wire to a value and back.

Constants

pub const Error = …

src
value
error{
    /// `grpc-status` was empty.
    Missing,
    /// A digit was not decimal, or there was more than one field's worth.
    InvalidCode,
    /// A `%` was not followed by two hexadecimal digits.
    InvalidEscape,
    /// The destination slice cannot hold the decoded message.
    NoSpace,
}

Functions

pub fn parse(bytes: []const u8) Error!Code

src

Parse the grpc-status field. Leading zeros are legal, more than three digits is not.

pub fn decode(out: []u8, wire: []const u8) Error![]const u8

src

Decode a grpc-message field. Every byte stands for itself except %, which introduces two hexadecimal digits naming one byte.

The result is UTF-8 in practice and this does not check it: a malformed message is the server's defect, and dropping the text would hide the status.

pub fn decodedLen(wire: []const u8) usize

src

The number of bytes decode writes for this field: never more than the wire length, since an escape is three bytes for one.

pub fn encodedLen(text: []const u8) usize

src

The number of bytes encodeMessage writes: three for each byte that needs an escape, one for the rest.

pub fn encodeMessage(out: []u8, text: []const u8) Error![]const u8

src

Encode text for the grpc-message field. A byte outside visible ASCII, or % itself, becomes %XX.

Types

enum Code

src
pub const Code = enum(u8)

The codes gRPC defines. The wire is a decimal number, not a name.

Fields

ok ok = 0
cancelled cancelled = 1
unknown unknown = 2
invalid_argument invalid_argument = 3
deadline_exceeded deadline_exceeded = 4
not_found not_found = 5
already_exists already_exists = 6
permission_denied permission_denied = 7
resource_exhausted resource_exhausted = 8
failed_precondition failed_precondition = 9
aborted aborted = 10
out_of_range out_of_range = 11
unimplemented unimplemented = 12
internal internal = 13
unavailable unavailable = 14
data_loss data_loss = 15
unauthenticated unauthenticated = 16

Functions

pub fn fromInt(raw: u8) Code

src

A decimal grpc-status value. A code outside the defined range reads as unknown, which is what the specification says to report.

pub fn fromHttp(code: u16) Code

src

The gRPC code for an HTTP status on a response that is not a gRPC answer.

struct Status

src

A finished call: the code and whatever text the server attached.

Fields

code: Code
message: []const u8 = ""

module timeout

src

The grpc-timeout request field: at most eight digits and one unit.

A client sends the time it will wait. The server reports DEADLINE_EXCEEDED when that time runs out, so the field is advisory in wording and a deadline in practice.

Constants

pub const max_digits = 8

src

The most digits the field may hold.

pub const Error = …

src
value
error{
    /// Fewer than one digit and one unit.
    Truncated,
    /// More than `max_digits` digits.
    TooManyDigits,
    /// The last byte was not one of `HMSmun`.
    InvalidUnit,
    /// A byte before the unit was not a decimal digit.
    InvalidDigit,
}

Functions

pub fn parse(bytes: []const u8) Error!Timeout

src

pub fn deadline(raw: ?[]const u8, now: time.Timestamp) time.Timestamp.Error!time.OptionalTimestamp

src

The absolute deadline for a grpc-timeout field read at now, or .none when the field is absent or malformed. A malformed field is ignored, not an error, so a request without a usable budget behaves as one with none.

pub fn encode(out: *[max_digits + 1]u8, nanos: u64) []const u8

src

Write a deadline as eight characters or fewer.

more

The unit is the coarsest one that represents the value exactly, so a whole second goes out as 1S and a millisecond and a half as 1500m. When no unit is exact in eight digits, the unit is the coarsest whose rounded-up count fits, and the count rounds up so the encoded deadline is never shorter than the one the caller asked for.

Types

enum Unit

src
pub const Unit = enum(u8)

Fields

hours hours = 'H'
minutes minutes = 'M'
seconds seconds = 'S'
milliseconds milliseconds = 'm'
microseconds microseconds = 'u'
nanoseconds nanoseconds = 'n'

Functions

pub fn nanos(self: Unit) u64

src

struct Timeout

src

Fields

value: u32
unit: Unit

Functions

pub fn toNanos(self: Timeout) u64

src

The same deadline in nanoseconds. Saturates rather than wraps, because a wrapped deadline is a shorter one than the caller asked for.