Skip to main content

plexus_macros/
lib.rs

1//! # plexus-macros
2//!
3//! Procedural macros for **Plexus RPC** activations. Your Rust function
4//! signature IS the schema — the macros extract method names, parameter
5//! types, return types, doc comments, deprecation metadata, child routing,
6//! and typed request extraction from the source.
7//!
8//! See the crate-level [`README`](https://github.com/hypermemetic/plexus-macros/blob/main/README.md)
9//! for a comprehensive example covering every option, a deep-dive on
10//! request forwarding (`PlexusRequest` + `request = ...`), and a
11//! per-macro reference.
12//!
13//! # Quick example
14//!
15//! ```ignore
16//! use futures::Stream;
17//! use async_stream::stream;
18//! use plexus_macros::PlexusRequest;
19//!
20//! #[derive(PlexusRequest)]
21//! pub struct BashRequest {
22//!     #[from_cookie("access_token")]
23//!     auth_token: String,
24//! }
25//!
26//! pub struct Bash;
27//!
28//! #[plexus_macros::activation(            // namespace "bash", implicitly
29//!     version = "1.0.0",
30//!     description = "Execute bash commands and stream output",
31//!     request = BashRequest,
32//! )]
33//! impl Bash {
34//!     /// Execute a bash command and stream output.
35//!     #[plexus_macros::method]
36//!     async fn execute(
37//!         &self,
38//!         command: String,
39//!         #[activation_param] auth_token: String,
40//!     ) -> impl Stream<Item = String> + Send + 'static {
41//!         let _ = (command, auth_token);
42//!         stream! { yield "ok".into(); }
43//!     }
44//! }
45//! ```
46//!
47//! # Macros at a glance
48//!
49//! | Macro | Purpose |
50//! |---|---|
51//! | `#[plexus_macros::activation]` | Turn an `impl` block into a Plexus RPC activation — and, with `client`, emit its typed client. |
52//! | `#[plexus_macros::method]` | Mark a method as an RPC endpoint. |
53//! | `#[plexus_macros::child]` | Register a child activation for `ChildRouter` dispatch. |
54//! | `#[plexus_macros::removed_in]` | Companion to `#[deprecated]` carrying the removal version. |
55//! | `#[derive(PlexusRequest)]` | Typed extraction from `RawRequestContext`. |
56//! | `#[derive(HandleEnum)]` | Type-safe handle enums for an activation. |
57//! | `#[derive(plexus_macros::Deserialize)]` | An internally tagged event's `Deserialize`, its `type` read first (serde's `Deserialize` otherwise). |
58//!
59//! # A method's return type is its contract (0.7)
60//!
61//! | signature | cardinality | schema `returns` / `error` / `progress` |
62//! |---|---|---|
63//! | `-> T` | one | T / — / — |
64//! | `-> Result<T, E>` | one | T / E / — |
65//! | `-> impl Stream<Item = T>` | many | T / — / — |
66//! | `-> impl Stream<Item = Result<T, E>>` | many | T / E / — |
67//! | `-> impl Stream<Item = Progress<T, P>>` | many | T / — / P |
68//! | `-> impl Stream<Item = Result<Progress<T, P>, E>>` | many | T / E / P |
69//!
70//! A Result item travels as data, `{"ok": t}` or `{"err": e}`; a
71//! `Progress::Update(p)` as a progress frame. The namespace is the stem of
72//! `impl FooActivation` (MACRO-13; `namespace = "..."` overrides it).
73//! `#[method(returns(..))]` and `#[derive(StreamEvent)]` are gone, and
74//! `#[method(streaming)]` is a deprecated no-op on a stream form. See the
75//! README's per-macro reference.
76//!
77//! Deprecated surfaces still accepted: `#[hub_methods]`, `#[hub_method]`, the
78//! `hub` and `children = [...]` flags on `#[activation]`. See the migration
79//! section of the README.
80//!
81//! ## Crate version (UMB-2)
82//!
83//! This crate is `proc-macro = true`, which means it can only export macro
84//! attributes — `pub const VERSION` etc. are forbidden by the compiler. The
85//! `plexus-rpc` umbrella reads `plexus-macros`'s version via a build-time
86//! environment variable populated from `Cargo.toml`'s dependency pin
87//! (see `plexus-rpc/build.rs`).
88
89mod codegen;
90mod credential;
91mod handle_enum;
92mod parse;
93mod request;
94mod type_first;
95
96
97use codegen::generate_all;
98use parse::HubMethodsAttrs;
99use proc_macro::TokenStream;
100use proc_macro2::TokenStream as TokenStream2;
101use quote::{format_ident, quote};
102use syn::{
103    parse::{Parse, ParseStream},
104    parse_macro_input, punctuated::Punctuated, Expr, ExprLit, FnArg, ItemFn, ItemImpl, Lit, Meta,
105    MetaNameValue, Pat, ReturnType, Token, Type,
106};
107
108/// Parsed attributes for hub_method (standalone version)
109struct HubMethodAttrs {
110    name: Option<String>,
111    /// Explicit description from `description = "..."`. When `Some`, this wins over
112    /// `///` doc comments. When `None`, doc comments are used as the default.
113    description: Option<String>,
114    /// Base crate path for imports (default: "crate")
115    crate_path: String,
116}
117
118impl Parse for HubMethodAttrs {
119    fn parse(input: ParseStream) -> syn::Result<Self> {
120        let mut name = None;
121        let mut description: Option<String> = None;
122        let mut crate_path = "crate".to_string();
123
124        if !input.is_empty() {
125            let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;
126
127            for meta in metas {
128                // RETURNS-8: the removed attributes fail here too, not only
129                // inside `#[activation]`.
130                match &meta {
131                    Meta::List(list) if list.path.is_ident("returns") => {
132                        return Err(syn::Error::new_spanned(&list.path, parse::RETURNS_REMOVED));
133                    }
134                    _ => {}
135                }
136                if let Meta::NameValue(MetaNameValue { path, value, .. }) = meta {
137                    if path.is_ident("name") {
138                        if let Expr::Lit(ExprLit {
139                            lit: Lit::Str(s), ..
140                        }) = value
141                        {
142                            name = Some(s.value());
143                        }
144                    } else if path.is_ident("description") {
145                        if let Expr::Lit(ExprLit {
146                            lit: Lit::Str(s), ..
147                        }) = value
148                        {
149                            description = Some(s.value());
150                        }
151                    } else if path.is_ident("crate_path") {
152                        if let Expr::Lit(ExprLit {
153                            lit: Lit::Str(s), ..
154                        }) = value
155                        {
156                            crate_path = s.value();
157                        }
158                    }
159                }
160            }
161        }
162
163        Ok(HubMethodAttrs { name, description, crate_path })
164    }
165}
166
167/// Attribute macro for individual methods within a `#[plexus::activation]` impl block.
168///
169/// # Example
170///
171/// ```ignore
172/// #[plexus::activation]                    // namespace "bash", implicitly
173/// impl Bash {
174///     /// Execute a bash command
175///     #[plexus::method]
176///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> {
177///         // ...
178///     }
179/// }
180/// ```
181///
182/// # The return type is the contract (RETURNS-8)
183///
184/// Six forms: `-> T`, `-> Result<T, E>`, `-> impl Stream<Item = T>`,
185/// `-> impl Stream<Item = Result<T, E>>`, `-> impl Stream<Item = Progress<T,
186/// P>>`, `-> impl Stream<Item = Result<Progress<T, P>, E>>`. A plain return
187/// yields one item, `impl Stream` many; `Result` and `Progress` are
188/// recognised by name. Any other return type is a compile error that lists
189/// the six. `returns(..)` is removed (a compile error); `streaming` is a
190/// deprecated no-op on a stream form and an error on a one-item one.
191///
192/// # Authorization arguments (R-1 / AUTHZ-CORE-2)
193///
194/// - `scope = "..."` — explicit required scope, emitted into the generated
195///   `MethodSchema.requires_credential`. Repeatable: `scope = "x.y",
196///   scope = "x.z"` means the caller must satisfy **ALL** listed scopes
197///   (conjunction — AND, not OR). Literals are validated at compile time
198///   against the AUTHZ-CORE-4 scope grammar (dot-separated `[a-z][a-z0-9_]*`
199///   segments, optional trailing `.*` segment wildcard, or bare `*`).
200/// - `input_window = N` (BIDIR-6) — on a method with an `Input<T>` parameter,
201///   the credit it grants (default 64). `input_max_buffered = N`: the bytes
202///   held past which it grants no credit until drained (default 64 MiB). `input_max_items = N`,
203///   `input_max_bytes = N`: limits over the call's life, none unless given.
204///   An `Input<T>` is at most one, top-level, and not one of the params:
205///   `MethodSchema.input` is `T`'s schema, and the client takes a stream.
206/// - `public` — the method is exempt from the default-deny gate; emitted as
207///   `MethodSchema.public = true`. Mixing `public` with `scope = "..."` is a
208///   compile error (a public method has no required scope to enforce).
209/// - Neither — the implicit `<activation>.<method>` scope rule applies at
210///   registry-build time (AUTHZ-CORE-4); the schema carries no
211///   `requires_credential` for the implicit case.
212#[proc_macro_attribute]
213pub fn method(attr: TokenStream, item: TokenStream) -> TokenStream {
214    let args = parse_macro_input!(attr as HubMethodAttrs);
215    let input_fn = parse_macro_input!(item as ItemFn);
216
217    match hub_method_impl(args, input_fn) {
218        Ok(tokens) => tokens.into(),
219        Err(e) => e.to_compile_error().into(),
220    }
221}
222
223/// Deprecated: use `plexus::method` instead.
224#[deprecated(since = "0.5.0", note = "Use `plexus::method` instead")]
225#[proc_macro_attribute]
226pub fn hub_method(attr: TokenStream, item: TokenStream) -> TokenStream {
227    method(attr, item)
228}
229
230/// Attribute macro for individual **child** methods within a
231/// `#[plexus_macros::activation]` impl block.
232///
233/// Two method shapes are accepted:
234///
235/// | Shape | Role | Example |
236/// |---|---|---|
237/// | `fn NAME(&self) -> Child` (no args) | Static child — routing name is the method name | `fn mercury(&self) -> Mercury` |
238/// | `fn NAME(&self, name: &str) -> Option<Child>` (sync or async) | Dynamic fallback dispatcher | `fn planet(&self, name: &str) -> Option<Planet>` |
239///
240/// The enclosing `#[plexus_macros::activation]` macro collects all `#[child]`
241/// methods and generates a `ChildRouter` impl whose `get_child(name)`
242/// dispatches over them. `#[child]` methods are **not** exposed as Plexus RPC
243/// methods — they contribute only to `ChildRouter` routing.
244///
245/// # Example
246///
247/// ```ignore
248/// #[plexus_macros::activation(namespace = "solar")]
249/// impl Solar {
250///     #[plexus_macros::child]
251///     fn mercury(&self) -> Mercury { self.mercury.clone() }
252///
253///     #[plexus_macros::child]
254///     async fn planet(&self, name: &str) -> Option<Planet> {
255///         self.lookup_planet(name).await
256///     }
257/// }
258/// ```
259///
260/// # How the child inherits its caller (MACRO-20)
261///
262/// `forward = "same_service" | "identity_only" | "pass_through" | "anonymous"`
263/// picks the policy the emitted `ChildRouter::forward_policy_for` hands
264/// the child. A static child defaults to `same_service`: the same service as
265/// its parent, it keeps the caller whole (principal stamp, session,
266/// ceiling). Write `#[plexus_macros::child(forward = "identity_only")]` for a
267/// deputy that must not see the caller's session. A dynamic child keeps the
268/// framework default (`IdentityOnly`) unless it names one.
269///
270/// Used standalone (outside an `#[activation]` block) this attribute is a
271/// no-op that returns the function unchanged.
272#[proc_macro_attribute]
273pub fn child(_attr: TokenStream, item: TokenStream) -> TokenStream {
274    // Outside of #[plexus_macros::activation] this attribute does nothing;
275    // the activation macro strips it and collects the method into the
276    // generated ChildRouter impl.
277    item
278}
279
280/// Companion attribute to Rust's built-in `#[deprecated]` for carrying a
281/// `removed_in = "VERSION"` hint that rustc doesn't recognize.
282///
283/// Rust's `#[deprecated(since = "X", note = "Y")]` supports only `since` and
284/// `note`. This companion attribute supplies the removal version that the
285/// `plexus-macros` codegen folds into the method's `DeprecationInfo.removed_in`
286/// field on the emitted `MethodSchema`.
287///
288/// # Example
289///
290/// ```ignore
291/// #[deprecated(since = "0.5", note = "use `new_method` instead")]
292/// #[plexus_macros::removed_in("0.6")]
293/// #[plexus_macros::method]
294/// async fn legacy(&self) -> impl Stream<Item = String> + Send + 'static {
295///     // ...
296/// }
297/// ```
298///
299/// # Requirements
300///
301/// `#[plexus_macros::removed_in]` is only meaningful when paired with
302/// `#[deprecated]`. The `#[plexus_macros::activation]` macro emits a compile
303/// error when it encounters `#[removed_in]` on a method that doesn't also
304/// carry `#[deprecated]`.
305///
306/// As a standalone attribute (outside an `#[activation]` block) this is a
307/// no-op that returns the item unchanged — the activation macro parses and
308/// strips it during codegen.
309#[proc_macro_attribute]
310pub fn removed_in(attr: TokenStream, item: TokenStream) -> TokenStream {
311    // When `#[plexus_macros::removed_in("X")]` is placed OUTSIDE
312    // `#[plexus_macros::activation(...)]` on the same impl block, the
313    // `removed_in` proc macro runs BEFORE the activation macro (outer
314    // attrs expand first), so a naive no-op implementation would consume
315    // the attribute before the activation macro ever sees it.
316    //
317    // Workaround: emit a synthetic `#[doc(hidden)]` marker attribute on
318    // the item's attr list that encodes the removed_in value. The
319    // activation / method codegen scans for this marker as an equivalent
320    // signal to the companion attribute and uses it to populate
321    // `DeprecationInfo.removed_in`.
322    //
323    // Stable rustc treats `#[doc(hidden)]` as a regular doc attribute and
324    // the sentinel payload rides along in the same literal string.
325    let attr_str: String = match syn::parse::<syn::LitStr>(attr.clone()) {
326        Ok(s) => s.value(),
327        Err(_) => {
328            // Not a bare string literal — just let the item pass through
329            // and let the activation/method layer produce the proper error.
330            return item;
331        }
332    };
333    let marker = format!("__plexus_removed_in:{}", attr_str);
334    let item_ts: proc_macro2::TokenStream = item.into();
335    let marker_lit = proc_macro2::Literal::string(&marker);
336    let out = quote::quote! {
337        #[doc(hidden)]
338        #[doc = #marker_lit]
339        #item_ts
340    };
341    out.into()
342}
343
344fn hub_method_impl(args: HubMethodAttrs, input_fn: ItemFn) -> syn::Result<TokenStream2> {
345    // Extract method name (from attr or function name)
346    let method_name = args
347        .name
348        .unwrap_or_else(|| input_fn.sig.ident.to_string());
349
350    // Resolve description: explicit `description = "..."` wins over `///` doc
351    // comments; if neither is present, description is the empty string.
352    let description = match args.description {
353        Some(explicit) => explicit,
354        None => extract_doc_comment(&input_fn),
355    };
356
357    // Extract input type from first parameter (if any)
358    let input_type = extract_input_type(&input_fn)?;
359
360    // Extract return type
361    let return_type = extract_return_type(&input_fn)?;
362
363    // Function name for the schema function
364    let fn_name = &input_fn.sig.ident;
365    let schema_fn_name = format_ident!("{}_schema", fn_name);
366
367    // Parse crate path
368    let crate_path: syn::Path = syn::parse_str(&args.crate_path)
369        .map_err(|e| syn::Error::new_spanned(&input_fn.sig, format!("Invalid crate_path: {}", e)))?;
370
371    // Generate the schema function
372    let schema_fn = generate_schema_fn(
373        &schema_fn_name,
374        &method_name,
375        &description,
376        input_type.as_ref(),
377        &return_type,
378        &crate_path,
379    );
380
381    // Return the original function plus the schema function
382    Ok(quote! {
383        #input_fn
384
385        #schema_fn
386    })
387}
388
389fn extract_doc_comment(input_fn: &ItemFn) -> String {
390    // Delegate to the shared helper so the standalone `#[method]` macro path
391    // follows the same doc-comment extraction rule as the in-activation path:
392    // lines joined with '\n', common leading whitespace stripped.
393    parse::extract_doc_description(&input_fn.attrs).unwrap_or_default()
394}
395
396fn extract_input_type(input_fn: &ItemFn) -> syn::Result<Option<Type>> {
397    // Skip self parameter, get first real parameter
398    for arg in &input_fn.sig.inputs {
399        match arg {
400            FnArg::Receiver(_) => continue, // Skip &self
401            FnArg::Typed(pat_type) => {
402                // Skip context-like parameters
403                if let Pat::Ident(ident) = &*pat_type.pat {
404                    let name = ident.ident.to_string();
405                    if name == "ctx" || name == "context" || name == "self_" {
406                        continue;
407                    }
408                }
409                return Ok(Some((*pat_type.ty).clone()));
410            }
411        }
412    }
413
414    Ok(None)
415}
416
417fn extract_return_type(input_fn: &ItemFn) -> syn::Result<Type> {
418    match &input_fn.sig.output {
419        ReturnType::Default => Err(syn::Error::new_spanned(
420            &input_fn.sig,
421            "hub_method requires a return type",
422        )),
423        ReturnType::Type(_, ty) => Ok((*ty.clone()).clone()),
424    }
425}
426
427fn generate_schema_fn(
428    fn_name: &syn::Ident,
429    method_name: &str,
430    description: &str,
431    input_type: Option<&Type>,
432    return_type: &Type,
433    crate_path: &syn::Path,
434) -> TokenStream2 {
435    // Z2H-2: the standalone `#[method]` macro has no activation-level shim
436    // module, so resolve the dep roots absolutely: through the plexus-rpc
437    // umbrella's `__deps` re-exports when the consumer depends on it, or the
438    // extern prelude (today's semantics) otherwise.
439    let (serde_json_root, schemars_root) =
440        match codegen::umbrella_crate(proc_macro2::Span::call_site()) {
441            Some(umbrella) => (
442                quote! { ::#umbrella::__deps::serde_json },
443                quote! { ::#umbrella::__deps::schemars },
444            ),
445            None => (quote! { serde_json }, quote! { schemars }),
446        };
447
448    let input_schema = if let Some(input_ty) = input_type {
449        quote! {
450            Some(#serde_json_root::to_value(#schemars_root::schema_for!(#input_ty)).unwrap())
451        }
452    } else {
453        quote! { None }
454    };
455
456    let _ = return_type; // Will be used for protocol schema in future
457    let _ = crate_path;
458
459    quote! {
460        /// Generated schema function for this hub method
461        #[allow(dead_code)]
462        pub fn #fn_name() -> #serde_json_root::Value {
463            #serde_json_root::json!({
464                "name": #method_name,
465                "description": #description,
466                "input": #input_schema,
467            })
468        }
469    }
470}
471
472/// Attribute macro for impl blocks defining a Plexus activation.
473///
474/// Generates:
475/// - Method enum for schema extraction
476/// - Activation trait implementation
477/// - RPC server trait and implementation
478///
479/// # Attributes
480///
481/// - `namespace = "..."` - The activation namespace (the name rule below
482///   gives it from `impl FooActivation`)
483/// - `version = "..."` (optional, default: "1.0.0") - Version string
484/// - `description = "..."` (optional) - Activation description
485/// - `crate_path = "..."` (optional, default: "crate") - Path to substrate crate
486/// - `client` (optional flag) - also emit the typed client (MACRO-2, below)
487/// - `server_cfg = "<cfg predicate>"` (optional) - compile the server half
488///   only under that `cfg` (MACRO-2, below)
489///
490/// # Example
491///
492/// ```ignore
493/// #[plexus::activation(namespace = "bash", version = "1.0.0", description = "Execute bash commands")]
494/// impl Bash {
495///     /// Execute a bash command and stream output
496///     #[plexus::method]
497///     async fn execute(&self, command: String) -> impl Stream<Item = BashEvent> + Send + 'static {
498///         self.executor.execute(&command).await
499///     }
500/// }
501/// ```
502///
503/// # The typed client (`client`, `server_cfg`) — MACRO-2, 0.7 shapes RETURNS-9
504///
505/// The macro already knows, when it runs, every method's wire name, its
506/// parameters and its precise contract (cardinality, item, error, progress).
507/// With `client` it also emits a **typed client** for the activation, and the
508/// activation's **aggregate** `{Ns}Event` (one variant per method, carrying
509/// that method's item), so a Rust consumer never hand-writes a call site or
510/// hand-mirrors an item type:
511///
512/// ```ignore
513/// #[plexus_macros::activation(client)]                 // namespace "tickets", implicitly
514/// impl Tickets { /* unchanged */ }
515///
516/// // emitted beside the impl: TicketsClient<T>, and TicketsEvent
517/// let client = TicketsClient::new(transport);                      // any plexus_client::Transport
518/// let health = client.health().await?;                             // one item: Health
519/// match client.get("MNG-2".into()).await? { Ok(t) => .., Err(no) => .. }   // one, fallible
520/// let rows: Vec<_> = client.list(None, None).try_collect().await?; // many: MethodStream
521/// let mut s = client.import(src).with_progress();                  // Frame<item, P>
522/// let mut ev = client.watch(None).events();                        // TicketsEvent
523/// ```
524///
525/// `?` is the call failing (`ClientError::Remote(RemoteError)` for the
526/// server's typed error frame); a match on the item is the activation's
527/// answer. The client is generic over the transport, so the emitted code
528/// names none of them; its parameter and item types are the activation's
529/// own, so a change to either is a compile error in every consumer. A crate
530/// that already defines a type named `{Ns}Event` renames it before turning
531/// `client` on.
532///
533/// **Requires** the consuming crate to depend on `plexus-client`. A
534/// proc-macro crate cannot check that for you at expansion time in general,
535/// but the path is resolved through `proc-macro-crate`, so a missing
536/// dependency is reported at the `client` flag rather than as an unresolved
537/// import in code you did not write.
538///
539/// **`server_cfg = "..."`** puts the *server* half of the expansion — the
540/// impl block, the method enum, the `Activation` impl, the jsonrpsee trait —
541/// behind a `cfg`, while the client half stays unconditional. That is what
542/// makes an activation crate reachable from `wasm32-unknown-unknown`:
543///
544/// ```ignore
545/// // Cargo.toml: server deps are optional and behind `feature = "server"`.
546/// // plexus-macros itself stays non-optional — a proc-macro crate is built
547/// // for the host, so it costs a wasm32 build nothing.
548/// #[plexus_macros::activation(
549///     namespace = "tickets",
550///     client,
551///     server_cfg = "feature = \"server\"",
552/// )]
553/// impl Tickets { /* .. */ }
554/// ```
555///
556/// A consumer then says one line — `tickets-api = { version = "..",
557/// default-features = false }` — and gets the types and the client, with no
558/// tokio, jsonrpsee or plexus-core anywhere in its tree. Gating your own
559/// struct definition and server-only imports is still yours to do; the macro
560/// only gates its own output.
561///
562/// Both flags are opt-in: an activation that names neither expands exactly
563/// as it did before.
564///
565/// # `#[activation]` needs nothing — MACRO-13
566///
567/// On `impl FooActivation` the stem `Foo` names everything, every key is an
568/// override, and the trait is always emitted (the owner's `always`):
569///
570/// ```ignore
571/// /// A deploy driver.                      // the activation's description
572/// #[plexus_macros::activation]
573/// impl DriverActivation {
574///     /// What this driver can do.          // the method's description
575///     pub async fn describe(&self) -> impl Stream<Item = DriverEvent> + Send + 'static { .. }
576///     pub fn new() -> Self { .. }           // not async: a plain method
577///     async fn helper(&self) -> u32 { .. }  // not pub: a plain method
578/// }
579/// // namespace "driver"; `pub trait Driver: Send + Sync + 'static` with
580/// // `fn describe(&self) -> BoxStream<'static, DriverEvent>`;
581/// // `impl Driver for DriverActivation`; `DriverClient<T>`, and
582/// // `impl<T: Transport + Clone + Send + Sync + 'static> Driver for DriverClient<T>`.
583/// ```
584///
585/// - **The name rule.** The namespace defaults to the stem in snake_case
586///   (`TicketsApiActivation` → `tickets_api`); the client is `FooClient<T>`.
587///   `trait = "Bar"` names the trait and the client (and, absent
588///   `namespace`, the namespace `bar`) whatever the type is called. A type
589///   not named `…Activation`, without `trait = "…"` or `namespace`, does not
590///   compile.
591/// - **The trait, always.** Each wire method is on it with the parameters a
592///   caller passes. Each event type must implement
593///   `plexus_client::FromClientError` when there is a client: the client's
594///   implementation yields an `Err(ClientError)` as
595///   `E::from_client_error(err)` and ends (`String` has it). The activation
596///   implements its own trait by cloning itself into each stream (`register`
597///   already asks for `Clone`) — unless a wire method takes what the server
598///   injects (`auth`, `reach`, `#[from_auth]`, `#[activation_param]`, a
599///   bidirectional `ctx`): then only the client implements it.
600/// - **Every public method a wire method.** Every `pub async fn` on `&self`
601///   returning `impl Stream<Item = E>` is on the wire with no `#[method]`
602///   (which stays for its overrides); one returning anything else is a
603///   compile error; `methods = marked` restores the `#[method]`-only rule.
604/// - **The client without a flag**, whenever the crate depends on
605///   `plexus-client`; `client` is accepted with a deprecation warning.
606/// - **The `server` feature default.** A crate whose manifest declares a
607///   `server` feature gets its server half under `#[cfg(feature =
608///   "server")]`; `server_cfg` overrides. The trait and the client are never
609///   gated.
610/// - **A bodiless activation is a contract.** When every wire method is
611///   bodiless (`pub async fn f(&self, ..) -> impl Stream<..>;`), the macro
612///   emits `pub struct FooActivation<D: Foo>(Arc<D>)` delegating to `D`,
613///   `impl<D: Foo> Foo for FooActivation<D>`, and `Foo::server(self)`:
614///   `hub.register(Local::new().server())`, or
615///   `hub.register(FooClient::new(transport).server())` for a proxy.
616///
617/// **Before the renames land.** An activation written before MACRO-13 — a
618/// type not named `…Activation`, no `trait = "…"`, its `namespace` given —
619/// expands exactly as it did (no trait; the client on the `client` flag;
620/// only `#[method]`s on the wire) with a deprecation warning asking for the
621/// rename. A later release refuses it.
622#[proc_macro_attribute]
623pub fn activation(attr: TokenStream, item: TokenStream) -> TokenStream {
624    let args = parse_macro_input!(attr as HubMethodsAttrs);
625    let input_impl = parse_macro_input!(item as ItemImpl);
626
627    match generate_all(args, input_impl) {
628        Ok(tokens) => tokens.into(),
629        Err(e) => e.to_compile_error().into(),
630    }
631}
632
633/// Deprecated: use `plexus::activation` instead.
634#[deprecated(since = "0.5.0", note = "Use `plexus::activation` instead")]
635#[proc_macro_attribute]
636pub fn hub_methods(attr: TokenStream, item: TokenStream) -> TokenStream {
637    activation(attr, item)
638}
639
640/// Derive macro for declaring credential-bearing fields on a return-type
641/// struct or enum (per `AUTHZ-CRED-MACRO-1`).
642///
643/// Apply `#[derive(Credentials)]` to a struct or enum. Within the item,
644/// annotate each credential-bearing field with the helper attribute
645/// `#[credential(kind = "...", attach_as = "...", ...)]` carrying the
646/// per-field metadata. The field's type must be `Credential<T>` (the sealed
647/// wrapper from `plexus_auth_core`); any other type produces a compile
648/// error citing the wrapper requirement.
649///
650/// **Why a derive macro and not a freestanding attribute macro?** Stable Rust
651/// proc-macros cannot intercept attribute macros applied directly to struct
652/// fields; only derive-helper attributes can appear there. See
653/// `plans/AUTHZ/AUTHZ-CRED-MACRO-1-RUN-NOTES.md` for the rationale.
654///
655/// # Example
656///
657/// ```ignore
658/// use plexus_auth_core::{
659///     AttachmentSite, Credential, CredentialKind, CredentialScheme,
660///     HeaderName, MethodPath, Scope,
661/// };
662///
663/// // `CredentialFieldMarker` lands in plexus-auth-core in a follow-up; for
664/// // now the macro emits code that references it by name and consumers
665/// // provide the definition (see run-notes).
666///
667/// #[derive(plexus_macros::Credentials, serde::Serialize)]
668/// pub struct LoginEvent {
669///     pub user_id: String,
670///
671///     #[credential(
672///         kind = "bearer",
673///         attach_as = "header:authorization",
674///         scheme = "Bearer ",
675///     )]
676///     pub session: Credential<String>,
677/// }
678/// ```
679///
680/// # Clauses
681///
682/// | Clause | Required? | Notes |
683/// |---|---|---|
684/// | `kind = "<name>"` | required | Closed enum: `"bearer"`, `"cookie"`, `"oauth_access"`, `"oauth_refresh"`, `"oidc_id"`, `"aws_sts"`, `"macaroon"`. The escape valve `kind(other = "<name>")` carries a backend-specific kind. |
685/// | `attach_as = "<spec>"` | required | One of `"header:<name>"`, `"cookie:<name>"`, `"first_frame:<setup-method>:<param>"`, `"in_rpc_param:<name>"`. |
686/// | `scheme = "<prefix>"` | optional | E.g. `"Bearer "` (trailing space significant). |
687/// | `scopes = ["a.b", ...]` | optional, default empty | List of scope identifiers. |
688/// | `refresh_via = "<method-path>"` | optional | E.g. `"auth.refresh"`. |
689/// | `revoke_via = "<method-path>"` | optional | E.g. `"auth.logout"`. |
690/// | `sensitive` | optional flag | Accepted for clarity; credentials are always sensitive. |
691///
692/// # Emitted artifacts
693///
694/// The macro emits two free functions in the same module:
695///
696/// - `fn __plexus_credential_marker_for_<TypeIdent>() -> Vec<CredentialFieldMarker>`
697/// - `fn __plexus_sensitive_fields_for_<TypeIdent>() -> Vec<(Option<&'static str>, &'static str)>`
698///
699/// The consumer (per `AUTHZ-CRED-CORE-3`) calls the first function during
700/// schema build; the second mirrors the implicit `#[sensitive]` rule for the
701/// redaction pipeline (per `AUTHZ-PRIVACY-2`).
702///
703/// The emitted code requires `CredentialFieldMarker`, `CredentialKind`,
704/// `AttachmentSite`, `CredentialScheme`, `Scope`, `MethodPath`, `HeaderName`,
705/// `CookieName`, `ParamName`, and `CredentialKindName` to be in scope at the
706/// emission site. Importing `plexus_auth_core::*` (or the equivalent named
707/// imports) at the top of the consuming module satisfies all but
708/// `CredentialFieldMarker`, which lands in `plexus_auth_core` in a follow-up.
709#[proc_macro_derive(Credentials, attributes(credential))]
710pub fn credentials_derive(input: TokenStream) -> TokenStream {
711    credential::expand_credentials_derive(input)
712}
713
714/// Derive macro for type-safe handle creation and parsing.
715///
716/// Generates:
717/// - `to_handle(&self) -> Handle` - converts enum variant to Handle
718/// - `impl TryFrom<&Handle>` - parses Handle back to enum variant
719/// - `impl From<EnumName> for Handle` - convenience conversion
720///
721/// # Attributes
722///
723/// Enum-level (required):
724/// - `plugin_id = "CONSTANT_NAME"` - Name of the constant holding the plugin UUID
725/// - `version = "1.0.0"` - Semantic version for handles
726/// - `crate_path = "..."` (optional, default: "plexus_core") - Path to plexus_core crate
727/// - `plugin_id_type = "Type<Args>"` (optional) - Concrete type whose associated
728///   constant `plugin_id` names. Use this when the owning activation is generic
729///   (e.g. `Cone<P: HubContext = NoParent>`) to pin the instantiation and avoid
730///   E0283 "cannot infer type" errors. Pairs with `plugin_id` — e.g.
731///   `plugin_id = "Cone::PLUGIN_ID", plugin_id_type = "Cone<NoParent>"` emits
732///   `<Cone<NoParent>>::PLUGIN_ID`.
733///
734/// Variant-level:
735/// - `method = "..."` (required) - The handle.method value
736/// - `table = "..."` (optional) - SQLite table name (for future resolution)
737/// - `key = "..."` (optional) - Primary key column (for future resolution)
738///
739/// # Example
740///
741/// ```ignore
742/// use hub_macro::HandleEnum;
743/// use uuid::Uuid;
744///
745/// pub const MY_PLUGIN_ID: Uuid = uuid::uuid!("550e8400-e29b-41d4-a716-446655440000");
746///
747/// #[derive(HandleEnum)]
748/// #[handle(plugin_id = "MY_PLUGIN_ID", version = "1.0.0")]
749/// pub enum MyPluginHandle {
750///     #[handle(method = "event", table = "events", key = "id")]
751///     Event { event_id: String },
752///
753///     #[handle(method = "message")]
754///     Message { message_id: String, role: String },
755/// }
756///
757/// // Usage:
758/// let handle_enum = MyPluginHandle::Event { event_id: "evt-123".into() };
759/// let handle: Handle = handle_enum.to_handle();
760/// // handle.method == "event"
761/// // handle.meta == ["evt-123"]
762///
763/// // Parsing back:
764/// let parsed = MyPluginHandle::try_from(&handle)?;
765/// ```
766#[proc_macro_derive(HandleEnum, attributes(handle))]
767pub fn handle_enum_derive(input: TokenStream) -> TokenStream {
768    handle_enum::derive(input)
769}
770
771/// PERF.115-43 · an internally tagged enum's `Deserialize`, its tag read
772/// first: in place of serde's, on a house event.
773///
774/// serde reads an internally tagged enum (`#[serde(tag = "type")]`, every
775/// event the house writes) whole into a private buffer before it reads the
776/// tag, then reads the variant out of the buffer. Written in serde's place,
777/// this derive reads the first key: when it is the tag, the variant is chosen
778/// by the tag's value and its fields are read straight from the rest of the
779/// object; when it is not, serde reads the object, buffer and all, as it
780/// always has. plexus-core writes `type` first, so a client, a hop or a
781/// service reading another's events reads them without the buffer.
782///
783/// ```ignore
784/// #[derive(Debug, Clone, serde::Serialize, plexus_macros::Deserialize, schemars::JsonSchema)]
785/// #[serde(tag = "type", rename_all = "snake_case")]
786/// pub enum TicketsEvent {
787///     Health { version: String, count: u64 },
788///     Ready,
789///     Error { message: String },
790/// }
791/// ```
792///
793/// Everything else about the enum is serde's: the derive has serde derive
794/// it twice more beside it (`#[serde(remote = …)]`), once as written and
795/// once without its tag, so every `#[serde]` attribute (`rename_all`,
796/// `rename`, `alias`, `other`, `default`, `skip`, `with`, `flatten`,
797/// `deny_unknown_fields`, `expecting`) is read by serde's own code. A struct
798/// variant and a unit variant are read straight; a newtype variant, a struct
799/// variant with a flattened field and a variant read `with` a function are
800/// read by serde's buffered read. What serde refuses is refused in serde's
801/// words. A value inside a variant is read by the deserializer itself, so a
802/// value only the input can carry (a `RawValue`, a map keyed by numbers)
803/// reaches a variant whose tag comes first.
804///
805/// It is for an internally tagged enum that is not generic, with no
806/// untagged variant (one is tried on the whole object once the tagged ones
807/// fail, which needs the buffer); anything else is a compile error that says
808/// to derive serde's `Deserialize`. The runtime is plexus-client's
809/// (`plexus_client::__rt::type_first`), so the deriving crate depends on
810/// plexus-client, as every crate with a generated client does.
811#[proc_macro_derive(Deserialize, attributes(serde))]
812pub fn deserialize_derive(input: TokenStream) -> TokenStream {
813    type_first::derive(input)
814}
815
816/// Derive macro for typed HTTP/WebSocket request extraction.
817///
818/// Generates `impl PlexusRequest` (extraction) and `impl schemars::JsonSchema`
819/// (with `x-plexus-source` extensions) for the annotated struct.
820///
821/// # Field annotations
822///
823/// - `#[from_cookie("name")]` — extract from named cookie
824/// - `#[from_header("name")]` — extract from named HTTP header
825/// - `#[from_query("name")]` — extract from named URI query parameter
826/// - `#[from_peer]` — copy `ctx.peer` (peer socket address)
827/// - `#[from_auth_context]` — copy `ctx.auth` (auth context)
828/// - (no annotation) — `Default::default()`
829///
830/// # Example
831///
832/// ```ignore
833/// use plexus_macros::PlexusRequest;
834///
835/// #[derive(PlexusRequest)]
836/// struct MyRequest {
837///     #[from_cookie("access_token")]
838///     auth_token: String,
839///
840///     #[from_header("origin")]
841///     origin: Option<String>,
842///
843///     #[from_peer]
844///     peer_addr: Option<std::net::SocketAddr>,
845/// }
846/// ```
847#[proc_macro_derive(
848    PlexusRequest,
849    attributes(from_cookie, from_header, from_query, from_peer, from_auth_context)
850)]
851pub fn plexus_request_derive(input: TokenStream) -> TokenStream {
852    request::derive(input)
853}
854
855/// No-op `JsonSchema` derive — used when plexus-macros is aliased as `schemars`
856/// in dev-dependencies to prevent duplicate `impl JsonSchema` conflicts with
857/// `#[derive(PlexusRequest)]` (which generates its own `impl JsonSchema`).
858///
859/// When plexus-macros is aliased as schemars in dev-deps:
860/// ```toml
861/// [dev-dependencies]
862/// schemars = { path = "../plexus-macros", package = "plexus-macros", features = ["schemars-compat"] }
863/// ```
864/// then `#[derive(schemars::JsonSchema)]` invokes THIS derive instead of the real schemars derive,
865/// producing no output, so only `PlexusRequest`'s `impl JsonSchema` exists.
866#[cfg(feature = "schemars-compat")]
867#[proc_macro_derive(JsonSchema, attributes(schemars, serde))]
868pub fn json_schema_noop_derive(_input: TokenStream) -> TokenStream {
869    // Intentionally produces no output.
870    // PlexusRequest already generates impl JsonSchema with x-plexus-source extensions.
871    TokenStream::new()
872}