Testing Tasks
Tasks can be tested independently using mock context:
1#[cfg(test)]2mod tests {3use super::*;4use orcher::testing::TestEnv;56#[tokio::test]7async fn test_send_email() -> Result<()> {8 let mut env = TestEnv::new();910 // Mock the task result the workflow will observe11 env.mock_task("send_email").returns(Ok(EmailResult {12 message_id: "test_123".to_string(),13 sent: true,14 }));1516 let input = EmailInput {17 to: "test@example.com".to_string(),18 subject: "Test".to_string(),19 body: "Test body".to_string(),20 };2122 // Drive the workflow that invokes the task23 let message_id: String = env.execute_workflow("notify_user", input).await?;2425 assert!(!message_id.is_empty());26 env.assert_task_called("send_email", 1);27 Ok(())28}2930#[tokio::test]31async fn test_idempotency() -> Result<()> {32 // Reset any global state33 reset_test_state();3435 let mut env = TestEnv::new();36 env.mock_task("process_payment").returns(Ok(payment_result()));3738 // Run the same workflow twice with identical input39 let _first: PaymentResult = env40 .execute_workflow("payment_workflow", payment_input())41 .await?;42 let _second: PaymentResult = env43 .execute_workflow("payment_workflow", payment_input())44 .await?;4546 // Verify no duplicate side effects occurred47 assert_eq!(get_charge_count(), 1);48 Ok(())49}50}Common Task Patterns
These patterns show how to structure tasks for real-world use cases. Each example demonstrates proper error handling, retry safety, and integration with the TaskContext.
API Integration
Tasks that call external HTTP APIs should handle transient errors (network timeouts, rate limits) with retries and use idempotency keys to prevent duplicate requests.
1use std::time::Duration;23#[task(4name = "call_external_api",5retry = 5,6timeout_mins = 27)]8pub async fn call_external_api(9ctx: TaskContext,10request: ApiRequest,11) -> Result<ApiResponse> {12let client = reqwest::Client::new();1314let response = client15 .post(&request.endpoint)16 .json(&request.payload)17 .header("X-API-Key", get_api_key())18 .timeout(Duration::from_secs(30))19 .send()20 .await21 .context("API request failed")?;2223if ctx.is_retry() {24 tracing::warn!(25 "API call retry (attempt {})",26 ctx.attempt()27 );28}2930let data = response31 .json()32 .await33 .context("Failed to parse API response")?;3435Ok(data)36}Batch Processing
Batch tasks process collections of items in a single execution. Use heartbeats to report progress and enable resumption from the last processed item if the task is interrupted.
1#[task(2name = "process_batch_parallel",3timeout_mins = 154)]5pub async fn process_batch_parallel(6ctx: TaskContext,7items: Vec<Item>,8) -> Result<BatchResult> {9use futures::future::join_all;1011let chunk_size = 10;12let chunks: Vec<_> = items.chunks(chunk_size).collect();1314let mut all_results = Vec::new();1516for (i, chunk) in chunks.iter().enumerate() {17 // Process chunk in parallel18 let futures = chunk.iter().map(|item| {19 process_single_item(item.clone())20 });2122 let results = join_all(futures).await;23 all_results.extend(results);2425 // Heartbeat after each chunk26 ctx.heartbeat_with_details(Some(Progress {27 current: (i + 1) * chunk_size,28 total: items.len(),29 })).await?;30}3132Ok(BatchResult {33 processed: all_results.len(),34 results: all_results,35})36}