Skip to main content

bpm_engine_worker_sdk/
client.rs

1//! HTTP client for Engine external-task API (design ยง3).
2
3use std::collections::HashMap;
4use std::time::Duration;
5
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8use tracing::debug;
9
10use crate::types::ExternalTask;
11
12/// Errors from the Engine client.
13#[derive(Debug, Error)]
14pub enum ClientError {
15    #[error("network/HTTP error: {0}")]
16    Transport(#[from] reqwest::Error),
17    #[error("engine error (HTTP {status}): {message}")]
18    Engine { status: u16, message: String },
19}
20
21/// Raw response from fetch-and-lock (matches Engine REST).
22#[derive(Debug, Deserialize)]
23struct FetchAndLockResponseItem {
24    task_id: String,
25    token_id: String,
26    process_instance_id: String,
27    task_type: String,
28    variables: HashMap<String, String>,
29}
30
31#[derive(Debug, Serialize)]
32struct FetchAndLockRequest {
33    worker_id: String,
34    task_types: Vec<String>,
35    max_tasks: u32,
36    lock_duration_ms: u64,
37}
38
39#[derive(Debug, Serialize)]
40struct CompleteRequest {
41    worker_id: String,
42    #[serde(skip_serializing_if = "HashMap::is_empty")]
43    variables: HashMap<String, String>,
44}
45
46#[derive(Debug, Serialize)]
47struct FailRequest {
48    worker_id: String,
49    error: String,
50    #[serde(skip_serializing_if = "Option::is_none")]
51    retry_after_ms: Option<u64>,
52}
53
54#[derive(Debug, Deserialize)]
55struct ErrorBody {
56    error: String,
57}
58
59/// HTTP client for Engine external-task endpoints.
60#[derive(Clone)]
61pub struct EngineClient {
62    client: reqwest::Client,
63    base_url: String,
64    tenant_id: Option<String>,
65}
66
67impl EngineClient {
68    pub fn new(base_url: impl Into<String>) -> Self {
69        Self {
70            client: reqwest::Client::new(),
71            base_url: base_url.into(),
72            tenant_id: None,
73        }
74    }
75
76    pub fn tenant_id(mut self, id: impl Into<String>) -> Self {
77        self.tenant_id = Some(id.into());
78        self
79    }
80
81    fn url(&self, path: &str) -> String {
82        let base = self.base_url.trim_end_matches('/');
83        format!("{}/api/v1/external-tasks{}", base, path)
84    }
85
86    fn headers(&self) -> reqwest::header::HeaderMap {
87        let mut h = reqwest::header::HeaderMap::new();
88        if let Some(ref id) = self.tenant_id {
89            h.insert(
90                reqwest::header::HeaderName::from_static("x-tenant-id"),
91                id.parse().unwrap(),
92            );
93        }
94        h
95    }
96
97    /// Fetch and lock tasks from the Engine.
98    pub async fn fetch_and_lock(
99        &self,
100        worker_id: &str,
101        task_types: &[String],
102        max_tasks: usize,
103        lock_duration_ms: u64,
104    ) -> Result<Vec<ExternalTask>, ClientError> {
105        let url = self.url("/fetch-and-lock");
106        let body = FetchAndLockRequest {
107            worker_id: worker_id.to_string(),
108            task_types: task_types.to_vec(),
109            max_tasks: max_tasks as u32,
110            lock_duration_ms,
111        };
112        debug!(%url, "fetch_and_lock");
113        let req = self.client.post(&url).json(&body).headers(self.headers());
114        let res = req.send().await?;
115        let status = res.status();
116        if !status.is_success() {
117            let message = res
118                .json::<ErrorBody>()
119                .await
120                .map(|b| b.error)
121                .unwrap_or_else(|_| status.to_string());
122            return Err(ClientError::Engine {
123                status: status.as_u16(),
124                message,
125            });
126        }
127        let items: Vec<FetchAndLockResponseItem> = res.json().await?;
128        let tasks = items
129            .into_iter()
130            .map(|i| ExternalTask {
131                task_id: i.task_id,
132                task_type: i.task_type,
133                variables: i.variables,
134                lock_expire_at: None,
135                retries: 0,
136                #[cfg(debug_assertions)]
137                token_id: Some(i.token_id),
138                #[cfg(debug_assertions)]
139                process_instance_id: Some(i.process_instance_id),
140            })
141            .collect();
142        Ok(tasks)
143    }
144
145    /// Complete a task.
146    pub async fn complete(
147        &self,
148        task_id: &str,
149        worker_id: &str,
150        variables: HashMap<String, String>,
151    ) -> Result<(), ClientError> {
152        let url = self.url(&format!("/{}/complete", task_id));
153        let body = CompleteRequest {
154            worker_id: worker_id.to_string(),
155            variables,
156        };
157        debug!(%url, "complete");
158        let res = self
159            .client
160            .post(&url)
161            .json(&body)
162            .headers(self.headers())
163            .send()
164            .await?;
165        if !res.status().is_success() {
166            let status = res.status();
167            let message = res
168                .json::<ErrorBody>()
169                .await
170                .map(|b| b.error)
171                .unwrap_or_else(|_| status.to_string());
172            return Err(ClientError::Engine {
173                status: status.as_u16(),
174                message,
175            });
176        }
177        Ok(())
178    }
179
180    /// Fail a task.
181    pub async fn fail(
182        &self,
183        task_id: &str,
184        worker_id: &str,
185        error: String,
186        retry_after: Option<Duration>,
187    ) -> Result<(), ClientError> {
188        let url = self.url(&format!("/{}/fail", task_id));
189        let retry_after_ms = retry_after.map(|d| d.as_millis() as u64);
190        let body = FailRequest {
191            worker_id: worker_id.to_string(),
192            error,
193            retry_after_ms,
194        };
195        debug!(%url, "fail");
196        let res = self
197            .client
198            .post(&url)
199            .json(&body)
200            .headers(self.headers())
201            .send()
202            .await?;
203        if !res.status().is_success() {
204            let status = res.status();
205            let message = res
206                .json::<ErrorBody>()
207                .await
208                .map(|b| b.error)
209                .unwrap_or_else(|_| status.to_string());
210            return Err(ClientError::Engine {
211                status: status.as_u16(),
212                message,
213            });
214        }
215        Ok(())
216    }
217}