1use std::collections::HashMap;
6use std::sync::Arc;
7
8use anyhow::Result;
9use async_trait::async_trait;
10use bytes::Bytes;
11use tokio::sync::mpsc;
12
13use crate::request::RequestPart;
14use crate::response::ResponseChunk;
15
16#[async_trait]
20pub trait Executor: Send + Sync + 'static {
21 async fn execute(&self, payload: Bytes) -> Result<Bytes> {
24 self.execute_method("dispatch", payload).await
25 }
26
27 async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes>;
29
30 async fn execute_value(
36 &self,
37 method: &str,
38 payload: serde_json::Value,
39 ) -> Result<serde_json::Value> {
40 let bytes = serde_json::to_vec(&payload)?;
41 let result = self.execute_method(method, Bytes::from(bytes)).await?;
42 Ok(serde_json::from_slice(&result)?)
43 }
44
45 async fn execute_value_traced(
52 &self,
53 method: &str,
54 payload: serde_json::Value,
55 ) -> Result<(serde_json::Value, Arc<str>)> {
56 let value = self.execute_value(method, payload).await?;
57 Ok((value, Arc::from("")))
58 }
59
60 async fn execute_streamed(
75 &self,
76 method: &str,
77 payload: serde_json::Value,
78 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
79 let (value, id) = self.execute_value_traced(method, payload).await?;
80 let (tx, rx) = mpsc::channel(4);
81 let _ = tx.send(ResponseChunk::Return(value)).await;
82 let _ = tx.send(ResponseChunk::End).await;
83 Ok((rx, id))
84 }
85
86 async fn execute_streamed_with_body(
98 &self,
99 method: &str,
100 payload: serde_json::Value,
101 body_rx: mpsc::Receiver<Bytes>,
102 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
103 drop(body_rx);
104 self.execute_streamed(method, payload).await
105 }
106
107 async fn execute_streamed_with_parts(
120 &self,
121 method: &str,
122 payload: serde_json::Value,
123 parts_rx: mpsc::Receiver<RequestPart>,
124 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
125 drop(parts_rx);
126 self.execute_streamed(method, payload).await
127 }
128}
129
130pub async fn value_to_chunks(value: serde_json::Value, tx: &mpsc::Sender<ResponseChunk>) {
135 let status =
136 u16::try_from(value.get("status").and_then(|v| v.as_u64()).unwrap_or(200)).unwrap_or(200);
137
138 let headers: HashMap<String, String> = value
139 .get("headers")
140 .and_then(|v| v.as_object())
141 .map(|obj| {
142 obj.iter()
143 .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
144 .collect()
145 })
146 .unwrap_or_default();
147
148 let _ = tx.send(ResponseChunk::Headers { status, headers }).await;
149
150 let body_str = value
151 .get("body")
152 .and_then(|v| v.as_str())
153 .unwrap_or("")
154 .to_string();
155 let body_encoding = value
156 .get("body_encoding")
157 .and_then(|v| v.as_str())
158 .map(str::to_string);
159
160 let body_bytes: Bytes = if body_encoding.as_deref() == Some("base64") {
161 use base64::Engine;
162 match base64::engine::general_purpose::STANDARD.decode(&body_str) {
163 Ok(b) => Bytes::from(b),
164 Err(e) => {
165 tracing::error!(error = ?e, "value_to_chunks: base64 decode failed");
166 Bytes::new()
167 }
168 }
169 } else {
170 Bytes::from(body_str.into_bytes())
171 };
172
173 if !body_bytes.is_empty() {
174 let _ = tx.send(ResponseChunk::Body(body_bytes)).await;
175 }
176
177 let _ = tx.send(ResponseChunk::End).await;
178}
179
180pub async fn chunks_to_value(rx: &mut mpsc::Receiver<ResponseChunk>) -> Result<serde_json::Value> {
192 let mut status: u16 = 200;
193 let mut headers: HashMap<String, String> = HashMap::new();
194 let mut body_bytes: Vec<u8> = Vec::new();
195 let mut return_value: Option<serde_json::Value> = None;
196
197 while let Some(chunk) = rx.recv().await {
198 match chunk {
199 ResponseChunk::Headers {
200 status: s,
201 headers: h,
202 } => {
203 status = s;
204 headers = h;
205 }
206 ResponseChunk::Body(b) => body_bytes.extend_from_slice(&b),
207 ResponseChunk::Return(v) => return_value = Some(v),
208 ResponseChunk::Error(e) => return Err(anyhow::Error::new(e)),
209 ResponseChunk::End => break,
210 }
211 }
212
213 if let Some(value) = return_value {
214 return Ok(value);
215 }
216
217 let headers_value: serde_json::Value = headers
219 .into_iter()
220 .map(|(k, v)| (k, serde_json::Value::String(v)))
221 .collect::<serde_json::Map<_, _>>()
222 .into();
223
224 Ok(serde_json::json!({
225 "status": status,
226 "headers": headers_value,
227 "body": String::from_utf8_lossy(&body_bytes),
228 }))
229}
230
231#[async_trait]
233impl<T: Executor + ?Sized> Executor for Arc<T> {
234 async fn execute(&self, payload: Bytes) -> Result<Bytes> {
235 (**self).execute(payload).await
236 }
237
238 async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
239 (**self).execute_method(method, payload).await
240 }
241
242 async fn execute_value(
243 &self,
244 method: &str,
245 payload: serde_json::Value,
246 ) -> Result<serde_json::Value> {
247 (**self).execute_value(method, payload).await
248 }
249
250 async fn execute_value_traced(
251 &self,
252 method: &str,
253 payload: serde_json::Value,
254 ) -> Result<(serde_json::Value, Arc<str>)> {
255 (**self).execute_value_traced(method, payload).await
256 }
257
258 async fn execute_streamed(
259 &self,
260 method: &str,
261 payload: serde_json::Value,
262 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
263 (**self).execute_streamed(method, payload).await
264 }
265
266 async fn execute_streamed_with_body(
267 &self,
268 method: &str,
269 payload: serde_json::Value,
270 body_rx: mpsc::Receiver<Bytes>,
271 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
272 (**self)
273 .execute_streamed_with_body(method, payload, body_rx)
274 .await
275 }
276
277 async fn execute_streamed_with_parts(
278 &self,
279 method: &str,
280 payload: serde_json::Value,
281 parts_rx: mpsc::Receiver<RequestPart>,
282 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
283 (**self)
284 .execute_streamed_with_parts(method, payload, parts_rx)
285 .await
286 }
287}