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