Skip to content

About

Connect RPC for Zig: Connect, gRPC and gRPC-Web clients and servers over HTTP/1.1, HTTP/2 and HTTP/3, with a protobuf runtime 2-30x faster than Go's. No allocator, no I/O, any event loop.

Resources

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Repository files navigation

connect-zig

CI License: Apache-2.0 Zig 0.16 Connect conformance: 3,714 of 3,714 server cases, 10,711 of 10,711 client cases Line coverage: 97.7%

Connect RPC for Zig. Write a .proto file, run buf generate, and serve the same handlers to Connect, gRPC, and gRPC-Web clients, in binary protobuf or JSON.

  • Conformant. It passes every case of connectrpc's conformance suite v1.0.7, server and client.
  • No allocator and no hidden I/O. Every buffer is yours, and the core reads no clock.
  • Fast. An OpenTelemetry receiver on connect-zig takes more spans a second than one on connect-go, connect-rust, or the OpenTelemetry Collector. See Performance.
  • HTTP from colibri: HTTP/1.1, HTTP/2, and HTTP/3 (h11, h2, and h3), in cleartext or over TLS.

Try it

You need Zig 0.16.0 and curl 7.82 or later. Start the example server:

git clone https://github.com/c4milo/connect-zig && cd connect-zig
zig build run-eliza-server -- 8080

When it prints listening on port 8080, call ELIZA from a second terminal:

curl --cacert examples/harness/tls/ca.pem --json '{"sentence":"I feel tired"}' \
  https://localhost:8080/connectrpc.eliza.v1.ElizaService/Say
{"sentence":"You said \"I feel tired\". How does that make you feel?"}

With the Buf CLI, buf curl calls it in any protocol: set --protocol to connect, grpc, or grpcweb, and add --http3 for h3:

buf curl --cacert examples/harness/tls/ca.pem --protocol grpc --schema examples/eliza/proto \
  -d '{"name":"Ada"}' https://localhost:8080/connectrpc.eliza.v1.ElizaService/Introduce

What's inside

Module What it does
protobuf The binary encoding and the proto3 JSON mapping, over generated structs.
connect The Connect, gRPC, and gRPC-Web rules, as functions over headers and bytes.
connect_colibri Routes for colibri's server, and calls for colibri's client. Programs import it as rpc.
protovalidate Checks a message against the protovalidate rules of its schema.
oidc Checks an OpenID Connect bearer token, with a server interceptor that requires one.
protoc-gen-connect-zig The plugin buf generate runs to write your .pb.zig files.

Each protocol supports the same features:

Connect gRPC gRPC-Web
Server: unary, all streams ✅ ✅ ✅
Client: unary, all streams ✅ ✅ ✅
Proto and JSON codecs ✅ ✅ ✅
gzip, zstd, and brotli both ways ✅ ✅ ✅
Unary GET for NO_SIDE_EFFECTS ✅ n/a1 n/a1
Full-duplex bidirectional streams, server and client, over h2 and h32 ✅ ✅ ✅
Interceptors, server and client ✅ ✅ ✅
Error details ✅ ✅ ✅

The protobuf runtime reads proto2, proto3, and editions 2023 and 2024, with every well-known type and its JSON form. A message keeps the fields its schema does not know.

Quick start

examples/quickstart holds these steps as a project, and docs/guide.md explains each one in full.

1. Add the package

zig fetch --save git+https://github.com/c4milo/connect-zig#v0.7.0

Then add its one module to your program in build.zig. It names the library, colibri, and the type of the CPU features your program detects, each the copy connect-zig builds on:

const connect_zig = b.dependency("connect_zig", .{ .target = target, .rotor = true });
module.addImport("connect_zig", connect_zig.module("connect_zig"));

A program that codes messages, or runs the protocol on an HTTP library of its own, passes .colibri = false: the same module, without colibri, links no TLS library. examples/std_http serves ELIZA that way on std.http.Server.

2. Generate code

Install the plugin, and point buf.gen.yaml at it:

const plugin = b.addInstallArtifact(connect_zig.artifact("protoc-gen-connect-zig"), .{});
b.step("plugin", "Install protoc-gen-connect-zig").dependOn(&plugin.step);
version: v2
plugins:
  - local: zig-out/bin/protoc-gen-connect-zig
    out: gen

Run zig build plugin, then buf generate. Each .proto file gives one <file>.pb.zig module, which imports connect_zig too:

const greet = b.createModule(.{ .root_source_file = b.path("gen/greet/v1/greet.pb.zig"), .target = target, .optimize = optimize });
greet.addImport("connect_zig", connect_zig.module("connect_zig"));

3. Write a handler

A handler fills the response and returns null, or returns the error the client reads:

const connect_zig = @import("connect_zig");
const connect = connect_zig.connect;
const rpc = connect_zig.connect_colibri;

