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