Skip to main content

posemesh_compute_node/dms/
client.rs

1use crate::auth::token_manager::TokenProvider;
2use crate::dms::types::{
3    CompleteTaskRequest, FailTaskRequest, HeartbeatRequest, HeartbeatResponse, LeaseResponse,
4};
5use anyhow::{anyhow, Context, Result};
6use reqwest::Client;
7use reqwest::{
8    header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE},
9    StatusCode,
10};
11use std::sync::Arc;
12use std::time::Duration;
13use tracing::Level;
14use url::Url;
15use uuid::Uuid;
16
17/// Minimal DMS HTTP client using rustls with sensitive Authorization header.
18#[derive(Clone)]
19pub struct DmsClient {
20    base: Url,
21    http: Client,
22    auth: Arc<dyn TokenProvider>,
23}
24impl DmsClient {
25    /// Create client with base URL, timeout, and a token provider for Authorization.
26    pub fn new(base: Url, timeout: Duration, auth: Arc<dyn TokenProvider>) -> Result<Self> {
27        let http = Client::builder()
28            .use_rustls_tls()
29            .timeout(timeout)
30            .build()
31            .context("build dms reqwest client")?;
32        Ok(Self { base, http, auth })
33    }
34
35    async fn auth_headers(&self) -> Result<HeaderMap> {
36        let mut h = HeaderMap::new();
37        let b = self
38            .auth
39            .bearer()
40            .await
41            .map_err(|e| anyhow!("token provider: {e}"))?;
42        let token = format!("Bearer {}", b);
43        let mut v = HeaderValue::from_str(&token)
44            .unwrap_or_else(|_| HeaderValue::from_static("Bearer INVALID"));
45        v.set_sensitive(true);
46        h.insert(AUTHORIZATION, v);
47        Ok(h)
48    }
49
50    fn join_segments(&self, segments: &[&str]) -> Result<Url> {
51        let mut url = self.base.clone();
52        url.path_segments_mut()
53            .map_err(|_| anyhow!("invalid DMS base URL; cannot be a base"))?
54            .extend(segments.iter().copied());
55        Ok(url)
56    }
57
58    /// Lease a task: GET /tasks
59    ///
60    /// `capability` is accepted for optional filter but not implemented yet.
61    pub async fn lease_by_capability(&self, _capability: &str) -> Result<Option<LeaseResponse>> {
62        let url = self.join_segments(&["tasks"]).context("join /tasks")?;
63        if tracing::enabled!(Level::DEBUG) {
64            tracing::debug!(
65                endpoint = %url,
66                "Sending DMS lease request"
67            );
68        }
69        // First attempt
70        let mut headers = self.auth_headers().await?;
71        let mut res = self
72            .http
73            .get(url.clone())
74            .headers(headers.clone())
75            .send()
76            .await
77            .context("send GET /tasks")?;
78        let mut status = res.status();
79        let mut bytes = res.bytes().await.context("read lease body")?;
80        // Retry once on 401
81        if status == StatusCode::UNAUTHORIZED {
82            tracing::warn!(
83                status = %status,
84                "DMS lease unauthorized; refreshing token and retrying"
85            );
86            self.auth.on_unauthorized().await;
87            headers = self.auth_headers().await?;
88            res = self
89                .http
90                .get(url)
91                .headers(headers)
92                .send()
93                .await
94                .context("retry GET /tasks")?;
95            status = res.status();
96            bytes = res.bytes().await.context("read lease body (retry)")?;
97        }
98        if status == StatusCode::NO_CONTENT {
99            tracing::debug!("DMS lease returned 204 (no work available)");
100            return Ok(None);
101        }
102        if status == StatusCode::CONFLICT {
103            tracing::debug!(
104                status = %status,
105                "DMS lease returned conflict (busy); treating as no work"
106            );
107            return Ok(None);
108        }
109        if !status.is_success() {
110            tracing::warn!(
111                status = %status,
112                "DMS lease request returned non-success status"
113            );
114            return Err(anyhow!("/tasks status: {}", status));
115        }
116        let lease: LeaseResponse = serde_json::from_slice(&bytes)
117            .map_err(|err| {
118                tracing::error!(
119                    status = %status,
120                    error = %err,
121                    "Failed to decode DMS lease response"
122                );
123                err
124            })
125            .context("decode lease")?;
126
127        if tracing::enabled!(Level::DEBUG) {
128            tracing::debug!(
129                status = %status,
130                task_id = %lease.task.id,
131                capability = %lease.task.capability,
132                access_token_updated = lease.access_token.is_some(),
133                "Decoded DMS lease response"
134            );
135        }
136
137        Ok(Some(lease))
138    }
139
140    /// Complete task: POST /tasks/{id}/complete
141    pub async fn complete(&self, task_id: Uuid, body: &CompleteTaskRequest) -> Result<()> {
142        let url = self
143            .join_segments(&["tasks", &task_id.to_string(), "complete"])
144            .context("join /complete")?;
145        let mut headers = self.auth_headers().await?;
146        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
147        if tracing::enabled!(Level::DEBUG) {
148            tracing::debug!(
149                endpoint = %url,
150                task_id = %task_id,
151                "Sending DMS complete request"
152            );
153        }
154        // First attempt
155        let mut res = self
156            .http
157            .post(url.clone())
158            .headers(headers.clone())
159            .json(body)
160            .send()
161            .await
162            .context("send POST /complete")?;
163        let mut status = res.status();
164        let _ = res.bytes().await;
165        if status == StatusCode::UNAUTHORIZED {
166            tracing::warn!(
167                status = %status,
168                task_id = %task_id,
169                "DMS complete unauthorized; refreshing token and retrying"
170            );
171            self.auth.on_unauthorized().await;
172            headers = self.auth_headers().await?;
173            res = self
174                .http
175                .post(url)
176                .headers(headers)
177                .json(body)
178                .send()
179                .await
180                .context("retry POST /complete")?;
181            status = res.status();
182            let _ = res.bytes().await;
183        }
184        if tracing::enabled!(Level::DEBUG) {
185            tracing::debug!(
186                status = %status,
187                task_id = %task_id,
188                "DMS complete response"
189            );
190        }
191        if !status.is_success() {
192            tracing::error!(
193                status = %status,
194                task_id = %task_id,
195                "DMS complete endpoint returned non-success status"
196            );
197            return Err(anyhow!("POST /tasks/{task_id}/complete status {status}"));
198        }
199        Ok(())
200    }
201
202    /// Fail task: POST /tasks/{id}/fail
203    pub async fn fail(&self, task_id: Uuid, body: &FailTaskRequest) -> Result<()> {
204        let url = self
205            .join_segments(&["tasks", &task_id.to_string(), "fail"])
206            .context("join /fail")?;
207        let mut headers = self.auth_headers().await?;
208        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
209        if tracing::enabled!(Level::DEBUG) {
210            tracing::debug!(
211                endpoint = %url,
212                task_id = %task_id,
213                "Sending DMS fail request"
214            );
215        }
216        // First attempt
217        let mut res = self
218            .http
219            .post(url.clone())
220            .headers(headers.clone())
221            .json(body)
222            .send()
223            .await
224            .context("send POST /fail")?;
225        let mut status = res.status();
226        let _ = res.bytes().await;
227        if status == StatusCode::UNAUTHORIZED {
228            tracing::warn!(
229                status = %status,
230                task_id = %task_id,
231                "DMS fail unauthorized; refreshing token and retrying"
232            );
233            self.auth.on_unauthorized().await;
234            headers = self.auth_headers().await?;
235            res = self
236                .http
237                .post(url)
238                .headers(headers)
239                .json(body)
240                .send()
241                .await
242                .context("retry POST /fail")?;
243            status = res.status();
244            let _ = res.bytes().await;
245        }
246        if tracing::enabled!(Level::DEBUG) {
247            tracing::debug!(
248                status = %status,
249                task_id = %task_id,
250                "DMS fail response"
251            );
252        }
253        if !status.is_success() {
254            tracing::error!(
255                status = %status,
256                task_id = %task_id,
257                "DMS fail endpoint returned non-success status"
258            );
259            return Err(anyhow!("POST /tasks/{task_id}/fail status {status}"));
260        }
261        Ok(())
262    }
263
264    /// Heartbeat: POST /tasks/{id}/heartbeat with progress payload.
265    /// Returns potential new access token for storage.
266    pub async fn heartbeat(
267        &self,
268        task_id: Uuid,
269        body: &HeartbeatRequest,
270    ) -> Result<HeartbeatResponse> {
271        let url = self
272            .join_segments(&["tasks", &task_id.to_string(), "heartbeat"])
273            .context("join /heartbeat")?;
274        let mut headers = self.auth_headers().await?;
275        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
276        if tracing::enabled!(Level::DEBUG) {
277            tracing::debug!(
278                endpoint = %url,
279                task_id = %task_id,
280                "Sending DMS heartbeat request"
281            );
282        }
283        // First attempt
284        let mut res = self
285            .http
286            .post(url.clone())
287            .headers(headers.clone())
288            .json(body)
289            .send()
290            .await
291            .context("send POST /heartbeat")?;
292        let mut status = res.status();
293        let mut bytes = res.bytes().await.context("read heartbeat response body")?;
294        if status == StatusCode::UNAUTHORIZED {
295            tracing::warn!(
296                status = %status,
297                task_id = %task_id,
298                "DMS heartbeat unauthorized; refreshing token and retrying"
299            );
300            self.auth.on_unauthorized().await;
301            headers = self.auth_headers().await?;
302            res = self
303                .http
304                .post(url)
305                .headers(headers)
306                .json(body)
307                .send()
308                .await
309                .context("retry POST /heartbeat")?;
310            status = res.status();
311            bytes = res
312                .bytes()
313                .await
314                .context("read heartbeat response body (retry)")?;
315        }
316        if !status.is_success() {
317            tracing::warn!(
318                status = %status,
319                task_id = %task_id,
320                "DMS heartbeat endpoint returned non-success status"
321            );
322            return Err(anyhow!("POST /tasks/{task_id}/heartbeat status {status}"));
323        }
324        let hb = serde_json::from_slice::<HeartbeatResponse>(&bytes)
325            .map_err(|err| {
326                tracing::error!(
327                    status = %status,
328                    task_id = %task_id,
329                    error = %err,
330                    "Failed to decode DMS heartbeat response"
331                );
332                err
333            })
334            .context("decode heartbeat response")?;
335        if tracing::enabled!(Level::DEBUG) {
336            tracing::debug!(
337                status = %status,
338                task_id = %task_id,
339                access_token_updated = hb.access_token.is_some(),
340                cancel = ?hb.cancel,
341                "Decoded DMS heartbeat response"
342            );
343        }
344        Ok(hb)
345    }
346}