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