Skip to main content

Crate ttrpc

Crate ttrpc 

Source
Expand description

A lightweight ttrpc client and server implementation for Rust.

ttrpc combines Protocol Buffers service definitions with a compact framing protocol that does not require HTTP/2. It is designed for resource-constrained system components such as container runtime shims and sandbox agents. ttrpc and gRPC can share .proto definitions, but they are not wire-compatible.

§Highlights

  • Synchronous and Tokio-based asynchronous clients and servers.
  • Unary, client-streaming, server-streaming, and bidirectional RPCs.
  • Client and server generation using rust-protobuf or Prost.
  • Unix domain socket, TCP, vsock, and Windows named-pipe transports.
  • Per-request metadata, deadlines, and structured RPC status errors.

§Getting started

Most applications use this crate together with ttrpc-codegen:

[dependencies]
protobuf = "3.7"
ttrpc = "0.10"

[build-dependencies]
ttrpc-codegen = "0.7"

To use the Tokio runtime, disable the default synchronous runtime or enable both:

# Async only
ttrpc = { version = "0.10", default-features = false, features = ["async", "rustprotobuf"] }

# Sync and async
# ttrpc = { version = "0.10", features = ["async"] }

Generate message types and service bindings from build.rs:

use ttrpc_codegen::{Codegen, Customize, ProtobufCustomize};

fn main() -> std::io::Result<()> {
    Codegen::new()
        .input("proto/greeter.proto")
        .include("proto")
        .rust_protobuf()
        .customize(Customize {
            // Set to `true` for Tokio-based bindings.
            async_all: false,
            gen_mod: true,
            ..Default::default()
        })
        .rust_protobuf_customize(ProtobufCustomize::default().gen_mod_rs(true))
        .run()
}

Generated bindings provide a typed client, a service trait to implement, and a registration helper for the server. See the repository’s complete client, server, and streaming examples for working programs.

When upgrading from ttrpc 0.9, use ttrpc-codegen 0.7 and ttrpc-compiler 0.9, regenerate bindings, and review the runtime changelog. The runtime and generators require Rust 1.80 or newer.

§Choosing a runtime

RuntimeFeatureExecution modelStreaming
syncsync (default)Blocking client calls and a server worker poolUnary RPCs
asynchronousasyncTokio tasks and asynchronous I/OAll RPC styles

Choose sync for blocking applications and existing thread-based services. Choose asynchronous when the application already uses Tokio, needs many concurrent connections, or uses streaming RPCs.

§Choosing a Protocol Buffers backend

The default rustprotobuf backend uses rust-protobuf message types. The prost backend uses Prost message types. Enable exactly one backend and pair it with sync, async, or both runtime features. Disabling default features also disables sync and rustprotobuf.

To use the Prost backend:

[dependencies]
prost = "0.13"
ttrpc = { version = "0.10", default-features = false, features = ["sync", "prost"] }

[build-dependencies]
ttrpc-codegen-prost = "0.1"

Install protoc for the runtime build and application code generation, and use the separate Prost generator in ttrpc-codegen-prost/. Its builder uses .prost() and supports Customize::async_all for async and streaming bindings. Generated Rust modules follow the protobuf package name; see the Prost examples for sync, async, and streaming applications. Both backends use the same ttrpc wire protocol.

On Unix, add security_extension to use connection hooks and payload transforms with either backend. To build the complete Prost runtime documentation locally:

RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --no-default-features \
    --features sync,async,prost,security_extension --open

§A tour of ttrpc

§Generated clients and services

ttrpc-codegen reads .proto files during the Cargo build and generates Protocol Buffers messages, typed clients, server traits, and service registration helpers. Applications usually interact with these generated APIs instead of constructing low-level Request and Response messages directly.

§Clients and servers

The sync module contains the default thread-based Client and Server. The asynchronous module contains the Tokio-based client, server, typed streaming handles, shutdown coordination, and pluggable transports.

§Request context

Every generated client call accepts a context::Context. It carries request metadata and a relative timeout that the client converts into the wire deadline:

