Skip to main content

tonneau_build/codegen/service/
openapi.rs

1use std::collections::BTreeMap;
2
3use anyhow::Context;
4use base64::Engine;
5use indexmap::IndexMap;
6use oas31::{Object, Ref, Schema, Type};
7use proc_macro2::TokenStream;
8use quote::quote;
9use tonneau_cel::{CelValue, NumberTy};
10
11use crate::codegen::cel::compiler::{CompiledExpr, Compiler, CompilerTarget, ConstantCompiledExpr};
12use crate::codegen::cel::{CelExpression, CelExpressions, functions};
13use crate::codegen::utils::field_ident_from_str;
14use crate::types::{
15    ProtoModifiedValueType, ProtoPath, ProtoType, ProtoTypeRegistry, ProtoValueType,
16    ProtoWellKnownType,
17};
18
19fn cel_to_json(
20    cel: &CelValue<'static>,
21    type_registry: &ProtoTypeRegistry,
22) -> anyhow::Result<serde_json::Value> {
23    match cel {
24        CelValue::Null => Ok(serde_json::Value::Null),
25        CelValue::Bool(b) => Ok(serde_json::Value::Bool(*b)),
26        CelValue::Map(map) => Ok(serde_json::Value::Object(
27            map.iter()
28                .map(|(key, value)| {
29                    if let CelValue::String(key) = key {
30                        Ok((key.to_string(), cel_to_json(value, type_registry)?))
31                    } else {
32                        anyhow::bail!("map keys must be a string")
33                    }
34                })
35                .collect::<anyhow::Result<_>>()?,
36        )),
37        CelValue::List(list) => Ok(serde_json::Value::Array(
38            list.iter()
39                .map(|i| cel_to_json(i, type_registry))
40                .collect::<anyhow::Result<_>>()?,
41        )),
42        CelValue::String(s) => Ok(serde_json::Value::String(s.to_string())),
43        CelValue::Number(NumberTy::F64(f)) => Ok(serde_json::Value::Number(
44            serde_json::Number::from_f64(*f).context("f64 is not a valid float")?,
45        )),
46        CelValue::Number(NumberTy::I64(i)) => Ok(serde_json::Value::Number(
47            serde_json::Number::from_i128(*i as i128).context("i64 is not a valid int")?,
48        )),
49        CelValue::Number(NumberTy::U64(u)) => Ok(serde_json::Value::Number(
50            serde_json::Number::from_u128(*u as u128).context("u64 is not a valid uint")?,
51        )),
52        CelValue::Duration(duration) => Ok(serde_json::Value::String(duration.to_string())),
53        CelValue::Timestamp(timestamp) => Ok(serde_json::Value::String(timestamp.to_rfc3339())),
54        CelValue::Bytes(bytes) => Ok(serde_json::Value::String(
55            base64::engine::general_purpose::STANDARD.encode(bytes),
56        )),
57        CelValue::Enum(cel_enum) => {
58            let enum_ty = type_registry
59                .get_enum(&cel_enum.tag)
60                .with_context(|| format!("couldnt find enum {}", cel_enum.tag.as_ref()))?;
61            if enum_ty.options.repr_enum {
62                Ok(serde_json::Value::from(cel_enum.value))
63            } else {
64                let variant = enum_ty
65                    .variants
66                    .values()
67                    .find(|v| v.value == cel_enum.value)
68                    .with_context(|| {
69                        format!(
70                            "{} has no value for {}",
71                            cel_enum.tag.as_ref(),
72                            cel_enum.value
73                        )
74                    })?;
75                Ok(serde_json::Value::from(variant.options.serde_name.clone()))
76            }
77        }
78    }
79}
80
81fn parse_resolve(compiler: &Compiler, expr: &str) -> anyhow::Result<CelValue<'static>> {
82    let expr = cel_parser::parse(expr).context("parse")?;
83    let resolved = compiler.resolve(&expr).context("resolve")?;
84    match resolved {
85        CompiledExpr::Constant(ConstantCompiledExpr { value }) => Ok(value),
86        CompiledExpr::Runtime(_) => anyhow::bail!("expression needs runtime evaluation"),
87    }
88}
89
90fn handle_expr(
91    mut ctx: Compiler,
92    ty: &ProtoType,
93    expr: &CelExpression,
94) -> anyhow::Result<Vec<Schema>> {
95    ctx.set_target(CompilerTarget::Serde);
96
97    if let Some(this) = expr.this.clone() {
98        ctx.add_variable("this", CompiledExpr::constant(this));
99    }
100
101    if let Some(ProtoValueType::Enum(path)) = ty.value_type() {
102        ctx.register_function(functions::Enum(Some(path.clone())));
103    }
104
105    let mut schemas = Vec::new();
106    for schema in &expr.jsonschemas {
107        let value = parse_resolve(&ctx, schema)?;
108        let value = cel_to_json(&value, ctx.registry())?;
109        if !value.is_null() {
110            schemas.push(serde_json::from_value(value).context("bad openapi schema")?);
111        }
112    }
113
114    Ok(schemas)
115}
116
117#[derive(Debug)]
118enum ExcludePaths {
119    True,
120    Child(BTreeMap<String, ExcludePaths>),
121}
122
123#[derive(Debug, Clone, Copy)]
124enum BytesEncoding {
125    Base64,
126    Binary,
127}
128
129#[derive(Debug, Clone, Copy)]
130pub(super) enum BodyMethod<'a> {
131    Text,
132    Json,
133    Binary(Option<&'a str>),
134}
135
136impl BodyMethod<'_> {
137    fn bytes_encoding(&self) -> BytesEncoding {
138        match self {
139            BodyMethod::Binary(_) => BytesEncoding::Binary,
140            _ => BytesEncoding::Base64,
141        }
142    }
143
144    fn deserialize_method(&self) -> syn::Ident {
145        match self {
146            BodyMethod::Text => syn::parse_quote!(deserialize_body_text),
147            BodyMethod::Binary(_) => syn::parse_quote!(deserialize_body_bytes),
148            BodyMethod::Json => syn::parse_quote!(deserialize_body_json),
149        }
150    }
151
152    fn content_type(&self) -> &str {
153        match self {
154            BodyMethod::Binary(ct) => ct.unwrap_or(self.default_content_type()),
155            _ => self.default_content_type(),
156        }
157    }
158
159    fn default_content_type(&self) -> &'static str {
160        match self {
161            BodyMethod::Binary(_) => "application/octet-stream",
162            BodyMethod::Json => "application/json",
163            BodyMethod::Text => "text/plain",
164        }
165    }
166}
167
168#[derive(Debug, Clone, Copy, PartialEq)]
169enum GenerateDirection {
170    Input,
171    Output,
172}
173
174struct FieldExtract {
175    full_name: ProtoPath,
176    tokens: proc_macro2::TokenStream,
177    ty: ProtoType,
178    cel: CelExpressions,
179    is_optional: bool,
180}
181
182fn input_field_getter_gen(
183    registry: &ProtoTypeRegistry,
184    ty: &ProtoValueType,
185    mut mapping: TokenStream,
186    field_str: &str,
187) -> anyhow::Result<FieldExtract> {
188    let ProtoValueType::Message(path) = ty else {
189        anyhow::bail!("cannot extract field on non-message type: {field_str}");
190    };
191
192    let mut next_message = Some(registry.get_message(path).unwrap());
193    let mut is_optional = false;
194    let mut kind = None;
195    let mut cel = None;
196    let mut full_name = None;
197    for part in field_str.split('.') {
198        let Some(field) = next_message.and_then(|message| message.fields.get(part)) else {
199            anyhow::bail!("message does not have field: {field_str}");
200        };
201
202        let field_ident = field_ident_from_str(part);
203
204        let optional_unwrap = is_optional.then(|| {
205            quote! {
206                let mut tracker = tracker.get_or_insert_default();
207                let mut target = target.get_or_insert_default();
208            }
209        });
210
211        full_name = Some(&field.full_name);
212        kind = Some(&field.ty);
213        cel = Some(&field.options.cel_exprs);
214        mapping = quote! {{
215            let (tracker, target) = #mapping;
216            #optional_unwrap
217            let tracker = tracker.#field_ident.get_or_insert_default();
218            let target = &mut target.#field_ident;
219            (tracker, target)
220        }};
221
222        is_optional = matches!(
223            field.ty,
224            ProtoType::Modified(
225                ProtoModifiedValueType::Optional(_) | ProtoModifiedValueType::OneOf(_)
226            )
227        );
228        next_message = match &field.ty {
229            ProtoType::Value(ProtoValueType::Message(path))
230            | ProtoType::Modified(ProtoModifiedValueType::Optional(ProtoValueType::Message(
231                path,
232            ))) => Some(registry.get_message(path).unwrap()),
233            _ => None,
234        }
235    }
236
237    Ok(FieldExtract {
238        full_name: full_name.unwrap().clone(),
239        tokens: mapping,
240        ty: kind.unwrap().clone(),
241        cel: cel.unwrap().clone(),
242        is_optional,
243    })
244}
245
246fn output_field_getter_gen(
247    registry: &ProtoTypeRegistry,
248    ty: &ProtoValueType,
249    mut mapping: TokenStream,
250    field_str: &str,
251) -> anyhow::Result<FieldExtract> {
252    let ProtoValueType::Message(path) = ty else {
253        anyhow::bail!("cannot extract field on non-message type: {field_str}");
254    };
255
256    let mut next_message = Some(registry.get_message(path).unwrap());
257    let mut was_optional = false;
258    let mut kind = None;
259    let mut cel = None;
260    let mut full_name = None;
261    for part in field_str.split('.') {
262        let Some(field) = next_message.and_then(|message| message.fields.get(part)) else {
263            anyhow::bail!("message does not have field: {field_str}");
264        };
265
266        let field_ident = field_ident_from_str(part);
267
268        full_name = Some(&field.full_name);
269        kind = Some(&field.ty);
270        cel = Some(&field.options.cel_exprs);
271        let is_optional = matches!(
272            field.ty,
273            ProtoType::Modified(
274                ProtoModifiedValueType::Optional(_) | ProtoModifiedValueType::OneOf(_)
275            )
276        );
277
278        mapping = match (is_optional, was_optional) {
279            (true, true) => quote!(#mapping.and_then(|m| m.#field_ident.as_ref())),
280            (false, true) => quote!(#mapping.map(|m| &m.#field_ident)),
281            (true, false) => quote!(#mapping.#field_ident.as_ref()),
282            (false, false) => quote!(&#mapping.#field_ident),
283        };
284
285        was_optional = was_optional || is_optional;
286
287        next_message = match &field.ty {
288            ProtoType::Value(ProtoValueType::Message(path))
289            | ProtoType::Modified(ProtoModifiedValueType::Optional(ProtoValueType::Message(
290                path,
291            ))) => Some(registry.get_message(path).unwrap()),
292            _ => None,
293        }
294    }
295
296    Ok(FieldExtract {
297        full_name: full_name.unwrap().clone(),
298        cel: cel.unwrap().clone(),
299        ty: kind.unwrap().clone(),
300        is_optional: was_optional,
301        tokens: mapping,
302    })
303}
304
305fn parse_route(route: &str) -> Vec<String> {
306    let mut params = Vec::new();
307    let mut chars = route.chars().peekable();
308
309    while let Some(ch) = chars.next() {
310        if ch != '{' {
311            continue;
312        }
313
314        // Skip escaped '{{'
315        if let Some(&'{') = chars.peek() {
316            chars.next();
317            continue;
318        }
319
320        let mut param = String::new();
321        for c in &mut chars {
322            if c == '}' {
323                params.push(param);
324                break;
325            }
326
327            param.push(c);
328        }
329    }
330
331    params
332}
333
334struct PathFields {
335    defs: Vec<proc_macro2::TokenStream>,
336    mappings: Vec<proc_macro2::TokenStream>,
337    param_schemas: IndexMap<String, (ProtoValueType, CelExpressions)>,
338}
339
340fn path_struct(
341    registry: &ProtoTypeRegistry,
342    ty: &ProtoValueType,
343    package: &str,
344    fields: &[String],
345    mapping: TokenStream,
346) -> anyhow::Result<PathFields> {
347    let mut defs = Vec::new();
348    let mut mappings = Vec::new();
349    let mut param_schemas = IndexMap::new();
350
351    let match_single_ty = |ty: &ProtoValueType| {
352        Some(match &ty {
353            ProtoValueType::Enum(path) => {
354                let path = registry
355                    .resolve_rust_path(package, path)
356                    .expect("enum not found");
357                quote! {
358                    #path
359                }
360            }
361            ProtoValueType::Bool => quote! {
362                ::core::primitive::bool
363            },
364            ProtoValueType::Float => quote! {
365                ::core::primitive::f32
366            },
367            ProtoValueType::Double => quote! {
368                ::core::primitive::f64
369            },
370            ProtoValueType::Int32 => quote! {
371                ::core::primitive::i32
372            },
373            ProtoValueType::Int64 => quote! {
374                ::core::primitive::i64
375            },
376            ProtoValueType::UInt32 => quote! {
377                ::core::primitive::u32
378            },
379            ProtoValueType::UInt64 => quote! {
380                ::core::primitive::u64
381            },
382            ProtoValueType::String => quote! {
383                ::std::string::String
384            },
385            ProtoValueType::WellKnown(ProtoWellKnownType::Duration) => quote! {
386                ::tonneau::__private::well_known::Duration
387            },
388            ProtoValueType::WellKnown(ProtoWellKnownType::Timestamp) => quote! {
389                ::tonneau::__private::well_known::Timestamp
390            },
391            ProtoValueType::WellKnown(ProtoWellKnownType::Value) => quote! {
392                ::tonneau::__private::well_known::Value
393            },
394            _ => return None,
395        })
396    };
397
398    match &ty {
399        ProtoValueType::Message(_) => {
400            for (idx, field) in fields.iter().enumerate() {
401                let field_str = field.as_ref();
402                let path_field_ident = quote::format_ident!("field_{idx}");
403                let FieldExtract {
404                    full_name: _full_name,
405                    cel,
406                    tokens,
407                    ty,
408                    is_optional,
409                } = input_field_getter_gen(registry, ty, mapping.clone(), field_str)?;
410
411                let setter = if is_optional {
412                    quote! {
413                        tracker.get_or_insert_default();
414                        target.insert(path.#path_field_ident.into());
415                    }
416                } else {
417                    quote! {
418                        *target = path.#path_field_ident.into();
419                    }
420                };
421
422                mappings.push(quote! {{
423                    let (tracker, target) = #tokens;
424                    #setter;
425                }});
426
427                let ty = match ty {
428                    ProtoType::Modified(ProtoModifiedValueType::Optional(value))
429                    | ProtoType::Value(value) => Some(value),
430                    _ => None,
431                };
432
433                let Some(tokens) = ty.as_ref().and_then(match_single_ty) else {
434                    anyhow::bail!("type cannot be mapped: {ty:?}");
435                };
436
437                let ty = ty.unwrap();
438
439                param_schemas.insert(field.clone(), (ty, cel));
440
441                defs.push(quote! {
442                    #[serde(rename = #field_str)]
443                    #path_field_ident: #tokens
444                });
445            }
446        }
447        ty => {
448            let Some(ty) = match_single_ty(ty) else {
449                anyhow::bail!("type cannot be mapped: {ty:?}");
450            };
451
452            if fields.len() != 1 {
453                anyhow::bail!("well-known type can only have one field");
454            }
455
456            if fields[0] != "value" {
457                anyhow::bail!("well-known type can only have field 'value'");
458            }
459
460            mappings.push(quote! {{
461                let (_, target) = #mapping;
462                *target = path.value.into();
463            }});
464
465            defs.push(quote! {
466                #[serde(rename = "value")]
467                value: #ty
468            });
469        }
470    }
471
472    Ok(PathFields {
473        defs,
474        mappings,
475        param_schemas,
476    })
477}
478
479pub(super) struct InputGenerator<'a> {
480    used_paths: BTreeMap<String, ExcludePaths>,
481    types: &'a ProtoTypeRegistry,
482    components: &'a mut oas31::Components,
483    package: &'a str,
484    root_ty: ProtoValueType,
485    tracker_ident: syn::Ident,
486    target_ident: syn::Ident,
487    state_ident: syn::Ident,
488}
489
490#[derive(Default)]
491pub(super) struct GeneratedParams {
492    pub tokens: TokenStream,
493    pub params: Vec<oas31::path::Parameter>,
494}
495
496pub(super) struct GeneratedBody<B> {
497    pub tokens: TokenStream,
498    pub body: B,
499}
500
501impl<'a> InputGenerator<'a> {
502    pub(super) fn new(
503        types: &'a ProtoTypeRegistry,
504        components: &'a mut oas31::Components,
505        package: &'a str,
506        ty: ProtoValueType,
507        tracker_ident: syn::Ident,
508        target_ident: syn::Ident,
509        state_ident: syn::Ident,
510    ) -> Self {
511        Self {
512            components,
513            types,
514            used_paths: BTreeMap::new(),
515            package,
516            root_ty: ty,
517            target_ident,
518            tracker_ident,
519            state_ident,
520        }
521    }
522}
523
524pub(super) struct OutputGenerator<'a> {
525    types: &'a ProtoTypeRegistry,
526    components: &'a mut oas31::Components,
527    root_ty: ProtoValueType,
528    response_ident: syn::Ident,
529    builder_ident: syn::Ident,
530}
531
532impl<'a> OutputGenerator<'a> {
533    pub(super) fn new(
534        types: &'a ProtoTypeRegistry,
535        components: &'a mut oas31::Components,
536        ty: ProtoValueType,
537        response_ident: syn::Ident,
538        builder_ident: syn::Ident,
539    ) -> Self {
540        Self {
541            components,
542            types,
543            root_ty: ty,
544            response_ident,
545            builder_ident,
546        }
547    }
548}
549
550impl InputGenerator<'_> {
551    fn consume_field(&mut self, field: &str) -> anyhow::Result<()> {
552        let mut parts = field.split('.').peekable();
553        let first_part = parts.next().expect("parts empty").to_owned();
554
555        // Start with the first part of the path
556        let mut current_map =
557            self.used_paths
558                .entry(first_part)
559                .or_insert(if parts.peek().is_none() {
560                    ExcludePaths::True
561                } else {
562                    ExcludePaths::Child(BTreeMap::new())
563                });
564
565        // Iterate over the remaining parts of the path
566        while let Some(part) = parts.next() {
567            match current_map {
568                ExcludePaths::True => anyhow::bail!("duplicate path: {field}"),
569                ExcludePaths::Child(map) => {
570                    current_map = map
571                        .entry(part.to_owned())
572                        .or_insert(if parts.peek().is_none() {
573                            ExcludePaths::True
574                        } else {
575                            ExcludePaths::Child(BTreeMap::new())
576                        });
577                }
578            }
579        }
580
581        anyhow::ensure!(
582            matches!(current_map, ExcludePaths::True),
583            "duplicate path: {field}"
584        );
585
586        Ok(())
587    }
588
589    fn base_extract(&self) -> TokenStream {
590        let tracker = &self.tracker_ident;
591        let target = &self.target_ident;
592        quote!((&mut #tracker, &mut #target))
593    }
594
595    pub(super) fn generate_query_parameter(
596        &mut self,
597        field: Option<&str>,
598    ) -> anyhow::Result<GeneratedParams> {
599        let mut params = Vec::new();
600
601        let extract = if let Some(field) = field {
602            input_field_getter_gen(self.types, &self.root_ty, self.base_extract(), field)?
603        } else {
604            FieldExtract {
605                // openapi cannot have cross-field expressions on parameters. so it doesnt matter
606                // if we keep the cel exprs.
607                full_name: ProtoPath::new(self.root_ty.proto_path()),
608                cel: CelExpressions::default(),
609                tokens: self.base_extract(),
610                is_optional: false,
611                ty: ProtoType::Value(self.root_ty.clone()),
612            }
613        };
614
615        let exclude_paths = if let Some(field) = field {
616            match self.used_paths.get(field) {
617                Some(ExcludePaths::Child(c)) => Some(c),
618                Some(ExcludePaths::True) => {
619                    anyhow::bail!("{field} is already used by another operation")
620                }
621                None => None,
622            }
623        } else {
624            Some(&self.used_paths)
625        };
626
627        if extract.ty.nested() {
628            anyhow::bail!("query string cannot be used on nested types.")
629        }
630
631        let message_ty = match extract.ty.value_type() {
632            Some(ProtoValueType::Message(path)) => self.types.get_message(path).unwrap(),
633            Some(ProtoValueType::WellKnown(ProtoWellKnownType::Empty)) => {
634                return Ok(GeneratedParams::default());
635            }
636            _ => anyhow::bail!("query string can only be used on message types."),
637        };
638
639        for (name, field) in &message_ty.fields {
640            let exclude_paths =
641                match exclude_paths.and_then(|exclude_paths| exclude_paths.get(name)) {
642                    Some(ExcludePaths::True) => continue,
643                    Some(ExcludePaths::Child(child)) => Some(child),
644                    None => None,
645                };
646            params.push(
647                oas31::path::Parameter::builder()
648                    .name(field.options.serde_name.clone())
649                    .required(!field.options.serde_omittable.is_true())
650                    .explode(true)
651                    .style(oas31::path::ParameterStyle::DeepObject)
652                    .schema(generate(
653                        &FieldInfo {
654                            full_name: &field.full_name,
655                            ty: &field.ty,
656                            cel: &field.options.cel_exprs,
657                        },
658                        self.components,
659                        self.types,
660                        exclude_paths.unwrap_or(&BTreeMap::new()),
661                        GenerateDirection::Input,
662                        BytesEncoding::Base64,
663                    )?)
664                    .parameter_in(oas31::path::ParameterIn::Query)
665                    .build(),
666            )
667        }
668
669        let extract = &extract.tokens;
670        let state_ident = &self.state_ident;
671
672        Ok(GeneratedParams {
673            params,
674            tokens: quote!({
675                let (mut tracker, mut target) = #extract;
676                if let Err(err) = ::tonneau::__private::deserialize_query_string(
677                    &parts,
678                    tracker,
679                    target,
680                    &mut #state_ident,
681                ) {
682                    return err;
683                }
684            }),
685        })
686    }
687
688    pub(super) fn generate_path_parameter(
689        &mut self,
690        path: &str,
691    ) -> anyhow::Result<GeneratedParams> {
692        let params = parse_route(path);
693        if params.is_empty() {
694            return Ok(GeneratedParams::default());
695        }
696
697        let PathFields {
698            defs,
699            mappings,
700            param_schemas,
701        } = path_struct(
702            self.types,
703            &self.root_ty,
704            self.package,
705            &params,
706            self.base_extract(),
707        )?;
708        let mut params = Vec::new();
709
710        for (path, (ty, cel)) in param_schemas {
711            self.consume_field(&path)?;
712            let full_field_path = ProtoPath::new(format!("{}.{}", self.root_ty.proto_path(), path));
713
714            params.push(
715                oas31::path::Parameter::builder()
716                    .name(path)
717                    .required(true)
718                    .schema(generate(
719                        &FieldInfo {
720                            full_name: &full_field_path,
721                            ty: &ProtoType::Value(ty.clone()),
722                            cel: &cel,
723                        },
724                        self.components,
725                        self.types,
726                        &BTreeMap::new(),
727                        GenerateDirection::Input,
728                        BytesEncoding::Base64,
729                    )?)
730                    .parameter_in(oas31::path::ParameterIn::Path)
731                    .build(),
732            )
733        }
734
735        Ok(GeneratedParams {
736            params,
737            tokens: quote!({
738                #[derive(::tonneau::reexports::serde::Deserialize)]
739                #[allow(non_snake_case, dead_code)]
740                struct ____PathContent {
741                    #(#defs),*
742                }
743
744                let path = match ::tonneau::__private::deserialize_path::<____PathContent>(&mut parts).await {
745                    Ok(path) => path,
746                    Err(err) => return err,
747                };
748
749                #(#mappings)*
750            }),
751        })
752    }
753
754    pub(super) fn generate_body(
755        &mut self,
756        cel: &[CelExpression],
757        body_method: BodyMethod,
758        field: Option<&str>,
759        content_type_field: Option<&str>,
760    ) -> anyhow::Result<GeneratedBody<oas31::request_body::RequestBody>> {
761        let content_type = if let Some(content_type_field) = content_type_field {
762            self.consume_field(content_type_field)?;
763            let extract = input_field_getter_gen(
764                self.types,
765                &self.root_ty,
766                self.base_extract(),
767                content_type_field,
768            )?;
769
770            anyhow::ensure!(
771                matches!(extract.ty.value_type(), Some(ProtoValueType::String)),
772                "content-type must be a string type"
773            );
774
775            anyhow::ensure!(!extract.ty.nested(), "content-type cannot be nested");
776
777            let modifier = if extract.is_optional {
778                quote! {
779                    tracker.get_or_insert_default();
780                    target.insert(ct.into());
781                }
782            } else {
783                quote! {
784                    let _ = tracker;
785                    *target = ct.into();
786                }
787            };
788
789            let extract = extract.tokens;
790
791            quote! {
792                if let Some(ct) = parts.headers.get(::tonneau::reexports::http::header::CONTENT_TYPE).and_then(|h| h.to_str().ok()) {
793                    let (mut tracker, mut target) = #extract;
794                    #modifier
795                }
796            }
797        } else {
798            TokenStream::new()
799        };
800
801        let exclude_paths = if let Some(field) = field {
802            match self.used_paths.get(field) {
803                Some(ExcludePaths::Child(c)) => Some(c),
804                Some(ExcludePaths::True) => {
805                    anyhow::bail!("{field} is already used by another operation")
806                }
807                None => None,
808            }
809        } else {
810            Some(&self.used_paths)
811        };
812
813        let extract = if let Some(field) = field {
814            input_field_getter_gen(self.types, &self.root_ty, self.base_extract(), field)?
815        } else {
816            FieldExtract {
817                full_name: ProtoPath::new(self.root_ty.proto_path()),
818                cel: CelExpressions {
819                    field: cel.to_vec(),
820                    ..Default::default()
821                },
822                is_optional: false,
823                tokens: self.base_extract(),
824                ty: ProtoType::Value(self.root_ty.clone()),
825            }
826        };
827
828        match body_method {
829            BodyMethod::Json => {}
830            BodyMethod::Binary(_) => {
831                anyhow::ensure!(
832                    matches!(extract.ty.value_type(), Some(ProtoValueType::Bytes)),
833                    "binary bodies must be on bytes fields."
834                );
835
836                anyhow::ensure!(!extract.ty.nested(), "binary bodies cannot be nested");
837            }
838            BodyMethod::Text => {
839                anyhow::ensure!(
840                    matches!(extract.ty.value_type(), Some(ProtoValueType::String)),
841                    "text bodies must be on string fields."
842                );
843
844                anyhow::ensure!(!extract.ty.nested(), "text bodies cannot be nested");
845            }
846        }
847
848        let func = body_method.deserialize_method();
849        let tokens = &extract.tokens;
850        let state_ident = &self.state_ident;
851
852        Ok(GeneratedBody {
853            tokens: quote! {{
854                #content_type
855                let (tracker, target) = #tokens;
856                if let Err(err) = ::tonneau::__private::#func(&parts, body, tracker, target, &mut #state_ident).await {
857                    return err;
858                }
859            }},
860            body: oas31::request_body::RequestBody::builder()
861                .content(
862                    body_method.content_type(),
863                    oas31::content::Content::new(Some(generate(
864                        &FieldInfo {
865                            full_name: &extract.full_name,
866                            ty: &extract.ty,
867                            cel: &extract.cel,
868                        },
869                        self.components,
870                        self.types,
871                        exclude_paths.unwrap_or(&BTreeMap::new()),
872                        GenerateDirection::Input,
873                        body_method.bytes_encoding(),
874                    )?)),
875                )
876                .build(),
877        })
878    }
879}
880
881impl OutputGenerator<'_> {
882    fn base_extract(&self) -> TokenStream {
883        let response_ident = &self.response_ident;
884        quote!((&#response_ident))
885    }
886
887    pub(super) fn generate_body(
888        &mut self,
889        body_method: BodyMethod,
890        field: Option<&str>,
891        content_type_field: Option<&str>,
892    ) -> anyhow::Result<GeneratedBody<oas31::response::Response>> {
893        let builder_ident = &self.builder_ident;
894
895        let content_type = if let Some(content_type_field) = content_type_field {
896            let extract = output_field_getter_gen(
897                self.types,
898                &self.root_ty,
899                self.base_extract(),
900                content_type_field,
901            )?;
902
903            anyhow::ensure!(
904                matches!(extract.ty.value_type(), Some(ProtoValueType::String)),
905                "content-type must be a string type"
906            );
907
908            anyhow::ensure!(!extract.ty.nested(), "content-type cannot be nested");
909
910            let modifier = if extract.is_optional {
911                quote!(Some(ct))
912            } else {
913                quote!(ct)
914            };
915
916            let extract = extract.tokens;
917            let default_ct = body_method.default_content_type();
918
919            quote! {
920                if let #modifier = #extract {
921                    #builder_ident.header(::tonneau::reexports::http::header::CONTENT_TYPE, ct)
922                } else {
923                    #builder_ident.header(::tonneau::reexports::http::header::CONTENT_TYPE, #default_ct)
924                }
925            }
926        } else {
927            let default_ct = body_method.default_content_type();
928            quote! {
929                #builder_ident.header(::tonneau::reexports::http::header::CONTENT_TYPE, #default_ct)
930            }
931        };
932
933        let extract = if let Some(field) = field {
934            output_field_getter_gen(self.types, &self.root_ty, self.base_extract(), field)?
935        } else {
936            FieldExtract {
937                full_name: ProtoPath::new(self.root_ty.proto_path()),
938                cel: CelExpressions::default(),
939                is_optional: false,
940                tokens: self.base_extract(),
941                ty: ProtoType::Value(self.root_ty.clone()),
942            }
943        };
944
945        let tokens = extract.tokens;
946
947        let tokens = match body_method {
948            BodyMethod::Json => quote!({
949                let mut writer = ::tonneau::reexports::bytes::BufMut::writer(
950                    ::tonneau::reexports::bytes::BytesMut::with_capacity(128)
951                );
952                match ::tonneau::reexports::serde_json::to_writer(&mut writer, #tokens) {
953                    ::core::result::Result::Ok(()) => {},
954                    ::core::result::Result::Err(err) => return ::tonneau::__private::handle_response_build_error(err),
955                }
956                (#content_type)
957                    .body(::tonneau::reexports::axum::body::Body::from(writer.into_inner().freeze()))
958            }),
959            BodyMethod::Binary(_) => {
960                anyhow::ensure!(
961                    matches!(extract.ty.value_type(), Some(ProtoValueType::Bytes)),
962                    "binary bodies must be on bytes fields."
963                );
964
965                anyhow::ensure!(!extract.ty.nested(), "binary bodies cannot be nested");
966
967                let matcher = if extract.is_optional {
968                    quote!(Some(bytes))
969                } else {
970                    quote!(bytes)
971                };
972
973                quote!({
974                    (#content_type)
975                        .body(if let #matcher = #tokens {
976                            ::tonneau::reexports::axum::body::Body::from(bytes.clone())
977                        } else {
978                            ::tonneau::reexports::axum::body::Body::empty()
979                        })
980                })
981            }
982            BodyMethod::Text => {
983                anyhow::ensure!(
984                    matches!(extract.ty.value_type(), Some(ProtoValueType::String)),
985                    "text bodies must be on string fields."
986                );
987
988                anyhow::ensure!(!extract.ty.nested(), "text bodies cannot be nested");
989
990                let matcher = if extract.is_optional {
991                    quote!(Some(text))
992                } else {
993                    quote!(text)
994                };
995
996                quote!({
997                    (#content_type)
998                        .body(if let #matcher = #tokens {
999                            ::tonneau::reexports::axum::body::Body::from(text.clone())
1000                        } else {
1001                            ::tonneau::reexports::axum::body::Body::empty()
1002                        })
1003                })
1004            }
1005        };
1006
1007        Ok(GeneratedBody {
1008            tokens,
1009            body: oas31::Response::builder()
1010                .content(
1011                    body_method.content_type(),
1012                    oas31::Content::new(Some(generate(
1013                        &FieldInfo {
1014                            full_name: &extract.full_name,
1015                            ty: &extract.ty,
1016                            cel: &extract.cel,
1017                        },
1018                        self.components,
1019                        self.types,
1020                        &BTreeMap::new(),
1021                        GenerateDirection::Output,
1022                        body_method.bytes_encoding(),
1023                    )?)),
1024                )
1025                .description("")
1026                .build(),
1027        })
1028    }
1029}
1030
1031struct FieldInfo<'a> {
1032    full_name: &'a ProtoPath,
1033    ty: &'a ProtoType,
1034    cel: &'a CelExpressions,
1035}
1036
1037fn generate(
1038    field_info: &FieldInfo,
1039    components: &mut oas31::Components,
1040    types: &ProtoTypeRegistry,
1041    used_paths: &BTreeMap<String, ExcludePaths>,
1042    direction: GenerateDirection,
1043    bytes: BytesEncoding,
1044) -> anyhow::Result<Schema> {
1045    fn internal_generate(
1046        field_info: &FieldInfo,
1047        components: &mut oas31::Components,
1048        types: &ProtoTypeRegistry,
1049        used_paths: &BTreeMap<String, ExcludePaths>,
1050        direction: GenerateDirection,
1051        bytes: BytesEncoding,
1052    ) -> anyhow::Result<Schema> {
1053        let mut schemas = Vec::new();
1054        let ty = field_info.ty.clone();
1055        let cel = field_info.cel;
1056        let full_field_name = field_info.full_name;
1057
1058        let compiler = Compiler::new(types);
1059        if !matches!(ty, ProtoType::Modified(ProtoModifiedValueType::Optional(_))) {
1060            for expr in &cel.field {
1061                schemas.extend(handle_expr(compiler.child(), &ty, expr)?);
1062            }
1063        }
1064
1065        schemas.push(match ty {
1066            ProtoType::Modified(ProtoModifiedValueType::Map(key, value)) => Schema::object(
1067                Object::builder()
1068                    .schema_type(Type::Object)
1069                    .property_names(match key {
1070                        ProtoValueType::String => {
1071                            let mut schemas = Vec::with_capacity(1 + cel.map_key.len());
1072
1073                            for expr in &cel.map_key {
1074                                schemas.extend(handle_expr(
1075                                    compiler.child(),
1076                                    &ProtoType::Value(key.clone()),
1077                                    expr,
1078                                )?);
1079                            }
1080
1081                            schemas
1082                                .push(Schema::object(Object::builder().schema_type(Type::String)));
1083
1084                            Object::all_ofs(schemas)
1085                        }
1086                        ProtoValueType::Int32 | ProtoValueType::Int64 => Object::builder()
1087                            .schema_type(Type::String)
1088                            .pattern("^-?[0-9]+$")
1089                            .build(),
1090                        ProtoValueType::UInt32 | ProtoValueType::UInt64 => Object::builder()
1091                            .schema_type(Type::String)
1092                            .pattern("^[0-9]+$")
1093                            .build(),
1094                        ProtoValueType::Bool => Object::builder()
1095                            .schema_type(Type::String)
1096                            .enum_values(["true", "false"])
1097                            .build(),
1098                        _ => Object::builder().schema_type(Type::String).build(),
1099                    })
1100                    .additional_properties({
1101                        let mut schemas = Vec::with_capacity(1 + cel.map_value.len());
1102                        for expr in &cel.map_value {
1103                            schemas.extend(handle_expr(
1104                                compiler.child(),
1105                                &ProtoType::Value(value.clone()),
1106                                expr,
1107                            )?);
1108                        }
1109
1110                        schemas.push(internal_generate(
1111                            &FieldInfo {
1112                                full_name: full_field_name,
1113                                ty: &ProtoType::Value(value.clone()),
1114                                cel: &CelExpressions::default(),
1115                            },
1116                            components,
1117                            types,
1118                            &BTreeMap::new(),
1119                            direction,
1120                            bytes,
1121                        )?);
1122
1123                        Object::all_ofs(schemas)
1124                    })
1125                    .build(),
1126            ),
1127            ProtoType::Modified(ProtoModifiedValueType::Repeated(item)) => Schema::object(
1128                Object::builder()
1129                    .schema_type(Type::Array)
1130                    .items(internal_generate(
1131                        &FieldInfo {
1132                            full_name: full_field_name,
1133                            ty: &ProtoType::Value(item.clone()),
1134                            cel,
1135                        },
1136                        components,
1137                        types,
1138                        used_paths,
1139                        direction,
1140                        bytes,
1141                    )?)
1142                    .build(),
1143            ),
1144            ProtoType::Modified(ProtoModifiedValueType::OneOf(oneof)) => Schema::object(
1145                Object::builder()
1146                    .schema_type(Type::Object)
1147                    .title(oneof.full_name.to_string())
1148                    .one_ofs(if let Some(tagged) = oneof.options.tagged {
1149                        oneof
1150                            .fields
1151                            .into_iter()
1152                            .filter(|(_, field)| match direction {
1153                                GenerateDirection::Input => field.options.visibility.has_input(),
1154                                GenerateDirection::Output => field.options.visibility.has_output(),
1155                            })
1156                            .map(|(name, field)| {
1157                                let ty = internal_generate(
1158                                    &FieldInfo {
1159                                        full_name: &field.full_name,
1160                                        ty: &ProtoType::Value(field.ty.clone()),
1161                                        cel: &field.options.cel_exprs,
1162                                    },
1163                                    components,
1164                                    types,
1165                                    &BTreeMap::new(),
1166                                    direction,
1167                                    bytes,
1168                                )?;
1169
1170                                anyhow::Ok(Schema::object(
1171                                    Object::builder()
1172                                        .schema_type(Type::Object)
1173                                        .title(name)
1174                                        .description(field.comments.to_string())
1175                                        .properties({
1176                                            let mut properties = IndexMap::new();
1177                                            properties.insert(
1178                                                tagged.tag.clone(),
1179                                                Schema::object(
1180                                                    Object::builder()
1181                                                        .schema_type(Type::String)
1182                                                        .const_value(
1183                                                            field.options.serde_name.clone(),
1184                                                        )
1185                                                        .build(),
1186                                                ),
1187                                            );
1188                                            properties.insert(tagged.content.clone(), ty);
1189                                            properties
1190                                        })
1191                                        .unevaluated_properties(false)
1192                                        .build(),
1193                                ))
1194                            })
1195                            .collect::<anyhow::Result<Vec<_>>>()?
1196                    } else {
1197                        oneof
1198                            .fields
1199                            .into_iter()
1200                            .filter(|(_, field)| match direction {
1201                                GenerateDirection::Input => field.options.visibility.has_input(),
1202                                GenerateDirection::Output => field.options.visibility.has_output(),
1203                            })
1204                            .map(|(name, field)| {
1205                                let ty = internal_generate(
1206                                    &FieldInfo {
1207                                        full_name: &field.full_name,
1208                                        ty: &ProtoType::Value(field.ty.clone()),
1209                                        cel: &field.options.cel_exprs,
1210                                    },
1211                                    components,
1212                                    types,
1213                                    &BTreeMap::new(),
1214                                    direction,
1215                                    bytes,
1216                                )?;
1217
1218                                anyhow::Ok(Schema::object(
1219                                    Object::builder()
1220                                        .schema_type(Type::Object)
1221                                        .title(name)
1222                                        .description(field.comments.to_string())
1223                                        .properties({
1224                                            let mut properties = IndexMap::new();
1225                                            properties.insert(&field.options.serde_name, ty);
1226                                            properties
1227                                        })
1228                                        .unevaluated_properties(false)
1229                                        .build(),
1230                                ))
1231                            })
1232                            .collect::<anyhow::Result<Vec<_>>>()?
1233                    })
1234                    .unevaluated_properties(false)
1235                    .build(),
1236            ),
1237            ProtoType::Modified(ProtoModifiedValueType::Optional(value)) => Schema::object(
1238                Object::builder()
1239                    .one_ofs([
1240                        Schema::object(Object::builder().schema_type(Type::Null).build()),
1241                        internal_generate(
1242                            &FieldInfo {
1243                                full_name: full_field_name,
1244                                ty: &ProtoType::Value(value.clone()),
1245                                cel,
1246                            },
1247                            components,
1248                            types,
1249                            used_paths,
1250                            direction,
1251                            bytes,
1252                        )?,
1253                    ])
1254                    .build(),
1255            ),
1256            ProtoType::Value(ProtoValueType::Bool) => {
1257                Schema::object(Object::builder().schema_type(Type::Boolean).build())
1258            }
1259            ProtoType::Value(ProtoValueType::Bytes) => Schema::object(
1260                Object::builder()
1261                    .schema_type(Type::String)
1262                    .content_encoding(match bytes {
1263                        BytesEncoding::Base64 => "base64",
1264                        BytesEncoding::Binary => "binary",
1265                    })
1266                    .build(),
1267            ),
1268            ProtoType::Value(ProtoValueType::Double | ProtoValueType::Float) => {
1269                if types.support_non_finite_vals(full_field_name) {
1270                    Schema::object(
1271                        Object::builder()
1272                            .one_ofs([
1273                                Schema::object(Object::builder().schema_type(Type::Number).build()),
1274                                Schema::object(
1275                                    Object::builder()
1276                                        .schema_type(Type::String)
1277                                        .enum_values(vec![
1278                                            serde_json::Value::from("Infinity"),
1279                                            serde_json::Value::from("-Infinity"),
1280                                            serde_json::Value::from("NaN"),
1281                                        ])
1282                                        .build(),
1283                                ),
1284                            ])
1285                            .build(),
1286                    )
1287                } else {
1288                    Schema::object(Object::builder().schema_type(Type::Number).build())
1289                }
1290            }
1291            ProtoType::Value(ProtoValueType::Int32) => Schema::object(Object::int32()),
1292            ProtoType::Value(ProtoValueType::UInt32) => Schema::object(Object::uint32()),
1293            ProtoType::Value(ProtoValueType::Int64) => Schema::object(Object::int64()),
1294            ProtoType::Value(ProtoValueType::UInt64) => Schema::object(Object::uint64()),
1295            ProtoType::Value(ProtoValueType::String) => {
1296                Schema::object(Object::builder().schema_type(Type::String).build())
1297            }
1298            ProtoType::Value(ProtoValueType::Enum(enum_path)) => {
1299                let ety = types
1300                    .get_enum(&enum_path)
1301                    .with_context(|| format!("missing enum: {enum_path}"))?;
1302                let schema_name =
1303                    if ety.variants.values().any(|v| {
1304                        v.options.visibility.has_input() != v.options.visibility.has_output()
1305                    }) {
1306                        format!("{direction:?}.{enum_path}")
1307                    } else {
1308                        enum_path.to_string()
1309                    };
1310
1311                if !components.schemas.contains_key(enum_path.as_ref()) {
1312                    components.add_schema(
1313                        schema_name.clone(),
1314                        Schema::object(
1315                            Object::builder()
1316                                .schema_type(if ety.options.repr_enum {
1317                                    Type::Integer
1318                                } else {
1319                                    Type::String
1320                                })
1321                                .enum_values(
1322                                    ety.variants
1323                                        .values()
1324                                        .filter(|v| match direction {
1325                                            GenerateDirection::Input => {
1326                                                v.options.visibility.has_input()
1327                                            }
1328                                            GenerateDirection::Output => {
1329                                                v.options.visibility.has_output()
1330                                            }
1331                                        })
1332                                        .map(|v| {
1333                                            if ety.options.repr_enum {
1334                                                serde_json::Value::from(v.value)
1335                                            } else {
1336                                                serde_json::Value::from(
1337                                                    v.options.serde_name.clone(),
1338                                                )
1339                                            }
1340                                        })
1341                                        .collect::<Vec<_>>(),
1342                                )
1343                                .title(enum_path.to_string())
1344                                .description(ety.comments.to_string())
1345                                .build(),
1346                        ),
1347                    );
1348                }
1349
1350                Schema::object(Ref::from_schema_name(schema_name))
1351            }
1352            ref ty @ ProtoType::Value(ProtoValueType::Message(ref message_path)) => {
1353                let message_ty = types
1354                    .get_message(message_path)
1355                    .with_context(|| format!("missing message: {message_path}"))?;
1356
1357                let schema_name =
1358                    if message_ty.fields.values().any(|v| {
1359                        v.options.visibility.has_input() != v.options.visibility.has_output()
1360                    }) {
1361                        format!("{direction:?}.{message_path}")
1362                    } else {
1363                        message_path.to_string()
1364                    };
1365
1366                if !components.schemas.contains_key(&schema_name) || !used_paths.is_empty() {
1367                    if used_paths.is_empty() {
1368                        components
1369                            .schemas
1370                            .insert(schema_name.clone(), Schema::Bool(false));
1371                    }
1372                    let mut properties = IndexMap::new();
1373                    let mut required = Vec::new();
1374                    let mut schemas = Vec::with_capacity(1);
1375
1376                    for expr in &message_ty.options.cel {
1377                        schemas.extend(handle_expr(compiler.child(), ty, expr)?);
1378                    }
1379
1380                    for (name, field) in
1381                        message_ty
1382                            .fields
1383                            .iter()
1384                            .filter(|(_, field)| match direction {
1385                                GenerateDirection::Input => field.options.visibility.has_input(),
1386                                GenerateDirection::Output => field.options.visibility.has_output(),
1387                            })
1388                    {
1389                        let exclude_paths = match used_paths.get(name) {
1390                            Some(ExcludePaths::True) => continue,
1391                            Some(ExcludePaths::Child(child)) => Some(child),
1392                            None => None,
1393                        };
1394                        if !field.options.serde_omittable.is_true() {
1395                            required.push(field.options.serde_name.clone());
1396                        }
1397
1398                        let ty = match (!field.options.nullable || field.options.flatten, &field.ty)
1399                        {
1400                            (true, ProtoType::Modified(ProtoModifiedValueType::Optional(ty))) => {
1401                                ProtoType::Value(ty.clone())
1402                            }
1403                            _ => field.ty.clone(),
1404                        };
1405
1406                        let field_schema = internal_generate(
1407                            &FieldInfo {
1408                                full_name: &field.full_name,
1409                                ty: &ty,
1410                                cel: &field.options.cel_exprs,
1411                            },
1412                            components,
1413                            types,
1414                            exclude_paths.unwrap_or(&BTreeMap::new()),
1415                            direction,
1416                            bytes,
1417                        )?;
1418
1419                        if field.options.flatten {
1420                            schemas.push(field_schema);
1421                        } else {
1422                            let schema = if field.options.nullable
1423                                && !matches!(
1424                                    &field.ty,
1425                                    ProtoType::Modified(ProtoModifiedValueType::Optional(_))
1426                                ) {
1427                                Schema::object(
1428                                    Object::builder()
1429                                        .one_ofs([
1430                                            Object::builder()
1431                                                .schema_type(Type::Null)
1432                                                .build()
1433                                                .into(),
1434                                            field_schema,
1435                                        ])
1436                                        .build(),
1437                                )
1438                            } else {
1439                                field_schema
1440                            };
1441
1442                            properties.insert(
1443                                field.options.serde_name.clone(),
1444                                Schema::object(Object::all_ofs([
1445                                    schema,
1446                                    Schema::object(
1447                                        Object::builder()
1448                                            .description(field.comments.to_string())
1449                                            .build(),
1450                                    ),
1451                                ])),
1452                            );
1453                        }
1454                    }
1455
1456                    schemas.push(Schema::object(
1457                        Object::builder()
1458                            .schema_type(Type::Object)
1459                            .title(message_path.to_string())
1460                            .description(message_ty.comments.to_string())
1461                            .properties(properties)
1462                            .required(required)
1463                            .unevaluated_properties(false)
1464                            .build(),
1465                    ));
1466
1467                    if used_paths.is_empty() {
1468                        components.add_schema(
1469                            schema_name.clone(),
1470                            Object::all_ofs(schemas).into_optimized(),
1471                        );
1472                        Schema::object(Ref::from_schema_name(schema_name))
1473                    } else {
1474                        Schema::object(Object::all_ofs(schemas))
1475                    }
1476                } else {
1477                    Schema::object(Ref::from_schema_name(schema_name))
1478                }
1479            }
1480            ProtoType::Value(ProtoValueType::WellKnown(ProtoWellKnownType::Timestamp)) => {
1481                Schema::object(
1482                    Object::builder()
1483                        .schema_type(Type::String)
1484                        .format("date-time")
1485                        .build(),
1486                )
1487            }
1488            ProtoType::Value(ProtoValueType::WellKnown(ProtoWellKnownType::Duration)) => {
1489                Schema::object(
1490                    Object::builder()
1491                        .schema_type(Type::String)
1492                        .format("duration")
1493                        .build(),
1494                )
1495            }
1496            ProtoType::Value(ProtoValueType::WellKnown(ProtoWellKnownType::Empty)) => {
1497                Schema::object(
1498                    Object::builder()
1499                        .schema_type(Type::Object)
1500                        .unevaluated_properties(false)
1501                        .build(),
1502                )
1503            }
1504            ProtoType::Value(ProtoValueType::WellKnown(ProtoWellKnownType::ListValue)) => {
1505                Schema::object(Object::builder().schema_type(Type::Array).build())
1506            }
1507            ProtoType::Value(ProtoValueType::WellKnown(ProtoWellKnownType::Value)) => {
1508                Schema::object(
1509                    Object::builder()
1510                        .schema_type(vec![
1511                            Type::Null,
1512                            Type::Boolean,
1513                            Type::Object,
1514                            Type::Array,
1515                            Type::Number,
1516                            Type::String,
1517                        ])
1518                        .build(),
1519                )
1520            }
1521            ProtoType::Value(ProtoValueType::WellKnown(ProtoWellKnownType::Struct)) => {
1522                Schema::object(Object::builder().schema_type(Type::Object).build())
1523            }
1524            ProtoType::Value(ProtoValueType::WellKnown(ProtoWellKnownType::Any)) => Schema::object(
1525                Object::builder()
1526                    .schema_type(Type::Object)
1527                    .property("@type", Object::builder().schema_type(Type::String))
1528                    .build(),
1529            ),
1530        });
1531
1532        Ok(Schema::object(Object::all_ofs(schemas)))
1533    }
1534
1535    internal_generate(field_info, components, types, used_paths, direction, bytes)
1536        .map(|schema| schema.into_optimized())
1537}