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