1use anyhow::Context;
2use indexmap::IndexMap;
3use oas31::HttpMethod;
4use openapi::{BodyMethod, GeneratedBody, GeneratedParams, InputGenerator, OutputGenerator};
5use quote::{format_ident, quote};
6use syn::{Ident, parse_quote};
7use tonneau_pb_prost::http_endpoint_options;
8
9use super::Package;
10use super::utils::{field_ident_from_str, type_ident_from_str};
11use crate::types::{
12 Comments, ProtoPath, ProtoService, ProtoServiceMethod, ProtoServiceMethodEndpoint,
13 ProtoServiceMethodIo, ProtoTypeRegistry, ProtoValueType,
14};
15
16mod openapi;
17
18struct GeneratedMethod {
19 function_body: proc_macro2::TokenStream,
20 openapi: oas31::path::PathItem,
21 http_method: Ident,
22 path: String,
23}
24
25impl GeneratedMethod {
26 #[allow(clippy::too_many_arguments)]
27 fn new(
28 name: &str,
29 package: &str,
30 service_name: &str,
31 service: &ProtoService,
32 method: &ProtoServiceMethod,
33 endpoint: &ProtoServiceMethodEndpoint,
34 types: &ProtoTypeRegistry,
35 components: &mut oas31::Components,
36 ) -> anyhow::Result<GeneratedMethod> {
37 let (http_method_oa, path) = match &endpoint.method {
38 tonneau_pb_prost::http_endpoint_options::Method::Get(path) => {
39 (oas31::HttpMethod::Get, path)
40 }
41 tonneau_pb_prost::http_endpoint_options::Method::Post(path) => {
42 (oas31::HttpMethod::Post, path)
43 }
44 tonneau_pb_prost::http_endpoint_options::Method::Put(path) => {
45 (oas31::HttpMethod::Put, path)
46 }
47 tonneau_pb_prost::http_endpoint_options::Method::Delete(path) => {
48 (oas31::HttpMethod::Delete, path)
49 }
50 tonneau_pb_prost::http_endpoint_options::Method::Patch(path) => {
51 (oas31::HttpMethod::Patch, path)
52 }
53 };
54
55 let full_path = match (
56 path.trim_matches('/'),
57 service
58 .options
59 .prefix
60 .as_deref()
61 .map(|p| p.trim_matches('/')),
62 ) {
63 ("", Some(prefix)) => format!("/{prefix}"),
64 (path, None | Some("")) => format!("/{path}"),
65 (path, Some(prefix)) => format!("/{prefix}/{path}"),
66 };
67
68 let http_method = quote::format_ident!("{http_method_oa}");
69 let tracker_ident = quote::format_ident!("tracker");
70 let target_ident = quote::format_ident!("target");
71 let state_ident = quote::format_ident!("state");
72 let mut openapi = oas31::path::Operation::new();
73 let mut generator = InputGenerator::new(
74 types,
75 components,
76 package,
77 method.input.value_type().clone(),
78 tracker_ident.clone(),
79 target_ident.clone(),
80 state_ident.clone(),
81 );
82
83 openapi.tag(service_name);
84
85 let GeneratedParams {
86 tokens: path_tokens,
87 params,
88 } = generator.generate_path_parameter(full_path.trim_end_matches("/"))?;
89 openapi.parameters(params);
90
91 let is_get_or_delete = matches!(http_method_oa, HttpMethod::Get | HttpMethod::Delete);
92 let request = endpoint
93 .request
94 .as_ref()
95 .and_then(|req| req.mode.clone())
96 .unwrap_or_else(|| {
97 if is_get_or_delete {
98 http_endpoint_options::request::Mode::Query(
99 http_endpoint_options::request::QueryParams::default(),
100 )
101 } else {
102 http_endpoint_options::request::Mode::Json(
103 http_endpoint_options::request::JsonBody::default(),
104 )
105 }
106 });
107
108 let request_tokens = match request {
109 http_endpoint_options::request::Mode::Query(
110 http_endpoint_options::request::QueryParams { field },
111 ) => {
112 let GeneratedParams { tokens, params } =
113 generator.generate_query_parameter(field.as_deref())?;
114 openapi.parameters(params);
115 tokens
116 }
117 http_endpoint_options::request::Mode::Binary(
118 http_endpoint_options::request::BinaryBody {
119 field,
120 content_type_accepts,
121 content_type_field,
122 },
123 ) => {
124 let GeneratedBody { tokens, body } = generator.generate_body(
125 &method.cel,
126 BodyMethod::Binary(content_type_accepts.as_deref()),
127 field.as_deref(),
128 content_type_field.as_deref(),
129 )?;
130 openapi.request_body = Some(body);
131 tokens
132 }
133 http_endpoint_options::request::Mode::Json(
134 http_endpoint_options::request::JsonBody { field },
135 ) => {
136 let GeneratedBody { tokens, body } = generator.generate_body(
137 &method.cel,
138 BodyMethod::Json,
139 field.as_deref(),
140 None,
141 )?;
142 openapi.request_body = Some(body);
143 tokens
144 }
145 http_endpoint_options::request::Mode::Text(
146 http_endpoint_options::request::TextBody { field },
147 ) => {
148 let GeneratedBody { tokens, body } = generator.generate_body(
149 &method.cel,
150 BodyMethod::Text,
151 field.as_deref(),
152 None,
153 )?;
154 openapi.request_body = Some(body);
155 tokens
156 }
157 };
158
159 let input_path = match &method.input {
160 ProtoServiceMethodIo::Single(input) => {
161 types.resolve_rust_path(package, input.proto_path())
162 }
163 ProtoServiceMethodIo::Stream(_) => {
164 anyhow::bail!("currently streaming is not supported by tonneau methods.")
165 }
166 };
167
168 let service_method_name = field_ident_from_str(name);
169
170 let response = endpoint
171 .response
172 .as_ref()
173 .and_then(|resp| resp.mode.clone())
174 .unwrap_or_else(|| {
175 http_endpoint_options::response::Mode::Json(
176 http_endpoint_options::response::Json::default(),
177 )
178 });
179
180 let response_ident = quote::format_ident!("response");
181 let builder_ident = quote::format_ident!("builder");
182 let mut generator = OutputGenerator::new(
183 types,
184 components,
185 method.output.value_type().clone(),
186 response_ident.clone(),
187 builder_ident.clone(),
188 );
189
190 let GeneratedBody {
191 body: response,
192 tokens: response_tokens,
193 } = match response {
194 http_endpoint_options::response::Mode::Binary(
195 http_endpoint_options::response::Binary {
196 field,
197 content_type_accepts,
198 content_type_field,
199 },
200 ) => generator.generate_body(
201 BodyMethod::Binary(content_type_accepts.as_deref()),
202 field.as_deref(),
203 content_type_field.as_deref(),
204 )?,
205 http_endpoint_options::response::Mode::Json(
206 http_endpoint_options::response::Json { field },
207 ) => generator.generate_body(BodyMethod::Json, field.as_deref(), None)?,
208 http_endpoint_options::response::Mode::Text(
209 http_endpoint_options::response::Text { field },
210 ) => generator.generate_body(BodyMethod::Text, field.as_deref(), None)?,
211 };
212
213 openapi.response("200", response);
214
215 let validate = if matches!(method.input.value_type(), ProtoValueType::Message(_)) {
216 quote! {
217 if let Err(err) = ::tonneau::__private::TonneauValidate::validate_http(&#target_ident, #state_ident, &#tracker_ident) {
218 return err;
219 }
220 }
221 } else {
222 quote!()
223 };
224
225 let function_impl = quote! {
226 let mut #state_ident = ::tonneau::__private::TrackerSharedState::default();
227 let mut #tracker_ident = <<#input_path as ::tonneau::__private::TrackerFor>::Tracker as ::core::default::Default>::default();
228 let mut #target_ident = <#input_path as ::core::default::Default>::default();
229
230 #path_tokens
231 #request_tokens
232
233 #validate
234
235 let request = ::tonneau::reexports::tonic::Request::from_parts(
236 ::tonneau::reexports::tonic::metadata::MetadataMap::from_headers(parts.headers),
237 parts.extensions,
238 target,
239 );
240
241 let (metadata, #response_ident, extensions) = match service.inner.#service_method_name(request).await {
242 ::core::result::Result::Ok(response) => response.into_parts(),
243 ::core::result::Result::Err(status) => return ::tonneau::__private::handle_tonic_status(&status),
244 };
245
246 let mut response = {
247 let mut #builder_ident = ::tonneau::reexports::http::Response::builder();
248 match #response_tokens {
249 ::core::result::Result::Ok(v) => v,
250 ::core::result::Result::Err(err) => return ::tonneau::__private::handle_response_build_error(err),
251 }
252 };
253
254 response.headers_mut().extend(metadata.into_headers());
255 *response.extensions_mut() = extensions;
256
257 response
258 };
259
260 Ok(GeneratedMethod {
261 function_body: function_impl,
262 http_method,
263 openapi: oas31::PathItem::new(http_method_oa, openapi),
264 path: full_path,
265 })
266 }
267
268 pub(crate) fn method_handler(
269 &self,
270 function_name: &Ident,
271 server_module_name: &Ident,
272 service_trait: &Ident,
273 tonneau_struct_name: &Ident,
274 ) -> proc_macro2::TokenStream {
275 let function_impl = &self.function_body;
276
277 quote! {
278 #[allow(non_snake_case, unused_mut, dead_code, unused_variables, unused_parens)]
279 async fn #function_name<T>(
280 ::tonneau::reexports::axum::extract::State(service): ::tonneau::reexports::axum::extract::State<#tonneau_struct_name<T>>,
281 request: ::tonneau::reexports::axum::extract::Request,
282 ) -> ::tonneau::reexports::axum::response::Response
283 where
284 T: super::#server_module_name::#service_trait,
285 {
286 let (mut parts, body) = ::tonneau::reexports::axum::RequestExt::with_limited_body(request).into_parts();
287 #function_impl
288 }
289 }
290 }
291
292 pub(crate) fn route(&self, function_name: &Ident) -> proc_macro2::TokenStream {
293 let path = &self.path;
294 let http_method = &self.http_method;
295
296 quote! {
297 .route(#path, ::tonneau::reexports::axum::routing::#http_method(#function_name::<T>))
298 }
299 }
300}
301
302#[derive(Debug, Clone, PartialEq)]
303pub(crate) struct ProcessedService {
304 pub full_name: ProtoPath,
305 pub package: ProtoPath,
306 pub comments: Comments,
307 pub openapi: oas31::OpenApi,
308 pub methods: IndexMap<String, ProcessedServiceMethod>,
309}
310
311impl ProcessedService {
312 pub(crate) fn name(&self) -> &str {
313 self.full_name
314 .strip_prefix(&*self.package)
315 .unwrap_or(&self.full_name)
316 .trim_matches('.')
317 }
318}
319
320#[derive(Debug, Clone, PartialEq)]
321pub(crate) struct ProcessedServiceMethod {
322 pub codec_path: Option<ProtoPath>,
323 pub input: ProtoServiceMethodIo,
324 pub output: ProtoServiceMethodIo,
325 pub comments: Comments,
326}
327
328pub(super) fn handle_service(
329 service: &ProtoService,
330 package: &mut Package,
331 registry: &ProtoTypeRegistry,
332) -> anyhow::Result<()> {
333 let name = service
334 .full_name
335 .strip_prefix(&*service.package)
336 .and_then(|s| s.strip_prefix('.'))
337 .unwrap_or(&*service.full_name);
338
339 let mut components = oas31::Components::new();
340 let mut paths = oas31::Paths::builder();
341
342 let snake_name = field_ident_from_str(name);
343 let pascal_name = type_ident_from_str(name);
344
345 let tonneau_module_name = quote::format_ident!("{snake_name}_tonneau");
346 let server_module_name = quote::format_ident!("{snake_name}_server");
347 let tonneau_struct_name = quote::format_ident!("{pascal_name}Tonneau");
348
349 let mut method_tokens = Vec::new();
350 let mut route_tokens = Vec::new();
351 let mut method_codecs = Vec::new();
352 let mut methods = IndexMap::new();
353
354 let package_name = format!("{}.{tonneau_module_name}", service.package);
355
356 for (method_name, method) in service.methods.iter() {
357 for (idx, endpoint) in method.endpoints.iter().enumerate() {
358 let gen_method = GeneratedMethod::new(
359 method_name,
360 &package_name,
361 name,
362 service,
363 method,
364 endpoint,
365 registry,
366 &mut components,
367 )?;
368 let function_name = quote::format_ident!("{method_name}_{idx}");
369
370 method_tokens.push(gen_method.method_handler(
371 &function_name,
372 &server_module_name,
373 &pascal_name,
374 &tonneau_struct_name,
375 ));
376 route_tokens.push(gen_method.route(&function_name));
377 paths = paths.path(gen_method.path, gen_method.openapi);
378 }
379
380 let codec_path = if matches!(method.input.value_type(), ProtoValueType::Message(_)) {
381 let input_path =
382 registry.resolve_rust_path(&package_name, method.input.value_type().proto_path());
383 let output_path =
384 registry.resolve_rust_path(&package_name, method.output.value_type().proto_path());
385 let codec_ident = format_ident!("{method_name}Codec");
386 method_codecs.push(quote! {
387 #[derive(Debug, Clone, Default)]
388 #[doc(hidden)]
389 pub struct #codec_ident<C>(C);
390
391 #[allow(clippy::all, dead_code, unused_imports, unused_variables, unused_parens)]
392 const _: () = {
393 #[derive(Debug, Clone, Default)]
394 pub struct Encoder<E>(E);
395 #[derive(Debug, Clone, Default)]
396 pub struct Decoder<D>(D);
397
398 impl<C> ::tonneau::reexports::tonic::codec::Codec for #codec_ident<C>
399 where
400 C: ::tonneau::reexports::tonic::codec::Codec<Encode = #output_path, Decode = #input_path>
401 {
402 type Encode = C::Encode;
403 type Decode = C::Decode;
404
405 type Encoder = C::Encoder;
406 type Decoder = Decoder<C::Decoder>;
407
408 fn encoder(&mut self) -> Self::Encoder {
409 ::tonneau::reexports::tonic::codec::Codec::encoder(&mut self.0)
410 }
411
412 fn decoder(&mut self) -> Self::Decoder {
413 Decoder(
414 ::tonneau::reexports::tonic::codec::Codec::decoder(&mut self.0)
415 )
416 }
417 }
418
419 impl<D> ::tonneau::reexports::tonic::codec::Decoder for Decoder<D>
420 where
421 D: ::tonneau::reexports::tonic::codec::Decoder<Item = #input_path, Error = ::tonneau::reexports::tonic::Status>
422 {
423 type Item = D::Item;
424 type Error = ::tonneau::reexports::tonic::Status;
425
426 fn decode(&mut self, buf: &mut ::tonneau::reexports::tonic::codec::DecodeBuf<'_>) -> Result<Option<Self::Item>, Self::Error> {
427 match ::tonneau::reexports::tonic::codec::Decoder::decode(&mut self.0, buf) {
428 ::core::result::Result::Ok(::core::option::Option::Some(item)) => {
429 ::tonneau::__private::TonneauValidate::validate_tonic(&item)?;
430 ::core::result::Result::Ok(::core::option::Option::Some(item))
431 },
432 ::core::result::Result::Ok(::core::option::Option::None) => ::core::result::Result::Ok(::core::option::Option::None),
433 ::core::result::Result::Err(err) => ::core::result::Result::Err(err),
434 }
435 }
436
437 fn buffer_settings(&self) -> ::tonneau::reexports::tonic::codec::BufferSettings {
438 ::tonneau::reexports::tonic::codec::Decoder::buffer_settings(&self.0)
439 }
440 }
441 };
442 });
443 Some(ProtoPath::new(format!("{package_name}.{codec_ident}")))
444 } else {
445 None
446 };
447
448 methods.insert(
449 method_name.clone(),
450 ProcessedServiceMethod {
451 codec_path,
452 input: method.input.clone(),
453 output: method.output.clone(),
454 comments: method.comments.clone(),
455 },
456 );
457 }
458
459 let openapi_tag = oas31::Tag::builder()
460 .name(name)
461 .description(service.comments.to_string())
462 .build();
463 let openapi = oas31::OpenApi::builder()
464 .components(components)
465 .paths(paths)
466 .tags(vec![openapi_tag])
467 .build();
468
469 let json_openapi = openapi
470 .to_json()
471 .context("invalid openapi schema generation")?;
472
473 package.push_item(parse_quote! {
474 #[allow(clippy::all)]
476 pub mod #tonneau_module_name {
477 #![allow(
478 unused_variables,
479 dead_code,
480 missing_docs,
481 clippy::wildcard_imports,
482 clippy::let_unit_value,
483 unused_parens,
484 irrefutable_let_patterns,
485 )]
486
487 pub struct #tonneau_struct_name<T> {
489 inner: ::std::sync::Arc<T>,
490 }
491
492 impl<T> #tonneau_struct_name<T> {
493 pub fn new(inner: T) -> Self {
495 Self { inner: ::std::sync::Arc::new(inner) }
496 }
497
498 pub fn from_arc(inner: ::std::sync::Arc<T>) -> Self {
500 Self { inner }
501 }
502 }
503
504 impl<T> ::std::clone::Clone for #tonneau_struct_name<T> {
505 fn clone(&self) -> Self {
506 Self { inner: ::std::clone::Clone::clone(&self.inner) }
507 }
508 }
509
510 impl<T> ::std::fmt::Debug for #tonneau_struct_name<T> {
511 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
512 write!(f, stringify!(#tonneau_struct_name))
513 }
514 }
515
516 impl<T> ::tonneau::TonneauService for #tonneau_struct_name<T>
517 where
518 T: super::#server_module_name::#pascal_name
519 {
520 fn into_router(self) -> ::tonneau::reexports::axum::Router {
521 #(#method_tokens)*
522
523 ::tonneau::reexports::axum::Router::new()
524 #(#route_tokens)*
525 .with_state(self)
526 }
527
528 fn openapi_schema_str(&self) -> &'static str {
529 #json_openapi
530 }
531 }
532
533 #(#method_codecs)*
534 }
535 });
536
537 package.services.push(ProcessedService {
538 full_name: service.full_name.clone(),
539 package: service.package.clone(),
540 comments: service.comments.clone(),
541 openapi,
542 methods,
543 });
544
545 Ok(())
546}