Skip to content
Durable Workflowrust

durable_workflow/
raw_request.rs

1//! Untyped Server requests over the client's configured transport.
2//!
3//! Typed `Client` methods remain the API for applications. These requests are
4//! for tools such as the CLI that must reach every Server route and report the
5//! Server's response unchanged. A raw request makes exactly one HTTP attempt
6//! and never rewrites its body: no failure-report reduction, no external
7//! payload handling, no activity-lease checks and no storage-admission retry.
8
9use std::time::Duration;
10
11use serde_json::Value;
12
13use crate::{
14    metrics::ClientObservation, percent_encode_path_segment, protocol_failure, Client, Error,
15    ProtocolFailure, RequestProtocol, Result, CONTROL_PLANE_VERSION,
16};
17
18const PROTOCOL_VERSION_HEADER: &str = "X-Durable-Workflow-Protocol-Version";
19const CONTROL_PLANE_VERSION_HEADER: &str = "X-Durable-Workflow-Control-Plane-Version";
20
21/// HTTP method of a [`RawRequest`].
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum RawMethod {
24    Get,
25    Post,
26    Put,
27    Patch,
28    Delete,
29}
30
31impl RawMethod {
32    fn as_reqwest(self) -> reqwest::Method {
33        match self {
34            Self::Get => reqwest::Method::GET,
35            Self::Post => reqwest::Method::POST,
36            Self::Put => reqwest::Method::PUT,
37            Self::Patch => reqwest::Method::PATCH,
38            Self::Delete => reqwest::Method::DELETE,
39        }
40    }
41}
42
43/// A Server API request addressed by path segments under `{base_url}/api`.
44///
45/// Each segment is percent-encoded like PHP `rawurlencode`: RFC 3986
46/// unreserved characters stay, everything else (including `/`) is escaped, so
47/// an identifier stays inside its own segment. Empty, `.` and `..` segments
48/// are refused before any request is sent.
49#[derive(Clone, Debug)]
50pub struct RawRequest {
51    method: RawMethod,
52    segments: Vec<String>,
53    query: Vec<(String, String)>,
54    body: Option<Value>,
55    timeout: Option<Duration>,
56    protocol_version: Option<String>,
57    control_plane_version: Option<String>,
58}
59
60impl RawRequest {
61    pub fn new<I, S>(method: RawMethod, segments: I) -> Self
62    where
63        I: IntoIterator<Item = S>,
64        S: Into<String>,
65    {
66        Self {
67            method,
68            segments: segments.into_iter().map(Into::into).collect(),
69            query: Vec::new(),
70            body: None,
71            timeout: None,
72            protocol_version: None,
73            control_plane_version: None,
74        }
75    }
76
77    pub fn get<I: IntoIterator<Item = S>, S: Into<String>>(segments: I) -> Self {
78        Self::new(RawMethod::Get, segments)
79    }
80
81    pub fn post<I: IntoIterator<Item = S>, S: Into<String>>(segments: I) -> Self {
82        Self::new(RawMethod::Post, segments)
83    }
84
85    pub fn put<I: IntoIterator<Item = S>, S: Into<String>>(segments: I) -> Self {
86        Self::new(RawMethod::Put, segments)
87    }
88
89    pub fn patch<I: IntoIterator<Item = S>, S: Into<String>>(segments: I) -> Self {
90        Self::new(RawMethod::Patch, segments)
91    }
92
93    pub fn delete<I: IntoIterator<Item = S>, S: Into<String>>(segments: I) -> Self {
94        Self::new(RawMethod::Delete, segments)
95    }
96
97    /// Append one query pair. Pairs keep their order.
98    pub fn query(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
99        self.query.push((key.into(), value.into()));
100        self
101    }
102
103    /// Send this JSON value as the request body, unchanged.
104    pub fn json(mut self, body: Value) -> Self {
105        self.body = Some(body);
106        self
107    }
108
109    /// Override the client's whole-request timeout for this request.
110    pub fn timeout(mut self, timeout: Duration) -> Self {
111        self.timeout = Some(timeout);
112        self
113    }
114
115    /// Override the `X-Durable-Workflow-Protocol-Version` header value.
116    /// Defaults to the client's worker protocol version.
117    pub fn protocol_version(mut self, version: impl Into<String>) -> Self {
118        self.protocol_version = Some(version.into());
119        self
120    }
121
122    /// Override the `X-Durable-Workflow-Control-Plane-Version` header value.
123    /// Defaults to [`CONTROL_PLANE_VERSION`].
124    pub fn control_plane_version(mut self, version: impl Into<String>) -> Self {
125        self.control_plane_version = Some(version.into());
126        self
127    }
128
129    pub fn method(&self) -> RawMethod {
130        self.method
131    }
132
133    /// The encoded path relative to `/api`, for example `/workflows/a%2Fb`.
134    pub fn path(&self) -> Result<String> {
135        if self.segments.is_empty() {
136            return Err(invalid_request("at least one path segment is required"));
137        }
138        let mut path = String::new();
139        for segment in &self.segments {
140            if segment.is_empty() || segment == "." || segment == ".." {
141                return Err(invalid_request(
142                    "path segments must not be empty, \".\" or \"..\"",
143                ));
144            }
145            path.push('/');
146            path.push_str(&percent_encode_path_segment(segment));
147        }
148        Ok(path)
149    }
150}
151
152fn invalid_request(reason: &str) -> Error {
153    Error::InvalidRawRequest(reason.to_string())
154}
155
156/// A Server response, unchanged, for any HTTP status.
157#[derive(Clone, Debug)]
158pub struct RawResponse {
159    status: u16,
160    headers: reqwest::header::HeaderMap,
161    body: Vec<u8>,
162}
163
164impl RawResponse {
165    pub fn status(&self) -> u16 {
166        self.status
167    }
168
169    pub fn is_success(&self) -> bool {
170        (200..300).contains(&self.status)
171    }
172
173    /// A response header value, when present and valid visible ASCII.
174    pub fn header(&self, name: &str) -> Option<&str> {
175        self.headers.get(name)?.to_str().ok()
176    }
177
178    /// Every response header as received. Names are lowercase.
179    pub fn headers(&self) -> impl Iterator<Item = (&str, &[u8])> {
180        self.headers
181            .iter()
182            .map(|(name, value)| (name.as_str(), value.as_bytes()))
183    }
184
185    /// The worker protocol version the Server echoed, if any.
186    pub fn protocol_version(&self) -> Option<&str> {
187        self.header(PROTOCOL_VERSION_HEADER)
188    }
189
190    /// The control-plane version the Server echoed, if any.
191    pub fn control_plane_version(&self) -> Option<&str> {
192        self.header(CONTROL_PLANE_VERSION_HEADER)
193    }
194
195    /// The exact response body bytes.
196    pub fn body_bytes(&self) -> &[u8] {
197        &self.body
198    }
199
200    /// The body as JSON. An empty body is `null`.
201    pub fn json(&self) -> Result<Value> {
202        if self.body.is_empty() {
203            return Ok(Value::Null);
204        }
205        Ok(serde_json::from_slice(&self.body)?)
206    }
207
208    /// The decoded refusal body of a non-2xx response whose body is a JSON
209    /// object. `None` for 2xx responses and other bodies.
210    pub fn refusal(&self) -> Option<HttpRefusal> {
211        if self.is_success() {
212            return None;
213        }
214        HttpRefusal::decode(self.status, serde_json::from_slice(&self.body).ok()?)
215    }
216
217    /// Return the response for 2xx. Otherwise return the error a typed call
218    /// would: [`Error::Protocol`] for a protocol-version refusal, else
219    /// [`Error::Http`] with the exact body text.
220    pub fn error_for_status(self) -> Result<Self> {
221        if self.is_success() {
222            return Ok(self);
223        }
224        let status = reqwest::StatusCode::from_u16(self.status)
225            .map_err(|_| invalid_request("response status is not a valid HTTP status"))?;
226        let body = String::from_utf8_lossy(&self.body).into_owned();
227        if let Some(failure) = protocol_failure(status, &body) {
228            return Err(Error::Protocol(failure));
229        }
230        Err(Error::Http { status, body })
231    }
232}
233
234/// The decoded body of a refused (non-2xx) Server request.
235#[derive(Clone, Debug, PartialEq)]
236#[non_exhaustive]
237pub struct HttpRefusal {
238    pub status: u16,
239    pub reason: Option<String>,
240    pub rejection_reason: Option<String>,
241    pub message: Option<String>,
242    pub error: Option<String>,
243    pub validation_errors: Option<Value>,
244    /// The full JSON body, unchanged.
245    pub body: Value,
246}
247
248impl HttpRefusal {
249    fn decode(status: u16, body: Value) -> Option<Self> {
250        let object = body.as_object()?;
251        let text = |key: &str| object.get(key).and_then(Value::as_str).map(str::to_owned);
252        Some(Self {
253            status,
254            reason: text("reason"),
255            rejection_reason: text("rejection_reason"),
256            message: text("message"),
257            error: text("error"),
258            validation_errors: object
259                .get("validation_errors")
260                .or_else(|| object.get("errors"))
261                .cloned(),
262            body,
263        })
264    }
265}
266
267impl Error {
268    /// Decode a Server refusal from [`Error::Http`] or [`Error::Protocol`].
269    ///
270    /// Returns `None` for other errors and for HTTP errors whose body is not
271    /// a JSON object.
272    pub fn refusal(&self) -> Option<HttpRefusal> {
273        match self {
274            Self::Http { status, body } => {
275                HttpRefusal::decode(status.as_u16(), serde_json::from_str(body).ok()?)
276            }
277            Self::Protocol(failure) => HttpRefusal::decode(failure.status, failure.body.clone()),
278            _ => None,
279        }
280    }
281}
282
283/// Whether a Server worker protocol version is compatible with the client's:
284/// same major, and a Server minor at least the client's. Versions that are
285/// not `major.minor` integers must match exactly. This is the CLI 2.x rule.
286pub fn worker_protocol_compatible(client: &str, server: &str) -> bool {
287    fn split(version: &str) -> Option<(u64, u64)> {
288        let (major, minor) = version.split_once('.')?;
289        let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
290        if !digits(major) || !digits(minor) {
291            return None;
292        }
293        Some((major.parse().ok()?, minor.parse().ok()?))
294    }
295    match (split(client), split(server)) {
296        (Some(client), Some(server)) => client.0 == server.0 && client.1 <= server.1,
297        _ => client == server,
298    }
299}
300
301fn invalid_worker_response(status: u16, message: String, requested: &str, body: Value) -> Error {
302    Error::Protocol(ProtocolFailure {
303        status,
304        reason: "invalid_worker_protocol_response".to_string(),
305        message,
306        supported_version: None,
307        requested_version: Some(requested.to_string()),
308        body,
309    })
310}
311
312impl Client {
313    /// Send a control-plane request with this client's base URL (including
314    /// any path prefix), TLS settings, namespace, control token, timeout and
315    /// metrics recorder.
316    ///
317    /// Every HTTP response is returned as a [`RawResponse`], including 4xx
318    /// and 5xx. Use [`RawResponse::error_for_status`] or
319    /// [`RawResponse::refusal`] to classify a refusal. Transport failures,
320    /// including timeouts, are [`Error::Transport`].
321    pub async fn control_plane_request(&self, request: RawRequest) -> Result<RawResponse> {
322        self.raw_request(request, RequestProtocol::ControlPlane)
323            .await
324    }
325
326    /// Send a worker-plane request with the worker token. Otherwise like
327    /// [`Client::control_plane_request`].
328    ///
329    /// A 2xx response must echo a compatible protocol version (see
330    /// [`worker_protocol_compatible`]) in its header, and its JSON body must
331    /// carry the same `protocol_version`; otherwise the result is
332    /// [`Error::Protocol`] with reason `invalid_worker_protocol_response`.
333    /// A numeric body value is compared in its JSON spelling (`1.2` stays
334    /// `"1.2"`, `1.20` becomes `"1.2"`). Servers send it as a string.
335    /// Non-2xx responses are not checked.
336    pub async fn worker_plane_request(&self, request: RawRequest) -> Result<RawResponse> {
337        self.raw_request(request, RequestProtocol::DefaultWorker)
338            .await
339    }
340
341    async fn raw_request(
342        &self,
343        request: RawRequest,
344        protocol: RequestProtocol,
345    ) -> Result<RawResponse> {
346        let path = request.path()?;
347        let method = request.method.as_reqwest();
348        let mut observation = ClientObservation::new(self, &method, &path, protocol);
349        let result = self
350            .send_raw_request(request, method, &path, protocol, &observation)
351            .await;
352        observation.finish(&result);
353        result
354    }
355
356    async fn send_raw_request(
357        &self,
358        request: RawRequest,
359        method: reqwest::Method,
360        path: &str,
361        protocol: RequestProtocol,
362        observation: &ClientObservation,
363    ) -> Result<RawResponse> {
364        // Both version headers go on every request, on both planes, as the
365        // CLI 2.x client sends them.
366        // The configured version, with no negotiation or worker-loop checks.
367        let worker_version = request
368            .protocol_version
369            .clone()
370            .unwrap_or_else(|| self.worker_protocol_version.as_str().to_string());
371        let control_version = request
372            .control_plane_version
373            .as_deref()
374            .unwrap_or(CONTROL_PLANE_VERSION);
375        let auth_token = self.auth_token(protocol)?;
376        let mut builder = self
377            .http
378            .request(method, format!("{}/api{}", self.base_url, path))
379            .header(reqwest::header::ACCEPT, "application/json")
380            .header("X-Namespace", &self.namespace)
381            .header(PROTOCOL_VERSION_HEADER, &worker_version)
382            .header(CONTROL_PLANE_VERSION_HEADER, control_version);
383        if let Some(timeout) = request.timeout {
384            builder = builder.timeout(timeout);
385        }
386        if let Some(token) = auth_token {
387            builder = builder.bearer_auth(token);
388        }
389        if !request.query.is_empty() {
390            builder = builder.query(&request.query);
391        }
392        if let Some(body) = &request.body {
393            builder = builder.json(body);
394        }
395
396        // Timeouts stay Error::Transport, as for typed calls.
397        let response = builder.send().await?;
398        let status = response.status();
399        observation.status(status);
400        let headers = response.headers().clone();
401        let response = RawResponse {
402            status: status.as_u16(),
403            headers,
404            body: crate::read_capped_body(response, self.max_response_bytes).await?,
405        };
406
407        if matches!(protocol, RequestProtocol::ControlPlane) || !response.is_success() {
408            return Ok(response);
409        }
410        let body = response.json().unwrap_or(Value::Null);
411        let echoed = response.protocol_version().map(str::trim);
412        if !echoed.is_some_and(|echoed| worker_protocol_compatible(&worker_version, echoed)) {
413            return Err(invalid_worker_response(
414                response.status,
415                format!(
416                    "worker response version {} is not same-major compatible with {worker_version}",
417                    echoed.unwrap_or("missing")
418                ),
419                &worker_version,
420                body,
421            ));
422        }
423        let body_version = body
424            .get("protocol_version")
425            .and_then(|version| match version {
426                Value::String(text) => Some(text.trim().to_string()),
427                Value::Number(number) => Some(number.to_string()),
428                _ => None,
429            });
430        if body_version.as_deref() != echoed {
431            return Err(invalid_worker_response(
432                response.status,
433                "worker response body protocol_version must equal the protocol header".into(),
434                &worker_version,
435                body,
436            ));
437        }
438        Ok(response)
439    }
440}