Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
kind: Added
body: |-
**Lazy views can defer fields of extern types.** A new `lazy_extern_path` option (`buffa_build::Config::lazy_extern_path`, plugin `lazy_extern_path=<proto>`) declares that the `extern_path` crate for a package or type ships the lazy view family, so a lazy view decodes fields of its types on access, as `LazyMessageFieldView` and `LazyRepeatedView` of the crate's `FooLazyView`, instead of eagerly. Well-known types mapped to `buffa-types` stay eager.
time: 2026-11-27T19:52:05+04:00
40 changes: 40 additions & 0 deletions buffa-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1116,6 +1116,43 @@ impl Config {
self
}

/// Declare that the [`extern_path`](Self::extern_path) crate for a proto
/// package or type ships the lazy view family, as a crate generated with
/// [`lazy_views(true)`](Self::lazy_views) does.
///
/// Lazy views keep message fields of extern types eager by default, since
/// an extern crate may not ship the lazy family. A field whose type falls
/// under `proto_path` is deferred like a local message field instead,
/// decoded on access through the extern crate's `FooLazyView`. Well-known
/// types mapped to `buffa-types` by default stay eager, as `buffa-types`
/// ships no lazy views.
///
/// `proto_path` takes the same form as in
/// [`extern_path`](Self::extern_path), and [`compile`](Self::compile)
/// validates it the same way. It has no effect unless
/// [`lazy_views`](Self::lazy_views) is enabled.
///
/// # Example
///
/// ```rust,ignore
/// buffa_build::Config::new()
/// .lazy_views(true)
/// .extern_path(".my.common", "::common_protos")
/// .lazy_extern_path(".my.common")
/// .files(&["proto/my_service.proto"])
/// .includes(&["proto/"])
/// .compile()
/// .unwrap();
/// ```
#[must_use]
pub fn lazy_extern_path(mut self, proto_path: impl Into<String>) -> Self {
// Stored as given, like `extern_path`: `compile` normalizes it.
self.codegen_config
.lazy_extern_paths
.push(proto_path.into());
self
}

