plexus-macros
Procedural macros for Plexus RPC activations. The macros are the source of truth for the client generation pipeline: your Rust function signature is the schema.
Versions: use plexus-macros and plexus-core from the same minor line (0.7 with 0.7). The macro emits paths into plexus-core but cannot depend on it, so cargo cannot enforce the pairing from this side; plexus-core requires plexus-macros on its own line and re-exports activation and method.
Overview: macros → schema → clients
#[plexus_macros::activation] Rust macros (this crate)
↓ schemars::schema_for!() + MethodRole / DeprecationInfo metadata
PluginSchema (serde JSON, pinned in plexus-core)
↓ Synapse (Haskell) fetches over Plexus RPC
Synapse IR (deduplicated, compiler-ready)
↓ plexus-codegen-{rust,typescript,python}
Client libraries (type-safe, documented, deprecation-aware)
Everything downstream — generated clients, OpenAPI docs, deprecation warnings in TypeScript IDEs — is derived from what #[plexus_macros::activation] emits into PluginSchema. Do not hand-write schemas; the macro owns them.
For Rust consumers there is a shorter path: the macro emits the client itself.
#[plexus_macros::activation(namespace = "tickets", client)]
↓ same expansion, same information
TicketsClient<T: plexus_client::Transport> ← typed params, typed events
The Synapse → IR → codegen pipeline above stays the path for TypeScript, Python and everything non-Rust. See The typed client.
Documentation is primary: /// everywhere
/// doc comments are the primary source of every description that reaches the wire. The macros extract them at expansion time and emit them into PluginSchema. Generated clients (TypeScript, Rust, Python) render them as TSDoc / rustdoc / docstrings. Synapse shows them in the CLI tree.
Where you write /// |
Where it appears on the wire |
|---|---|
On the impl block annotated with #[plexus_macros::activation] |
PluginSchema.description |
On each #[plexus_macros::method] fn |
MethodSchema.description |
On each #[plexus_macros::child] fn |
MethodSchema.description (role: StaticChild / DynamicChild) |
On a struct / enum that derives JsonSchema |
JSON Schema description for that type |
| On a field of such a struct | JSON Schema description for that field |
| On an enum variant | JSON Schema description for that variant |
Parameters are the only exception — individual parameter descriptions must use the params(name = "...", other = "...") attr on #[plexus_macros::method] (Rust has no per-argument doc-comment syntax).
Precedence — if both an explicit attr arg and a /// doc comment are present, the explicit attr arg wins. In practice, prefer ///; reach for the attr arg only when you need to diverge (e.g., a deliberately terser wire description than the internal Rust docs).
Minimal example — best practices
The smallest realistic activation. Uses /// for every description, has one method with a params(...) attr, and exposes a static #[plexus_macros::child] into a nested namespace. No description = "..." attr args anywhere — the macros pick up doc comments automatically.
use stream;
use Stream;
use JsonSchema;
use ;
/// A message echoed back to the caller.
/// Echo service — returns messages verbatim and exposes a nested `stats` child.
;
/// Echo messages back verbatim; nested `stats` child exposes call introspection.
/// Call-count introspection for the `echo` service.
;
/// Introspection for the Echo service — invocation counts and timing.
What this demonstrates:
///on theimplblock (line with#[plexus_macros::activation]) suppliesPluginSchema.description. Nodescription = "..."attr arg needed.///on each method fn suppliesMethodSchema.description. Again, nodescription = "..."attr arg.params(message = "...")is the only way to document individual params — Rust has no per-argument doc-comment syntax.#[plexus_macros::child]on a zero-arg accessor fn creates a static child namespace.synapse lforge echo stats totalroutes into the nested activation.- Stream item type derives
JsonSchema, so its variant and field///doc comments flow through to the wire.
Synapse invocations:
Upgrade path from this minimal form: add params(...) as more methods gain documented params; add more #[plexus_macros::child] accessors for nested namespaces; introduce #[derive(PlexusRequest)] + request = ... once you need auth / cookies / per-request context; add #[deprecated] + #[plexus_macros::removed_in] when rotating methods. Each of those is covered in the comprehensive example below.
Comprehensive example
A single realistic activation that exercises every macro in the crate. Every attribute shown is currently supported on 0.7.x. Features that are less common are called out inline.
The example below uses several
description = "..."attr args explicitly — partly for readability in a reference doc, partly because the comprehensive activation description is the easier way to show thelong_descriptioncompanion. In your own code prefer///doc comments per the Documentation is primary section above.
use stream;
use Stream;
use ;
use StandardBidirChannel;
use JsonSchema;
use ;
use Arc;
// -------------------------------------------------------------------
// 1. Stream item type — a plain domain enum.
// The caller-wraps streaming architecture means you do NOT need a
// `StreamEvent` derive. Standard serde + JsonSchema is enough.
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// 2. Typed handles — generated by `#[derive(HandleEnum)]`.
// Handles are opaque strings on the wire; this derive makes them
// typed on the Rust side. `plugin_id_type` pins the instantiation
// when the owning activation is generic (IR-21).
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// 3. Typed request — generated by `#[derive(PlexusRequest)]`.
// This struct describes the per-request HTTP context: cookies,
// headers, query params, peer address, auth context. The
// activation-level `request = CounterRequest` attr below wires it
// into the dispatch path; fields become injectable via
// `#[activation_param]` on method parameters.
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// 4. The activation itself.
// -------------------------------------------------------------------
; // stand-in for the child activation
;
The example above is the full feature surface of plexus-macros 0.7.x. Real activations typically use a subset — see plexus-substrate for concrete, minimally-documented usage (echo and bash are the smallest; cone, claudecode, and solar exercise children, handles, and generics).
Request forwarding: PlexusRequest + request = ...
A typed view of an inbound HTTP request. Without it, your method sees only the RPC arguments; with it, you get cookies / headers / query params / peer address / auth context as first-class Rust fields — extracted, validated, and type-checked at dispatch time.
What it is
plexus_core::request::PlexusRequest is a trait implemented by #[derive(PlexusRequest)]. It has two methods:
RawRequestContext is the raw inputs — http::HeaderMap, Uri, optional AuthContext, optional SocketAddr. The derive generates both extract (run per-call by the dispatch code) and request_schema (included in the activation's PluginSchema with x-plexus-source hints).
Why it exists
Auth tokens live in cookies. CSRF checks need the Origin header. Tenancy lives in query strings. Per-peer rate limits need the socket address. Before PlexusRequest, every activation had to hand-parse this out of a RawRequestContext — boilerplate, inconsistent errors, no schema. With the derive:
- Typed extraction: one
#[from_cookie("...")]replaces several lines of header parsing. - Consistent errors: missing required fields return
PlexusError::Unauthenticated. - Schema metadata: generated clients know which inputs come from cookies vs. body.
- Composition: the same struct is reused across every method of the activation.
Field attributes
| Attribute | Source | Required? | Notes |
|---|---|---|---|
#[from_cookie("name")] |
Named Cookie header value |
Non-Option → required (401 if missing) |
Multi-value cookie headers are parsed correctly. |
#[from_header("name")] |
Named HTTP header | Non-Option → required |
Case-insensitive per http crate. |
#[from_query("name")] |
Named URI query parameter | Non-Option → required |
Uses form_urlencoded::parse. |
#[from_peer] |
ctx.peer (socket addr) |
Option<SocketAddr> recommended |
Transports without peer addr → None. |
#[from_auth_context] |
ctx.auth (AuthContext) |
Option<AuthContext> recommended |
Populated by auth middleware. |
| (no attribute) | PlexusRequestField::extract_from_raw |
Defined by the field type | Use for newtypes like ValidOrigin. |
Option<T> fields treat "absent" as None and never fail; non-Option fields return PlexusError::Unauthenticated on missing input. Parse failures (e.g. a cookie value that cannot parse into the declared type) also return Unauthenticated.
Wiring it into an activation
The activation attribute takes a request = <Type> argument:
Two ways to consume the extracted fields in methods:
-
#[activation_param]— the named parameter is pulled from the request struct by field name. The Rust type must match the declared field type (the macro enforces this):async + Send + 'static -
#[from_auth(expr)]— runs an arbitrary resolver expression against the extracted auth context. Useful when you want a validated user type, not raw auth:async + Send + 'staticThe resolver's error decides the refusal (MACRO-14). A resolver returning
Result<_, PlexusError>is answered with that error unchanged —Forbidden { MissingGrant { … } }reaches the wire as-32003witherror_kind: "forbidden"and itsgrant/scope/roles/held_on,Unauthenticatedas-32001— so a refusal stays typed. Any otherDisplayerror isExecutionError(e.to_string())(-32000).
To opt a method out of activation-level extraction (e.g. a public health probe), use request = ():
async + Send + 'static
Wire-level: x-plexus-source
The derive augments the generated JSON Schema with a non-standard x-plexus-source key on each property, so generated clients know which input channel to use:
End-to-end example
Given this activation:
A request:
POST /rpc HTTP/1.1
Cookie: access_token=eyJhbGci...
Origin: https://app.example.com
Content-Type: application/json
{ "method": "app.me", "params": {} }
is dispatched as:
- Transport builds a
RawRequestContextfrom headers + URI. - Dispatch calls
AppRequest::extract(&raw)→AppRequest { token: "eyJhbGci…", origin: Some("https://app.example.com") }. - The
tokenfield is threaded intomeas itstokenparameter. meruns; streamed output is serialised back over the transport.
When to use PlexusRequest vs. method params
Rule of thumb:
- Method params — per-call inputs that belong to the business logic:
item_id,query,body. PlexusRequest+#[activation_param]— per-request context that crosses every method: auth tokens, session cookies, tenancy, peer addr.
If a value would be the same for every method call in a request, it belongs in the request struct.
#[activation] needs nothing (MACRO-13)
On impl FooActivation the stem Foo names the namespace (foo), the
trait (trait Foo) and the client (FooClient<T>); descriptions come from
/// (and /** … */ before a parameter); plexus-core is found in the
manifest. Every key below is an override, and none is needed:
/// A deploy driver: describe, trigger, watch.
// emitted:
// pub trait Driver: Send + Sync + 'static { fn describe(&self) -> BoxStream<'static, DriverEvent>; … }
// impl Driver for DriverActivation (the server half)
// pub struct DriverClient<T>; impl<T: Transport + Clone + Send + Sync + 'static> Driver for DriverClient<T>
| rule | |
|---|---|
| the trait, always | every activation has one; a type not named …Activation names it with trait = "Bar" (which also names the client BarClient and, absent namespace, the namespace bar). Without either it does not compile — except an activation written before MACRO-13, which says its namespace: it expands as it did, with a deprecation warning asking for the rename |
| wire methods | every pub async fn on &self returning impl Stream<Item = E>, no #[method] needed (it stays for its overrides); a pub async fn on &self returning anything else is a compile error; methods = marked restores the #[method]-only rule |
| one event type | the trait's methods yield one E across the activation |
| the client | emitted whenever the crate depends on plexus-client, no flag (client is accepted with a deprecation warning); its trait impl yields a ClientError as E::from_client_error(err) and ends, so E: plexus_client::FromClientError (String has it) |
| injected parameters | a method taking auth, reach, #[from_auth], #[activation_param] or a bidirectional ctx is on the trait with what a caller passes; the client implements the trait and the activation does not (it has no caller to take them from) |
the server feature |
a crate whose manifest declares server gets the server half under #[cfg(feature = "server")]; server_cfg overrides; the trait and the client are never gated |
| a contract | every wire method bodiless (pub async fn f(&self) -> impl Stream<…>;) and no struct written: the macro emits pub struct FooActivation<D: Foo>(Arc<D>), delegating, and Foo::server(self), so hub.register(Local::new().server()) serves an implementation and hub.register(FooClient::new(t).server()) a remote one as a proxy. A mix of bodied and bodiless is refused at the first bodiless method |
The typed client (client + server_cfg)
The macro sees every method's wire name, its parameters and its
Stream<Item = E> event type at the moment it runs. With the client flag it
emits a typed client from that same information, so a Rust consumer never
hand-writes a call site or hand-mirrors an event type.
emits, beside the activation's own items:
Requires the consuming crate to depend on
plexus-client — the wasm-safe runtime the emitted code
links against. A missing dependency is reported at the client flag, not as
an unresolved import in code you did not write.
What you get
| Typed params | the method's own parameter types, in signature order. #[activation_param], #[from_auth] and auth: params are absent — the server injects those. |
| Typed events | EventStream<'_, E> for the method's Stream<Item = E>. E is the activation's own type, not a copy. |
| Two shapes | m(..) streams; m_all(..) drives to completion and returns Vec<E>. |
| Transport-generic | any plexus_client::Transport — in-process, WebSocket JSON-RPC, REST + SSE. The emitted code names none of them. |
| Two error layers | ClientError::Transport (the connection failed) vs ClientError::Remote (the server answered error). An activation's own Error variant stays a data event. |
| Zero drift | rename a field on an event type and every consumer of the client stops compiling. |
| Children (MACRO-16) | a static #[child] fn inputs(&self) -> Inputs gives the parent's client fn inputs(&self) -> InputsClient<&T>, whose calls go to tickets.inputs.<method>, the path the hub routes. Accessors nest, so client.inputs().history().tail(..) goes to tickets.inputs.history.tail. The child must be declared with client too, or InputsClient does not resolve at the accessor's return type. InputsClient::new(t) alone still sends inputs.<method>. InputsClient::at(t, "tickets.inputs") mounts it by hand. Dynamic children (fn x(&self, name: &str)) get no accessor. |
Option parameters that are None are omitted from the params object,
not sent as null — matching what a server with
skip_serializing_if = "Option::is_none" puts on the wire.
Reaching wasm32: server_cfg
An activation crate is usually also a server, and tokio / jsonrpsee /
plexus-core do not build for wasm32-unknown-unknown. server_cfg puts the
server half of the expansion — the impl block, the method enum, the
Activation impl, the jsonrpsee trait — behind a cfg, while the client half
stays unconditional:
# Cargo.toml
[]
= ["server"]
= ["dep:plexus-core", "dep:tokio", "dep:jsonrpsee", "dep:serde_json", "dep:uuid", "dep:async-trait"]
[]
# NOT optional: a proc-macro crate is built for the host, never the target,
# so a wasm32 build pays nothing for it — and that is what lets the macro run,
# and emit the client, in a build with no server dependencies at all.
= "0.7"
= "0.7"
= { = "1", = ["derive"] }
A consumer then needs one dependency line:
= { = "0.1", = false }
and gets the types and the client with no tokio, jsonrpsee or plexus-core anywhere in its tree. Gating your own struct definition and server-only imports is still yours to do — the macro only gates its own output.
Worked end to end in fixtures/tickets-api (the
activation) and
fixtures/tickets-wasm-consumer (a
consumer with no wire code of its own). Both build for
wasm32-unknown-unknown.
Transports
| Transport | Where | Status |
|---|---|---|
MemoryTransport |
plexus-client |
scripted test double; wasm-safe by construction |
InProcessTransport |
plexus-core (plexus::in_process) |
drives an Activation directly — no server |
WsTransport |
plexus-client, feature ws-native / ws-web |
WebSocket JSON-RPC; one connection, subscriptions multiplexed |
| REST + SSE | — | not yet built |
WsTransport::connect(url, hub_namespace) is the wire transport, and the
only one that carries the full StreamMetadata. It is behind a feature
so that plexus-client's default stays the four-dependency wasm-clean core:
ws-native builds on tokio-tungstenite, ws-web on web_sys::WebSocket,
and both expose the same type and the same constructor — a consumer picks
the backend in Cargo.toml and changes no code. The protocol itself (ids,
routing, cancellation, both frame shapes) is written once and shared, so the
backends cannot drift.
let transport = connect.await?;
let tickets = new; // …and reuse it for every activation
hub_namespace is the server's DynamicHub::new(ns) namespace, not an
activation namespace: the same tickets.list goes to menger.call on one
deployment and to another hub's call elsewhere. Worked end to end against a
real server by menger itself: its tickets activation carries client and
server_cfg, the browser app takes the crate with default-features = false, and tests/wire_client.rs there drives the emitted TicketsClient
over WsTransport against the in-process server. (A client-only mirror of
menger's declarations lived under fixtures/ while menger was still on the
0.5 line; it is gone — one declaration, nothing to drift.)
Both flags are opt-in: an activation naming neither expands exactly as before.
Security model
This documents the actual generated behavior, not an aspiration. Read it before assuming a method is protected.
- Auth is fail-open by default. A method whose signature carries no auth signal — no
auth: &AuthContext, noauth: Option<&AuthContext>, no#[from_auth(...)]resolver — is generated with no auth check at all and is callable unauthenticated. The dispatch arm only injects an auth check when the method requested one (src/codegen/activation.rs, theauth_injectionlogic ingenerate_dispatch_arms). - Default activation posture is
Optional— it enforces nothing.auth = "required"is opt-in and is the only fail-closed posture. Even underrequired, a method declaringOption<&AuthContext>is downgraded to a warning (it still receivesNonerather than being rejected). - Roles, scopes, and credential metadata are schema metadata only. Declared roles/scopes and
#[credential(...)]clauses are reflected into the schema for clients and tooling. They are never enforced at dispatch — the framework does not check them before invoking your method. - A
#[from_auth(expr)]resolver must itself fail closed. The macro splicesexprverbatim into the dispatch arm and binds its result with?. It does not verify that the resolver actually denies unauthorized callers. If your resolver returnsOk(...)for an unauthenticated/under-privileged principal, the call proceeds. Enforcement is entirely the resolver's responsibility.
The practical consequence: authorization is opt-in, per-method, and only as strong as the code you write. The macro provides plumbing, not a policy.
Per-macro reference
#[plexus_macros::activation(...)]
Attached to an impl block to generate the activation's Activation trait impl, method enum, RPC trait, and (when #[child] methods are present) ChildRouter impl.
| Arg | Type | Default | Notes |
|---|---|---|---|
namespace = "..." |
string | the stem of impl FooActivation, snake_case |
Activation namespace. Appears as plugin_schema.namespace. MACRO-13: an override. |
trait = "..." |
string | the stem | MACRO-13: names the trait and the client whatever the type is called. |
methods = marked |
word | every pub async fn on &self returning a stream |
MACRO-13: only #[method]s are on the wire. |
version = "..." |
string | CARGO_PKG_VERSION |
Semver; used by handles and deprecation schemas. |
description = "..." |
string | (none) | Max 15 words — macro errors on overflow. Use long_description for more. |
long_description = "..." |
string | (none) | Unbounded documentation; projected into PluginSchema. |
request = MyType |
type | (none) | Typed request struct; see the Request forwarding section. |
resolve_handle |
flag | (off) | Generates Activation::resolve_handle that delegates to self.resolve_handle_impl(handle). You implement the impl. |
crate_path = "..." |
string | auto (via proc-macro-crate) |
Override the plexus-core import path. Rarely needed after CHILD-6. |
plugin_id = "UUID" |
string | deterministic UUIDv5 from namespace | Explicit plugin UUID. Must parse as a UUID. |
namespace_fn = "method" |
string | (none) | Advanced: generate namespace() as a method call instead of a constant. |
client |
flag | (off) | Also emit the typed client — see The typed client. Requires a plexus-client dependency. MACRO-13: under the name rule the client is emitted whenever plexus-client is a dependency, and client is ignored with a deprecation warning. |
server_cfg = "<pred>" |
string | (none) | Compile the server half of the expansion only under that cfg (e.g. feature = "server"). Requires client (MACRO-13: not under the name rule, where feature = "server" is the default when the crate declares it). This is what makes an activation crate reachable from wasm32. |
typed_params |
flag | (off) | MACRO-12: a method parameter typed literally String, &str, Option<String>, Option<&str> or Vec<String> is a compile error on that parameter: `<method>.<param>`: a bare string parameter; give it a type (typed_params). Injected parameters (auth, reach, #[from_auth], #[activation_param]) are exempt. An alias (type Name = String) is not seen through. MACRO-31: and a key of the params object that names no wire parameter is refused at dispatch, before the method runs — -32602 invalid_params, Invalid params: unknown field `sumary`; tickets.list takes: after, limit, summary (every unknown key named, sorted; the parameters sorted; … takes no parameters for a method of none). unknown field is synapse's word for a stale cached schema (it re-reads the schema and runs the call again), so it is said verbatim. The method is named by its activation's own namespace (a child's, not the path it is mounted at). null, {} and a bare value are answered as before; keys inside a parameter's value are its type's serde's. Off by default for 0.7; on by default is MACRO-8's call. |
hub |
flag | (off, deprecated) | Deprecated — hub mode is inferred from #[child] methods. Still accepted in 0.7. |
children = [ident, ...] |
ident list | (empty, deprecated) | Deprecated — use #[child] methods. Still accepted in 0.7. |
#[plexus_macros::method(...)]
Attached to methods inside an #[activation] impl. Marks the method as an RPC endpoint and collects schema metadata.
| Arg | Type | Default | Notes |
|---|---|---|---|
description = "..." |
string | first /// doc-comment block (CHILD-5) |
Explicit arg wins over doc comments. |
name = "..." |
string | method identifier | Override the RPC name without renaming the Rust fn. |
streaming |
flag | (off) | Advertises the method as AsyncGenerator-shaped in generated clients. |
bidirectional |
flag | (off) | Method uses StandardBidirChannel. Use bidirectional(request = "...", response = "...") for custom types. |
http_method = "..." |
string | (none) | One of GET|POST|PUT|DELETE|PATCH. Hint for REST generators. |
params(name = "doc", ...) |
key/value list | (empty) | Per-parameter descriptions. Less common now that field-level /// extraction works; retained for cases where parameters have no natural Rust doc site. |
returns(Variant, ...) |
ident list | (all variants) | Filter the return enum to named variants. Rare. |
group = "..." |
string | (none) | SYNAPSE-13: the method's group in a listing ("read", "write", …) — OpenAPI's tag, one per method. MethodSchema.group; synapse lists a group's methods together, the groups in the order they first appear. |
values(param = ["A", "B"], ...) |
key / string-array list | (none) | SYNAPSE-13: the values a param is meant to take — a hint, never enforced (the method may accept synonyms). Emitted as x-plexus-values on the param's property; synapse shows [values: …]. A name that is no param is a compile error. |
example(note = "...", params = r#"{...}"#) |
repeatable | (none) | SYNAPSE-13: a worked call — a JSON object of the method's params (checked at expansion: JSON, an object, naming only its params) and a note. MethodSchema.examples; synapse renders each as a command line. Use r##"…"## when the JSON holds "#. |
request = () |
tuple | (inherits) | Skip activation-level request extraction for this method (public endpoint escape hatch). |
request = OtherType |
type | (inherits) | Reserved — per-method request type override is not yet wired end-to-end. |
Method parameter attributes (applied inside the fn signature):
#[activation_param]— inject a field from the activation-level request struct; name + type must match.#[from_auth(expr)]— callexpr(&auth_context)and bind the result; useful for validated user types.
#[plexus_macros::child] / #[plexus_macros::child(list = "...", search = "...", forward = "...")]
Attached to methods inside an #[activation] impl to register them in the generated ChildRouter. Two accepted shapes:
| Shape | Role | Notes |
|---|---|---|
fn NAME(&self) -> Child |
Static child | Routing name is the method identifier. Sync or async. |
fn NAME(&self, name: &str) -> Option<Child> |
Dynamic fallback | Called for any name not matched by a static child. Sync or async. |
Optional arguments on dynamic #[child]:
| Arg | Type | Advertises capability | Sibling method shape |
|---|---|---|---|
list = "method" |
ident | ChildCapabilities::LIST |
(async) fn METHOD(&self) -> impl Stream<Item = String> (or BoxStream<'_, String>) |
search = "method" |
ident | ChildCapabilities::SEARCH |
(async) fn METHOD(&self, query: &str) -> impl Stream<Item = String> |
Sibling methods are validated at macro-expansion time — typos in list = "..." or a wrong signature become compile errors pointing at the attribute.
#[child] methods do not appear as RPC endpoints in the schema; they contribute to routing only. The presence of any #[child] method flips the activation into hub mode (replacing the deprecated hub flag).
How a child inherits its caller (MACRO-20). A call routed into a child gets a context derived by a forward policy, emitted as ChildRouter::forward_policy_for. A static child is the same service as its parent (a value built from the parent's own fields, in-process), so by default it gets SameService: the caller whole, with the verified user, the session, and the metadata that holds the principal stamp, the session key and expiry, and the gate's ceiling. Under login, that's what lets a child's #[from_auth] / Access::verify see who called and keeps a ceilinged session from widening inside the child. A child that must not see the caller's session says so:
forward = … |
the child keeps |
|---|---|
"same_service" (a static child's default) |
everything (plexus_core::plexus::SameService) |
"identity_only" |
the user id and session id only; the metadata (principal stamp, session, ceiling) is dropped (IdentityOnly) |
"pass_through" |
everything, named as a pass-through (PassThrough) |
"anonymous" |
nothing (Anonymous) |
A dynamic child keeps the framework default (IdentityOnly) unless it names a policy. The parent also describes its static children (ChildRouter::router_static_child_schemas, Activation::static_child_schemas), so a DynamicHub gates a child's method by its whole path (tickets.commits.link, with the child's own target), seeds the child's roles(...) qualified by that path in declared_roles, and lists the methods in auth.requires and the caller's view (plexus-core plexus::children).
#[plexus_macros::removed_in("X")]
Companion to Rust's built-in #[deprecated]. Carries the removal-version field that rustc's #[deprecated] doesn't accept.
async + Send + 'static
The macro writes this into MethodSchema.deprecation as DeprecationInfo { since, removed_in, message }. Without the companion attribute, removed_in defaults to the string "unspecified".
Applying #[plexus_macros::removed_in] to a method without #[deprecated] is a compile error.
#[derive(PlexusRequest)]
See Request forwarding for the full treatment. Generates:
impl PlexusRequest for YourStruct(extraction + schema).impl schemars::JsonSchema for YourStructusingplexus_core::__schemars(no directschemarsdependency required from the caller).
Supported field attributes:
#[from_cookie("name")] #[from_header("name")] #[from_query("name")]
#[from_peer] #[from_auth_context]
Fields without any source attribute must implement PlexusRequestField — used for newtype wrappers that carry their own validation.
#[derive(HandleEnum)]
Generates to_handle(), impl TryFrom<&Handle>, and impl From<_> for Handle for an enum that represents the set of typed handles an activation issues.
Enum-level #[handle(...)] arguments:
| Arg | Required? | Notes |
|---|---|---|
plugin_id = "CONST_OR_PATH" |
yes | Path to the activation's plugin UUID constant — e.g. "Counter::PLUGIN_ID" or "MY_PLUGIN_ID". |
version = "X.Y.Z" |
yes | Semver for handles emitted by this enum. |
plugin_id_type = "Type" |
no | Concrete instantiation to qualify plugin_id when the owning activation is generic (e.g. "Cone<NoParent>"). Fixes E0283 ambiguity. |
crate_path = "..." |
no ("plexus_core") |
Override import path. |
Variant-level #[handle(...)] arguments:
| Arg | Required? | Notes |
|---|---|---|
method = "..." |
yes | The handle.method value on the wire. |
table = "..." |
no | SQLite table name (consumed by future handle-resolution tooling). |
key = "..." |
no | Primary key column. |
key_field = "..." |
no | Which variant field holds the key. Defaults to the first field. |
strip_prefix = "..." |
no | Strip this prefix before looking up by key. |
#[derive(Credentials)]
Marks the credential-bearing fields of a response struct or enum so the
framework can mint, redact, and reflect them. Applied to the item
(struct / enum); individual fields carry an inner #[credential(...)]
helper attribute. The derive is additive — your type is re-emitted
unchanged; the macro emits sibling registry functions plus an
impl HasCredentialMarkers for the type.
A credential-bearing field's type must be Credential<T> (the sealed
wrapper from plexus_auth_core); the macro errors otherwise.
use Credentials;
use Credential;
Field-level #[credential(...)] clauses:
| Clause | Required? | Notes |
|---|---|---|
kind = "..." |
yes | Closed CredentialKind: bearer, cookie, oauth_access, oauth_refresh, oidc_id, aws_sts, macaroon. Validated at compile time (a typo is a compile error). |
kind(other = "name") |
(alt) | Structured escape valve for backend-specific kinds. The bare kind = "other" form is rejected — use this parenthesized form. |
attach_as = "..." |
yes | Where the credential is projected on the wire. Prefixed-string grammar (see below). |
scheme = "..." |
no | Value prefix, e.g. "Bearer ". |
scopes = ["a.b", ...] |
no | Array of scope-name string literals. |
refresh_via = "ns.method" |
no | MethodPath (<namespace>.<method>[.<sub>]*, each segment [a-z][a-z0-9_]*). Validated at macro time. |
revoke_via = "ns.method" |
no | Same MethodPath grammar. |
sensitive |
no | Bare flag or `sensitive = true |
attach_as grammar (one of four prefixed-string forms):
| Form | Meaning |
|---|---|
"header:<name>" |
Project to the named response header (e.g. "header:authorization"). |
"cookie:<name>" |
Project to a Set-Cookie with the named cookie. |
"in_rpc_param:<name>" |
Carried in the named RPC parameter. |
"first_frame:<setup-method>:<param>" |
Supplied as <param> on the first frame of <setup-method>. |
What the macro emits (consumed downstream for schema + redaction):
__plexus_credential_marker_for_<Type>() -> Vec<CredentialFieldMarker>— one entry per credential field, in declaration order, with all parsed metadata. For enums each entry carries its variant name.__plexus_sensitive_fields_for_<Type>() -> Vec<(Option<&str>, &str)>— the(variant, field)pairs treated as sensitive (mirrors the credential set, since credentials are always sensitive — used for log/serialization redaction).impl HasCredentialMarkers for <Type>— opts the type into the specialized marker-slice path read by#[plexus_macros::method]at schema-build time.
#[derive(Credentials)] cannot be applied to a union.
#[derive(StreamEvent)] — deprecated
Kept for backward compatibility. The caller-wraps streaming architecture means stream-item enums should just use Serialize + Deserialize + JsonSchema (standard derives). Do not reach for StreamEvent in new code.
#[derive(JsonSchema)] (compat shim)
Only available when plexus-macros is compiled with the schemars-compat feature and aliased as schemars in a crate's dev-dependencies. Produces a no-op impl JsonSchema, preventing a duplicate-impl conflict with the impl JsonSchema generated by #[derive(PlexusRequest)] when test code writes #[derive(PlexusRequest, schemars::JsonSchema)].
Library crates almost never need this directly; the companion crate plexus-schemars-compat is the public entry point.
Migration from deprecated surfaces
All deprecations in plexus-macros 0.5 still compile with warnings in 0.7; none has a removal version yet.
#[hub_methods] → #[plexus_macros::activation]
Before:
After:
Identical semantics. #[hub_methods] emits a deprecation warning pointing at the replacement.
#[hub_method] → #[plexus_macros::method]
Before:
async
After:
async
hub = true / children = [...] → #[plexus_macros::child] methods
Before:
After:
Hub mode is now inferred from the presence of #[child] methods (CHILD-8). The hub flag and children = [...] list emit deprecation warnings and still work in 0.7.
Output pipeline
The macro output feeds the same pipeline today as it did in 0.4, but with richer metadata:
#[plexus_macros::activation] (this crate)
↓ emits
PluginSchema { methods: [MethodSchema { role, deprecation, params, ... }] }
↓ served over Plexus RPC (plexus-transport)
Synapse (Haskell) fetches, deduplicates, builds Synapse IR
↓ feeds
plexus-codegen-{rust,typescript,python}
↓ produces
Generated clients with typed methods, streaming iterators, and
deprecation warnings that mirror your `#[deprecated]` annotations
See the substrate reference server (plexus-substrate) for end-to-end examples of every feature in production use:
bash,echo— minimal single-method activations.cone,claudecode— generic activations withHandleEnum, dynamic children, andresolve_handle.solar— hub activation with dynamic child routing +listcapability.interactive— bidirectional channels.changelog,mustache— multi-method flat activations.
License
MIT