Skip to main content

toolkit_macros/
lib.rs

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
12/// Implementation of the `api_dto` attribute macro.
13mod api_dto;
14mod domain_model;
15mod expand_vars;
16mod grpc_client;
17mod gts_publication;
18mod temporary;
19/// Implementation of the `temporary` attribute macro.
20mod utils;
21
22/// Configuration parsed from #[gear(...)] attribute
23struct GearConfig {
24    name: String,
25    deps: Vec<Ident>,
26    caps: Vec<Capability>,
27    ctor: Option<Expr>,           // arbitrary constructor expression
28    client: Option<Path>,         // trait path for client DX helpers
29    lifecycle: Option<LcGearCfg>, // optional lifecycle config (on type)
30    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) // Only suggest if reasonably similar
60            .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
125/// Validates that a gear name follows kebab-case naming convention.
126///
127/// # Rules
128/// - Must contain only lowercase letters (a-z), digits (0-9), and hyphens (-)
129/// - Must start with a lowercase letter
130/// - Must not end with a hyphen
131/// - Must not contain consecutive hyphens
132/// - Must not contain underscores (use hyphens instead)
133///
134/// # Examples
135/// Valid: "file-parser", "api-gateway", "simple-user-settings", "types-registry"
136/// Invalid: "`file_parser`" (underscores), "`FileParser`" (uppercase), "-parser" (starts with hyphen)
137fn 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    // Check for underscores (common mistake)
143    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    // Must start with a lowercase letter
151    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        // This should never happen due to the empty check above
159        return Err("gear name cannot be empty".to_owned());
160    }
161
162    // Must not end with hyphen
163    if name.ends_with('-') {
164        return Err("gear name must not end with a hyphen".to_owned());
165    }
166
167    // Check for invalid characters and consecutive hyphens
168    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,                // entry method name (e.g., "serve")
190    stop_timeout: Option<String>, // human duration (e.g., "30s")
191    stop_timeout_fn: Option<Ident>,
192    await_ready: bool,                // require ReadySignal gating
193    ready_warn_after: Option<String>, // human duration bounding the ready signal
194}
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                            // Validate kebab-case format
246                            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                    // Reject string literals with a clear message.
269                    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                // `one_per_installation = <bool>`: this gear may exist only once in
307                // a running installation.
308                //
309                // Validated here and deliberately not stored. There is nothing
310                // for the runtime to do with it: a process can refuse a second
311                // `rest_host` because it can see its own gears, and no process
312                // can see another, so an installation-wide claim has no runtime
313                // vantage point. What acts on it is composition tooling, which
314                // reads this attribute's source rather than this macro's output.
315                //
316                // So the macro's job here is to make a typo a compile error
317                // instead of a silently ignored argument -- which is what the
318                // fallthrough below would otherwise make it.
319                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                // Accept `lifecycle(...)` and also namespaced like `toolkit::gear::lifecycle(...)`
426                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/// Main #[gear] attribute macro
570///
571/// `ctor` must be a Rust expression that evaluates to the gear instance,
572/// e.g. `ctor = MyGear::new()` or `ctor = Default::default()`.
573///
574/// # Gear dependencies (`deps`)
575///
576/// `deps` lists the **crate identifiers** (`snake_case`) of gears that this gear
577/// depends on.  The runtime gear name is derived by replacing underscores with
578/// hyphens (`authn_resolver` → `"authn-resolver"`), which matches the universal
579/// convention that `lib-name == gear-name` across the workspace.
580///
581/// The macro generates hidden `pub use` re-exports so the linker keeps each
582/// dependency's `inventory::submit!` registration alive.  Because these
583/// re-exports only exist in macro-expanded code, `cargo-shear` cannot see
584/// them and will flag the dependency crates as unused.
585///
586/// **When adding a new gear dependency** you must also add the crate name to
587/// the `[workspace.metadata.cargo-shear] ignored` list in the workspace
588/// `Cargo.toml`, otherwise the `shear` CI job will fail.
589#[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    // --- Clone all needed pieces early to avoid use-after-move issues ---
596    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    // Prepare string literals for name/deps
610    let name_lit = LitStr::new(&name_owned, Span::call_site());
611    // Derive runtime dep names from crate identifiers: authn_resolver -> "authn-resolver"
612    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    // Constructor expression (provided or Default::default())
618    let constructor = if let Some(expr) = &ctor_expr_opt {
619        quote! { #expr }
620    } else {
621        // Use `<T as Default>::default()` so generics/where-clause are honored.
622        quote! { <#struct_ident #ty_generics as ::core::default::Default>::default() }
623    };
624
625    // Compile-time capability assertions (no calls in consts)
626    let mut cap_asserts = Vec::new();
627
628    // Always assert Gear is implemented
629    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                    // Only require direct RunnableCapability impl when lifecycle(...) is NOT used.
671                    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                // Selects the system group; the registration below requires
686                // `SystemCapability`.
687                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 &gts_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    // Registrator name (avoid lowercasing to reduce collisions)
742    let struct_name_snake = struct_ident.to_string().to_snake_case();
743    let registrator_name = format_ident!("__{}_registrator", struct_name_snake);
744
745    // === Top-level extras (impl Runnable + optional ready shim) ===
746    let mut extra_top_level = proc_macro2::TokenStream::new();
747
748    if let Some(lc) = &lifecycle_cfg_opt {
749        // If the type declares lifecycle(...), we generate Runnable at top-level.
750        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            // Runnable calls entry(cancel, ready). Shim is used by WithLifecycle in ready mode.
763            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            // Convenience `into_gear()` API.
785            extra_top_level.extend(quote! {
786                impl #impl_generics #struct_ident #ty_generics #where_clause {
787                    /// Wrap this instance into a stateful gear with lifecycle configuration.
788                    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            // No ready gating: Runnable calls entry(cancel).
798            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                    /// Wrap this instance into a stateful gear with lifecycle configuration.
808                    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    // Capability registrations (builder API), with special handling for stateful + lifecycle
820    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                    // Alternative path: the type itself must implement RunnableCapability
877                    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    // ClientHub DX helpers (optional)
899    // Note: The `client` parameter now only triggers compile-time trait checks.
900    // For client registration/access, use `hub.register::<dyn Trait>(client)` and
901    // `hub.get::<dyn Trait>()` directly, or provide helpers in your *-sdk crate.
902    let client_code = if let Some(client_trait_path) = &client_trait_opt {
903        quote! {
904            // Compile-time trait checks: object-safe + Send + Sync + 'static
905            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        // Even without a client trait, expose MODULE_NAME for ergonomics.
916        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    // Generate re-exports for gear dependencies so their `inventory::submit!`
924    // registrations survive linking when this gear is pulled in transitively.
925    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    // Final expansion:
938    let expanded = quote! {
939        #input
940
941        // Compile-time capability assertions (better errors if trait impls are missing)
942        #(#cap_asserts)*
943
944        // Re-export gear dependencies to force-link their inventory registrations
945        #(#dep_reexports)*
946
947        // Registrator that targets the *builder*, not the final registry
948        #[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            // register core with metadata (name + deps)
955            b.register_core_with_meta(
956                #name_lit,
957                &[#(#deps_lits),*],
958                gear.clone() as Arc<dyn ::toolkit::contracts::Gear>
959            );
960
961            // capabilities
962            #(#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        // Top-level extras for lifecycle-enabled types (impl Runnable, ready shim, into_gear)
973        #extra_top_level
974
975        // GTS publication capability (`gts_publication(...)`)
976        #gts_publication_items
977    };
978
979    TokenStream::from(expanded)
980}
981
982// ============================================================================
983// Lifecycle Macro (impl-block attribute) — still supported for opt-in usage
984// ============================================================================
985
986#[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    // Extract impl type ident
1006    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    // Fixed timeout or a provider evaluated at stop
1080    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    // Generated additions (outside of impl-block)
1091    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                /// Converts this value into a stateful gear wrapper with configured stop-timeout.
1130                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                /// Converts this value into a stateful gear wrapper with configured stop-timeout.
1149                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
1303/// Builder tokens for a per-gear readiness warning period. Emits nothing when
1304/// unset, so the lifecycle's `DEFAULT_READY_WARN_AFTER` applies.
1305fn 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
1317/// `ready_warn_after` only bounds the readiness-signal wait, which exists only
1318/// under `await_ready`; without it the value is silently dropped, so reject it at
1319/// compile time instead of expanding to a no-op.
1320fn 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// ============================================================================
1359// Client Generation Macros
1360// ============================================================================
1361
1362/// Generate a gRPC client that wraps a tonic-generated service client
1363///
1364/// This macro generates a client struct that implements an API trait by delegating
1365/// to a tonic gRPC client, converting between domain types and protobuf messages.
1366///
1367/// # Example
1368///
1369/// ```ignore
1370/// #[toolkit::grpc_client(
1371///     api = "crate::contracts::UsersApi",
1372///     tonic = "toolkit_users_v1::users_service_client::UsersServiceClient<tonic::transport::Channel>",
1373///     package = "toolkit.users.v1"
1374/// )]
1375/// pub struct UsersGrpcClient;
1376/// ```
1377///
1378/// This generates:
1379/// - A struct wrapping the tonic client
1380/// - An async `connect(uri)` method
1381/// - A `from_channel(Channel)` constructor
1382/// - Validation that the client implements the API trait
1383///
1384/// Note: The actual trait implementation must be provided manually, as procedural
1385/// macros cannot introspect trait methods from external gears at compile time.
1386/// Each method should convert requests/responses using `.into()`.
1387#[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/// Generates API DTO (Data Transfer Object) boilerplate for REST API types.
1399///
1400/// This macro automatically derives the necessary traits and attributes for types
1401/// used in REST API requests and responses, ensuring they follow API conventions.
1402///
1403/// # Arguments
1404///
1405/// - `request` - Marks the type as a request DTO (adds `Deserialize` and `RequestApiDto`)
1406/// - `response` - Marks the type as a response DTO (adds `Serialize` and `ResponseApiDto`)
1407///
1408/// At least one of `request` or `response` must be specified. Both can be used together
1409/// for types that serve as both request and response DTOs.
1410///
1411/// # Generated Code
1412///
1413/// The macro generates:
1414/// - `#[derive(serde::Serialize)]` if `response` is specified
1415/// - `#[derive(serde::Deserialize)]` if `request` is specified
1416/// - `#[derive(utoipa::ToSchema)]` for `OpenAPI` schema generation
1417/// - `#[serde(rename_all = "snake_case")]` to enforce `snake_case` field naming
1418/// - `impl RequestApiDto` if `request` is specified
1419/// - `impl ResponseApiDto` if `response` is specified
1420///
1421/// # Examples
1422///
1423/// ```ignore
1424/// // Request-only DTO
1425/// #[api_dto(request)]
1426/// pub struct CreateUserRequest {
1427///     pub user_name: String,
1428///     pub email: String,
1429/// }
1430///
1431/// // Response-only DTO
1432/// #[api_dto(response)]
1433/// pub struct UserResponse {
1434///     pub id: String,
1435///     pub user_name: String,
1436/// }
1437///
1438/// // Both request and response
1439/// #[api_dto(request, response)]
1440/// pub struct UserDto {
1441///     pub id: String,
1442///     pub user_name: String,
1443/// }
1444/// ```
1445///
1446/// # Field Naming
1447///
1448/// All fields are automatically converted to `snake_case` in JSON serialization,
1449/// regardless of the Rust field name.
1450#[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/// Marks a struct or enum as a domain model, enforcing DDD boundaries at compile time.
1458///
1459/// This macro:
1460/// - Implements `DomainModel` for the type
1461/// - Validates at compile-time that fields do not use forbidden infrastructure types
1462///
1463/// # Usage
1464///
1465/// ```ignore
1466/// // Note: This example requires `toolkit` crate which is not available in proc-macro doctest context
1467/// use toolkit_macros::domain_model;
1468///
1469/// #[domain_model]
1470/// pub struct User {
1471///     pub id: i64,
1472///     pub email: String,
1473///     pub active: bool,
1474/// }
1475/// ```
1476///
1477/// # Compile-Time Enforcement
1478///
1479/// If any field uses an infrastructure type (e.g., `http::StatusCode`, `sqlx::Pool`),
1480/// the code will fail to compile with a clear error message:
1481///
1482/// ```compile_fail
1483/// use toolkit_macros::domain_model;
1484///
1485/// #[domain_model]
1486/// pub struct BadModel {
1487///     pub status: http::StatusCode,  // ERROR: forbidden crate 'http'
1488/// }
1489/// ```
1490///
1491/// # Forbidden Types
1492///
1493/// The macro blocks types from infrastructure crates:
1494/// - Database: `sqlx::*`, `sea_orm::*`
1495/// - HTTP/Web: `http::*`, `axum::*`, `hyper::*`
1496/// - External clients: `reqwest::*`, `tonic::*`
1497/// - File system: `std::fs::*`, `tokio::fs::*`
1498/// - Database-specific names: `PgPool`, `MySqlPool`, `SqlitePool`, `DatabaseConnection`
1499#[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/// Marks an item as a temporary stand-in, tracked by a follow-up issue.
1506///
1507/// No-op at runtime: expands to the item unchanged plus an injected `#[doc]`
1508/// line, so it's both greppable (`grep -rn "TEMPORARY("`) and visible in
1509/// rustdoc/IDE hover. Applies to any item - struct, enum, impl block, fn.
1510///
1511/// # Usage
1512///
1513/// ```ignore
1514/// use toolkit_macros::temporary;
1515///
1516/// #[temporary(
1517///     tracking = "gears-rust#4347",
1518///     reason = "in-memory stand-in until the real storage backend lands"
1519/// )]
1520/// pub struct InMemoryFooRepo {
1521///     // ...
1522/// }
1523/// ```
1524///
1525/// Both `tracking` (`<repo>#<issue-number>`, e.g. `gears-rust#4347` or
1526/// `cargo-gears#89`) and `reason` are required and fail to compile if
1527/// missing, empty, or malformed.
1528#[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/// Derive macro that implements [`toolkit::var_expand::ExpandVars`].
1537///
1538/// Mark individual `String` or `Option<String>` fields with `#[expand_vars]`
1539/// to have `${VAR}` placeholders expanded from environment variables when
1540/// `expand_vars()` is called.
1541///
1542/// ```ignore
1543/// #[derive(Deserialize, Default, ExpandVars)]
1544/// pub struct MyConfig {
1545///     #[expand_vars]
1546///     pub api_key: String,
1547///     #[expand_vars]
1548///     pub endpoint: Option<String>,
1549///     pub retries: u32, // not expanded
1550/// }
1551/// ```
1552#[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        // `ready_warn_after` only bounds the readiness-signal wait, which exists
1612        // only under `await_ready`; without it the value would silently expand to
1613        // a no-op, so it must be a compile error.
1614        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        // A non-string literal and a non-literal expression both fail.
1645        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}