forked from conductor-oss/rust-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker_example.rs
More file actions
301 lines (244 loc) · 11.6 KB
/
Copy pathworker_example.rs
File metadata and controls
301 lines (244 loc) · 11.6 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Copyright {{.Year}} Conductor OSS
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
use conductor::{
client::ConductorClient,
configuration::Configuration,
error::Result,
models::{StartWorkflowRequest, Task, TaskDef, WorkflowDef, WorkflowTask},
worker::{FnWorker, TaskHandler, WorkerOutput},
};
use std::collections::HashMap;
use std::time::Duration;
use tracing::info;
#[tokio::main]
async fn main() -> Result<()> {
// Initialize logging
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
.add_directive("conductor=info".parse().unwrap()),
)
.init();
// Load configuration
let config = Configuration::default();
info!("Connecting to Conductor at {}", config.server_api_url);
// Create the Conductor client
let client = ConductorClient::new(config.clone())?;
// Register task definitions and workflow
register_definitions(&client).await?;
// Create and configure the task handler
let mut handler = TaskHandler::new(config.clone())?;
// ============================================================================
// ASYNC WORKERS - I/O-Bound Tasks
// ============================================================================
// Worker 1: Fetch user data - simulates I/O-bound API call
let fetch_user_worker = FnWorker::new("fetch_user_data", |task: Task| async move {
let user_id = task
.get_input_string("user_id")
.unwrap_or_else(|| "unknown".to_string());
info!("Fetching user data for user_id={}", user_id);
// Simulate async HTTP call or database query
tokio::time::sleep(Duration::from_millis(500)).await;
let mut output = HashMap::new();
output.insert("user_id".to_string(), serde_json::json!(user_id));
output.insert(
"name".to_string(),
serde_json::json!(format!("User {}", user_id)),
);
output.insert(
"email".to_string(),
serde_json::json!(format!("user{}@example.com", user_id)),
);
output.insert("status".to_string(), serde_json::json!("active"));
info!("Successfully fetched user data for user_id={}", user_id);
Ok(WorkerOutput::Completed(output))
})
.with_thread_count(50); // High concurrency for I/O-bound tasks
// Worker 2: Send notification - simulates sending email/SMS/push
let send_notification_worker = FnWorker::new("send_notification", |task: Task| async move {
let user_id = task
.get_input_string("user_id")
.unwrap_or_else(|| "unknown".to_string());
let message = task
.get_input_string("message")
.unwrap_or_else(|| "No message".to_string());
info!("Sending notification to user_id={}: {}", user_id, message);
// Simulate async notification service call
tokio::time::sleep(Duration::from_millis(200)).await;
let mut output = HashMap::new();
output.insert("user_id".to_string(), serde_json::json!(user_id));
output.insert("status".to_string(), serde_json::json!("sent"));
info!("Notification sent to user_id={}", user_id);
Ok(WorkerOutput::Completed(output))
})
.with_thread_count(100); // Very high concurrency for fast I/O tasks
// ============================================================================
// CPU-BOUND WORKER PATTERN
// ============================================================================
// Worker 3: Process image - simulates CPU-bound image processing
let process_image_worker = FnWorker::new("process_image", |task: Task| async move {
let image_url = task
.get_input_string("image_url")
.unwrap_or_else(|| "unknown.jpg".to_string());
let filters: serde_json::Value = task
.get_input("filters")
.unwrap_or_else(|| serde_json::json!([]));
info!(
"Processing image: {} with filters: {:?}",
image_url, filters
);
// Simulate CPU-intensive image processing
// In a real app, you might use tokio::task::spawn_blocking for CPU work
tokio::time::sleep(Duration::from_secs(2)).await;
let output_url = format!("{}_processed", image_url);
info!("Image processing complete: {}", output_url);
let mut output = HashMap::new();
output.insert("input_url".to_string(), serde_json::json!(image_url));
output.insert("output_url".to_string(), serde_json::json!(output_url));
output.insert("filters_applied".to_string(), filters);
Ok(WorkerOutput::Completed(output))
})
.with_thread_count(4); // Lower concurrency for CPU-bound tasks
// ============================================================================
// LONG-RUNNING TASK PATTERN
// ============================================================================
// Worker 4: Long-running task with progress tracking
let long_running_worker = FnWorker::new("long_running_task", |task: Task| async move {
let job_id = task
.get_input_string("job_id")
.unwrap_or_else(|| "job_unknown".to_string());
// Get poll count from task input (track progress across polls)
let poll_count: i32 = task.get_input("poll_count").unwrap_or(0);
info!("Processing job {}, poll {}/5", job_id, poll_count + 1);
// Simulate work
tokio::time::sleep(Duration::from_millis(500)).await;
if poll_count < 4 {
// Still processing - return InProgress to poll again
let mut output = HashMap::new();
output.insert("job_id".to_string(), serde_json::json!(job_id));
output.insert("status".to_string(), serde_json::json!("processing"));
output.insert("poll_count".to_string(), serde_json::json!(poll_count + 1));
output.insert(
"progress_percent".to_string(),
serde_json::json!((poll_count + 1) * 20),
);
// Return InProgress with callback_after_seconds
Ok(WorkerOutput::in_progress(1))
} else {
// Complete after 5 polls
info!("Job {} completed", job_id);
let mut output = HashMap::new();
output.insert("job_id".to_string(), serde_json::json!(job_id));
output.insert("status".to_string(), serde_json::json!("completed"));
output.insert("result".to_string(), serde_json::json!("success"));
output.insert("total_polls".to_string(), serde_json::json!(poll_count + 1));
Ok(WorkerOutput::Completed(output))
}
})
.with_thread_count(5);
// ============================================================================
// ERROR HANDLING PATTERN
// ============================================================================
// Worker 5: Demonstrates error handling
let error_handling_worker = FnWorker::new("may_fail_task", |task: Task| async move {
let should_fail: bool = task.get_input("should_fail").unwrap_or(false);
info!("Task may_fail_task, should_fail={}", should_fail);
if should_fail {
// Return a failure result
Ok(WorkerOutput::failed("Task deliberately failed for testing"))
} else {
let mut output = HashMap::new();
output.insert("status".to_string(), serde_json::json!("success"));
output.insert(
"message".to_string(),
serde_json::json!("Task completed successfully"),
);
Ok(WorkerOutput::Completed(output))
}
})
.with_thread_count(10);
// Add all workers to the handler
handler.add_worker(fetch_user_worker);
handler.add_worker(send_notification_worker);
handler.add_worker(process_image_worker);
handler.add_worker(long_running_worker);
handler.add_worker(error_handling_worker);
// Start the task handler
info!("Starting task handler with workers...");
handler.start().await?;
println!("\n{}", "=".repeat(80));
println!("Conductor Rust Worker Example - Async Workers");
println!("{}", "=".repeat(80));
println!("\nWorkers registered:");
println!(" Async (I/O-bound):");
println!(" - fetch_user_data: Fetch user data from API/DB (50 threads)");
println!(" - send_notification: Send email/SMS/push notifications (100 threads)");
println!("\n CPU-bound:");
println!(" - process_image: CPU-intensive image processing (4 threads)");
println!("\n Patterns:");
println!(" - long_running_task: Polling-based long-running task (5 threads)");
println!(" - may_fail_task: Demonstrates error handling (10 threads)");
println!("\nPress Ctrl+C to stop");
println!("{}\n", "=".repeat(80));
// Execute a sample workflow to test the workers
let workflow_client = client.workflow_client();
let request = StartWorkflowRequest::new("worker_demo")
.with_version(1)
.with_input_value("user_id", "12345");
match workflow_client.start_workflow(&request).await {
Ok(workflow_id) => {
info!("Started demo workflow: {}", workflow_id);
info!("View at: {}", config.execution_url(&workflow_id));
// Wait for workflow to complete
tokio::time::sleep(Duration::from_secs(5)).await;
let workflow = workflow_client.get_workflow(&workflow_id, false).await?;
info!("Demo workflow status: {:?}", workflow.status);
}
Err(e) => {
info!(
"Failed to start demo workflow: {}. Workers are still running.",
e
);
}
}
// Keep running until interrupted
info!("Workers are running. Press Ctrl+C to stop...");
tokio::signal::ctrl_c().await.ok();
// Stop the handler
handler.stop().await?;
info!("Workers stopped. Goodbye!");
Ok(())
}
async fn register_definitions(client: &ConductorClient) -> Result<()> {
let metadata = client.metadata_client();
// Register task definitions
let task_defs = vec![
TaskDef::new("fetch_user_data").with_description("Fetch user data from API/DB"),
TaskDef::new("send_notification").with_description("Send notifications"),
TaskDef::new("process_image").with_description("Process images"),
TaskDef::new("long_running_task").with_description("Long-running task with progress"),
TaskDef::new("may_fail_task").with_description("Task that may fail"),
];
info!("Registering {} task definitions...", task_defs.len());
metadata.register_task_defs(&task_defs).await?;
// Create a sample workflow that uses the workers
let workflow = WorkflowDef::new("worker_demo")
.with_description("Demo workflow for worker example")
.with_version(1)
.with_task(
WorkflowTask::simple("fetch_user_data", "fetch_user_ref")
.with_input_param("user_id", "${workflow.input.user_id}"),
)
.with_task(
WorkflowTask::simple("send_notification", "send_notification_ref")
.with_input_param("user_id", "${fetch_user_ref.output.user_id}")
.with_input_param("message", "Welcome ${fetch_user_ref.output.name}!"),
)
.with_output_param("user", "${fetch_user_ref.output}")
.with_output_param("notification", "${send_notification_ref.output}");
info!("Registering workflow: {}", workflow.name);
metadata
.register_or_update_workflow_def(&workflow, true)
.await?;
Ok(())
}