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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// Copyright {{.Year}} Conductor OSS
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
use std::time::Duration;
use tracing::{debug, warn};
use crate::error::{ConductorError, Result};
use crate::http::{ApiClient, ApiPath};
use crate::models::{Task, TaskResult};
/// Client for task operations (polling and updates).
#[derive(Clone)]
pub struct TaskClient {
api: ApiClient,
}
impl TaskClient {
/// Create a new task client.
#[must_use]
pub fn new(api: ApiClient) -> Self {
Self { api }
}
/// Poll for a single task.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn poll_task(
&self,
task_type: &str,
worker_id: Option<&str>,
domain: Option<&str>,
) -> Result<Option<Task>> {
let mut params = vec![];
if let Some(wid) = worker_id {
params.push(("workerid", wid));
}
if let Some(d) = domain {
params.push(("domain", d));
}
let path = format!("/tasks/poll/{task_type}");
let result: Option<Task> = self
.api
.get_with_params(ApiPath::templated(&path, "/tasks/poll/{taskType}"), ¶ms)
.await?;
Ok(result)
}
/// Batch poll for multiple tasks.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn batch_poll(
&self,
task_type: &str,
worker_id: Option<&str>,
domain: Option<&str>,
count: usize,
timeout: Duration,
) -> Result<Vec<Task>> {
let count_str = count.to_string();
let timeout_str = timeout.as_millis().to_string();
let mut params = vec![
("count", count_str.as_str()),
("timeout", timeout_str.as_str()),
];
if let Some(wid) = worker_id {
params.push(("workerid", wid));
}
if let Some(d) = domain {
params.push(("domain", d));
}
let path = format!("/tasks/poll/batch/{task_type}");
debug!(
task_type = task_type,
count = count,
timeout_ms = timeout.as_millis(),
"Batch polling tasks"
);
let tasks: Vec<Task> = self
.api
.get_with_params(
ApiPath::templated(&path, "/tasks/poll/batch/{taskType}"),
¶ms,
)
.await?;
debug!(
task_type = task_type,
tasks_received = tasks.len(),
"Batch poll completed"
);
Ok(tasks)
}
/// Update a task result.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn update_task(&self, result: &TaskResult) -> Result<String> {
debug!(
task_id = %result.task_id,
status = ?result.status,
"Updating task"
);
let response: String = self.api.post_text("/tasks", result).await?;
Ok(response)
}
/// Update task with retry logic.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn update_task_with_retry(
&self,
result: &TaskResult,
max_attempts: u32,
) -> Result<String> {
let delays = [
Duration::from_secs(10),
Duration::from_secs(20),
Duration::from_secs(30),
];
let mut last_error = None;
for attempt in 0..max_attempts {
match self.update_task(result).await {
Ok(response) => return Ok(response),
Err(e) => {
if !e.is_retryable() {
return Err(e);
}
last_error = Some(e);
if attempt < max_attempts - 1 {
let delay = delays
.get(attempt as usize)
.copied()
.unwrap_or(Duration::from_secs(30));
warn!(
task_id = %result.task_id,
attempt = attempt + 1,
delay_secs = delay.as_secs(),
"Task update failed, retrying"
);
tokio::time::sleep(delay).await;
}
}
}
}
Err(last_error.unwrap_or_else(|| ConductorError::internal("Update failed with no error")))
}
/// Get task by ID.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_task(&self, task_id: &str) -> Result<Task> {
let path = format!("/tasks/{task_id}");
self.api
.get(ApiPath::templated(&path, "/tasks/{taskId}"))
.await
}
/// Get tasks in progress for a task type.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_tasks_in_progress(
&self,
task_type: &str,
start_key: Option<&str>,
count: Option<i32>,
) -> Result<Vec<Task>> {
let mut params = vec![];
let count_str;
if let Some(key) = start_key {
params.push(("startKey", key));
}
if let Some(c) = count {
count_str = c.to_string();
params.push(("count", &count_str));
}
let path = format!("/tasks/in_progress/{task_type}");
self.api
.get_with_params(
ApiPath::templated(&path, "/tasks/in_progress/{taskType}"),
¶ms,
)
.await
}
/// Add a log to a task.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn add_task_log(&self, task_id: &str, log: &str) -> Result<()> {
let path = format!("/tasks/{task_id}/log");
let _: serde_json::Value = self
.api
.post(ApiPath::templated(&path, "/tasks/{taskId}/log"), &log)
.await?;
Ok(())
}
/// Get logs for a task.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_task_logs(
&self,
task_id: &str,
) -> Result<Vec<crate::models::task::TaskExecLog>> {
let path = format!("/tasks/{task_id}/log");
self.api
.get(ApiPath::templated(&path, "/tasks/{taskId}/log"))
.await
}
/// Get task queue sizes.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn get_queue_sizes(
&self,
task_types: &[&str],
) -> Result<std::collections::HashMap<String, i64>> {
let params: Vec<(&str, &str)> = task_types.iter().map(|t| ("taskType", *t)).collect();
self.api
.get_with_params("/tasks/queue/sizes", ¶ms)
.await
}
/// Remove task from queue.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, or an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status.
pub async fn remove_task_from_queue(&self, task_type: &str, task_id: &str) -> Result<()> {
let path = format!("/tasks/queue/{task_type}/{task_id}");
self.api
.delete_no_content(ApiPath::templated(
&path,
"/tasks/queue/{taskType}/{taskId}",
))
.await
}
/// Update task by reference name.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn update_task_by_ref_name(
&self,
workflow_id: &str,
task_ref_name: &str,
status: crate::models::TaskResultStatus,
output: serde_json::Value,
worker_id: Option<&str>,
) -> Result<String> {
let path = format!(
"/tasks/{}/{}/{}",
workflow_id,
task_ref_name,
status_to_string(status)
);
let mut params = vec![];
if let Some(wid) = worker_id {
params.push(("workerid", wid));
}
// POST with output as body
self.api
.post_text(
ApiPath::templated(&path, "/tasks/{workflowId}/{taskRefName}/{status}"),
&output,
)
.await
}
/// Update task synchronously and return the updated workflow.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn update_task_sync(
&self,
workflow_id: &str,
task_ref_name: &str,
status: crate::models::TaskResultStatus,
output: serde_json::Value,
worker_id: Option<&str>,
) -> Result<crate::models::Workflow> {
let path = format!(
"/tasks/{}/{}/{}/sync",
workflow_id,
task_ref_name,
status_to_string(status)
);
let mut params: Vec<(&str, String)> = vec![];
if let Some(wid) = worker_id {
params.push(("workerid", wid.to_owned()));
}
let params_ref: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
self.api
.post_with_params(
ApiPath::templated(&path, "/tasks/{workflowId}/{taskRefName}/{status}/sync"),
&output,
¶ms_ref,
)
.await
}
/// Get queue size for a specific task type.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_queue_size_for_task(&self, task_type: &str) -> Result<i64> {
let sizes = self.get_queue_sizes(&[task_type]).await?;
Ok(*sizes.get(task_type).unwrap_or(&0))
}
/// Get poll data for a task type.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_task_poll_data(&self, task_type: &str) -> Result<Vec<PollData>> {
let path = format!("/tasks/queue/polldata/{task_type}");
self.api
.get(ApiPath::templated(
&path,
"/tasks/queue/polldata/{taskType}",
))
.await
}
/// Get all poll data.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_all_poll_data(&self) -> Result<Vec<PollData>> {
self.api.get("/tasks/queue/polldata/all").await
}
/// Get poll data (alias for `get_task_poll_data`).
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn get_poll_data(&self, task_type: &str) -> Result<Vec<PollData>> {
self.get_task_poll_data(task_type).await
}
/// Search for tasks.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn search_tasks(
&self,
query: Option<&str>,
free_text: Option<&str>,
start: i32,
size: i32,
) -> Result<crate::client::workflow_client::SearchResult<Task>> {
let mut params = vec![("start", start.to_string()), ("size", size.to_string())];
if let Some(q) = query {
params.push(("query", q.to_owned()));
}
if let Some(ft) = free_text {
params.push(("freeText", ft.to_owned()));
}
let params: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
self.api.get_with_params("/tasks/search", ¶ms).await
}
/// Search for tasks V2 (returns full task objects).
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn search_tasks_v2(
&self,
query: Option<&str>,
free_text: Option<&str>,
start: i32,
size: i32,
) -> Result<crate::client::workflow_client::SearchResult<Task>> {
let mut params = vec![("start", start.to_string()), ("size", size.to_string())];
if let Some(q) = query {
params.push(("query", q.to_owned()));
}
if let Some(ft) = free_text {
params.push(("freeText", ft.to_owned()));
}
let params: Vec<(&str, &str)> = params.iter().map(|(k, v)| (*k, v.as_str())).collect();
self.api.get_with_params("/tasks/search-v2", ¶ms).await
}
/// Requeue pending tasks.
///
/// # Errors
///
/// Returns [`crate::error::ConductorError::Http`] if the request fails at the transport level, an [`crate::error::ConductorError::Auth`]/[`crate::error::ConductorError::Api`]/[`crate::error::ConductorError::Server`] variant if the server responds with a non-2xx status, or [`crate::error::ConductorError::Json`] if the response body can't be deserialized.
pub async fn requeue_pending_tasks(&self, task_type: &str) -> Result<String> {
let path = format!("/tasks/queue/requeue/{task_type}");
self.api
.post_text(
ApiPath::templated(&path, "/tasks/queue/requeue/{taskType}"),
&serde_json::Value::Null,
)
.await
}
}
/// Poll data for a task queue.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PollData {
/// Queue name / task type.
#[serde(default)]
pub queue_name: String,
/// Domain.
#[serde(skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
/// Worker ID that last polled.
#[serde(skip_serializing_if = "Option::is_none")]
pub worker_id: Option<String>,
/// Last poll time.
#[serde(default)]
pub last_poll_time: i64,
}
fn status_to_string(status: crate::models::TaskResultStatus) -> &'static str {
match status {
crate::models::TaskResultStatus::Completed => "COMPLETED",
crate::models::TaskResultStatus::Failed => "FAILED",
crate::models::TaskResultStatus::FailedWithTerminalError => "FAILED_WITH_TERMINAL_ERROR",
crate::models::TaskResultStatus::InProgress => "IN_PROGRESS",
crate::models::TaskResultStatus::Canceled => "CANCELED",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::TaskResultStatus;
#[test]
fn test_task_result_creation() {
let result = TaskResult::completed("task-1", "wf-1")
.with_worker_id("worker-1")
.with_output_value("result", "success");
assert_eq!(result.task_id, "task-1");
assert_eq!(result.workflow_instance_id, "wf-1");
assert_eq!(result.status, TaskResultStatus::Completed);
}
}