diff --git a/.changes/unreleased/added-20261127-195205-lazy-extern-path.yaml b/.changes/unreleased/added-20261127-195205-lazy-extern-path.yaml new file mode 100644 index 000000000..1eac6e43d --- /dev/null +++ b/.changes/unreleased/added-20261127-195205-lazy-extern-path.yaml @@ -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=`) 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 diff --git a/buffa-build/src/lib.rs b/buffa-build/src/lib.rs index 3eb7c6bae..ffdea742a 100644 --- a/buffa-build/src/lib.rs +++ b/buffa-build/src/lib.rs @@ -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) -> 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"`, @@ -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 diff --git a/buffa-codegen/src/lazy_view.rs b/buffa-codegen/src/lazy_view.rs index 472a42316..606bdfd14 100644 --- a/buffa-codegen/src/lazy_view.rs +++ b/buffa-codegen/src/lazy_view.rs @@ -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 { @@ -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`. diff --git a/buffa-codegen/src/lib.rs b/buffa-codegen/src/lib.rs index a235b4960..1bbc7124b 100644 --- a/buffa-codegen/src/lib.rs +++ b/buffa-codegen/src/lib.rs @@ -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, /// 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 @@ -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(), @@ -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). diff --git a/buffa-codegen/src/tests/view_codegen.rs b/buffa-codegen/src/tests/view_codegen.rs index 7a92b7968..ed854830f 100644 --- a/buffa-codegen/src/tests/view_codegen.rs +++ b/buffa-codegen/src/tests/view_codegen.rs @@ -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| 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::(); + 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}"); +} diff --git a/buffa-test/build.rs b/buffa-test/build.rs index 5f78c50bc..d4cdff164 100644 --- a/buffa-test/build.rs +++ b/buffa-test/build.rs @@ -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. diff --git a/buffa-test/protos/lazy_extern.proto b/buffa-test/protos/lazy_extern.proto new file mode 100644 index 000000000..fb0d34572 --- /dev/null +++ b/buffa-test/protos/lazy_extern.proto @@ -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; +} diff --git a/buffa-test/src/lib.rs b/buffa-test/src/lib.rs index 258fb83e9..0da570c9f 100644 --- a/buffa-test/src/lib.rs +++ b/buffa-test/src/lib.rs @@ -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`. diff --git a/buffa-test/src/tests/lazy_views.rs b/buffa-test/src/tests/lazy_views.rs index a4252f4d0..c26a7a954 100644 --- a/buffa-test/src/tests/lazy_views.rs +++ b/buffa-test/src/tests/lazy_views.rs @@ -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> = view.pairs.iter().map(Result::unwrap).collect(); + assert_eq!(many.iter().map(|p| p.k).collect::>(), ["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 diff --git a/docs/guide.md b/docs/guide.md index 10c100a51..f61b4b8bf 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -650,6 +650,7 @@ Passed via `opt:` (works for `remote:` and `local:`): | `with_setters=false` | Disable `with_()` 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=` | 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]` (no UTF-8 validation) instead of `String`/`&str`. Alias: `strict_utf8_mapping`. | @@ -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 @@ -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` — 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` solves this by storing the `bytes::Bytes` buffer alongside the decoded view, producing a `'static + Send + Sync` type: diff --git a/protoc-gen-buffa/src/main.rs b/protoc-gen-buffa/src/main.rs index f8668a4b3..5294aa234 100644 --- a/protoc-gen-buffa/src/main.rs +++ b/protoc-gen-buffa/src/main.rs @@ -50,6 +50,11 @@ The proto side of extern_path is a dotted protobuf package or type name (leading dot optional); a name with an empty or non-identifier segment is an error. +With lazy_views=true, a field of an extern type stays eager unless its +crate also ships the lazy view family; name those packages or types with +lazy_extern_path, in the same form: + --buffa_opt=lazy_views=true,extern_path=.my.pkg=::my_crate,lazy_extern_path=.my.pkg + To skip a package pulled in by include_imports (e.g. an option-only import that is never referenced as a field), use exclude_package: --buffa_opt=exclude_package=.buf.validate,exclude_package=.gnostic @@ -185,6 +190,11 @@ struct PluginConfig { /// every type: /// --buffa_opt=extern_path=.my.common=::common_protos /// --buffa_opt=extern_path=.my.common.Shared=::shared_types::Shared +/// +/// `lazy_extern_path=`, in the same form, declares that the extern +/// crate for `` ships the lazy view family, so lazy views defer fields +/// of its types: +/// --buffa_opt=lazy_extern_path=.my.common fn parse_config(params: &str) -> Result { let mut codegen = CodeGenConfig::default(); let mut unbox_oneof = false; @@ -440,6 +450,10 @@ fn parse_config(params: &str) -> Result { )); } } + "lazy_extern_path" => { + let proto = buffa_codegen::normalize_extern_path_proto_name(value)?; + codegen.lazy_extern_paths.push(proto); + } "mod_file" => { return Err("the mod_file option was removed in 0.2; use \ protoc-gen-buffa-packaging instead. See CHANGELOG \ @@ -901,6 +915,31 @@ mod tests { assert_eq!(config.codegen.extern_paths[0].1, "::common_protos"); } + #[test] + fn lazy_extern_path_is_normalized_and_repeatable() { + let config = + parse_config("lazy_extern_path=my.common,lazy_extern_path=.other.Shared").unwrap(); + assert_eq!( + config.codegen.lazy_extern_paths, + [".my.common", ".other.Shared"] + ); + assert!(parse_config("") + .unwrap() + .codegen + .lazy_extern_paths + .is_empty()); + } + + #[test] + fn lazy_extern_path_rejects_invalid_names() { + for proto in ["", "..my", ".my..common", ".my.1common"] { + assert!( + parse_config(&format!("lazy_extern_path={proto}")).is_err(), + "{proto}" + ); + } + } + #[test] fn extern_path_without_leading_dot_is_normalized() { let config = parse_config("extern_path=my.common=::common_protos").unwrap();