### Install Buffa via Homebrew Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Optional: Install the buffa protoc plugins using Homebrew. This makes `protoc-gen-buffa` and `protoc-gen-buffa-packaging` available on your PATH. ```sh brew install buffa ``` -------------------------------- ### Install buf CLI Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Install the buf CLI tool using Homebrew on macOS or npm on any platform with Node.js. This is the recommended method for compiling .proto files with Buffa. ```sh # Install buf — see https://buf.build/docs/installation for other methods brew install bufbuild/buf/buf # macOS npm install -g @bufbuild/buf # any platform with Node.js ``` -------------------------------- ### Install Buffa Plugins from Crates.io with Cargo Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Installs the latest buffa plugins from crates.io using Cargo. This is the recommended method for installing from source. ```sh cargo install --locked protoc-gen-buffa protoc-gen-buffa-packaging ``` -------------------------------- ### TypeRegistry Setup for JSON Extension Keys Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md This code demonstrates the necessary setup for handling JSON representations of protobuf extensions using a TypeRegistry. ```rust use buffa::type_registry::{TypeRegistry, set_type_registry}; let mut reg = TypeRegistry::new(); // Codegen emits one register_types per package under __buffa; covers Any // types AND extensions, for both JSON and text: my_pkg::__buffa::register_types(&mut reg); buf_validate::__buffa::register_types(&mut reg); set_type_registry(reg); ``` -------------------------------- ### Install protoc Compiler Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Install the protoc compiler using your system's package manager. This is an alternative to buf, especially if you are using buffa-build without .use_buf(). Note that default Debian/Ubuntu versions may not support editions. ```sh brew install protobuf # macOS (v33+) apt install protobuf-compiler # Debian/Ubuntu (v21.12) nix-env -i protobuf # Nix (v29+) ``` -------------------------------- ### Install Downloaded Buffa Plugins Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Makes the downloaded buffa plugin binaries executable and moves them to a directory in the system's PATH. ```sh # Install both chmod +x protoc-gen-buffa-v0.7.0-linux-x86_64 protoc-gen-buffa-packaging-v0.7.0-linux-x86_64 mv protoc-gen-buffa-v0.7.0-linux-x86_64 ~/.local/bin/protoc-gen-buffa mv protoc-gen-buffa-packaging-v0.7.0-linux-x86_64 ~/.local/bin/protoc-gen-buffa-packaging ``` -------------------------------- ### Proto definitions for multi-package references Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Example of two proto packages referencing each other. `api/v1/service.proto` imports `context/v1/context.proto`. ```protobuf // context/v1/context.proto package myapp.context.v1; message RequestContext { string request_id = 1; } ``` ```protobuf // api/v1/service.proto package myapp.api.v1; import "context/v1/context.proto"; message Request { myapp.context.v1.RequestContext context = 1; } ``` -------------------------------- ### Install Buffa Plugins from Git Ref with Cargo Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Installs buffa plugins directly from a Git repository reference using Cargo, useful for unreleased changes. ```sh cargo install --locked --git https://github.com/anthropics/buffa protoc-gen-buffa protoc-gen-buffa-packaging ``` -------------------------------- ### Install Buffa Plugins with Optimized Release Profile Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Installs buffa plugins using Cargo with environment variables to enable LTO and reduce codegen units for smaller binaries. ```sh CARGO_PROFILE_RELEASE_LTO=true CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1 \ cargo install --locked protoc-gen-buffa protoc-gen-buffa-packaging ``` -------------------------------- ### Buf Generate Configuration (Local Packaging Plugin) Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Configure `buf.gen.yaml` to use both the remote Buffa plugin and the local `protoc-gen-buffa-packaging` plugin. This setup generates a `mod.rs` file automatically. ```yaml # buf.gen.yaml version: v2 plugins: - remote: buf.build/anthropics/buffa out: src/gen opt: - json=true - local: protoc-gen-buffa-packaging out: src/gen strategy: all ``` -------------------------------- ### Rust Module Declaration Source: https://github.com/anthropics/buffa/blob/main/README.md Example of how to wire generated Buffa Rust files into your crate using `pub mod`. ```rust // src/gen/mod.rs (hand-written) pub mod example { pub mod v1 { include!("example.v1.rs"); } } ``` -------------------------------- ### Install 32-bit Rust Targets Source: https://github.com/anthropics/buffa/blob/main/CONTRIBUTING.md Installs additional 32-bit Rust targets required for specific checks. This command is idempotent and also installs the no_std target. ```bash task install-targets ``` -------------------------------- ### Install Specific Buffa Plugin Version with Cargo Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Installs a specific version of the buffa plugins using Cargo. Use this if your `Cargo.toml` requires a particular version. ```sh cargo install --locked --version 0.7.1 protoc-gen-buffa protoc-gen-buffa-packaging ``` -------------------------------- ### Feature Resolution Pipeline Diagram Source: https://github.com/anthropics/buffa/blob/main/DESIGN.md This diagram illustrates the feature resolution pipeline, starting from .proto files, processed by protoc/buf, then buffa-build/protoc-gen-buffa, and finally buffa-codegen for Rust code generation. ```text .proto file(s) │ ▼ ┌──────────────────────────────────────────┐ │ protoc / buf │ │ (parse, resolve, edition feature │ │ resolution baked into descriptors) │ └───────────┬──────────────────────────────┘ │ FileDescriptorSet (binary proto) ▼ ┌─────────────────────────┐ │ buffa-build / │ │ protoc-gen-buffa │ │ (decode + dispatch) │ └───────────┬─────────────┘ │ FileDescriptorProto (per file) ▼ ┌─────────────────────────┐ │ buffa-codegen │ │ (Rust code generation) │ │ (owned + view types) │ └─────────────────────────┘ ``` -------------------------------- ### JSON Serialization and Deserialization Source: https://github.com/anthropics/buffa/blob/main/README.md Example of using the `json` feature for serializing a message to a JSON string and deserializing it back. ```rust let json = serde_json::to_string(&msg).unwrap(); let decoded: MyMessage = serde_json::from_str(&json).unwrap(); ``` -------------------------------- ### Lazy View Decoding Example Source: https://github.com/anthropics/buffa/blob/main/DESIGN.md Illustrates how to use lazy views for decoding protobuf messages. This approach decodes sub-messages and fields only when they are accessed, optimizing performance for workloads that read a few fields from large messages. ```rust let person = PersonLazyView::decode_lazy(&wire_bytes)?; // one non-recursive scan if let Some(addr) = person.address.get()? { // decoded here, by value println!("city: {}", addr.city); } ``` -------------------------------- ### Implementing ProtoString for a Custom String Type Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Example of implementing the `ProtoString` trait for a custom string newtype. This involves defining the `from_wire` constructor and ensuring all required supertraits are implemented. ```rust use buffa::{DecodeError, ProtoString, WirePayload}; #[derive(Clone, PartialEq, Eq, Default, Debug)] pub struct CompactStr(pub compact_str::CompactString); // … Deref, AsRef, From, From<&str> forwards … impl ProtoString for CompactStr { fn from_wire(p: WirePayload<'_>) -> Result { let s = core::str::from_utf8(p.as_slice()).map_err(|_| DecodeError::InvalidUtf8)?; Ok(CompactStr(s.into())) } } ``` -------------------------------- ### Manual Proto Inclusion (Not Recommended) Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md This demonstrates the manual approach to including generated proto code without using `include_file`. It uses the `buffa::include_proto!` macro for each package, which is less convenient for multi-package projects. ```rust // Manual approach (not recommended for multi-package projects) pub mod my_package { buffa::include_proto!("my.package"); // dotted protobuf package name } ``` -------------------------------- ### Buffa-Build Configuration in build.rs Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Use this `build.rs` script to compile proto files at build time using `buffa-build`. It requires `protoc` on PATH and allows specifying proto files, include paths, and an output file for module definitions. ```rust // build.rs fn main() { buffa_build::Config::new() .files(&["proto/my_service.proto"]) .includes(&["proto/"]) .include_file("_include.rs") .compile() .unwrap(); } ``` -------------------------------- ### Build and Run Conformance Tests with Docker Source: https://github.com/anthropics/buffa/blob/main/CONTRIBUTING.md Use this command to build the Docker tools image locally and then run the conformance tests. This ensures you are using a locally built image for testing. ```bash task tools-image-local task conformance ``` -------------------------------- ### Protobuf Definition for Int64Range Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Defines a simple 64-bit integer range with start and end fields in protobuf. ```protobuf // common/range.proto package my.common; message Int64Range { int64 start = 1; int64 end = 2; } ``` -------------------------------- ### Proto2 Extension with Default Value Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Example of declaring an optional extension with a default value in Proto2 syntax. ```proto extend MyOptions { optional int32 retry_count = 50001 [default = 3]; } ``` -------------------------------- ### Run Bare-Metal Benchmark Script Source: https://github.com/anthropics/buffa/blob/main/benchmarks/charts/README.md Executes the bare-metal build and run script for benchmarks. Output is redirected to a temporary file for further processing. ```bash benchmarks/charts/cross_metal_run.sh > /tmp/cross.out ``` -------------------------------- ### Proto Definition of a Field Option Extension Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md This is an example of how a field option extension is declared in a .proto file. ```proto extend google.protobuf.FieldOptions { optional FieldRules field = 1159; } ``` -------------------------------- ### Protoc Reflection Command-Line Options Source: https://github.com/anthropics/buffa/blob/main/docs/investigations/reflection.md Sets reflection modes for Buffa messages using protoc command-line arguments. Allows specifying default and per-message modes. ```bash --buffa_opt=reflect=bridge --buffa_opt=reflect_for=mypkg.HotPath:vtable ``` -------------------------------- ### Include proto package with buffa macro Source: https://github.com/anthropics/buffa/blob/main/docs/migration-from-prost.md Replace prost's include! macro with buffa's include_proto! macro in src/lib.rs for per-package inclusion. ```diff pub mod proto { - include!(concat!(env!("OUT_DIR"), "/my.package.rs")); + buffa::include_proto!("my.package"); } ``` -------------------------------- ### Extendee Identity Check Panic Example Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md This code demonstrates an incorrect usage where an extension declared for one message type is used with another, resulting in a panic. ```rust // (buf.validate.message) extends MessageOptions, not FieldOptions — this // is a bug in the caller. Panics with a clear message. let _ = field.options.extension(&buf_validate::__buffa::ext::MESSAGE); ``` -------------------------------- ### Build and Run Conformance Tests Natively Source: https://github.com/anthropics/buffa/blob/main/CONTRIBUTING.md Execute these commands to build the conformance test runner locally without Docker. This method populates necessary files and then runs the conformance tests. ```bash task conformance-tools-local task conformance-local ``` -------------------------------- ### Verify Buffa Plugins with Cosign Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Verifies a downloaded buffa plugin binary using `cosign` for signature and certificate verification. ```sh # Or with cosign (standalone, no gh required) — shown for one binary cosign verify-blob \ --signature protoc-gen-buffa-v0.7.0-linux-x86_64.sig \ --certificate protoc-gen-buffa-v0.7.0-linux-x86_64.pem \ --certificate-identity-regexp "github.com/anthropics/buffa" \ --certificate-oidc-issuer https://token.actions.githubusercontent.com \ protoc-gen-buffa-v0.7.0-linux-x86_64 ``` -------------------------------- ### Buffa Build Configuration Source: https://github.com/anthropics/buffa/blob/main/README.md Configuration for `buffa-build` within a `build.rs` file. Requires `protoc` to be on the system PATH. ```rust // build.rs fn main() { buffa_build::Config::new() .files(&["proto/my_service.proto"]) .includes(&["proto/"]) .compile() .unwrap(); } ``` -------------------------------- ### Generated Rust Module Structure (Manual) Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md This is an example of how you might manually structure your `mod.rs` file to include generated Rust code. It assumes a nested module hierarchy based on proto packages. ```rust // src/gen/mod.rs (hand-written — one nested `pub mod` per proto package) pub mod example { pub mod v1 { include!("example.v1.rs"); } } // src/main.rs or src/lib.rs mod gen; ``` -------------------------------- ### Rewrite build.rs from protobuf v3 Source: https://github.com/anthropics/buffa/blob/main/docs/migration-from-protobuf.md Adapt the `build.rs` file to use `buffa_build::Config` for compiling proto files, replacing the `protobuf_codegen` approach. ```diff -protobuf_codegen::Codegen::new() - .protoc() - .protoc_path(&protoc_bin_vendored::protoc_bin_path().unwrap()) - .includes(&["src/protos"]) - .input("src/protos/my_message.proto") - .cargo_out_dir("protos") - .run_from_script(); +buffa_build::Config::new() + .files(&["src/protos/my_message.proto"]) + .includes(&["src/protos"]) + .compile() + .unwrap(); ``` -------------------------------- ### EnumValue for Open Enums Source: https://github.com/anthropics/buffa/blob/main/DESIGN.md Shows how Buffa uses EnumValue to wrap open-enum fields, preserving type safety and unknown values for round-tripping. Includes the definition of EnumValue and an example PhoneType enum. ```rust #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] #[repr(i32)] pub enum PhoneType { MOBILE = 0, // variant names are verbatim from the .proto — no case transform HOME = 1, WORK = 2, } pub enum EnumValue { Known(T), Unknown(i32), } ``` -------------------------------- ### Download Buffa Plugins from GitHub Releases Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Downloads buffa plugin binaries for Linux x86_64 from GitHub releases using the `gh` CLI. ```sh # Download binaries + cosign signatures + certificates (both plugins match) gh release download v0.7.0 --repo anthropics/buffa \ --pattern 'protoc-gen-buffa*-linux-x86_64*' ``` -------------------------------- ### Configure buffa build with options Source: https://github.com/anthropics/buffa/blob/main/docs/migration-from-prost.md Update build.rs to use buffa_build::Config with specific options like output directory and JSON generation. ```diff -prost_build::Config::new() - .btree_map(&["."]) - .bytes(&["my_pkg.MyMessage.data"]) - .type_attribute(".", "#[derive(serde::Serialize)]") - .out_dir("src/generated/") - .compile_protos(&["src/items.proto"], &["src/"])?; + buffa_build::Config::new() + .files(&["src/items.proto"]) + .includes(&["src/"]) + .out_dir("src/generated/") + .generate_json(true) // built-in, proto-conformant JSON + .compile()?; ``` -------------------------------- ### ReflectMessage Implementation for FooView Source: https://github.com/anthropics/buffa/blob/main/docs/investigations/reflection-vtable.md Implements the `ReflectMessage` trait for a generated view type `FooView`. The `get` method handles different field types by borrowing or copying data, and `has` and `for_each_set` methods are outlined. ```rust impl<'a> ::buffa_descriptor::reflect::ReflectMessage for FooView<'a> { fn message_descriptor(&self) -> &MessageDescriptor { // memoized — see component 2 } fn pool(&self) -> &Arc { #buffa_path::reflect::descriptor_pool() } fn get(&self, field: &FieldDescriptor) -> ValueRef<'_> { match field.number() { // string/bytes — borrow wire bytes, the actual zero-copy win 1 => ValueRef::String(self.ans_uri), 2 => ValueRef::Bytes(self.payload), // scalars — copy, trivially cheap 3 => ValueRef::I32(self.count), // proto3-implicit-presence optional scalar — return default if absent. // `ReflectMessage::get` contract: absent singular fields return the // type's default value; presence is queried via `has()`. 4 => ValueRef::String(self.label.as_deref().unwrap_or("")), // enum — number only, matching DynamicMessage 5 => ValueRef::EnumNumber(self.kind as i32), // singular message — borrow via MessageFieldView or default. // `MessageFieldView` is a struct field, so `&self.workload` // is a real borrow tied to `&self`. `DefaultViewInstance` already // provides a static default for the unset case (no allocation). 6 => ValueRef::Message(ReflectCow::Borrowed( self.workload .get() .map(|w| w as &dyn ReflectMessage) .unwrap_or(WorkloadView::default_view_instance()), )), // repeated/map — just borrow the view container; the blanket // ReflectList/ReflectMap impls (§3) do the rest. No per-field codegen. 7 => ValueRef::List(&self.tags), 8 => ValueRef::Map(&self.labels), _ => { debug_assert!(false, "field {} not in {}", field.number(), Self::FULL_NAME); ValueRef::Bool(false) // arbitrary, unreachable in correct code } } } fn has(&self, field: &FieldDescriptor) -> bool { // Parallel match. Implicit-presence scalars: != default. // Explicit-presence (optional, message): is_set(). // Repeated/map: !is_empty(). match field.number() { /* ... */ } } fn for_each_set(&self, f: &mut dyn FnMut(&FieldDescriptor, ValueRef<'_>)) { // Iterate all field descriptors, call has() then get() for each set field. // Or unroll inline — codegen can emit a flat sequence of // `if has { f(fd, get) }` blocks, avoiding the descriptor iteration. } fn to_dynamic(&self) -> DynamicMessage { // Fall back to bridge-style materialization for this one call. // Used by `ReflectCow::to_dynamic()` and by consumers that need an // owned snapshot. Acceptable cost — it's an explicit opt-in. DynamicMessage::from_message(&self.to_owned_message(), pool, idx) } } ``` -------------------------------- ### Rewrite build.rs from protobuf v4 Source: https://github.com/anthropics/buffa/blob/main/docs/migration-from-protobuf.md Update the `build.rs` file to use `buffa_build::Config` for proto compilation, migrating from the `protobuf_codegen::CodeGen` method. ```diff -protobuf_codegen::CodeGen::new() - .inputs(["my_file.proto"]) - .include("proto/") - .generate_and_compile() - .expect("failed to compile protos"); +buffa_build::Config::new() + .files(&["my_file.proto"]) + .includes(&["proto/"]) + .compile() + .unwrap(); ``` -------------------------------- ### Enable Reflection in build.rs Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Configure Buffa's build script to generate reflection capabilities for your proto files. This sets the reflection mode to VTable by default. ```rust buffa_build::Config::new() .generate_reflection(true) // ReflectMode::VTable .files(&["proto/my_service.proto"]) .includes(&["proto/"]) .compile()?; ``` -------------------------------- ### Repeated and Map Fields: v3 vs Buffa Source: https://github.com/anthropics/buffa/blob/main/docs/migration-from-protobuf.md Repeated fields (Vec) and map fields (HashMap) have consistent usage between v3 and Buffa. The examples show how to push to a repeated field and insert into a map. ```diff ```diff // Repeated — Vec in both v3 and buffa msg.tags.push("foo".into()); // Maps — HashMap in both v3 and buffa msg.labels.insert("key".into(), "value".into()); ``` ``` -------------------------------- ### Using the Reflection API Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Access and interact with generated message types using the reflection API. The `reflect()` method provides a handle to the message, allowing access to its descriptor and fields. This example demonstrates borrowing the message in place for VTable mode. ```rust use buffa_descriptor::{Reflectable, ReflectMessage}; let person = Person { name: "alice".into(), id: 42, ..Default::default() }; let handle = person.reflect(); // borrows `person` in vtable mode let descriptor = handle.message_descriptor(); handle.for_each_set(&mut |field, value| { println!("{} = {value:?}", field.name()); }); let id = handle.get(descriptor.field_by_name("id").unwrap()); ``` -------------------------------- ### Configure Buffa Build for Text Format Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md In your `build.rs` file, configure Buffa to generate text format support by calling `generate_text(true)`. ```rust // build.rs buffa_build::Config::new() .files(&["proto/my_service.proto"]) .includes(&["proto/"]) .generate_text(true) .compile() .unwrap(); ``` -------------------------------- ### Building Dynamic Values with Value and Struct Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Illustrates the creation of dynamic, JSON-like data structures using `Value`, `Struct`, and `ListValue` from `buffa_types`. Shows how to create primitive values, lists, and structured objects. ```rust use buffa_types::{Value, Struct, ListValue}; let val = Value::from("hello"); let val = Value::from(42.0); let val = Value::from(true); let val = Value::null(); let list = ListValue::from_values(vec![ Value::from(1.0), Value::from("two"), ]); let obj = Struct::from_fields([ ("name", Value::from("Alice")), ("age", Value::from(30.0)), ]); ``` -------------------------------- ### Run Lint and Test Commands Source: https://github.com/anthropics/buffa/blob/main/CONTRIBUTING.md Before committing, ensure code quality and correctness by running the lint and test tasks. Use `task verify` for a more comprehensive check including the conformance suite. ```bash task lint && task test ``` ```bash task verify ``` -------------------------------- ### Proto File Normalization to Editions Model Source: https://github.com/anthropics/buffa/blob/main/DESIGN.md Illustrates how proto2, proto3, and edition N files are normalized to the editions model during compilation. This ensures a single code path for code generation, parameterized by resolved features. ```text proto2 file → proto2 feature defaults proto3 file → proto3 feature defaults edition N file → edition N defaults + file-level feature overrides ``` -------------------------------- ### Local Buffa Plugins for Development Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Configure local Buffa plugins for development or in-tree builds. `protoc-gen-buffa` does not emit `mod.rs`, and `protoc-gen-buffa-packaging` requires `strategy: all` to process the full file set. ```yaml # buf.gen.yaml version: v2 plugins: - local: protoc-gen-buffa out: src/gen - local: protoc-gen-buffa-packaging out: src/gen strategy: all ``` -------------------------------- ### Run Benchmark Variants and Capture Output Source: https://github.com/anthropics/buffa/blob/main/benchmarks/history/README.md Runs each benchmark variant on a quiesced machine and captures its stdout using criterion. Ensure to use the --bench flag. ```bash # 2. Run each variant on a quiesced machine, capturing its stdout — criterion # needs the --bench flag: for v in /tmp/cgu/cgu*.bench; do "$v" --bench --measurement-time 4 > "$(basename "$v" .bench).txt" done # (yields cgu1.txt, cgu16.txt, …) ``` -------------------------------- ### Generate Code and Run Project Source: https://github.com/anthropics/buffa/blob/main/examples/bsr-quickstart/README.md Run this command after editing proto files to generate Rust code. The generated code is committed to the repository. Then, run the Rust application. ```sh buf generate # only needed after editing proto/ — generated code is checked in cargo run ``` -------------------------------- ### Buf Generate Command Source: https://github.com/anthropics/buffa/blob/main/README.md The command to execute `buf generate` after setting up the configuration. ```sh buf generate ``` -------------------------------- ### Generated module tree for multi-package protos Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Illustrates the generated Rust module tree structure for nested proto packages, showing how cross-package types are resolved using `super::`. ```text pub mod myapp { pub mod context { pub mod v1 { // RequestContext defined here } } pub mod api { pub mod v1 { // Request defined here, references // super::super::context::v1::RequestContext } } } ``` -------------------------------- ### Create a new changelog entry Source: https://github.com/anthropics/buffa/blob/main/CONTRIBUTING.md Use this command to create a new changelog fragment file. It prompts for the change kind and a multi-line body. Commit the generated file with your changes. ```sh task changelog-new ``` -------------------------------- ### Buffa Reflection Build Configuration Source: https://github.com/anthropics/buffa/blob/main/docs/investigations/reflection.md Configures reflection modes per message type using FQN glob patterns in the build script. Supports `Bridge`, `VTable`, and `Off` modes. ```rust // build.rs .reflection(ReflectMode::Bridge) // default .reflection_for("mypkg.HotPath", ReflectMode::VTable) .reflection_for("mypkg.Internal.**", ReflectMode::Off) ``` -------------------------------- ### Packing and Unpacking Messages with Any Source: https://github.com/anthropics/buffa/blob/main/docs/guide.md Shows how to use the `Any` type from `buffa_types` to pack messages into a generic Any type and unpack them back into their original message types. Includes checking the type of a packed message. ```rust use buffa_types::google::protobuf::Any; use buffa::Message; // Pack let any = Any::pack(&my_message, MyMessage::TYPE_URL); // Check type if any.is_type(MyMessage::TYPE_URL) { /* ... */ } // Unpack let msg: Option = any.unpack_if::(MyMessage::TYPE_URL)?; ``` -------------------------------- ### Pluggable String Type Configuration Source: https://github.com/anthropics/buffa/blob/main/DESIGN.md Demonstrates configuring a custom string type using `buffa_build`'s `string_type` knob for specific field paths. ```rust string_type = "smol_str::SmolStr" ``` -------------------------------- ### Buf Generate with Local Plugin Source: https://github.com/anthropics/buffa/blob/main/README.md Alternative `buf generate` configuration using a local plugin for module tree generation. Note the removal of `file_per_package=true`. ```yaml version: v2 plugins: - remote: buf.build/anthropics/buffa out: src/gen opt: - json=true - local: protoc-gen-buffa-packaging out: src/gen strategy: all ``` -------------------------------- ### Include generated protobuf code with buffa Source: https://github.com/anthropics/buffa/blob/main/docs/migration-from-protobuf.md Use `buffa::include_proto!` macro to include generated Rust code from protobuf definitions. The argument is the dotted protobuf package name. ```diff // v3 -include!(concat!(env!("OUT_DIR"), "/protos/my_message.rs")); -// v4 -include!(concat!(env!("OUT_DIR"), "/protobuf_generated/generated.rs")); +// buffa +buffa::include_proto!("my.package"); ``` -------------------------------- ### Upgrade Protobuf Version and Tools Image Source: https://github.com/anthropics/buffa/blob/main/CONTRIBUTING.md Commands to update the protobuf version used by Buffa. This involves updating the tools image, fetching new protos, and regenerating types. ```bash task tools-image task vendor-bootstrap-protos task gen-bootstrap-types ``` -------------------------------- ### Migrate Prost Build to Buffa for JSON Serialization Source: https://github.com/anthropics/buffa/blob/main/docs/migration-from-prost.md Compares the build configuration for JSON serialization between Prost and Buffa. Buffa integrates JSON generation directly, eliminating the need for a separate `pbjson-build` crate. ```diff // build.rs -prost_build::Config::new() - .compile_protos(&["my.proto"], &["proto/"])?; -pbjson_build::Builder::new() - .register_descriptors(&descriptor_bytes)? - .build(&[ ".my_package" ])?; +buffa_build::Config::new() + .files(&["my.proto"]) + .includes(&["proto/"]) + .generate_json(true) // built-in, no separate crate needed + .compile()?; ```