/// Exclude a proto package from code generation.
///
/// `package` is the proto package to exclude (e.g. `"buf.validate"`,
Expand Down Expand Up @@ -2410,6 +2447,9 @@ impl Config {
for (proto, _) in &mut self.codegen_config.extern_paths {
*proto = buffa_codegen::normalize_extern_path_proto_name(proto)?;
}
for proto in &mut self.codegen_config.lazy_extern_paths {
*proto = buffa_codegen::normalize_extern_path_proto_name(proto)?;
}

// Validate the shared-pool prerequisites before doing any work, and
// check reflection first so the error names the actually-missing
Expand Down
6 changes: 4 additions & 2 deletions buffa-codegen/src/lazy_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ use crate::CodeGenError;
/// defer), and map/oneof message values are reached through eager types.
/// Fields resolving to **extern** types (WKTs via `buffa-types`,
/// `extern_path`-mapped crates) also stay eager: the target crate may not
/// ship a lazy family, and WKT JSON needs the hand-written eager impls.
/// ship a lazy family, and WKT JSON needs the hand-written eager impls. An
/// extern type under `lazy_extern_paths` is the exception: its crate is
/// declared to ship the family, so its fields defer like local ones.
fn is_lazy_field(scope: MessageScope<'_>, field: &FieldDescriptorProto) -> bool {
let features = crate::features::resolve_field(scope.ctx, field, scope.features);
if effective_type(scope.ctx, field, &features) != Type::TYPE_MESSAGE {
Expand All @@ -52,7 +54,7 @@ fn is_lazy_field(scope: MessageScope<'_>, field: &FieldDescriptorProto) -> bool
scope
.ctx
.rust_type_relative_split(type_name, scope.current_package, scope.nesting)
.is_some_and(|split| !split.is_extern)
.is_some_and(|split| !split.is_extern || scope.ctx.config.defers_extern_type(type_name))
}

/// Generate the `FooLazyView` struct + impls for `msg`.
Expand Down
37 changes: 37 additions & 0 deletions buffa-codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1357,6 +1357,24 @@ pub struct CodeGenConfig {
/// values in bytes-keyed maps; ordinary message containers use serde
/// directly.
pub extern_paths: Vec<(String, String)>,
/// Proto packages or types, named like the proto side of
/// [`extern_paths`](Self::extern_paths), whose extern crate was generated
/// with [`lazy_views`](Self::lazy_views) and so ships the lazy view family.
///
/// A lazy view keeps a message field of an extern type eager, since the
/// extern crate may not ship the lazy family. A field whose type falls
/// under one of these entries is deferred like a local message field
/// instead: a `LazyMessageFieldView` or `LazyRepeatedView` of the extern
/// crate's `FooLazyView`, at the same `__buffa::lazy_view` layout this
/// crate generates. Well-known types mapped to `buffa-types` by default
/// stay eager, as `buffa-types` ships no lazy views; to defer them, map
/// `.google.protobuf` to a crate that does.
///
/// Has no effect unless [`lazy_views`](Self::lazy_views) is enabled. Like
/// [`extern_paths`](Self::extern_paths), [`generate`] does not validate
/// entries: a caller that fills this field directly should pass each name
/// through [`normalize_extern_path_proto_name`].
pub lazy_extern_paths: Vec<String>,
/// Ordered (proto-path-prefix, [`BytesRepr`]) rules selecting the Rust type
/// for `bytes` fields. Later rules win, so a broad rule (e.g. `"."` →
/// `Bytes`) can be refined by a more specific one. Fields matching no rule
Expand Down Expand Up @@ -2032,6 +2050,7 @@ impl Default for CodeGenConfig {
generate_arbitrary: false,
skip_debug: Vec::new(),
extern_paths: Vec::new(),
lazy_extern_paths: Vec::new(),
bytes_fields: Vec::new(),
string_fields: Vec::new(),
map_fields: Vec::new(),
Expand Down Expand Up @@ -2072,6 +2091,24 @@ impl Default for CodeGenConfig {
}

impl CodeGenConfig {
/// Whether a lazy view defers a field of the extern type `fqn`: it falls
/// under a [`lazy_extern_paths`](Self::lazy_extern_paths) entry, and isn't
/// a well-known type from `buffa-types`, which ships no lazy views.
pub(crate) fn defers_extern_type(&self, fqn: &str) -> bool {
// the same override test as `effective_extern_paths`: only an exact
// `.google.protobuf` mapping replaces `buffa-types`
let from_buffa_types = context::matches_proto_prefix(".google.protobuf", fqn)
&& !self
.extern_paths
.iter()
.any(|(proto, _)| proto == ".google.protobuf");
!from_buffa_types
&& self
.lazy_extern_paths
.iter()
.any(|prefix| context::matches_proto_prefix(prefix, fqn))
}

/// Whether any [`FeatureOverride::EnumType`] rule is configured — the
/// gate for the open-enum declared-default machinery (which can only
/// fire when a closed enum has been opened by such a rule).
Expand Down
130 changes: 130 additions & 0 deletions buffa-codegen/src/tests/view_codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,3 +721,133 @@ fn map_entries_omit_defaults_compares_view_enum_values_with_their_default() {
assert_eq!(view.matches(closed).count(), 3, "{view}");
assert_eq!(view.matches("v.to_i32()!=0").count(), 3, "{view}");
}

/// `app.Holder`'s lazy view, with whitespace removed, for a `Holder` holding
/// a singular and a repeated `dep.Thing` and a `google.protobuf.Timestamp`,
/// none of which this run generates.
fn lazy_extern_holder(config: CodeGenConfig) -> String {
let message = |name: &str, field: Vec<FieldDescriptorProto>| DescriptorProto {
name: Some(name.to_string()),
field,
..Default::default()
};
let message_field = |name: &str, number, label, type_name: &str| FieldDescriptorProto {
type_name: Some(type_name.to_string()),
..make_field(name, number, label, Type::TYPE_MESSAGE)
};
let mut dep = proto3_file("dep.proto");
dep.package = Some("dep".to_string());
dep.message_type.push(message(
"Thing",
vec![make_field(
"name",
1,
Label::LABEL_OPTIONAL,
Type::TYPE_STRING,
)],
));
let mut wkt = proto3_file("google/protobuf/timestamp.proto");
wkt.package = Some("google.protobuf".to_string());
wkt.message_type.push(message(
"Timestamp",
vec![make_field(
"seconds",
1,
Label::LABEL_OPTIONAL,
Type::TYPE_INT64,
)],
));
let mut app = proto3_file("app.proto");
app.package = Some("app".to_string());
app.dependency = vec![
"dep.proto".to_string(),
"google/protobuf/timestamp.proto".to_string(),
];
app.message_type.push(message(
"Holder",
vec![
message_field("one", 1, Label::LABEL_OPTIONAL, ".dep.Thing"),
message_field("many", 2, Label::LABEL_REPEATED, ".dep.Thing"),
message_field("at", 3, Label::LABEL_OPTIONAL, ".google.protobuf.Timestamp"),
],
));
let mut config = CodeGenConfig {
lazy_views: true,
..config
};
config
.extern_paths
.push((".dep".to_string(), "::dep_crate".to_string()));
let files =
generate(&[dep, wkt, app], &["app.proto".to_string()], &config).expect("should generate");
let mut lazy = files
.iter()
.filter(|f| f.content.contains("pub struct HolderLazyView"))
.map(|f| f.content.as_str())
.collect::<String>();
lazy.retain(|c| !c.is_whitespace());
lazy
}

#[test]
fn test_lazy_view_extern_fields_stay_eager_by_default() {
let lazy = lazy_extern_holder(CodeGenConfig::default());
assert!(
lazy.contains("pubone:::buffa::MessageFieldView<::dep_crate::__buffa::view::ThingView<'a>"),
"{lazy}"
);
assert!(!lazy.contains("lazy_view::ThingLazyView"), "{lazy}");
}

#[test]
fn test_lazy_extern_path_defers_extern_fields() {
let lazy = lazy_extern_holder(CodeGenConfig {
lazy_extern_paths: vec![".dep".to_string()],
..Default::default()
});
assert!(
lazy.contains(
"pubone:::buffa::LazyMessageFieldView<'a,::dep_crate::__buffa::lazy_view::ThingLazyView<'a>"
),
"{lazy}"
);
assert!(
lazy.contains(
"pubmany:::buffa::LazyRepeatedView<'a,::dep_crate::__buffa::lazy_view::ThingLazyView<'a>"
),
"{lazy}"
);
}

#[test]
fn test_lazy_extern_path_keeps_buffa_types_wkts_eager() {
// "." covers every type, but buffa-types ships no lazy views
let lazy = lazy_extern_holder(CodeGenConfig {
lazy_extern_paths: vec![".".to_string()],
..Default::default()
});
assert!(lazy.contains("lazy_view::ThingLazyView"), "{lazy}");
assert!(
lazy.contains(
"pubat:::buffa::MessageFieldView<::buffa_types::google::protobuf::__buffa::view::TimestampView<'a>"
),
"{lazy}"
);
assert!(!lazy.contains("TimestampLazyView"), "{lazy}");
}

#[test]
fn test_lazy_extern_path_defers_wkts_mapped_to_another_crate() {
let lazy = lazy_extern_holder(CodeGenConfig {
extern_paths: vec![(".google.protobuf".to_string(), "::wkt_crate".to_string())],
lazy_extern_paths: vec![".google.protobuf".to_string()],
..Default::default()
});
assert!(
lazy.contains(
"pubat:::buffa::LazyMessageFieldView<'a,::wkt_crate::__buffa::lazy_view::TimestampLazyView<'a>"
),
"{lazy}"
);
assert!(!lazy.contains("lazy_view::ThingLazyView"), "{lazy}");
}
11 changes: 11 additions & 0 deletions buffa-test/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,17 @@ fn main() {
.compile()
.expect("buffa_build failed for lazy_views.proto");

// lazy_extern_path — test.lazyviews ships the lazy family (above), so a
// package mapping it with extern_path can defer its types like local ones.
buffa_build::Config::new()
.files(&["protos/lazy_extern.proto"])
.includes(&["protos/"])
.extern_path(".test.lazyviews", "crate::lazyviews")
.lazy_views(true)
.lazy_extern_path(".test.lazyviews")
.compile()
.expect("buffa_build failed for lazy_extern.proto");

// lazy_views + preserve_unknown_fields(false): compiles the lazy decode
// loop without unknown-field capture, and the PhantomData lifetime anchor
// for an all-scalar lazy struct — branches lazy_views.proto can't reach.
Expand Down
15 changes: 15 additions & 0 deletions buffa-test/protos/lazy_extern.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Exercises `lazy_extern_path`: test.lazyviews is generated with lazy views
// into crate::lazyviews, so this package's lazy views defer its types like
// local ones, while the well-known type from buffa-types stays eager.
syntax = "proto3";

package test.lazyextern;

import "google/protobuf/timestamp.proto";
import "lazy_views.proto";

message Wrapper {
test.lazyviews.Pair pair = 1;
repeated test.lazyviews.Pair pairs = 2;
google.protobuf.Timestamp at = 3;
}
7 changes: 7 additions & 0 deletions buffa-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,13 @@ pub mod lazyviews {
buffa::include_proto!("test.lazyviews");
}

/// `lazy_extern_path` — lazy views deferring [`lazyviews`] types, which they
/// reach through `extern_path`.
#[allow(clippy::derivable_impls, clippy::match_single_binding)]
pub mod lazyextern {
buffa::include_proto!("test.lazyextern");
}

/// `lazy_views(true)` + `preserve_unknown_fields(false)` — the lazy decode
/// loop without unknown-field capture, and an all-scalar lazy struct whose
/// lifetime is anchored by `PhantomData`.
Expand Down
29 changes: 29 additions & 0 deletions buffa-test/src/tests/lazy_views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,35 @@ fn extern_wkt_field_stays_eager() {
assert_eq!(view.to_owned_message().unwrap(), owned);
}

#[test]
fn lazy_extern_path_defers_extern_fields() {
// `test.lazyviews` ships the lazy family and is declared with
// `lazy_extern_path`, so its types decode on access through its own
// `PairLazyView`; the buffa-types Timestamp stays eager.
use crate::lazyextern::{Wrapper, WrapperLazyView};
use crate::lazyviews::PairLazyView;

let owned = Wrapper {
pair: pair("a", "1").into(),
pairs: vec![pair("b", "2"), pair("c", "3")],
at: buffa_types::google::protobuf::Timestamp {
seconds: 7,
..Default::default()
}
.into(),
..Default::default()
};
let bytes = owned.encode_to_vec();
let view = WrapperLazyView::decode_lazy(&bytes).unwrap();

let one: PairLazyView<'_> = view.pair.get().unwrap().expect("set");
assert_eq!((one.k, one.v), ("a", "1"));
let many: Vec<PairLazyView<'_>> = view.pairs.iter().map(Result::unwrap).collect();
assert_eq!(many.iter().map(|p| p.k).collect::<Vec<_>>(), ["b", "c"]);
assert_eq!(view.at.as_option().expect("set").seconds, 7);
assert_eq!(view.to_owned_message().unwrap(), owned);
}

#[test]
fn unknown_field_allowance_flows_through_lazy_boundary() {
// The allowance remaining at the deferred field's record site is captured
Expand Down
22 changes: 21 additions & 1 deletion docs/guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,7 @@ Passed via `opt:` (works for `remote:` and `local:`):
| `with_setters=false` | Disable `with_<name>()` builder-style setters for explicit-presence fields (default: emitted) |
| `map_entries_omit_defaults=true` | Encode map entries as prost does: an entry's key or value at its default is left out, the entry itself is kept, in the messages generated with it (default: both written). Maps with several entries keep `HashMap` order, so they match prost's `btree_map` bytes only through `buffa-build`'s `map_type` — see [Map entries](migration-from-prost.md#map-entries) |
| `lazy_views=true` | Generate the lazy view family alongside the strict views (default: false) — see [Lazy views](#lazy-views--lazy_viewstrue) |
| `lazy_extern_path=<proto>` | Declare that the `extern_path` crate for a package or type ships the lazy view family, so lazy views defer fields of its types instead of decoding them eagerly; repeatable, inert without `lazy_views=true` — see [Lazy views](#lazy-views--lazy_viewstrue) |
| `register_types=false` | Disable the per-package `register_types()` helper that populates a `MessageRegistry` (default: emitted) |
| `allow_message_set=true` | Permit `option message_set_wire_format = true;` instead of rejecting it (default: false) |
| `strict_utf8=true` | Map `string` fields to `Vec<u8>`/`&[u8]` (no UTF-8 validation) instead of `String`/`&str`. Alias: `strict_utf8_mapping`. |
Expand Down Expand Up @@ -1455,7 +1456,8 @@ impl reports deferred errors as serde errors); repeated access re-decodes (no
caching — bind the result when reading several fields); lazy repeated fields
are not slice-backed (`.get(i)`/`.iter()`/`.len()` instead of indexing);
groups, oneof message variants, map message values, and extern-typed fields
(WKTs, `extern_path`) stay eagerly decoded inside the lazy view; re-encoding
(WKTs, `extern_path`, unless declared with `lazy_extern_path` below) stay
eagerly decoded inside the lazy view; re-encoding
replays the recorded bytes verbatim without validating them; and the lazy
family has no reflection, `OwnedView`, or text-format surface — use the
eager `PersonView` for those. The recursion and unknown-field budgets
Expand All @@ -1474,6 +1476,24 @@ a deferred subtree is accessed and its own elements are recorded. The budget
remaining at the record site is what an access replays, so a subtree cannot
spend more than was left when its bytes were set aside.

An extern crate generated with `lazy_views(true)` ships the lazy family too,
but codegen can't tell, so its types stay eager inside your lazy views until
you declare it with `lazy_extern_path`, in the form `extern_path` takes:

```rust,ignore
buffa_build::Config::new()
.files(&["protos/blocks.proto"])
.lazy_views(true)
.extern_path(".sf.ethereum.type.v2", "::substreams_ethereum::pb::eth::v2")
.lazy_extern_path(".sf.ethereum.type.v2")
.compile()?;
```

Fields of those types then become `LazyMessageFieldView` and
`LazyRepeatedView` of the extern crate's `LogLazyView`, decoded on access
like local ones. Well-known types mapped to `buffa-types` stay eager, as
`buffa-types` ships no lazy views.

### `OwnedView<V>` — views with `'static` lifetime

The `'a` lifetime on `PersonView<'a>` ties the view to the input buffer, preventing it from being used across async boundaries, in tower services, or anywhere a `'static` bound is required. `OwnedView<V>` solves this by storing the `bytes::Bytes` buffer alongside the decoded view, producing a `'static + Send + Sync` type:
Expand Down
Loading