pub fn say(app: *App, ctx: *rpc.Context, request: *const rpc.Request(eliza.SayRequest), response: *rpc.Response(eliza.SayResponse)) ?connect.RpcError {
    if (request.message.sentence.len == 0) return .{ .code = .invalid_argument, .message = "say something" };
    response.message.sentence = reply(app, "You said \"{s}\". How does that make you feel?", .{request.message.sentence});
    return null;
}

Streams take a RequestStream or a ResponseStream in place of the request or the response.

4. Route it and serve it

The routes share one context, your App, which holds the CPU features. Set them once at start, with .cpu_features = .detect():

const CpuFeatures = @import("connect_zig").CpuFeatures;

/// What every route reads: your program's state, and the CPU features it detected as it started.
const App = struct {
    cpu_features: CpuFeatures,
};

A generated service's Routes lists each method as a route of colibri's server.Router, for every protocol and codec:

pub const Router = server.Router(App, .{
    .error_handler = on_error,
    .routes = Service.Routes(rpc, App, @This(), .{ .message_bytes = 4096 }).routes,
}, .{ .requests = 8, .body_bytes = 8192, .response_bytes = 8192, .header_bytes = 0 });

colibri.Server serves the router: h11, h2, and h3 with a certificate, and h11 and h2 in cleartext without one.

5. Call it

colibri's connection pool sends each request, and connect.Client builds it. Make the client once:

const client: connect.Client = .{ .cpu_features = .detect() };

A call is a connect_colibri.ClientCall(method, .{}), whose .protocol picks Connect, gRPC, or gRPC-Web. pool is colibri's connection pool, and buffers and storage are your memory:

try say.init(&client, {}, &.{ .protocol = .grpc }, &.{.{ .sentence = "I feel tired" }}, &buffers);
_ = try pool.request(&say.request, &say.response);
// Once the pool reports the call finished:
var response = say.read(storage);
const answer = try response.next(eliza.SayResponse);

examples/ holds twelve projects to copy.

Validate requests

The protovalidate module checks each request against its schema's protovalidate rules:

  1. Add rules to your schema:

    import "buf/validate/validate.proto";
    
    message User {
      string email = 1 [(buf.validate.field).string.email = true];
      int32 age = 2 [(buf.validate.field).int32 = {gte: 18, lt: 150}];
    }
  2. Add the interceptor, which reads your App's cpu_features:

    pub const Values = struct {
        protovalidate: protovalidate.InterceptorRoom(connect, .{}) = .{},
    };
    const Validate = protovalidate.Interceptor(connect, Values, .{});
    pub const route_options: rpc.RouteOptions = .{ .interceptors = &.{Validate} };

A message that breaks a rule gets invalid_argument, with each violation in an error detail. The rules compile with your program, CEL included, and nothing interprets them at run time. docs/protovalidate.md has the details.

Require a bearer token

The oidc module checks an OpenID Connect JWT signed with RS256, ES256, or EdDSA. Your program passes the provider's keys and the time. One interceptor requires a token on every method but those you exclude:

const Auth = oidc.Interceptor(Values, .{ .exclude = &.{"/grpc.health.v1.Health/"} });

docs/guide.md shows the rest.

Performance

The benchmark loads an OpenTelemetry (OTLP) receiver on one core, over TLS and h2, with a gateway core's traffic for 33,000 servers. Each bar is the highest rate held with p99 under 100 ms, the median of three rounds:

Bars of the spans a second one core holds with p99 under 100 ms over TLS, the median of three rounds with their range, and lines of p99 as the rate climbs, on arm64, for connect-zig, connect-go, connect-rust, the OpenTelemetry Collector, and Vector

CI runs the benchmarks on each tag and attaches the charts to the tag's release. Each chart names its run. docs/benchmarks.md holds every chart and the method: the codec, a routed call, validation, and the receivers with protovalidate and with compression.

How it is tested

docs/testing.md lists every check and how to run it.

Known limits

  • A function handler writes its whole stream in one call; a long stream needs a type handler.
  • The library does not report a missing required field.
  • A server stream cannot yet wait for your program's own events once its request has ended (colibri issue 130).

Contributing

See CONTRIBUTING.md and SECURITY.md. docs/design.md describes the design, docs/decisions.md each choice, and CHANGELOG.md each release.

License

connect-zig is licensed under the Apache License 2.0.

Footnotes

  1. The Connect protocol defines Unary-Get. gRPC's HTTP/2 spec requires :method POST, and gRPC-Web keeps that request shape. ↩ ↩2

  2. Over h11 a stream is half-duplex: the whole request goes before the response is read. ↩

About

Connect RPC for Zig: Connect, gRPC and gRPC-Web clients and servers over HTTP/1.1, HTTP/2 and HTTP/3, with a protobuf runtime 2-30x faster than Go's. No allocator, no I/O, any event loop.

Resources

Contributing

Security policy

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages