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