Skip to main content

Config

Struct Config 

Source
pub struct Config { /* private fields */ }
Expand description

Builder for configuring and running connectrpc code generation.

See the crate-level docs for a worked example.

Implementations§

Source§

impl Config

Source

pub fn new() -> Self

Create a new configuration with defaults.

Source

pub fn files(self, files: &[impl AsRef<Path>]) -> Self

Add .proto files to compile.

Source

pub fn includes(self, includes: &[impl AsRef<Path>]) -> Self

Add include directories for protoc to search for imports.

Ignored when using Config::use_buf (buf resolves imports via buf.yaml).

Source

pub fn out_dir(self, dir: impl Into<PathBuf>) -> Self

Set the output directory. Defaults to $OUT_DIR.

Source

pub fn emit_rerun_directives(self, enabled: bool) -> Self

Emit cargo:rerun-if-changed= directives to stdout (default: true).

Set to false when running outside a Cargo build.rs context (e.g. from a Bazel genrule or a standalone host tool) where the directives are noise on stdout rather than instructions to a build system.

Source

pub fn strict_utf8_mapping(self, enabled: bool) -> Self

Honor features.utf8_validation = NONE by emitting Vec<u8>/&[u8] for such string fields. See CodeGenConfig::strict_utf8_mapping.

Source

pub fn generate_json(self, enabled: bool) -> Self

Emit serde derives and proto3 JSON helpers on generated message types (default: true).

Disable for proto-only builds that never speak the Connect JSON codec: message types are emitted without #[derive(serde::Serialize, serde::Deserialize)], cutting code size and serde compile time. Pair it with connectrpc’s default-features = false (the json cargo feature off) so the runtime drops its matching serde bounds — proto-only generated code only compiles against a proto-only runtime, and a JSON request to such a server returns Unimplemented. With json left on, the runtime still requires these derives. See CodeGenConfig::generate_json.

Source

pub fn emit_register_fn(self, enabled: bool) -> Self

Emit the per-file register_types(&mut TypeRegistry) aggregator (default: true).

Set to false when the generated files are include!d into the same module — the identically-named functions would otherwise collide. See CodeGenConfig::emit_register_fn.

Source

pub fn file_per_package(self, enabled: bool) -> Self

Emit one <dotted.pkg>.rs per proto package instead of the per-proto split + per-package stitcher (default: false).

Under this layout the connect service stubs are inlined directly into buffa’s single <dotted.pkg>.rs PackageMod per package — no <stem>.__connect.rs companion files, no per-proto buffa content files, and no <pkg>.mod.rs stitchers are written. Combine with Config::include_file as usual: the include file wires PackageMod entries by file.name, so the new filename (<dotted.pkg>.rs instead of <pkg>.mod.rs) is picked up transparently — your lib.rs still reads connectrpc::include_generated!() with no change. If you instead include! or #[path = ...]-mount per-proto files directly, migrate to the include file or to the per-package filenames first; the per-proto files no longer exist under this layout.

Match this to the file_per_package buf plugin option when generating Buf Schema Registry cargo SDKs or any consumer that synthesises a module tree from <dotted.package>.rs filenames (tonic’s convention). See CodeGenConfig::file_per_package.

Source

pub fn gate_client_feature(self, enabled: bool) -> Self

Prefix every generated FooClient<T> struct and its impl block with #[cfg(feature = "client")] (default: false). Use Config::client_feature_name to gate on a feature other than "client" — note that calling client_feature_name re-enables gating, so order it before gate_client_feature(false) if you need to set a name but leave gating off.

Opt in when you want a server-only build of your crate to drop the connectrpc/client transport stack from its dependency graph. The consumer crate then declares the gate’s Cargo feature and forwards it to connectrpc/client; see the # Client-side cfg gate section in connectrpc_codegen::codegen::generate’s docs for the minimal pattern. With the option off (the default), generated client items are unconditional — external consumers don’t have to declare any Cargo feature.

Source

pub fn encodable_impls(self, mode: EncodableImpls) -> Self

Select which messages get ::connectrpc::Encodable view impls (default: EncodableImpls::Outputs — RPC output types only).

