1use 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#[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#[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 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 pub fn json(mut self, body: Value) -> Self {
105 self.body = Some(body);
106 self
107 }
108
109 pub fn timeout(mut self, timeout: Duration) -> Self {
111 self.timeout = Some(timeout);
112 self
113 }
114
115 pub fn protocol_version(mut self, version: impl Into<String>) -> Self {
118 self.protocol_version = Some(version.into());
119 self
120 }
121
122 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 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#[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 pub fn header(&self, name: &str) -> Option<&str> {
175 self.headers.get(name)?.to_str().ok()
176 }
177
178 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 pub fn protocol_version(&self) -> Option<&str> {
187 self.header(PROTOCOL_VERSION_HEADER)
188 }
189
190 pub fn control_plane_version(&self) -> Option<&str> {
192 self.header(CONTROL_PLANE_VERSION_HEADER)
193 }
194
195 pub fn body_bytes(&self) -> &[u8] {
197 &self.body
198 }
199
200 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 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 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#[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 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 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
283pub 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 pub async fn control_plane_request(&self, request: RawRequest) -> Result<RawResponse> {
322 self.raw_request(request, RequestProtocol::ControlPlane)
323 .await
324 }
325
326 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 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 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}