1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2use heck::ToSnakeCase;
3use proc_macro::TokenStream;
4use proc_macro2::Span;
5use quote::{format_ident, quote};
6use syn::{
7 DeriveInput, Expr, Ident, ImplItem, ItemImpl, Lit, LitBool, LitStr, Meta, MetaList,
8 MetaNameValue, Path, Token, TypePath, parse::Parse, parse::ParseStream, parse_macro_input,
9 punctuated::Punctuated,
10};
11
12mod api_dto;
14mod domain_model;
15mod expand_vars;
16mod grpc_client;
17mod gts_publication;
18mod temporary;
19mod utils;
21
22struct GearConfig {
24 name: String,
25 deps: Vec<Ident>,
26 caps: Vec<Capability>,
27 ctor: Option<Expr>, client: Option<Path>, lifecycle: Option<LcGearCfg>, gts_publication: Option<gts_publication::GtsPublicationCfg>,
31}
32
33#[derive(Debug, PartialEq, Clone)]
34enum Capability {
35 Db,
36 Rest,
37 RestHost,
38 Stateful,
39 System,
40 GrpcHub,
41 Grpc,
42}
43
44impl Capability {
45 const VALID_CAPABILITIES: &'static [&'static str] = &[
46 "db",
47 "rest",
48 "rest_host",
49 "stateful",
50 "system",
51 "grpc_hub",
52 "grpc",
53 ];
54
55 fn suggest_similar(input: &str) -> Vec<&'static str> {
56 let mut suggestions: Vec<(&str, f64)> = Self::VALID_CAPABILITIES
57 .iter()
58 .map(|&cap| (cap, strsim::jaro_winkler(input, cap)))
59 .filter(|(_, score)| *score > 0.6) .collect();
61
62 suggestions.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
63 suggestions
64 .into_iter()
65 .take(2)
66 .map(|(cap, _)| cap)
67 .collect()
68 }
69
70 fn from_ident(ident: &Ident) -> syn::Result<Self> {
71 let input = ident.to_string();
72 match input.as_str() {
73 "db" => Ok(Capability::Db),
74 "rest" => Ok(Capability::Rest),
75 "rest_host" => Ok(Capability::RestHost),
76 "stateful" => Ok(Capability::Stateful),
77 "system" => Ok(Capability::System),
78 "grpc_hub" => Ok(Capability::GrpcHub),
79 "grpc" => Ok(Capability::Grpc),
80 other => {
81 let suggestions = Self::suggest_similar(other);
82 let error_msg = if suggestions.is_empty() {
83 format!(
84 "unknown capability '{other}', expected one of: db, rest, rest_host, stateful, system, grpc_hub, grpc"
85 )
86 } else {
87 format!(
88 "unknown capability '{other}'\n = help: did you mean one of: {}?",
89 suggestions.join(", ")
90 )
91 };
92 Err(syn::Error::new_spanned(ident, error_msg))
93 }
94 }
95 }
96
97 fn from_str_lit(lit: &LitStr) -> syn::Result<Self> {
98 let input = lit.value();
99 match input.as_str() {
100 "db" => Ok(Capability::Db),
101 "rest" => Ok(Capability::Rest),
102 "rest_host" => Ok(Capability::RestHost),
103 "stateful" => Ok(Capability::Stateful),
104 "system" => Ok(Capability::System),
105 "grpc_hub" => Ok(Capability::GrpcHub),
106 "grpc" => Ok(Capability::Grpc),
107 other => {
108 let suggestions = Self::suggest_similar(other);
109 let error_msg = if suggestions.is_empty() {
110 format!(
111 "unknown capability '{other}', expected one of: db, rest, rest_host, stateful, system, grpc_hub, grpc"
112 )
113 } else {
114 format!(
115 "unknown capability '{other}'\n = help: did you mean one of: {}?",
116 suggestions.join(", ")
117 )
118 };
119 Err(syn::Error::new_spanned(lit, error_msg))
120 }
121 }
122 }
123}
124
125fn validate_kebab_case(name: &str) -> Result<(), String> {
138 if name.is_empty() {
139 return Err("gear name cannot be empty".to_owned());
140 }
141
142 if name.contains('_') {
144 let suggested = name.replace('_', "-");
145 return Err(format!(
146 "gear name must use kebab-case, not snake_case\n = help: use '{suggested}' instead of '{name}'"
147 ));
148 }
149
150 if let Some(first_char) = name.chars().next() {
152 if !first_char.is_ascii_lowercase() {
153 return Err(format!(
154 "gear name must start with a lowercase letter, found '{first_char}'"
155 ));
156 }
157 } else {
158 return Err("gear name cannot be empty".to_owned());
160 }
161
162 if name.ends_with('-') {
164 return Err("gear name must not end with a hyphen".to_owned());
165 }
166
167 let mut prev_was_hyphen = false;
169 for ch in name.chars() {
170 if ch == '-' {
171 if prev_was_hyphen {
172 return Err("gear name must not contain consecutive hyphens".to_owned());
173 }
174 prev_was_hyphen = true;
175 } else if ch.is_ascii_lowercase() || ch.is_ascii_digit() {
176 prev_was_hyphen = false;
177 } else {
178 return Err(format!(
179 "gear name must contain only lowercase letters, digits, and hyphens, found '{ch}'"
180 ));
181 }
182 }
183
184 Ok(())
185}
186
187#[derive(Debug, Clone)]
188struct LcGearCfg {
189 entry: String, stop_timeout: Option<String>, stop_timeout_fn: Option<Ident>,
192 await_ready: bool, ready_warn_after: Option<String>, }
195
196impl Default for LcGearCfg {
197 fn default() -> Self {
198 Self {
199 entry: "serve".to_owned(),
200 stop_timeout: None,
201 stop_timeout_fn: None,
202 await_ready: false,
203 ready_warn_after: None,
204 }
205 }
206}
207
208impl Parse for GearConfig {
209 #[allow(clippy::too_many_lines)]
210 fn parse(input: ParseStream) -> syn::Result<Self> {
211 let mut name: Option<String> = None;
212 let mut deps: Vec<Ident> = Vec::new();
213 let mut caps: Vec<Capability> = Vec::new();
214 let mut ctor: Option<Expr> = None;
215 let mut client: Option<Path> = None;
216 let mut lifecycle: Option<LcGearCfg> = None;
217 let mut gts_publication: Option<gts_publication::GtsPublicationCfg> = None;
218
219 let mut seen_name = false;
220 let mut seen_deps = false;
221 let mut seen_caps = false;
222 let mut seen_ctor = false;
223 let mut seen_client = false;
224 let mut seen_lifecycle = false;
225 let mut seen_one_per_installation = false;
226
227 let punctuated: Punctuated<Meta, Token![,]> =
228 input.parse_terminated(Meta::parse, Token![,])?;
229
230 for meta in punctuated {
231 match meta {
232 Meta::NameValue(nv) if nv.path.is_ident("name") => {
233 if seen_name {
234 return Err(syn::Error::new_spanned(
235 nv.path,
236 "duplicate `name` parameter",
237 ));
238 }
239 seen_name = true;
240 match nv.value {
241 Expr::Lit(syn::ExprLit {
242 lit: Lit::Str(s), ..
243 }) => {
244 let gear_name = s.value();
245 if let Err(err) = validate_kebab_case(&gear_name) {
247 return Err(syn::Error::new_spanned(s, err));
248 }
249 name = Some(gear_name);
250 }
251 other => {
252 return Err(syn::Error::new_spanned(
253 other,
254 "name must be a string literal, e.g. name = \"my-gear\"",
255 ));
256 }
257 }
258 }
259 Meta::NameValue(nv) if nv.path.is_ident("ctor") => {
260 if seen_ctor {
261 return Err(syn::Error::new_spanned(
262 nv.path,
263 "duplicate `ctor` parameter",
264 ));
265 }
266 seen_ctor = true;
267
268 match &nv.value {
270 Expr::Lit(syn::ExprLit {
271 lit: Lit::Str(s), ..
272 }) => {
273 return Err(syn::Error::new_spanned(
274 s,
275 "ctor must be a Rust expression, not a string literal. \
276 Use: ctor = MyType::new() (with parentheses), \
277 or: ctor = Default::default()",
278 ));
279 }
280 _ => {
281 ctor = Some(nv.value.clone());
282 }
283 }
284 }
285 Meta::NameValue(nv) if nv.path.is_ident("client") => {
286 if seen_client {
287 return Err(syn::Error::new_spanned(
288 nv.path,
289 "duplicate `client` parameter",
290 ));
291 }
292 seen_client = true;
293 let value = nv.value.clone();
294 match value {
295 Expr::Path(ep) => {
296 client = Some(ep.path);
297 }
298 other => {
299 return Err(syn::Error::new_spanned(
300 other,
301 "client must be a trait path, e.g. client = crate::api::MyClient",
302 ));
303 }
304 }
305 }
306 Meta::NameValue(nv) if nv.path.is_ident("one_per_installation") => {
320 if seen_one_per_installation {
321 return Err(syn::Error::new_spanned(
322 nv.path,
323 "duplicate `one_per_installation` parameter",
324 ));
325 }
326 seen_one_per_installation = true;
327 if !matches!(
328 nv.value,
329 Expr::Lit(syn::ExprLit {
330 lit: Lit::Bool(_),
331 ..
332 })
333 ) {
334 return Err(syn::Error::new_spanned(
335 nv.value,
336 "one_per_installation must be a bool, e.g. one_per_installation = true",
337 ));
338 }
339 }
340 Meta::NameValue(nv) if nv.path.is_ident("deps") => {
341 if seen_deps {
342 return Err(syn::Error::new_spanned(
343 nv.path,
344 "duplicate `deps` parameter",
345 ));
346 }
347 seen_deps = true;
348 let value = nv.value.clone();
349 match value {
350 Expr::Array(arr) => {
351 for elem in arr.elems {
352 match elem {
353 Expr::Path(ref path) => {
354 if let Some(ident) = path.path.get_ident() {
355 deps.push(ident.clone());
356 } else {
357 return Err(syn::Error::new_spanned(
358 path,
359 "deps must be crate identifiers, e.g. deps = [authn_resolver, types_registry]",
360 ));
361 }
362 }
363 other => {
364 return Err(syn::Error::new_spanned(
365 other,
366 "deps must be crate identifiers, e.g. deps = [authn_resolver, types_registry]",
367 ));
368 }
369 }
370 }
371 }
372 other => {
373 return Err(syn::Error::new_spanned(
374 other,
375 "deps must be an array, e.g. deps = [authn_resolver, types_registry]",
376 ));
377 }
378 }
379 }
380 Meta::NameValue(nv) if nv.path.is_ident("capabilities") => {
381 if seen_caps {
382 return Err(syn::Error::new_spanned(
383 nv.path,
384 "duplicate `capabilities` parameter",
385 ));
386 }
387 seen_caps = true;
388 let value = nv.value.clone();
389 match value {
390 Expr::Array(arr) => {
391 for elem in arr.elems {
392 match elem {
393 Expr::Path(ref path) => {
394 if let Some(ident) = path.path.get_ident() {
395 caps.push(Capability::from_ident(ident)?);
396 } else {
397 return Err(syn::Error::new_spanned(
398 path,
399 "capability must be a simple identifier (db, rest, rest_host, stateful)",
400 ));
401 }
402 }
403 Expr::Lit(syn::ExprLit {
404 lit: Lit::Str(s), ..
405 }) => {
406 caps.push(Capability::from_str_lit(&s)?);
407 }
408 other => {
409 return Err(syn::Error::new_spanned(
410 other,
411 "capability must be an identifier or string literal (\"db\", \"rest\", \"rest_host\", \"stateful\")",
412 ));
413 }
414 }
415 }
416 }
417 other => {
418 return Err(syn::Error::new_spanned(
419 other,
420 "capabilities must be an array, e.g. capabilities = [db, rest]",
421 ));
422 }
423 }
424 }
425 Meta::List(list) if path_last_is(&list.path, "lifecycle") => {
427 if seen_lifecycle {
428 return Err(syn::Error::new_spanned(
429 list.path,
430 "duplicate `lifecycle(...)` parameter",
431 ));
432 }
433 seen_lifecycle = true;
434 lifecycle = Some(parse_lifecycle_list(&list)?);
435 }
436 Meta::List(list) if list.path.is_ident("gts_publication") => {
437 if gts_publication.is_some() {
438 return Err(syn::Error::new_spanned(
439 list.path,
440 "duplicate `gts_publication(...)` parameter",
441 ));
442 }
443 gts_publication = Some(gts_publication::parse(&list)?);
444 }
445 other => {
446 return Err(syn::Error::new_spanned(
447 other,
448 "unknown attribute parameter",
449 ));
450 }
451 }
452 }
453
454 let name = name.ok_or_else(|| {
455 syn::Error::new(
456 Span::call_site(),
457 "name parameter is required, e.g. #[gear(name = \"my-gear\", ...)]",
458 )
459 })?;
460
461 Ok(GearConfig {
462 name,
463 deps,
464 caps,
465 ctor,
466 client,
467 lifecycle,
468 gts_publication,
469 })
470 }
471}
472
473fn parse_lifecycle_list(list: &MetaList) -> syn::Result<LcGearCfg> {
474 let mut cfg = LcGearCfg::default();
475
476 let inner: Punctuated<Meta, Token![,]> =
477 list.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?;
478
479 for m in inner {
480 match m {
481 Meta::NameValue(MetaNameValue { path, value, .. }) if path.is_ident("entry") => {
482 if let Expr::Lit(syn::ExprLit {
483 lit: Lit::Str(s), ..
484 }) = value
485 {
486 cfg.entry = s.value();
487 } else {
488 return Err(syn::Error::new_spanned(
489 value,
490 "entry must be a string literal, e.g. entry = \"serve\"",
491 ));
492 }
493 }
494 Meta::NameValue(MetaNameValue { path, value, .. }) if path.is_ident("stop_timeout") => {
495 if let Expr::Lit(syn::ExprLit {
496 lit: Lit::Str(s), ..
497 }) = value
498 {
499 cfg.stop_timeout = Some(s.value());
500 } else {
501 return Err(syn::Error::new_spanned(
502 value,
503 "stop_timeout must be a string literal like \"45s\"",
504 ));
505 }
506 }
507 Meta::NameValue(MetaNameValue { path, value, .. })
508 if path.is_ident("stop_timeout_fn") =>
509 {
510 if let Expr::Lit(syn::ExprLit {
511 lit: Lit::Str(s), ..
512 }) = value
513 {
514 cfg.stop_timeout_fn = Some(s.parse()?);
515 } else {
516 return Err(syn::Error::new_spanned(
517 value,
518 "stop_timeout_fn must name a method in a string literal",
519 ));
520 }
521 }
522 Meta::NameValue(MetaNameValue { path, value, .. })
523 if path.is_ident("ready_warn_after") =>
524 {
525 if let Expr::Lit(syn::ExprLit {
526 lit: Lit::Str(s), ..
527 }) = value
528 {
529 cfg.ready_warn_after = Some(s.value());
530 } else {
531 return Err(syn::Error::new_spanned(
532 value,
533 "ready_warn_after must be a string literal like \"90s\"",
534 ));
535 }
536 }
537 Meta::Path(p) if p.is_ident("await_ready") => {
538 cfg.await_ready = true;
539 }
540 Meta::NameValue(MetaNameValue { path, value, .. }) if path.is_ident("await_ready") => {
541 if let Expr::Lit(syn::ExprLit {
542 lit: Lit::Bool(LitBool { value: b, .. }),
543 ..
544 }) = value
545 {
546 cfg.await_ready = b;
547 } else {
548 return Err(syn::Error::new_spanned(
549 value,
550 "await_ready must be a bool literal (true/false) or a bare flag",
551 ));
552 }
553 }
554 other => {
555 return Err(syn::Error::new_spanned(
556 other,
557 "expected lifecycle args: entry=\"...\", stop_timeout=\"...\" or stop_timeout_fn=\"...\", await_ready[=true|false], ready_warn_after=\"...\"",
558 ));
559 }
560 }
561 }
562
563 lifecycle_timeout_tokens(cfg.stop_timeout.as_deref(), cfg.stop_timeout_fn.as_ref())?;
564 validate_ready_warn_after(cfg.ready_warn_after.as_deref(), cfg.await_ready)?;
565 ready_warn_after_tokens(cfg.ready_warn_after.as_deref())?;
566 Ok(cfg)
567}
568
569#[proc_macro_attribute]
590#[allow(clippy::too_many_lines)]
591pub fn gear(attr: TokenStream, item: TokenStream) -> TokenStream {
592 let config = parse_macro_input!(attr as GearConfig);
593 let input = parse_macro_input!(item as DeriveInput);
594
595 let struct_ident = input.ident.clone();
597 let generics_clone = input.generics.clone();
598 let (impl_generics, ty_generics, where_clause) = generics_clone.split_for_impl();
599
600 let name_owned: String = config.name.clone();
601 let deps_idents: Vec<Ident> = config.deps.clone();
602 let caps_for_asserts: Vec<Capability> = config.caps.clone();
603 let caps_for_regs: Vec<Capability> = config.caps.clone();
604 let ctor_expr_opt: Option<Expr> = config.ctor.clone();
605 let client_trait_opt: Option<Path> = config.client.clone();
606 let lifecycle_cfg_opt: Option<LcGearCfg> = config.lifecycle;
607 let gts_publication_cfg = config.gts_publication;
608
609 let name_lit = LitStr::new(&name_owned, Span::call_site());
611 let deps_lits: Vec<LitStr> = deps_idents
613 .iter()
614 .map(|ident| LitStr::new(&ident.to_string().replace('_', "-"), Span::call_site()))
615 .collect();
616
617 let constructor = if let Some(expr) = &ctor_expr_opt {
619 quote! { #expr }
620 } else {
621 quote! { <#struct_ident #ty_generics as ::core::default::Default>::default() }
623 };
624
625 let mut cap_asserts = Vec::new();
627
628 cap_asserts.push(quote! {
630 const _: () = {
631 #[allow(dead_code)]
632 fn __toolkit_require_Gear_impl()
633 where
634 #struct_ident #ty_generics: ::toolkit::contracts::Gear,
635 {}
636 };
637 });
638
639 for cap in &caps_for_asserts {
640 let q = match cap {
641 Capability::Db => quote! {
642 const _: () = {
643 #[allow(dead_code)]
644 fn __toolkit_require_DatabaseCapability_impl()
645 where
646 #struct_ident #ty_generics: ::toolkit::contracts::DatabaseCapability,
647 {}
648 };
649 },
650 Capability::Rest => quote! {
651 const _: () = {
652 #[allow(dead_code)]
653 fn __toolkit_require_RestApiCapability_impl()
654 where
655 #struct_ident #ty_generics: ::toolkit::contracts::RestApiCapability,
656 {}
657 };
658 },
659 Capability::RestHost => quote! {
660 const _: () = {
661 #[allow(dead_code)]
662 fn __toolkit_require_ApiGatewayCapability_impl()
663 where
664 #struct_ident #ty_generics: ::toolkit::contracts::ApiGatewayCapability,
665 {}
666 };
667 },
668 Capability::Stateful => {
669 if lifecycle_cfg_opt.is_none() {
670 quote! {
672 const _: () = {
673 #[allow(dead_code)]
674 fn __toolkit_require_RunnableCapability_impl()
675 where
676 #struct_ident #ty_generics: ::toolkit::contracts::RunnableCapability,
677 {}
678 };
679 }
680 } else {
681 quote! {}
682 }
683 }
684 Capability::System => {
685 quote! {}
688 }
689 Capability::GrpcHub => quote! {
690 const _: () = {
691 #[allow(dead_code)]
692 fn __toolkit_require_GrpcHubCapability_impl()
693 where
694 #struct_ident #ty_generics: ::toolkit::contracts::GrpcHubCapability,
695 {}
696 };
697 },
698 Capability::Grpc => quote! {
699 const _: () = {
700 #[allow(dead_code)]
701 fn __toolkit_require_GrpcServiceCapability_impl()
702 where
703 #struct_ident #ty_generics: ::toolkit::contracts::GrpcServiceCapability,
704 {}
705 };
706 },
707 };
708 cap_asserts.push(q);
709 }
710
711 let gts_publication_items = match >s_publication_cfg {
712 Some(_) if !input.generics.params.is_empty() => {
713 return syn::Error::new_spanned(
714 &input.generics,
715 "`gts_publication(...)` is not supported on a generic gear struct",
716 )
717 .to_compile_error()
718 .into();
719 }
720 Some(_) if caps_for_asserts.contains(&Capability::System) => {
721 return syn::Error::new(
722 proc_macro2::Span::call_site(),
723 "`gts_publication(...)` is not supported on a `system` gear: the system group \
724 initializes before the GTS barrier",
725 )
726 .to_compile_error()
727 .into();
728 }
729 Some(cfg) => gts_publication::expand(cfg, &struct_ident, &name_lit),
730 None => proc_macro2::TokenStream::new(),
731 };
732 let gts_publication_registration = if gts_publication_cfg.is_some() {
733 quote! {
734 b.register_gts_publication_with_meta(#name_lit,
735 gear.clone() as ::std::sync::Arc<dyn ::toolkit::gts_publication::GtsPublicationCapability>);
736 }
737 } else {
738 proc_macro2::TokenStream::new()
739 };
740
741 let struct_name_snake = struct_ident.to_string().to_snake_case();
743 let registrator_name = format_ident!("__{}_registrator", struct_name_snake);
744
745 let mut extra_top_level = proc_macro2::TokenStream::new();
747
748 if let Some(lc) = &lifecycle_cfg_opt {
749 let entry_ident = format_ident!("{}", lc.entry);
751 let timeout_config =
752 lifecycle_timeout_tokens(lc.stop_timeout.as_deref(), lc.stop_timeout_fn.as_ref())
753 .unwrap_or_else(|e| e.to_compile_error());
754 let ready_warn_after_config = ready_warn_after_tokens(lc.ready_warn_after.as_deref())
755 .unwrap_or_else(|e| e.to_compile_error());
756 let await_ready_bool = lc.await_ready;
757
758 if await_ready_bool {
759 let ready_shim_ident =
760 format_ident!("__toolkit_run_ready_shim_for_{}", struct_name_snake);
761
762 extra_top_level.extend(quote! {
764 #[::async_trait::async_trait]
765 impl #impl_generics ::toolkit::lifecycle::Runnable for #struct_ident #ty_generics #where_clause {
766 async fn run(self: ::std::sync::Arc<Self>, cancel: ::tokio_util::sync::CancellationToken) -> ::anyhow::Result<()> {
767 let (_tx, _rx) = ::toolkit::tokio::sync::oneshot::channel::<()>();
768 let ready = ::toolkit::lifecycle::ReadySignal::from_sender(_tx);
769 self.#entry_ident(cancel, ready).await
770 }
771 }
772
773 #[doc(hidden)]
774 #[allow(dead_code, non_snake_case)]
775 fn #ready_shim_ident(
776 this: ::std::sync::Arc<#struct_ident #ty_generics>,
777 cancel: ::tokio_util::sync::CancellationToken,
778 ready: ::toolkit::lifecycle::ReadySignal,
779 ) -> ::core::pin::Pin<Box<dyn ::core::future::Future<Output = ::anyhow::Result<()>> + Send>> {
780 Box::pin(async move { this.#entry_ident(cancel, ready).await })
781 }
782 });
783
784 extra_top_level.extend(quote! {
786 impl #impl_generics #struct_ident #ty_generics #where_clause {
787 pub fn into_gear(self) -> ::toolkit::lifecycle::WithLifecycle<Self> {
789 ::toolkit::lifecycle::WithLifecycle::new_with_name(self, #name_lit)
790 #timeout_config
791 #ready_warn_after_config
792 .with_ready_mode(true, true, Some(#ready_shim_ident))
793 }
794 }
795 });
796 } else {
797 extra_top_level.extend(quote! {
799 #[::async_trait::async_trait]
800 impl #impl_generics ::toolkit::lifecycle::Runnable for #struct_ident #ty_generics #where_clause {
801 async fn run(self: ::std::sync::Arc<Self>, cancel: ::tokio_util::sync::CancellationToken) -> ::anyhow::Result<()> {
802 self.#entry_ident(cancel).await
803 }
804 }
805
806 impl #impl_generics #struct_ident #ty_generics #where_clause {
807 pub fn into_gear(self) -> ::toolkit::lifecycle::WithLifecycle<Self> {
809 ::toolkit::lifecycle::WithLifecycle::new_with_name(self, #name_lit)
810 #timeout_config
811 #ready_warn_after_config
812 .with_ready_mode(false, false, None)
813 }
814 }
815 });
816 }
817 }
818
819 let capability_registrations = caps_for_regs.iter().map(|cap| {
821 match cap {
822 Capability::Db => quote! {
823 b.register_db_with_meta(#name_lit,
824 gear.clone() as ::std::sync::Arc<dyn ::toolkit::contracts::DatabaseCapability>);
825 },
826 Capability::Rest => quote! {
827 b.register_rest_with_meta(#name_lit,
828 gear.clone() as ::std::sync::Arc<dyn ::toolkit::contracts::RestApiCapability>);
829 },
830 Capability::RestHost => quote! {
831 b.register_rest_host_with_meta(#name_lit,
832 gear.clone() as ::std::sync::Arc<dyn ::toolkit::contracts::ApiGatewayCapability>);
833 },
834 Capability::Stateful => {
835 if let Some(lc) = &lifecycle_cfg_opt {
836 let timeout_config = lifecycle_timeout_tokens(lc.stop_timeout.as_deref(), lc.stop_timeout_fn.as_ref())
837 .unwrap_or_else(|e| e.to_compile_error());
838 let ready_warn_after_config = ready_warn_after_tokens(lc.ready_warn_after.as_deref())
839 .unwrap_or_else(|e| e.to_compile_error());
840 let await_ready_bool = lc.await_ready;
841 let ready_shim_ident =
842 format_ident!("__toolkit_run_ready_shim_for_{}", struct_name_snake);
843
844 if await_ready_bool {
845 quote! {
846 let wl = ::toolkit::lifecycle::WithLifecycle::from_arc_with_name(
847 gear.clone(),
848 #name_lit,
849 )
850 #timeout_config
851 #ready_warn_after_config
852 .with_ready_mode(true, true, Some(#ready_shim_ident));
853
854 b.register_stateful_with_meta(
855 #name_lit,
856 ::std::sync::Arc::new(wl) as ::std::sync::Arc<dyn ::toolkit::contracts::RunnableCapability>
857 );
858 }
859 } else {
860 quote! {
861 let wl = ::toolkit::lifecycle::WithLifecycle::from_arc_with_name(
862 gear.clone(),
863 #name_lit,
864 )
865 #timeout_config
866 #ready_warn_after_config
867 .with_ready_mode(false, false, None);
868
869 b.register_stateful_with_meta(
870 #name_lit,
871 ::std::sync::Arc::new(wl) as ::std::sync::Arc<dyn ::toolkit::contracts::RunnableCapability>
872 );
873 }
874 }
875 } else {
876 quote! {
878 b.register_stateful_with_meta(#name_lit,
879 gear.clone() as ::std::sync::Arc<dyn ::toolkit::contracts::RunnableCapability>);
880 }
881 }
882 },
883 Capability::System => quote! {
884 b.register_system_with_meta(#name_lit,
885 gear.clone() as ::std::sync::Arc<dyn ::toolkit::contracts::SystemCapability>);
886 },
887 Capability::GrpcHub => quote! {
888 b.register_grpc_hub_with_meta(#name_lit,
889 gear.clone() as ::std::sync::Arc<dyn ::toolkit::contracts::GrpcHubCapability>);
890 },
891 Capability::Grpc => quote! {
892 b.register_grpc_service_with_meta(#name_lit,
893 gear.clone() as ::std::sync::Arc<dyn ::toolkit::contracts::GrpcServiceCapability>);
894 },
895 }
896 });
897
898 let client_code = if let Some(client_trait_path) = &client_trait_opt {
903 quote! {
904 const _: () = {
906 fn __toolkit_obj_safety<T: ?Sized + ::core::marker::Send + ::core::marker::Sync + 'static>() {}
907 let _ = __toolkit_obj_safety::<dyn #client_trait_path> as fn();
908 };
909
910 impl #impl_generics #struct_ident #ty_generics #where_clause {
911 pub const MODULE_NAME: &'static str = #name_lit;
912 }
913 }
914 } else {
915 quote! {
917 impl #impl_generics #struct_ident #ty_generics #where_clause {
918 pub const MODULE_NAME: &'static str = #name_lit;
919 }
920 }
921 };
922
923 let dep_reexports: Vec<_> = deps_idents
926 .iter()
927 .map(|crate_ident| {
928 let alias_ident = format_ident!("_gear_dep_{}", crate_ident);
929 quote! {
930 #[cfg(not(test))]
931 #[doc(hidden)]
932 pub use ::#crate_ident as #alias_ident;
933 }
934 })
935 .collect();
936
937 let expanded = quote! {
939 #input
940
941 #(#cap_asserts)*
943
944 #(#dep_reexports)*
946
947 #[doc(hidden)]
949 fn #registrator_name(b: &mut ::toolkit::registry::RegistryBuilder) {
950 use ::std::sync::Arc;
951
952 let gear: Arc<#struct_ident #ty_generics> = Arc::new(#constructor);
953
954 b.register_core_with_meta(
956 #name_lit,
957 &[#(#deps_lits),*],
958 gear.clone() as Arc<dyn ::toolkit::contracts::Gear>
959 );
960
961 #(#capability_registrations)*
963 #gts_publication_registration
964 }
965
966 ::toolkit::inventory::submit! {
967 ::toolkit::registry::Registrator(#registrator_name)
968 }
969
970 #client_code
971
972 #extra_top_level
974
975 #gts_publication_items
977 };
978
979 TokenStream::from(expanded)
980}
981
982#[derive(Debug)]
987struct LcCfg {
988 method: String,
989 stop_timeout: Option<String>,
990 stop_timeout_fn: Option<Ident>,
991 await_ready: bool,
992 ready_warn_after: Option<String>,
993}
994
995#[proc_macro_attribute]
996pub fn lifecycle(attr: TokenStream, item: TokenStream) -> TokenStream {
997 let args = parse_macro_input!(attr with Punctuated::<Meta, Token![,]>::parse_terminated);
998 let impl_item = parse_macro_input!(item as ItemImpl);
999
1000 let cfg = match parse_lifecycle_args(args) {
1001 Ok(c) => c,
1002 Err(e) => return e.to_compile_error().into(),
1003 };
1004
1005 let ty = match &*impl_item.self_ty {
1007 syn::Type::Path(TypePath { path, .. }) => path.clone(),
1008 other => {
1009 return syn::Error::new_spanned(other, "unsupported impl target")
1010 .to_compile_error()
1011 .into();
1012 }
1013 };
1014
1015 let runner_ident = format_ident!("{}", cfg.method);
1016 let mut has_runner = false;
1017 let mut takes_ready_signal = false;
1018 for it in &impl_item.items {
1019 if let ImplItem::Fn(f) = it
1020 && f.sig.ident == runner_ident
1021 {
1022 has_runner = true;
1023 if f.sig.asyncness.is_none() {
1024 return syn::Error::new_spanned(f.sig.fn_token, "runner must be async")
1025 .to_compile_error()
1026 .into();
1027 }
1028 let input_count = f.sig.inputs.len();
1029 match input_count {
1030 2 => {}
1031 3 => {
1032 if let Some(syn::FnArg::Typed(pat_ty)) = f.sig.inputs.iter().nth(2) {
1033 match &*pat_ty.ty {
1034 syn::Type::Path(tp) => {
1035 if let Some(seg) = tp.path.segments.last() {
1036 if seg.ident == "ReadySignal" {
1037 takes_ready_signal = true;
1038 } else {
1039 return syn::Error::new_spanned(
1040 &pat_ty.ty,
1041 "third parameter must be ReadySignal when await_ready=true",
1042 )
1043 .to_compile_error()
1044 .into();
1045 }
1046 }
1047 }
1048 other => {
1049 return syn::Error::new_spanned(
1050 other,
1051 "third parameter must be ReadySignal when await_ready=true",
1052 )
1053 .to_compile_error()
1054 .into();
1055 }
1056 }
1057 }
1058 }
1059 _ => {
1060 return syn::Error::new_spanned(
1061 f.sig.inputs.clone(),
1062 "invalid runner signature; expected (&self, CancellationToken) or (&self, CancellationToken, ReadySignal)",
1063 )
1064 .to_compile_error()
1065 .into();
1066 }
1067 }
1068 }
1069 }
1070 if !has_runner {
1071 return syn::Error::new(
1072 Span::call_site(),
1073 format!("runner method `{}` not found in impl", cfg.method),
1074 )
1075 .to_compile_error()
1076 .into();
1077 }
1078
1079 let timeout_config =
1081 match lifecycle_timeout_tokens(cfg.stop_timeout.as_deref(), cfg.stop_timeout_fn.as_ref()) {
1082 Ok(ts) => ts,
1083 Err(e) => return e.to_compile_error().into(),
1084 };
1085 let ready_warn_after_config = match ready_warn_after_tokens(cfg.ready_warn_after.as_deref()) {
1086 Ok(ts) => ts,
1087 Err(e) => return e.to_compile_error().into(),
1088 };
1089
1090 let ty_ident = match ty.segments.last() {
1092 Some(seg) => seg.ident.clone(),
1093 None => {
1094 return syn::Error::new_spanned(
1095 &ty,
1096 "unsupported impl target: expected a concrete type path",
1097 )
1098 .to_compile_error()
1099 .into();
1100 }
1101 };
1102 let ty_snake = ty_ident.to_string().to_snake_case();
1103
1104 let ready_shim_ident = format_ident!("__toolkit_run_ready_shim{ty_snake}");
1105 let await_ready_bool = cfg.await_ready;
1106
1107 let extra = if takes_ready_signal {
1108 quote! {
1109 #[async_trait::async_trait]
1110 impl ::toolkit::lifecycle::Runnable for #ty {
1111 async fn run(self: ::std::sync::Arc<Self>, cancel: ::tokio_util::sync::CancellationToken) -> ::anyhow::Result<()> {
1112 let (_tx, _rx) = ::toolkit::tokio::sync::oneshot::channel::<()>();
1113 let ready = ::toolkit::lifecycle::ReadySignal::from_sender(_tx);
1114 self.#runner_ident(cancel, ready).await
1115 }
1116 }
1117
1118 #[doc(hidden)]
1119 #[allow(non_snake_case, dead_code)]
1120 fn #ready_shim_ident(
1121 this: ::std::sync::Arc<#ty>,
1122 cancel: ::tokio_util::sync::CancellationToken,
1123 ready: ::toolkit::lifecycle::ReadySignal,
1124 ) -> ::core::pin::Pin<Box<dyn ::core::future::Future<Output = ::anyhow::Result<()>> + Send>> {
1125 Box::pin(async move { this.#runner_ident(cancel, ready).await })
1126 }
1127
1128 impl #ty {
1129 pub fn into_gear(self) -> ::toolkit::lifecycle::WithLifecycle<Self> {
1131 ::toolkit::lifecycle::WithLifecycle::new(self)
1132 #timeout_config
1133 #ready_warn_after_config
1134 .with_ready_mode(#await_ready_bool, true, Some(#ready_shim_ident))
1135 }
1136 }
1137 }
1138 } else {
1139 quote! {
1140 #[async_trait::async_trait]
1141 impl ::toolkit::lifecycle::Runnable for #ty {
1142 async fn run(self: ::std::sync::Arc<Self>, cancel: ::tokio_util::sync::CancellationToken) -> ::anyhow::Result<()> {
1143 self.#runner_ident(cancel).await
1144 }
1145 }
1146
1147 impl #ty {
1148 pub fn into_gear(self) -> ::toolkit::lifecycle::WithLifecycle<Self> {
1150 ::toolkit::lifecycle::WithLifecycle::new(self)
1151 #timeout_config
1152 #ready_warn_after_config
1153 .with_ready_mode(#await_ready_bool, false, None)
1154 }
1155 }
1156 }
1157 };
1158
1159 let out = quote! {
1160 #impl_item
1161 #extra
1162 };
1163 out.into()
1164}
1165
1166fn parse_lifecycle_args(args: Punctuated<Meta, Token![,]>) -> syn::Result<LcCfg> {
1167 let mut method: Option<String> = None;
1168 let mut stop_timeout = None;
1169 let mut stop_timeout_fn = None;
1170 let mut await_ready = false;
1171 let mut ready_warn_after = None;
1172
1173 for m in args {
1174 match m {
1175 Meta::NameValue(nv) if nv.path.is_ident("method") => {
1176 if let Expr::Lit(el) = nv.value {
1177 if let Lit::Str(s) = el.lit {
1178 method = Some(s.value());
1179 } else {
1180 return Err(syn::Error::new_spanned(
1181 el,
1182 "method must be a string literal",
1183 ));
1184 }
1185 } else {
1186 return Err(syn::Error::new_spanned(
1187 nv,
1188 "method must be a string literal",
1189 ));
1190 }
1191 }
1192 Meta::NameValue(nv) if nv.path.is_ident("stop_timeout") => {
1193 if let Expr::Lit(el) = nv.value {
1194 if let Lit::Str(s) = el.lit {
1195 stop_timeout = Some(s.value());
1196 } else {
1197 return Err(syn::Error::new_spanned(
1198 el,
1199 "stop_timeout must be a string literal like \"45s\"",
1200 ));
1201 }
1202 } else {
1203 return Err(syn::Error::new_spanned(
1204 nv,
1205 "stop_timeout must be a string literal like \"45s\"",
1206 ));
1207 }
1208 }
1209 Meta::NameValue(nv) if nv.path.is_ident("stop_timeout_fn") => {
1210 if let Expr::Lit(syn::ExprLit {
1211 lit: Lit::Str(s), ..
1212 }) = nv.value
1213 {
1214 stop_timeout_fn = Some(s.parse()?);
1215 } else {
1216 return Err(syn::Error::new_spanned(
1217 nv,
1218 "stop_timeout_fn must name a method in a string literal",
1219 ));
1220 }
1221 }
1222 Meta::NameValue(nv) if nv.path.is_ident("ready_warn_after") => {
1223 if let Expr::Lit(el) = nv.value {
1224 if let Lit::Str(s) = el.lit {
1225 ready_warn_after = Some(s.value());
1226 } else {
1227 return Err(syn::Error::new_spanned(
1228 el,
1229 "ready_warn_after must be a string literal like \"90s\"",
1230 ));
1231 }
1232 } else {
1233 return Err(syn::Error::new_spanned(
1234 nv,
1235 "ready_warn_after must be a string literal like \"90s\"",
1236 ));
1237 }
1238 }
1239 Meta::NameValue(nv) if nv.path.is_ident("await_ready") => {
1240 if let Expr::Lit(el) = nv.value {
1241 if let Lit::Bool(b) = el.lit {
1242 await_ready = b.value();
1243 } else {
1244 return Err(syn::Error::new_spanned(
1245 el,
1246 "await_ready must be a bool literal (true/false)",
1247 ));
1248 }
1249 } else {
1250 return Err(syn::Error::new_spanned(
1251 nv,
1252 "await_ready must be a bool literal (true/false)",
1253 ));
1254 }
1255 }
1256 Meta::Path(p) if p.is_ident("await_ready") => {
1257 await_ready = true;
1258 }
1259 other => {
1260 return Err(syn::Error::new_spanned(
1261 other,
1262 "expected named args: method=\"...\", stop_timeout=\"...\" or stop_timeout_fn=\"...\", await_ready=true|false, ready_warn_after=\"...\"",
1263 ));
1264 }
1265 }
1266 }
1267
1268 let method = method.ok_or_else(|| {
1269 syn::Error::new(
1270 Span::call_site(),
1271 "missing required arg: method=\"runner_name\"",
1272 )
1273 })?;
1274 lifecycle_timeout_tokens(stop_timeout.as_deref(), stop_timeout_fn.as_ref())?;
1275 validate_ready_warn_after(ready_warn_after.as_deref(), await_ready)?;
1276 ready_warn_after_tokens(ready_warn_after.as_deref())?;
1277 Ok(LcCfg {
1278 method,
1279 stop_timeout,
1280 stop_timeout_fn,
1281 await_ready,
1282 ready_warn_after,
1283 })
1284}
1285
1286fn lifecycle_timeout_tokens(
1287 fixed: Option<&str>,
1288 provider: Option<&Ident>,
1289) -> syn::Result<proc_macro2::TokenStream> {
1290 match (fixed, provider) {
1291 (Some(_), Some(_)) => Err(syn::Error::new(
1292 Span::call_site(),
1293 "stop_timeout and stop_timeout_fn are mutually exclusive",
1294 )),
1295 (None, Some(method)) => Ok(quote! { .with_stop_timeout_fn(|gear| gear.#method()) }),
1296 (fixed, None) => {
1297 let duration = parse_duration_tokens(fixed.unwrap_or("30s"))?;
1298 Ok(quote! { .with_stop_timeout(#duration) })
1299 }
1300 }
1301}
1302
1303fn ready_warn_after_tokens(
1306 ready_warn_after: Option<&str>,
1307) -> syn::Result<proc_macro2::TokenStream> {
1308 match ready_warn_after {
1309 None => Ok(quote! {}),
1310 Some(s) => {
1311 let duration = parse_duration_tokens(s)?;
1312 Ok(quote! { .with_ready_warn_after(#duration) })
1313 }
1314 }
1315}
1316
1317fn validate_ready_warn_after(ready_warn_after: Option<&str>, await_ready: bool) -> syn::Result<()> {
1321 if ready_warn_after.is_some() && !await_ready {
1322 return Err(syn::Error::new(
1323 Span::call_site(),
1324 "ready_warn_after requires await_ready (it bounds the readiness signal, which only applies when await_ready is set)",
1325 ));
1326 }
1327 Ok(())
1328}
1329
1330fn parse_duration_tokens(s: &str) -> syn::Result<proc_macro2::TokenStream> {
1331 let err = || {
1332 syn::Error::new(
1333 Span::call_site(),
1334 format!("invalid duration: {s}. Use e.g. \"500ms\", \"45s\", \"2m\", \"1h\""),
1335 )
1336 };
1337 if let Some(stripped) = s.strip_suffix("ms") {
1338 let v: u64 = stripped.parse().map_err(|_| err())?;
1339 Ok(quote! { ::std::time::Duration::from_millis(#v) })
1340 } else if let Some(stripped) = s.strip_suffix('s') {
1341 let v: u64 = stripped.parse().map_err(|_| err())?;
1342 Ok(quote! { ::std::time::Duration::from_secs(#v) })
1343 } else if let Some(stripped) = s.strip_suffix('m') {
1344 let v: u64 = stripped.parse().map_err(|_| err())?;
1345 Ok(quote! { ::std::time::Duration::from_secs(#v * 60) })
1346 } else if let Some(stripped) = s.strip_suffix('h') {
1347 let v: u64 = stripped.parse().map_err(|_| err())?;
1348 Ok(quote! { ::std::time::Duration::from_secs(#v * 3600) })
1349 } else {
1350 Err(err())
1351 }
1352}
1353
1354fn path_last_is(path: &syn::Path, want: &str) -> bool {
1355 path.segments.last().is_some_and(|s| s.ident == want)
1356}
1357
1358#[proc_macro_attribute]
1388pub fn grpc_client(attr: TokenStream, item: TokenStream) -> TokenStream {
1389 let config = parse_macro_input!(attr as grpc_client::GrpcClientConfig);
1390 let input = parse_macro_input!(item as DeriveInput);
1391
1392 match grpc_client::expand_grpc_client(config, input) {
1393 Ok(expanded) => TokenStream::from(expanded),
1394 Err(e) => TokenStream::from(e.to_compile_error()),
1395 }
1396}
1397
1398#[proc_macro_attribute]
1451pub fn api_dto(attr: TokenStream, item: TokenStream) -> TokenStream {
1452 let attrs = parse_macro_input!(attr with Punctuated::<Ident, Token![,]>::parse_terminated);
1453 let input = parse_macro_input!(item as DeriveInput);
1454 TokenStream::from(api_dto::expand_api_dto(&attrs, &input))
1455}
1456
1457#[proc_macro_attribute]
1500pub fn domain_model(_attr: TokenStream, item: TokenStream) -> TokenStream {
1501 let input = parse_macro_input!(item as DeriveInput);
1502 TokenStream::from(domain_model::expand_domain_model(&input))
1503}
1504
1505#[proc_macro_attribute]
1529pub fn temporary(attr: TokenStream, item: TokenStream) -> TokenStream {
1530 match temporary::expand_temporary(attr.into(), &item.into()) {
1531 Ok(tokens) => TokenStream::from(tokens),
1532 Err(err) => TokenStream::from(err.to_compile_error()),
1533 }
1534}
1535
1536#[proc_macro_derive(ExpandVars, attributes(expand_vars))]
1553pub fn derive_expand_vars(input: TokenStream) -> TokenStream {
1554 let input = parse_macro_input!(input as DeriveInput);
1555 TokenStream::from(expand_vars::derive(&input))
1556}
1557
1558#[cfg(test)]
1559mod lifecycle_timeout_tests {
1560 use super::*;
1561 use syn::parse::Parser;
1562
1563 #[test]
1564 fn rejects_fixed_and_computed_timeouts_in_both_macros() {
1565 let list: MetaList = syn::parse_quote!(lifecycle(
1566 stop_timeout = "30s",
1567 stop_timeout_fn = "shutdown_timeout"
1568 ));
1569 assert!(
1570 parse_lifecycle_list(&list)
1571 .unwrap_err()
1572 .to_string()
1573 .contains("mutually exclusive")
1574 );
1575 let args = Punctuated::<Meta, Token![,]>::parse_terminated.parse2(quote!(
1576 method = "serve",
1577 stop_timeout_fn = "shutdown_timeout",
1578 stop_timeout = "30s"
1579 ));
1580 assert!(
1581 parse_lifecycle_args(args.unwrap())
1582 .unwrap_err()
1583 .to_string()
1584 .contains("mutually exclusive")
1585 );
1586 }
1587
1588 #[test]
1589 fn parses_ready_warn_after_in_both_macros() {
1590 let list: MetaList = syn::parse_quote!(lifecycle(
1591 entry = "serve",
1592 await_ready,
1593 ready_warn_after = "30s"
1594 ));
1595 let cfg = parse_lifecycle_list(&list).unwrap();
1596 assert_eq!(cfg.ready_warn_after.as_deref(), Some("30s"));
1597
1598 let args = Punctuated::<Meta, Token![,]>::parse_terminated
1599 .parse2(quote!(
1600 method = "serve",
1601 await_ready = true,
1602 ready_warn_after = "90s"
1603 ))
1604 .unwrap();
1605 let cfg = parse_lifecycle_args(args).unwrap();
1606 assert_eq!(cfg.ready_warn_after.as_deref(), Some("90s"));
1607 }
1608
1609 #[test]
1610 fn rejects_ready_warn_after_without_await_ready_in_both_macros() {
1611 let list: MetaList =
1615 syn::parse_quote!(lifecycle(entry = "serve", ready_warn_after = "30s"));
1616 assert!(
1617 parse_lifecycle_list(&list)
1618 .unwrap_err()
1619 .to_string()
1620 .contains("ready_warn_after requires await_ready")
1621 );
1622
1623 let args = Punctuated::<Meta, Token![,]>::parse_terminated
1624 .parse2(quote!(method = "serve", ready_warn_after = "90s"))
1625 .unwrap();
1626 assert!(
1627 parse_lifecycle_args(args)
1628 .unwrap_err()
1629 .to_string()
1630 .contains("ready_warn_after requires await_ready")
1631 );
1632 }
1633
1634 #[test]
1635 fn rejects_non_string_ready_warn_after_in_both_macros() {
1636 let list: MetaList = syn::parse_quote!(lifecycle(entry = "serve", ready_warn_after = 30));
1637 assert!(
1638 parse_lifecycle_list(&list)
1639 .unwrap_err()
1640 .to_string()
1641 .contains("ready_warn_after must be a string literal")
1642 );
1643
1644 for tokens in [
1646 quote!(method = "serve", ready_warn_after = 30),
1647 quote!(
1648 method = "serve",
1649 ready_warn_after = std::time::Duration::from_secs(30)
1650 ),
1651 ] {
1652 let args = Punctuated::<Meta, Token![,]>::parse_terminated
1653 .parse2(tokens)
1654 .unwrap();
1655 assert!(
1656 parse_lifecycle_args(args)
1657 .unwrap_err()
1658 .to_string()
1659 .contains("ready_warn_after must be a string literal")
1660 );
1661 }
1662 }
1663}