Skip to main content

Module examples

Module examples 

Source
Expand description

Workflow examples demonstrating common patterns.

This module provides example workflows that can be used as documentation and templates for building custom workflows.

§Cooperative Cancellation Examples

This module includes examples demonstrating cooperative cancellation patterns:

  • Polling Pattern: CancellationAwareTask shows how to poll the cancellation token in long-running loops
  • Tokio Select Pattern: PollingTask demonstrates using tokio::select! to race between work completion and cancellation
  • Timeout + Cancellation: TimeoutAndCancellationTask shows handling both timeout and cancellation simultaneously

§Best Practices

§When to Use Polling vs. Waiting

  • Use polling (poll_cancelled()) in tight loops where you check frequently
  • Use waiting (wait_cancelled()) with tokio::select! when racing cancellation against other async operations

§Handling Cleanup on Cancellation

When a task is cancelled, it should clean up resources gracefully:

while !context.cancellation_token().map_or(false, |t| t.poll_cancelled()) {
    // Do work
    if cancelled {
        // Clean up resources
        return Ok(TaskResult::Cancelled);
    }
}

§Interaction with Timeouts

Tasks can be cancelled by either a timeout or an explicit cancellation signal. Always check context.cancellation_token() even when using timeouts.

§Common Pitfalls

  • Blocking code: Long-running synchronous operations prevent cancellation checking
  • Forgetting to poll: If you don’t check the token, cancellation won’t work
  • Assuming cancellation is immediate: Cooperative cancellation relies on tasks checking the token voluntarily

§Example

use forge_agent::workflow::{
    WorkflowBuilder, CancellationAwareTask,
    TaskId,
};

// Create a cancellation-aware workflow
let task = CancellationAwareTask::new(
    TaskId::new("task1"),
    "Long running task".to_string(),
    1000,
    10,
);

let workflow = WorkflowBuilder::sequential(vec![Box::new(task)])?;

Structs§

CancellationAwareTask
Cancellation-aware task that demonstrates polling pattern.
PollingTask
Polling task that demonstrates tokio::select! pattern.
TimeoutAndCancellationTask
Timeout and cancellation aware task.

Functions§

cooperative_cancellation_example
Creates a cooperative cancellation example workflow.
example_agent_workflow
Creates an agent workflow with AI-driven operations.
example_branching_workflow
Creates a branching workflow with conditional paths.
example_graph_aware_workflow
Creates a graph-aware workflow that uses the Forge SDK.
example_linear_workflow
Creates a linear workflow that executes tasks sequentially.
timeout_cancellation_example
Creates a timeout and cancellation example workflow.