Guides

Testing Tasks


Tasks can be tested independently using mock context:

1
#[cfg(test)]
2
mod tests {
3
use super::*;
4
use orcher::testing::TestEnv;
5
6
#[tokio::test]
7
async fn test_send_email() -> Result<()> {
8
let mut env = TestEnv::new();
9
10
// Mock the task result the workflow will observe
11
env.mock_task("send_email").returns(Ok(EmailResult {
12
message_id: "test_123".to_string(),
13
sent: true,
14
}));
15
16
let input = EmailInput {
17
to: "test@example.com".to_string(),
18
subject: "Test".to_string(),
19
body: "Test body".to_string(),
20
};
21
22
// Drive the workflow that invokes the task
23
let message_id: String = env.execute_workflow("notify_user", input).await?;
24
25
assert!(!message_id.is_empty());
26
env.assert_task_called("send_email", 1);
27
Ok(())
28
}
29
30
#[tokio::test]
31
async fn test_idempotency() -> Result<()> {
32
// Reset any global state
33
reset_test_state();
34
35
let mut env = TestEnv::new();
36
env.mock_task("process_payment").returns(Ok(payment_result()));
37
38
// Run the same workflow twice with identical input
39
let _first: PaymentResult = env
40
.execute_workflow("payment_workflow", payment_input())
41
.await?;
42
let _second: PaymentResult = env
43
.execute_workflow("payment_workflow", payment_input())
44
.await?;
45
46
// Verify no duplicate side effects occurred
47
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.

1
use std::time::Duration;
2
3
#[task(
4
name = "call_external_api",
5
retry = 5,
6
timeout_mins = 2
7
)]
8
pub async fn call_external_api(
9
ctx: TaskContext,
10
request: ApiRequest,
11
) -> Result<ApiResponse> {
12
let client = reqwest::Client::new();
13
14
let response = client
15
.post(&request.endpoint)
16
.json(&request.payload)
17
.header("X-API-Key", get_api_key())
18
.timeout(Duration::from_secs(30))
19
.send()
20
.await
21
.context("API request failed")?;
22
23
if ctx.is_retry() {
24
tracing::warn!(
25
"API call retry (attempt {})",
26
ctx.attempt()
27
);
28
}
29
30
let data = response
31
.json()
32
.await
33
.context("Failed to parse API response")?;
34
35
Ok(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(
2
name = "process_batch_parallel",
3
timeout_mins = 15
4
)]
5
pub async fn process_batch_parallel(
6
ctx: TaskContext,
7
items: Vec<Item>,
8
) -> Result<BatchResult> {
9
use futures::future::join_all;
10
11
let chunk_size = 10;
12
let chunks: Vec<_> = items.chunks(chunk_size).collect();
13
14
let mut all_results = Vec::new();
15
16
for (i, chunk) in chunks.iter().enumerate() {
17
// Process chunk in parallel
18
let futures = chunk.iter().map(|item| {
19
process_single_item(item.clone())
20
});
21
22
let results = join_all(futures).await;
23
all_results.extend(results);
24
25
// Heartbeat after each chunk
26
ctx.heartbeat_with_details(Some(Progress {
27
current: (i + 1) * chunk_size,
28
total: items.len(),
29
})).await?;
30
}
31
32
Ok(BatchResult {
33
processed: all_results.len(),
34
results: all_results,
35
})
36
}

Next Steps