orcher_sdk_macros/lib.rs
1//! # ORCHER Macros
2//!
3//! Procedural macros for defining Orcher workflows, tasks, handlers, and actors.
4//!
5//! Each macro keeps the item you wrote and generates the glue around it: payload
6//! (de)serialization, typed references, and registration so a worker finds the item at
7//! startup without manual wiring.
8//!
9//! ## Available Macros
10//!
11//! - `#[task]` and `#[tasks]`: define tasks, the units of work that touch the outside world.
12//! - `#[workflow]`: define a workflow, the deterministic code that orchestrates tasks.
13//! - `#[query]`, `#[update]`, `#[event]`: handlers that read, change, or send events to a
14//! running workflow.
15//! - `#[actor]`, `#[operations]`, `#[operation]`: stateful actors.
16//! - `#[derive(Payload)]` (feature `derive`): payload conversion methods for a type.
17//!
18//! These macros are re-exported by the `orcher-sdk` crate, which the generated code refers
19//! to, so depend on `orcher-sdk` and import them from its prelude.
20//!
21//! ## Examples
22//!
23//! ### Task Macro
24//!
25//! ```rust
26//! use orcher_sdk::prelude::*;
27//!
28//! #[task(
29//! retry_policy(max_attempts = 3, initial_interval = 1, backoff_coefficient = 2.0),
30//! timeout = 30
31//! )]
32//! async fn process_data(_ctx: TaskContext, input: String) -> Result<String> {
33//! // Do the work here.
34//! Ok(format!("Processed: {input}"))
35//! }
36//! ```
37//!
38//! ### Workflow Macro
39//!
40//! ```rust
41//! use orcher_sdk::prelude::*;
42//!
43//! # #[task]
44//! # async fn process_data(_ctx: TaskContext, input: String) -> Result<String> { Ok(input) }
45//! #[workflow(name = "data-pipeline")]
46//! async fn data_pipeline(ctx: WorkflowContext, input: String) -> Result<String> {
47//! // Orchestrate tasks here.
48//! ctx.execute_task(process_data, input).await
49//! }
50//! ```
51
52extern crate proc_macro;
53
54mod actor;
55mod common;
56mod event;
57mod query;
58mod task;
59mod update;
60mod workflow;
61
62#[cfg(feature = "derive")]
63mod derive;
64
65use proc_macro::TokenStream;
66
67/// Turns an `async fn` into a task that workers can run.
68///
69/// The function must be `async`, take `TaskContext` as its first parameter, and have a
70/// return type. The macro keeps the function, renamed to `<name>_impl`, and turns
71/// `<name>` into a typed task reference that workflows schedule it by. It also adds a
72/// payload-level handler and a registration that makes the task available to workers.
73///
74/// # Attributes
75///
76/// - `name`: task name; defaults to the function name. Workflows schedule tasks by
77/// this name.
78/// - `timeout`: timeout in seconds. `timeout_mins` sets it in minutes instead.
79/// - `heartbeat_timeout`: seconds without a heartbeat before the task counts as stalled.
80/// - `retry`: maximum attempts, with exponential backoff (1 s initial, 60 s maximum,
81/// coefficient 2.0).
82/// - `retry_policy(...)`: an explicit policy; takes precedence over `retry`.
83/// - `max_attempts`: maximum attempts, including the first (default: 3).
84/// Use `max_attempts = unlimited` for no attempt limit. This requires an
85/// engine release that treats zero attempts as unlimited; engines through
86/// 0.5.5 interpret zero as the default three attempts.
87/// - `initial_interval`: first retry delay in seconds (default: 1)
88/// - `max_interval`: cap on the retry delay in seconds (default: 60)
89/// - `backoff_coefficient`: multiplier applied to the delay after each retry (default: 2.0)
90/// - `non_retryable_errors = ["..."]`: error types that are never retried.
91/// - `preset`: fills in the retry and timeout values that are not set explicitly.
92/// `"long-running"` is 3 attempts and 30 minutes, `"quick"` 1 attempt and 1 minute,
93/// `"critical"` 5 attempts and 60 minutes. Any other name is a compile error.
94///
95/// `description`, `version`, `task_queue`, `priority`, `max_concurrent`, `rate_limit`,
96/// `resources(...)`, `memory`, `idempotency_key`, `condition`, `parallel`,
97/// `requires_approval`, `approval_timeout`, and `approvers` are accepted but have no
98/// effect, and each produces a deprecation warning that says what to do instead. A task
99/// runs on the task queue of the workflow that schedules it.
100///
101/// There is no `namespace` option: a task runs in whatever namespace its worker serves,
102/// so the namespace is set on the worker (`WorkerBuilder::namespace`). Unknown attributes
103/// are a compile error.
104///
105/// # Examples
106///
107/// ```rust
108/// use orcher_sdk::prelude::*;
109///
110/// /// Fetches data from an external API.
111/// #[task(
112/// name = "fetch_data",
113/// retry_policy(max_attempts = 5, initial_interval = 2, max_interval = 30),
114/// non_retryable_errors = ["NotFound"],
115/// timeout = 60,
116/// heartbeat_timeout = 10
117/// )]
118/// async fn fetch_data(ctx: TaskContext, url: String) -> Result<String> {
119/// // Call the API here, reporting progress as it goes.
120/// ctx.heartbeat().await?;
121/// Ok(format!("data from {url}"))
122/// }
123/// ```
124///
125/// # Testing
126///
127/// The task body stays callable as `<name>_impl`, with the signature written. Call it
128/// with a context from `orcher_sdk::testing::TestTaskContext`, whose probe can cancel
129/// the task and read its heartbeats:
130///
131/// ```rust
132/// use orcher_sdk::prelude::*;
133/// use orcher_sdk::testing::TestTaskContext;
134///
135/// #[task]
136/// async fn greet(ctx: TaskContext, name: String) -> Result<String> {
137/// ctx.heartbeat().await?;
138/// Ok(format!("hello {name}, attempt {}", ctx.attempt()))
139/// }
140///
141/// # #[tokio::main(flavor = "current_thread")]
142/// # async fn main() -> Result<()> {
143/// let (ctx, probe) = TestTaskContext::new().attempt(2).build();
144/// assert_eq!(greet_impl(ctx, "ada".into()).await?, "hello ada, attempt 2");
145/// assert_eq!(probe.heartbeat_count(), 1);
146/// # Ok(())
147/// # }
148/// ```
149#[proc_macro_attribute]
150pub fn task(attr: TokenStream, item: TokenStream) -> TokenStream {
151 task::task_impl(attr, item)
152}
153
154/// Defines a group of tasks as methods on an impl block.
155///
156/// Mark each task method with `#[task]`. Attributes on `#[tasks(...)]` are defaults for
157/// every task in the group; a method's own `#[task(...)]` attributes override them.
158///
159/// # Group Attributes
160///
161/// - `retry`: default maximum attempts
162/// - `timeout`: default timeout in seconds
163/// - `timeout_mins`: default timeout in minutes
164/// - `heartbeat_timeout`: default heartbeat timeout in seconds
165/// - `preset`: default preset (`"long-running"`, `"quick"`, `"critical"`)
166/// - `version`, `memory`, `task_queue`, `priority`, `max_concurrent`, `rate_limit`:
167/// accepted but have no effect, and warn as on `#[task]`
168///
169/// `namespace` is rejected, as on `#[task]`.
170///
171/// # Method Attributes
172///
173/// Each `#[task]` method accepts the same attributes as a standalone `#[task]`.
174///
175/// # Examples
176///
177/// ```rust
178/// use orcher_sdk::prelude::*;
179///
180/// #[derive(Serialize, Deserialize)]
181/// pub struct Payment {
182/// amount_cents: u64,
183/// }
184///
185/// pub struct PaymentTasks;
186///
187/// #[tasks(retry = 3, timeout = 60)]
188/// impl PaymentTasks {
189/// #[task]
190/// async fn charge(_ctx: TaskContext, payment: Payment) -> Result<String> {
191/// // Uses the group defaults: retry = 3, timeout = 60.
192/// Ok(format!("charged {}", payment.amount_cents))
193/// }
194///
195/// #[task(retry = 10)]
196/// async fn refund(_ctx: TaskContext, charge_id: String) -> Result<bool> {
197/// // Overrides retry; keeps timeout = 60 from the group.
198/// Ok(!charge_id.is_empty())
199/// }
200/// }
201///
202/// // In a workflow, call a task through its typed reference:
203/// #[workflow]
204/// async fn checkout(ctx: WorkflowContext, payment: Payment) -> Result<String> {
205/// ctx.execute_task(PaymentTasks::charge, payment).await
206/// }
207/// ```
208#[proc_macro_attribute]
209pub fn tasks(attr: TokenStream, item: TokenStream) -> TokenStream {
210 task::tasks_impl(attr, item)
211}
212
213/// Turns an `async fn` into a workflow definition.
214///
215/// The function must be `async`, take `WorkflowContext` as its first parameter, and have
216/// a return type. Workflow code must be deterministic so it can be replayed: use the
217/// context for time, randomness, and side effects, and run I/O in tasks.
218///
219/// # Attributes
220///
221/// - `name`: workflow name; defaults to the function name. Workflows are started by this
222/// name.
223///
224/// Unrecognized attributes are ignored.
225///
226/// `timeout`, `version`, `description`, `task_queue`, `max_concurrent`, `tags(...)`,
227/// `retry_policy(...)`, `enabled`, `cron`, and `schedule` are accepted but have no effect,
228/// and each produces a deprecation warning that names the replacement. Most of them belong
229/// to a start of the workflow: set the timeout, task queue, retry policy, and cron schedule
230/// with `StartWorkflowOptions`, and the code release with `WorkerBuilder::version_id`.
231///
232/// There is no `namespace` option: a workflow runs in whatever namespace its worker serves,
233/// so the namespace is set on the worker (`WorkerBuilder::namespace`) and where workflows are
234/// started (`ClientConfig::with_namespace`, `StartWorkflowOptions::with_namespace`).
235///
236/// # Examples
237///
238/// ```rust
239/// use orcher_sdk::prelude::*;
240///
241/// /// Extracts, transforms, and loads data.
242/// #[workflow(name = "etl-pipeline")]
243/// async fn etl_pipeline(ctx: WorkflowContext, source: String) -> Result<u64> {
244/// // Orchestrate tasks here.
245/// let rows: u64 = ctx.execute_task("extract", source).await?;
246/// Ok(rows)
247/// }
248/// ```
249#[proc_macro_attribute]
250pub fn workflow(attr: TokenStream, item: TokenStream) -> TokenStream {
251 workflow::workflow_impl(attr, item)
252}
253
254/// Declares a query: a read of a running workflow's state that does not affect its
255/// execution.
256///
257/// The macro keeps the function and generates a `<Name>Query` struct (the function name
258/// with its first letter capitalized) holding the query's name and settings. It does not
259/// register the function: a workflow answers the query by passing a handler to
260/// `WorkflowContext::register_query_handler`, as below, or to
261/// `WorkflowContext::register_query_handler_with_args` to receive the arguments the
262/// client sends with the query.
263///
264/// # Attributes
265///
266/// - `name`: query name; defaults to the function name.
267/// - `description`: query description.
268/// - `timeout`: query timeout in seconds.
269/// - `namespace`: namespace the query belongs to.
270/// - `cache_ttl`: how long a result may be cached, in seconds (0 disables caching).
271/// - `version`: query version.
272///
273/// # Requirements
274///
275/// - Must not be `async`: queries are meant to be fast reads.
276/// - Must have a return type.
277/// - Must have no side effects.
278///
279/// # Examples
280///
281/// ```rust
282/// use orcher_sdk::prelude::*;
283///
284/// #[query(
285/// name = "order_status",
286/// description = "Get current order status",
287/// timeout = 10,
288/// cache_ttl = 60
289/// )]
290/// fn status(phase: String) -> String {
291/// format!("order is {phase}")
292/// }
293///
294/// // The function is kept, and `StatusQuery` describes the query:
295/// assert_eq!(StatusQuery::name(), "order_status");
296/// assert_eq!(StatusQuery::cache_ttl_seconds(), Some(60));
297///
298/// // A running workflow answers the query through a registered handler:
299/// #[workflow]
300/// async fn order(ctx: WorkflowContext, order_id: String) -> Result<String> {
301/// ctx.register_query_handler(StatusQuery::name(), || status("processing".to_string()));
302/// ctx.execute_task("ship", order_id).await
303/// }
304/// ```
305#[proc_macro_attribute]
306pub fn query(attr: TokenStream, item: TokenStream) -> TokenStream {
307 query::query_impl(attr, item)
308}
309
310/// Turns an `async fn` into an update handler for a running workflow.
311///
312/// An update is a synchronous request, sent with `WorkflowService.UpdateWorkflow`, that
313/// runs inside the workflow's execution context. Unlike a query, it can read and change
314/// workflow state. Its result is journaled as `UpdateAccepted` and `UpdateCompleted`
315/// events, so replay reproduces it.
316///
317/// # Attributes
318///
319/// - `name`: update name; defaults to the function name.
320/// - `description`: update description.
321/// - `timeout`: timeout in seconds.
322/// - `namespace`: namespace the update belongs to.
323/// - `version`: update version.
324///
325/// # Requirements
326///
327/// - Must be `async`.
328/// - Must have a return type.
329/// - First parameter must be `WorkflowContext`.
330///
331/// # Examples
332///
333/// ```rust
334/// use orcher_sdk::prelude::*;
335///
336/// #[derive(Serialize, Deserialize)]
337/// struct Address {
338/// street: String,
339/// }
340///
341/// #[derive(Serialize, Deserialize)]
342/// struct AddressChangeResult {
343/// accepted: bool,
344/// }
345///
346/// #[update]
347/// async fn change_address(ctx: WorkflowContext, new_address: Address) -> Result<AddressChangeResult> {
348/// let phase: Option<String> = ctx.get_state("phase")?;
349/// if phase.as_deref() == Some("shipped") {
350/// return Ok(AddressChangeResult { accepted: false });
351/// }
352/// ctx.set_state("address", &new_address)?;
353/// Ok(AddressChangeResult { accepted: true })
354/// }
355///
356/// #[update(name = "cancel_order", timeout = 30)]
357/// async fn cancel(ctx: WorkflowContext, reason: String) -> Result<bool> {
358/// ctx.set_state("phase", &"cancelled")?;
359/// ctx.set_state("cancel_reason", &reason)?;
360/// Ok(true)
361/// }
362/// ```
363#[proc_macro_attribute]
364pub fn update(attr: TokenStream, item: TokenStream) -> TokenStream {
365 update::update_impl(attr, item)
366}
367
368/// Declares an event: an asynchronous message sent to a running workflow to trigger an
369/// action or a state change. The sender does not wait for a result.
370///
371/// The macro keeps the function and generates a `<Name>Event` struct (the function name
372/// with its first letter capitalized) holding the event's name and settings. It does not
373/// register the function: a workflow receives the event with
374/// `WorkflowContext::wait_for_event`, as below.
375///
376/// # Attributes
377///
378/// - `name`: event name; defaults to the function name.
379/// - `description`: event description.
380/// - `timeout`: handler timeout in seconds.
381/// - `namespace`: namespace the event belongs to.
382/// - `version`: event version.
383/// - `max_queue_size`: maximum number of buffered events (default: 1000).
384/// - `priority`: 0 to 100; higher is more important.
385///
386/// # Requirements
387///
388/// - Must be `async`.
389///
390/// # Examples
391///
392/// ```rust
393/// use orcher_sdk::prelude::*;
394///
395/// #[derive(Serialize, Deserialize)]
396/// struct Approval {
397/// approver: String,
398/// }
399///
400/// #[event(
401/// name = "order_approved",
402/// description = "Handle order approval",
403/// timeout = 30,
404/// priority = 90,
405/// max_queue_size = 500
406/// )]
407/// async fn approved(approval: Approval) -> Result<String> {
408/// Ok(format!("approved by {}", approval.approver))
409/// }
410///
411/// // The function is kept, and `ApprovedEvent` describes the event:
412/// assert_eq!(ApprovedEvent::name(), "order_approved");
413///
414/// // A running workflow receives the event by waiting for it:
415/// #[workflow]
416/// async fn order(ctx: WorkflowContext, order_id: String) -> Result<String> {
417/// let approval: Approval = ctx.wait_for_event(ApprovedEvent::name()).await?;
418/// approved(approval).await
419/// }
420/// ```
421#[proc_macro_attribute]
422pub fn event(attr: TokenStream, item: TokenStream) -> TokenStream {
423 event::event_impl(attr, item)
424}
425
426/// Marks a struct as a stateful actor type.
427///
428/// Each actor instance is addressed by a key, and its exclusive operations run one at a
429/// time per key (single writer). Define the operations with `#[operations]`.
430///
431/// # Attributes
432///
433/// - `name`: actor type name; defaults to the struct name.
434///
435/// # Examples
436///
437/// ```rust
438/// use orcher_sdk::prelude::*;
439///
440/// #[actor]
441/// pub struct ShoppingCart;
442///
443/// #[actor(name = "CustomCart")]
444/// pub struct Cart;
445///
446/// assert_eq!(ShoppingCart::ACTOR_NAME, "ShoppingCart");
447/// assert_eq!(Cart::ACTOR_NAME, "CustomCart");
448/// ```
449///
450/// # Generated Code
451///
452/// - An `Actor` trait implementation with an `actor_name()` method
453/// - An `ACTOR_NAME` constant holding the actor type name
454///
455/// # Usage with Operations
456///
457/// ```rust
458/// use orcher_sdk::prelude::*;
459///
460/// #[derive(Serialize, Deserialize)]
461/// pub struct Item {
462/// name: String,
463/// }
464///
465/// #[actor]
466/// pub struct ShoppingCart;
467///
468/// #[operations]
469/// impl ShoppingCart {
470/// #[operation(exclusive)]
471/// pub async fn add_item(ctx: ActorContext, item: Item) -> Result<usize> {
472/// // Add the item and return the new item count.
473/// let state = ctx.state();
474/// let mut items: Vec<Item> = state.get("items").await?.unwrap_or_default();
475/// items.push(item);
476/// state.set("items", &items).await?;
477/// Ok(items.len())
478/// }
479/// }
480/// ```
481#[proc_macro_attribute]
482pub fn actor(attr: TokenStream, item: TokenStream) -> TokenStream {
483 actor::actor_impl(attr, item)
484}
485
486/// Defines the operations of an actor on its impl block.
487///
488/// Generates a typed client call for each operation, with serialization and dispatch
489/// handled for you.
490///
491/// # Operation Attributes
492///
493/// Mark each operation method with one of:
494///
495/// - `#[operation(exclusive)]`: single-writer; runs one at a time per actor key.
496/// - `#[operation(shared)]`: read-only. Shared operations on the same key run
497/// concurrently with each other; an exclusive operation waits for them to finish and
498/// then runs alone. State writes from a shared operation are refused.
499///
500/// Methods without `#[operation]` are kept as ordinary methods.
501///
502/// # Method Requirements
503///
504/// - First parameter must be `ActorContext` (exclusive) or `SharedActorContext` (shared).
505/// - Must be `async`.
506/// - Must return `Result<T, E>` where `T` is serializable.
507///
508/// # Examples
509///
510/// ```rust
511/// use orcher_sdk::prelude::*;
512///
513/// #[derive(Default, Serialize, Deserialize)]
514/// pub struct Cart {
515/// items: Vec<String>,
516/// }
517///
518/// #[actor]
519/// pub struct ShoppingCart;
520///
521/// #[operations]
522/// impl ShoppingCart {
523/// #[operation(exclusive)]
524/// pub async fn add_item(ctx: ActorContext, item: String) -> Result<Cart> {
525/// let state = ctx.state();
526/// let mut cart = state.get::<Cart>("cart").await?.unwrap_or_default();
527/// cart.items.push(item);
528/// state.set("cart", &cart).await?;
529/// Ok(cart)
530/// }
531///
532/// #[operation(shared)]
533/// pub async fn view_cart(ctx: SharedActorContext) -> Result<Cart> {
534/// Ok(ctx.state().get::<Cart>("cart").await?.unwrap_or_default())
535/// }
536/// }
537///
538/// assert_eq!(ShoppingCart::operations().len(), 2);
539///
540/// // Callers use the generated typed client:
541/// async fn add(client: &Client) -> Result<Cart> {
542/// client.actor::<ShoppingCart>("user-123").add_item("tea".to_string()).await
543/// }
544/// ```
545///
546/// # Generated Code
547///
548/// For each operation:
549/// - A static method for client calls: `ShoppingCart::add_item(key, item).await`
550/// - Dispatcher integration with serialization and deserialization
551/// - An internal `*_impl` method holding the original body
552///
553/// It also generates `ShoppingCart::operations()`, which returns metadata for every
554/// operation.
555#[proc_macro_attribute]
556pub fn operations(attr: TokenStream, item: TokenStream) -> TokenStream {
557 actor::operations_impl(attr, item)
558}
559
560/// Marks a method in an `#[operations]` block as an actor operation.
561///
562/// The mode is required: `#[operation(exclusive)]` for a single-writer operation or
563/// `#[operation(shared)]` for a read-only one. On its own this attribute does nothing;
564/// `#[operations]` reads it.
565///
566/// # Examples
567///
568/// ```rust
569/// use orcher_sdk::prelude::*;
570///
571/// #[actor]
572/// pub struct Counter;
573///
574/// #[operations]
575/// impl Counter {
576/// #[operation(exclusive)]
577/// pub async fn add(ctx: ActorContext, delta: i64) -> Result<i64> {
578/// // Changes actor state.
579/// let state = ctx.state();
580/// let count = state.get::<i64>("count").await?.unwrap_or(0) + delta;
581/// state.set("count", &count).await?;
582/// Ok(count)
583/// }
584///
585/// #[operation(shared)]
586/// pub async fn read(ctx: SharedActorContext) -> Result<i64> {
587/// // Reads actor state only.
588/// Ok(ctx.state().get::<i64>("count").await?.unwrap_or(0))
589/// }
590/// }
591/// ```
592#[proc_macro_attribute]
593pub fn operation(_attr: TokenStream, item: TokenStream) -> TokenStream {
594 // A marker read by `#[operations]`; the item passes through unchanged.
595 item
596}
597
598/// Derives JSON payload conversion methods for a type.
599///
600/// The type must implement serde's `Serialize` and `Deserialize`. The derive works on
601/// structs and enums, not unions. It adds inherent methods only; the `PayloadCodec` trait
602/// already applies to the type through the SDK's blanket implementation.
603///
604/// # Generated Methods
605///
606/// - `to_payload(&self) -> Result<Payload, Error>`
607/// - `from_payload(payload: &Payload) -> Result<Self, Error>`
608/// - `try_into_payload(self) -> Result<Payload, Error>`
609///
610/// # Examples
611///
612/// ```rust
613/// use orcher_sdk::prelude::*;
614///
615/// #[derive(Payload, Serialize, Deserialize)]
616/// struct OrderInput {
617/// order_id: String,
618/// amount_cents: u64,
619/// }
620///
621/// // Round-trip the value through a payload:
622/// let input = OrderInput {
623/// order_id: "order-123".to_string(),
624/// amount_cents: 9_999,
625/// };
626/// let payload = input.to_payload()?;
627/// let decoded = OrderInput::from_payload(&payload)?;
628/// assert_eq!(decoded.order_id, "order-123");
629/// # Ok::<(), orcher_sdk::Error>(())
630/// ```
631///
632/// # Integration with Macros
633///
634/// Such types can be used directly as `#[task]` and `#[workflow]` inputs and outputs:
635///
636/// ```rust
637/// use orcher_sdk::prelude::*;
638///
639/// #[derive(Payload, Serialize, Deserialize)]
640/// struct MyInput {
641/// value: String,
642/// }
643///
644/// #[task]
645/// async fn my_task(_ctx: TaskContext, input: MyInput) -> Result<String> {
646/// // The generated handler decodes `MyInput` from the task's payload.
647/// Ok(input.value)
648/// }
649/// ```
650#[cfg(feature = "derive")]
651#[proc_macro_derive(Payload)]
652pub fn derive_payload(input: TokenStream) -> TokenStream {
653 let input = syn::parse_macro_input!(input as syn::DeriveInput);
654
655 match derive::payload::derive_payload(input) {
656 Ok(tokens) => tokens.into(),
657 Err(err) => err.to_compile_error().into(),
658 }
659}