Pass EncodableImpls::AllMessages when this crate’s message types are consumed by other crates’ services (a shared proto crate in a multi-crate split). Rust’s orphan rules require the impl Encodable<M> for MView<'_> blocks to live in the crate that defines the view types, so a downstream service crate cannot emit them itself — without this, its handlers must return owned messages or PreEncoded::from_view for these types instead of views.

Note that connectrpc-build drives the unified generation path, which ignores extern_paths — the consuming service crates of the split must be generated through the protoc-gen-connect-rust buf plugin with extern_path=<pkg>=::this_crate::... so their stubs reference this crate’s types. Mirrors the plugin’s encodable_impls=all_messages option; see connectrpc_codegen::codegen::Options::encodable_impls.

Source

pub fn client_feature_name(self, feature: impl Into<String>) -> Self

Enable Config::gate_client_feature and set the Cargo feature name it gates on (default: "client").

Use this when the generated crate exposes its client surface under a different feature name, such as grpc-client or transport. Calling this implies gate_client_feature(true), mirroring the plugin’s gate_client_feature=<name> form, so you don’t need both calls.

Source

pub fn buffa_config(self, config: CodeGenConfig) -> Self

Replace the underlying buffa CodeGenConfig wholesale.

Any buffa knob not surfaced as a builder method here can be set this way. The convenience builders above remain available for the common cases. generate_views is forced to true regardless (service stubs require view types); see Options::buffa.

Calls to the convenience builders above made before this method are discarded; calls made after override individual fields in the supplied config.

Source

pub fn use_buf(self) -> Self

Invoke buf build instead of protoc.

Requires buf on PATH. Uses buf’s dependency resolution (BSR modules) and buf.yaml configuration; Config::includes is ignored. When using buf, Config::files must contain proto-relative names as they appear in the buf module (e.g. "my/service.proto"), not filesystem paths.

Source

pub fn descriptor_set(self, path: impl Into<PathBuf>) -> Self

Read a precompiled FileDescriptorSet from disk instead of invoking a compiler.

Produce the file once with protoc --descriptor_set_out=... --include_imports or buf build --as-file-descriptor-set -o ..., then ship it with your source.

Config::files selects which files in the set to generate code for. These must be the proto-relative names as they appear in the descriptor set (e.g. "my/service.proto"), not filesystem paths. See the .proto file’s name field in the descriptor, which protoc sets to the path relative to --proto_path.

Source

pub fn emit_descriptor_set(self, name: impl Into<String>) -> Self

Also write the input FileDescriptorSet (the full set handed to codegen, not just the files selected for generation) to <out_dir>/<name> as wire-format bytes. name must be a bare file name — no path separators.

The set carries the full transitive import closure for every descriptor source (protoc --include_imports, buf --as-file-descriptor-set, or a precompiled set), so it is ready to back grpc.reflection.v1.ServerReflection for clients such as grpcurl. Pair it with include_bytes!:

// build.rs
connectrpc_build::Config::new()
    .files(&["proto/svc.proto"])
    .includes(&["proto/"])
    .emit_descriptor_set("svc_descriptor.bin")
    .compile()?;
// src/lib.rs
pub const FILE_DESCRIPTOR_SET: &[u8] =
    include_bytes!(concat!(env!("OUT_DIR"), "/svc_descriptor.bin"));

The inverse of Config::descriptor_set, which reads a precompiled set; this writes the one connectrpc-build already computed, so build scripts no longer need a second protoc --descriptor_set_out pass.

Source

pub fn include_file(self, name: impl Into<String>) -> Self

Emit an include!-based module tree file alongside the per-file .rs outputs.

The file contains nested pub mod blocks matching the proto package hierarchy, each include!-ing the relevant generated file. Include it from your crate root:

connectrpc::include_generated!();
Source

pub fn compile(self) -> Result<()>

Run code generation and write output files.

§Errors
  • $OUT_DIR is unset and no out_dir was configured
  • protoc or buf is not on PATH (when using those sources)
  • the compiler exits non-zero (syntax error, missing import, …)
  • a precompiled descriptor set cannot be read or decoded
  • codegen fails (unsupported proto feature)
  • the output directory cannot be created or written to
  • Config::emit_descriptor_set was given a name containing path separators, or the descriptor set cannot be written

Trait Implementations§

Source§

impl Default for Config

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.