Repository navigation
Expand file tree
/
Copy pathbasic_pipeline.rs
More file actions
239 lines (205 loc) · 7.52 KB
/
Copy pathbasic_pipeline.rs
File metadata and controls
239 lines (205 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
//! Basic Treadle pipeline example.
//!
//! This example demonstrates:
//! - Building a workflow with stages and dependencies
//! - Advancing work items through the pipeline
//! - Handling review stages
//! - Checking pipeline status
//! - Observing workflow events
//!
//! Run with: `cargo run --example basic_pipeline`
use async_trait::async_trait;
use treadle::{
MemoryStateStore, Result, Stage, StageContext, StageOutcome, WorkItem, Workflow,
WorkflowEvent,
};
/// Our work item - a document to process.
#[derive(Debug, Clone)]
struct Document {
id: String,
content: String,
}
impl Document {
fn new(id: &str, content: &str) -> Self {
Self {
id: id.to_string(),
content: content.to_string(),
}
}
}
impl WorkItem for Document {
fn id(&self) -> &str {
&self.id
}
}
/// Stage 1: Scan the document for structure.
#[derive(Debug)]
struct ScanStage;
#[async_trait]
impl Stage for ScanStage {
fn name(&self) -> &str {
"scan"
}
async fn execute(
&self,
item: &dyn WorkItem,
_ctx: &mut StageContext,
) -> Result<StageOutcome> {
let item_id = item.id().to_string();
println!(" 📄 Scanning document '{}'", item_id);
// Simulate some processing
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
println!(" ✓ Document structure identified");
Ok(StageOutcome::Complete)
}
}
/// Stage 2: Extract entities from the document.
#[derive(Debug)]
struct ExtractStage;
#[async_trait]
impl Stage for ExtractStage {
fn name(&self) -> &str {
"extract"
}
async fn execute(
&self,
item: &dyn WorkItem,
_ctx: &mut StageContext,
) -> Result<StageOutcome> {
let item_id = item.id().to_string();
println!(" 🔍 Extracting entities from '{}'", item_id);
tokio::time::sleep(std::time::Duration::from_millis(150)).await;
println!(" ✓ Found: 2 people, 1 organization");
Ok(StageOutcome::Complete)
}
}
/// Stage 3: Human review of extracted entities.
#[derive(Debug)]
struct ReviewStage;
#[async_trait]
impl Stage for ReviewStage {
fn name(&self) -> &str {
"review"
}
async fn execute(
&self,
item: &dyn WorkItem,
_ctx: &mut StageContext,
) -> Result<StageOutcome> {
let item_id = item.id().to_string();
println!(" 👀 Review requested for '{}'", item_id);
println!(" Entities to review:");
println!(" - Person: John Doe");
println!(" - Org: Acme Inc");
// Stage will pause here for human review
Ok(StageOutcome::NeedsReview)
}
}
/// Stage 4: Export the finalized document.
#[derive(Debug)]
struct ExportStage;
#[async_trait]
impl Stage for ExportStage {
fn name(&self) -> &str {
"export"
}
async fn execute(
&self,
item: &dyn WorkItem,
_ctx: &mut StageContext,
) -> Result<StageOutcome> {
let item_id = item.id().to_string();
println!(" 💾 Exporting document '{}'", item_id);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
println!(" ✓ Exported to output.json");
Ok(StageOutcome::Complete)
}
}
#[tokio::main]
async fn main() -> Result<()> {
println!("╔═══════════════════════════════════════════╗");
println!("║ Treadle Basic Pipeline Example ║");
println!("╚═══════════════════════════════════════════╝\n");
// Build the workflow
println!("📋 Building workflow...");
let workflow = Workflow::builder()
.stage("scan", ScanStage)
.stage("extract", ExtractStage)
.stage("review", ReviewStage)
.stage("export", ExportStage)
.dependency("extract", "scan")
.dependency("review", "extract")
.dependency("export", "review")
.build()?;
println!(" Stages: {:?}\n", workflow.stages());
// Subscribe to events (in background)
let mut event_receiver = workflow.subscribe();
tokio::spawn(async move {
while let Ok(event) = event_receiver.recv().await {
match event {
WorkflowEvent::StageStarted { stage, .. } => {
println!(" [Event] Stage '{}' started", stage);
}
WorkflowEvent::StageCompleted { stage, .. } => {
println!(" [Event] Stage '{}' completed", stage);
}
WorkflowEvent::ReviewRequired { stage, .. } => {
println!(" [Event] Review required at stage '{}'", stage);
}
WorkflowEvent::WorkflowCompleted { item_id } => {
println!(" [Event] Workflow completed for '{}'", item_id);
}
_ => {}
}
}
});
// Create state store (in-memory for this example)
let mut store = MemoryStateStore::new();
// Create a document to process
let doc = Document::new(
"doc-001",
"John Doe works at Acme Inc. He manages the engineering team.",
);
println!("📄 Processing document: {}", doc.id);
println!(" Content: \"{}\"\n", doc.content);
// First advance - will stop at review
println!("▶️ First Advance (automatic stages)");
println!("─────────────────────────────────────────");
workflow.advance(&doc, &mut store).await?;
// Give events time to print
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
// Check status
println!("\n📊 Status after first advance:");
println!("─────────────────────────────────────────");
let status = workflow.status(doc.id(), &store).await?;
println!("{}", status);
// Check what stages need review
if status.has_pending_reviews() {
println!("⏸️ Workflow paused - awaiting human review\n");
// Simulate human review decision
println!("👤 Human reviewer checking entities...");
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
println!(" Decision: APPROVED ✓\n");
// Approve the review
println!("✅ Approving review stage");
println!("─────────────────────────────────────────");
workflow
.approve_review(doc.id(), "review", &mut store)
.await?;
}
// Second advance - will complete
println!("\n▶️ Second Advance (remaining stages)");
println!("─────────────────────────────────────────");
workflow.advance(&doc, &mut store).await?;
// Give events time to print
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
// Final status
println!("\n📊 Final Status:");
println!("─────────────────────────────────────────");
let final_status = workflow.status(doc.id(), &store).await?;
println!("{}", final_status);
if workflow.is_complete(doc.id(), &store).await? {
println!("\n🎉 Success! Document processing complete!\n");
}
Ok(())
}