orcher_sdk/lib.rs
1//! # Orcher Rust SDK
2//!
3//! Build durable workflows and tasks for the Orcher workflow engine.
4//!
5//! Workflows are async functions whose progress the engine records, so they
6//! survive crashes and restarts and resume where they left off. Tasks are the
7//! steps that touch the outside world, and are retried under a policy when they
8//! fail. A [`Worker`] polls the engine and runs both; a [`Client`] starts
9//! workflows and reads their results.
10//!
11//! ## Quick start
12//!
13//! ```rust,no_run
14//! use orcher_sdk::prelude::*;
15//!
16//! // A worker is I/O-bound, so a single-threaded runtime is enough.
17//! #[tokio::main(flavor = "current_thread")]
18//! async fn main() -> Result<()> {
19//! let worker = Worker::builder()
20//! .server_url("http://localhost:50051")
21//! .task_queue("my-queue")
22//! .build()
23//! .await?;
24//!
25//! worker.run().await
26//! }
27//! ```
28//!
29//! ## Tokio runtime
30//!
31//! A worker spends its time waiting on gRPC long-polls, so the single-threaded
32//! runtime (`#[tokio::main(flavor = "current_thread")]`) is recommended: its
33//! event loop sleeps while it waits, whereas the multi-threaded work-stealing
34//! scheduler keeps its threads busy even when the worker is idle.
35//!
36//! Run CPU-heavy work with `tokio::task::spawn_blocking()`, which uses a
37//! separate thread pool and does not hold up the event loop:
38//!
39//! ```rust
40//! use orcher_sdk::prelude::*;
41//!
42//! #[task]
43//! async fn checksum(_ctx: TaskContext, data: Vec<u8>) -> Result<u64> {
44//! let sum = tokio::task::spawn_blocking(move || {
45//! // CPU-intensive work here.
46//! data.iter().map(|&b| u64::from(b)).sum::<u64>()
47//! })
48//! .await
49//! .map_err(|e| Error::Other(e.to_string()))?;
50//! Ok(sum)
51//! }
52//! ```
53//!
54//! ## Modules
55//!
56//! - [`workflow`](mod@workflow): the workflow context and the durable operations it offers
57//! - [`task`](mod@task): the task context, retry policies and task options
58//! - [`actor`](mod@actor): keyed actors with durable state
59//! - [`worker`]: building and running a worker
60//! - [`client`]: starting, querying and sending events to workflows
61//! - [`error`]: the SDK's error types
62//! - [`prelude`]: the imports most programs need
63
64#![warn(missing_docs)]
65#![warn(rust_2018_idioms)]
66#![allow(clippy::module_inception)]
67// Protocol messages are built with `..Default::default()` even when every
68// field is set today: a field added to the protocol then leaves an older
69// release of this crate building, sending the field unset.
70#![allow(clippy::needless_update)]
71
72// Re-exported so that macro-generated `#[::orcher_sdk::ctor::ctor]` resolves in user crates.
73#[cfg(feature = "auto-register")]
74#[doc(hidden)]
75pub extern crate ctor;
76
77/// Crates that macro-generated code names through `::orcher_sdk::__private`, so a crate
78/// using the macros needs no dependency on them. Not public API.
79#[doc(hidden)]
80pub mod __private {
81 #[cfg(feature = "auto-register")]
82 pub use inventory;
83 pub use serde_json;
84}
85
86pub mod actor;
87pub mod client;
88pub mod debugging;
89pub mod error;
90pub mod interceptor;
91pub mod payload;
92pub mod task;
93mod tls;
94pub mod worker;
95pub mod workflow;
96
97#[cfg(any(test, feature = "testing"))]
98pub mod testing;
99
100pub use actor::{ActorContext, ActorKey, SharedActorContext};
101pub use client::Client;
102pub use error::{Error, ErrorCode, Result, Severity, TaskFailureCode};
103pub use payload::{Payload, PayloadCodec};
104pub use task::{Task, TaskContext};
105pub use worker::{HealthReport, HealthStatus, RuntimeStats, Worker, WorkerBuilder};
106pub use workflow::{Workflow, WorkflowContext};
107
108// These are orcher-sdk-core's (and orcher-proto's) own types, so a release
109// that moves to a newer orcher-sdk-core is a minor release of this crate: a
110// crate that also depends on orcher-sdk-core or orcher-proto must move to
111// the same versions.
112pub use orcher_sdk_core::{
113 ListWorkflowsOptions, ListWorkflowsSortOrder, SearchWorkflowsOptions,
114 WorkflowExecutionDescription, WorkflowExecutionInfo, WorkflowListPage, WorkflowStatus,
115};
116
117/// A namespace, as the namespace calls on [`Client`] return it.
118pub use orcher_sdk_core::Namespace;
119
120/// A worker's wire measurements; see [`Worker::wire_metrics`].
121pub use orcher_sdk_core::observability::{MethodStats, WireMetricsSnapshot, WorkStats};
122
123#[cfg(feature = "auto-register")]
124pub use orcher_sdk_macros::{actor, event, operations, query, task, tasks, update, workflow};
125
126#[cfg(feature = "derive")]
127pub use orcher_sdk_macros::Payload;
128
129/// The imports most programs need.
130///
131/// ```rust
132/// use orcher_sdk::prelude::*;
133/// ```
134///
135/// # Result type
136///
137/// Workflows and tasks must return [`orcher_sdk::Result`](crate::Result), which the
138/// prelude exports, not `anyhow::Result`. Converting through `anyhow::Error`
139/// loses the error's type, and the worker relies on that type to tell a
140/// workflow that is suspending from one that has failed. An explicit
141/// `use anyhow::Result;` overrides the prelude's `Result`, so do not import both
142/// in workflow and task modules.
143pub mod prelude {
144 pub use crate::error::{Error, ErrorCode, Result, Severity};
145
146 // Workflow and task contexts
147 pub use crate::task::{Task, TaskContext};
148 pub use crate::workflow::{
149 ChildWorkflowHandle, ChildWorkflowOptions, ClosureExecution, RestartFreshOptions, Workflow,
150 WorkflowContext,
151 };
152
153 // Actor types
154 pub use crate::actor::{ActorContext, ActorKey, SharedActorContext};
155
156 // Client types
157 pub use crate::client::{Client, WorkflowHandle};
158
159 // Workflow query/list types
160 pub use crate::{
161 ListWorkflowsOptions, SearchWorkflowsOptions, WorkflowExecutionDescription,
162 WorkflowExecutionInfo, WorkflowListPage, WorkflowStatus,
163 };
164
165 // Worker types
166 pub use crate::worker::{HealthReport, HealthStatus, RuntimeStats, Worker, WorkerBuilder};
167
168 // Payload utilities
169 pub use crate::payload::{from_payload, to_payload, Payload, PayloadCodec, PayloadExt};
170
171 #[cfg(feature = "auto-register")]
172 pub use orcher_sdk_macros::{actor, event, operations, query, task, tasks, update, workflow};
173
174 #[cfg(feature = "derive")]
175 pub use orcher_sdk_macros::Payload;
176
177 // Commonly needed items from dependencies.
178 pub use async_trait::async_trait;
179 pub use serde::{Deserialize, Serialize};
180}
181
182/// The version of this crate.
183pub const VERSION: &str = env!("CARGO_PKG_VERSION");
184
185/// The name this SDK reports itself under.
186pub const SDK_NAME: &str = "orcher-rust-sdk";
187
188/// Calls the crate's generated `__orcher_force_registration()` function.
189///
190/// Most programs do not need this macro. With the `auto-register` feature,
191/// every `#[task]` and `#[workflow]` registers itself when the program starts,
192/// and [`WorkerBuilder::new`] collects them.
193///
194/// The macro is for crates that generate explicit registration code instead:
195/// a build script writes `$OUT_DIR/auto_register.rs` defining
196/// `__orcher_force_registration()`, and the crate root includes it with
197/// `include!(concat!(env!("OUT_DIR"), "/auto_register.rs"));`. Without that
198/// function in scope, the macro fails to compile with a "not found" error.
199///
200/// # Example
201///
202/// ```rust,no_run
203/// use orcher_sdk::prelude::*;
204///
205/// #[task]
206/// async fn my_task(ctx: TaskContext, input: String) -> Result<String> {
207/// Ok(format!("Processed: {}", input))
208/// }
209///
210/// #[workflow]
211/// async fn my_workflow(ctx: WorkflowContext, input: String) -> Result<String> {
212/// Ok(input)
213/// }
214///
215/// // Defines `__orcher_force_registration()`; written by the build script.
216/// // include!(concat!(env!("OUT_DIR"), "/auto_register.rs"));
217/// # fn __orcher_force_registration() {}
218///
219/// #[tokio::main]
220/// async fn main() -> Result<()> {
221/// // Registers my_task and my_workflow.
222/// orcher_sdk::initialize_handlers!();
223///
224/// let service = Worker::builder()
225/// .server_url("http://localhost:50051")
226/// .build()
227/// .await?;
228///
229/// service.run().await
230/// }
231/// ```
232#[cfg(feature = "auto-register")]
233#[macro_export]
234macro_rules! initialize_handlers {
235 () => {
236 // Defined by the calling crate's generated `auto_register.rs`.
237 __orcher_force_registration();
238 };
239}
240
241/// Fails to compile: `initialize_handlers!` requires the `auto-register` feature.
242#[cfg(not(feature = "auto-register"))]
243#[macro_export]
244macro_rules! initialize_handlers {
245 () => {
246 compile_error!(
247 "initialize_handlers!() requires the 'auto-register' feature. \
248 Enable it in Cargo.toml: orcher-sdk = { version = \"...\", features = [\"auto-register\"] }"
249 );
250 };
251}