Skip to main content

toolkit_contract_macros/
lib.rs

1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2
3use proc_macro::TokenStream;
4use syn::parse_macro_input;
5
6/// Code generation for the `#[contract]` trait expansion.
7mod codegen;
8mod consumes;
9mod contract_error;
10mod grpc_contract;
11mod grpc_contract_parse;
12/// Code generation for `#[derive(ContractError)]`.
13mod model;
14/// Code generation for the `#[grpc_contract]` projection.
15mod parse;
16mod projection;
17mod proto_bridge;
18mod provides;
19mod query_params;
20mod rest_contract;
21mod rest_contract_parse;
22mod stream_attr;
23mod support;
24
25#[proc_macro_attribute]
26pub fn contract(attr: TokenStream, item: TokenStream) -> TokenStream {
27    let contract_attr = parse_macro_input!(attr as parse::ContractAttr);
28    let item_trait = parse_macro_input!(item as syn::ItemTrait);
29
30    match parse::parse_trait(contract_attr, &item_trait) {
31        Ok(model) => codegen::generate(&model).into(),
32        Err(err) => err.to_compile_error().into(),
33    }
34}
35
36#[proc_macro_attribute]
37pub fn rest_contract(attr: TokenStream, item: TokenStream) -> TokenStream {
38    let attr = parse_macro_input!(attr as rest_contract_parse::RestContractAttr);
39    let item = parse_macro_input!(item as syn::ItemTrait);
40
41    match rest_contract_parse::parse(attr, item) {
42        Ok(model) => rest_contract::generate(&model).into(),
43        Err(err) => err.to_compile_error().into(),
44    }
45}
46
47/// `#[toolkit::grpc_contract(package = "...", service = "...", stubs_module = "...")]`
48/// — the gRPC projection of a base contract trait.
49///
50/// Generates client-side code only (servers are hand-written): the binding IR
51/// (`<trait>_grpc_binding()`), `<BASE>_GRPC_SERVICE` (the `package.Service`
52/// name), the `<base>_grpc_schemas` visitor for protogen, a compile-time check
53/// that a `vN` package matches the contract's major version, and, under
54/// `grpc-client`, `<Trait>Client` (`new`, `connect`, `connect_lazy`) and
55/// `<Trait>ResolvingClient`, both implementing the base trait. Methods take
56/// `#[rpc(name = "...")]`, `#[idempotency_level(...)]`, and optionally
57/// `#[streaming]`, `#[retryable]` and `#[circuit_breaker(skip)]`.
58#[proc_macro_attribute]
59pub fn grpc_contract(attr: TokenStream, item: TokenStream) -> TokenStream {
60    let attr = parse_macro_input!(attr as grpc_contract_parse::GrpcContractAttr);
61    let item = parse_macro_input!(item as syn::ItemTrait);
62
63    match grpc_contract_parse::parse(attr, item) {
64        Ok(model) => grpc_contract::generate(&model).into(),
65        Err(err) => err.to_compile_error().into(),
66    }
67}
68
69/// `#[toolkit::provides(contract = ..., local = ..., transports = [...])]` —
70/// auto-wire a generated contract client into the host `ClientHub`.
71///
72/// Applied on a module struct in the provider crate; generates an inherent
73/// `wire_<contract_snake>` async method that validates the contract IR,
74/// reads typed wiring config, and registers the appropriate Local/REST/gRPC
75/// client. `contract = [sdk::Api(local = ...), sdk::OtherApi(...)]` provides
76/// several contracts from one attribute. See `toolkit_contract_macros::provides`
77/// for the full attribute surface.
78#[proc_macro_attribute]
79pub fn provides(attr: TokenStream, item: TokenStream) -> TokenStream {
80    let attr = parse_macro_input!(attr as provides::ProvidesAttr);
81    let item = parse_macro_input!(item as syn::ItemStruct);
82    match provides::generate(&attr, &item) {
83        Ok(tokens) => tokens.into(),
84        Err(err) => err.to_compile_error().into(),
85    }
86}
87
88/// `#[toolkit::consumes(contract = ..., from = "gear")]` — declare a contract
89/// dependency wired via eventual-readiness directory discovery.
90///
91/// Applied on the gear struct (alongside `#[toolkit::gear]`). Emits a
92/// `ConsumerRegistration` that the runtime's
93/// proxy-wiring phase replays: a compile-time local impl wins, otherwise a
94/// directory-resolving client is registered — `<Contract>RestResolvingClient`
95/// by default, `<Contract>GrpcResolvingClient` with `transport = grpc` (top
96/// level or per entry).
97/// `contract = [sdk::Api, sdk::OtherApi(from = "other")]` consumes several
98/// contracts from one attribute. Does NOT inject a topo-sort dependency — see
99/// `toolkit_contract_macros::consumes` docs.
100#[proc_macro_attribute]
101pub fn consumes(attr: TokenStream, item: TokenStream) -> TokenStream {
102    let attr = parse_macro_input!(attr as consumes::ConsumesAttr);
103    let item = parse_macro_input!(item as syn::ItemStruct);
104    match consumes::generate(&attr, &item) {
105        Ok(tokens) => tokens.into(),
106        Err(err) => err.to_compile_error().into(),
107    }
108}
109
110#[proc_macro_derive(ProtoBridge, attributes(proto_bridge))]
111pub fn derive_proto_bridge(input: TokenStream) -> TokenStream {
112    let input = parse_macro_input!(input as syn::DeriveInput);
113    match proto_bridge::generate(&input) {
114        Ok(tokens) => tokens.into(),
115        Err(err) => err.to_compile_error().into(),
116    }
117}
118
119/// `#[derive(QueryParams)]` — mark a struct as a REST query parameter.
120///
121/// Generates `impl QueryParams`, whose `openapi_params()` describes each field
122/// for the `OpenAPI` document. The generated route registers those parameters, so
123/// the spec is derived from the same declaration that determines the wire
124/// format instead of being inferred separately.
125///
126/// Field rules, both enforced at compile time:
127/// - every field's leaf type must implement
128///   [`QueryScalar`](toolkit_contract::query::QueryScalar) — scalars,
129///   `Option<scalar>`, and `Vec<scalar>`. Nested structs are rejected: a query
130///   string is a flat key/value list and cannot represent them unambiguously.
131/// - a `Vec<..>` field must carry `#[serde(default)]`, since an empty vector
132///   emits no key and would otherwise fail to deserialize.
133///
134/// `#[serde(rename = "...")]` and `#[serde(skip)]` are honoured so the spec
135/// matches what serde actually puts on the wire.
136#[proc_macro_derive(QueryParams)]
137pub fn derive_query_params(input: TokenStream) -> TokenStream {
138    let input = parse_macro_input!(input as syn::DeriveInput);
139    match query_params::generate(&input) {
140        Ok(tokens) => tokens.into(),
141        Err(err) => err.to_compile_error().into(),
142    }
143}
144
145/// `#[derive(ContractError)]` — wire a typed Rust error enum into the
146/// PRD #1536 RFC 9457 envelope.
147///
148/// Per-variant attributes:
149/// - `#[error_code("INSUFFICIENT_FUNDS")]` (required)
150/// - `#[error_domain("billing.v1")]` (required, or set once on the enum)
151/// - `#[canonical(FailedPrecondition)]` (required — one of the 16
152///   `ProblemCategory` variants)
153///
154/// Generates `From<MyError> for Problem` (server-side) and
155/// `TryFrom<Problem> for MyError` (client-side); unknown
156/// `error_code`/`error_domain` pairs round-trip back as the original
157/// `Problem` so callers can still handle them as generic envelopes.
158///
159/// Mark exactly one variant `#[contract_error(fallback)]` (unit, or a single
160/// named field receiving the original `Problem`) to additionally generate a
161/// **total** `From<TransportError> for MyError`, gated on the SDK having either
162/// the `rest-client` or the `grpc-client` feature. Both generated clients call
163/// that conversion on every failure, and they use it to reconstruct typed
164/// variants from an RFC 9457 envelope — the response body over HTTP, the
165/// `x-toolkit-problem-bin` trailer over gRPC — and to route
166/// un-reconstructable transport/protocol failures into the fallback variant.
167///
168/// **Declare a `ContractError` enum as a contract method's error type whenever
169/// the caller branches on a typed variant's payload.** `CanonicalError` cannot
170/// carry one: it has no field for `error_code`, `error_domain` or
171/// `context["data"]`, so converting through it strips the domain identity in
172/// both directions, and for the categories whose context type has required
173/// fields (`FailedPrecondition`, `ResourceExhausted`, `InvalidArgument`,
174/// `Aborted`) it also loses or corrupts the *category*.
175///
176/// The fallback field may be `Problem` **or** `Box<Problem>`. Prefer the boxed
177/// form: a `Problem` is ~208 bytes and the fallback variant sets the size of
178/// the whole enum, hence of every `Result<_, MyError>` the contract returns,
179/// which trips `clippy::result_large_err` on each generated method.
180#[proc_macro_derive(
181    ContractError,
182    attributes(error_code, error_domain, canonical, contract_error)
183)]
184pub fn derive_contract_error(input: TokenStream) -> TokenStream {
185    let input = parse_macro_input!(input as syn::DeriveInput);
186    match contract_error::generate(input) {
187        Ok(tokens) => tokens.into(),
188        Err(err) => err.to_compile_error().into(),
189    }
190}