use std::time::Duration;
use ttrpc::context;

let mut ctx = context::with_duration(Duration::from_millis(500));
ctx.add("request-id".into(), "7f3a".into());

assert_eq!(ctx.timeout_nano, 500_000_000);
assert_eq!(ctx.metadata["request-id"], ["7f3a"]);

§Errors and status

Fallible operations return this crate’s Result alias. Error::RpcStatus represents a status returned by the remote service, while the other variants cover transport, protocol, timeout, and local stream failures. Code and Status expose the Protocol Buffers status model used on the wire.

§Feature flags

  • sync (default): thread-based client and server.
  • rustprotobuf (default): rust-protobuf message types and codec.
  • prost: Prost message types and codec; mutually exclusive with rustprotobuf.
  • async: Tokio-based client and server, streaming RPCs, and asynchronous transports.
  • security_extension: connection hooks and payload transforms for application-defined authentication, encryption, and other per-connection policies. Unix only.

The docs.rs configuration enables sync, async, and rustprotobuf. Build locally with the command above to view the Prost and security extension APIs.

§Transport addresses

AddressTransportPlatforms
unix:///run/service.sockUnix domain socketUnix
unix://@serviceAbstract Unix domain socketLinux, Android
tcp://127.0.0.1:5000TCPUnix
vsock://3:1024VM socketLinux, Android
\\.\pipe\serviceNamed pipeWindows

For macOS, ttrpc-rust only supports normal Unix domain socket:

The async transport layer can also wrap application-defined byte streams and listeners. See the crate’s transport modules for the ownership and runtime requirements of raw descriptors.

§Security and compatibility

ttrpc does not provide TLS. Protect TCP traffic at the deployment or network layer when it crosses an untrusted boundary. Do not connect a ttrpc endpoint directly to a gRPC endpoint; their framing protocols are different even when their service definitions match.

Re-exports§

pub use sync::Client;sync

Modules§

asynchronousasync
Tokio-based ttrpc clients, servers, and streaming RPCs.
context
Request metadata and timeout configuration. Per-request timeout and metadata.
error
Error handling for clients, servers, transports, and streams.
proto
Low-level ttrpc wire messages and Protocol Buffers codec support. Low-level wire framing and codec primitives.
security_extension
Per-connection hooks, metadata, and payload transformation support. Connection Extension Framework.
syncsync
Thread-based ttrpc clients and servers.

Macros§

async_client_requestasync
Send request through async client.
async_client_streamasync
Duplex streaming through async client.
async_client_stream_receiveasync
Only receive streaming through async client.
async_client_stream_sendasync
Only send streaming through async client.
async_client_streamimg_handlerasync
Handle client streaming in async mode.
async_duplex_streamimg_handlerasync
Handle duplex streaming in async mode.
async_request_handlerasync
Handle request in async mode.
async_server_streamimg_handlerasync
Handle server streaming in async mode.
client_requestsync
Send request through sync client.
err_to_others
Convert to ttrpc::Error::Others.
request_handlersync
Handle request in sync mode.

Structs§

ConnectionDataNon-security_extension
Zero-sized placeholder when security_extension is disabled. Arc<ConnectionData> costs ~24 bytes (ArcInner header only, no HashMap).
MessageHeader
The fixed-width header that precedes every ttrpc payload.
Requestrustprotobuf
Responserustprotobuf
Serversync
A configurable, thread-based ttrpc server.
Statusrustprotobuf
TtrpcContextsync
Server-side context for a synchronous request.

Enums§

Coderustprotobuf
Error
The error type for ttrpc.

Traits§

ConnectionDataExt
Helper to extract typed values from ConnectionData.
MethodHandlersync
Dispatches a request to a synchronous service method.
PayloadTransform
Optional bidirectional payload transform, attached per-connection.

Functions§

get_statusrustprotobuf
Creates a ttrpc Status from a status Code and message.
send_responsesync
Send a Response through the channel with full outbound pipeline.

Type Aliases§

Result
A specialized Result type for ttrpc.