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
180#[async_trait]
182impl<T: Executor + ?Sized> Executor for Arc<T> {
183 async fn execute(&self, payload: Bytes) -> Result<Bytes> {
184 (**self).execute(payload).await
185 }
186
187 async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
188 (**self).execute_method(method, payload).await
189 }
190
191 async fn execute_value(
192 &self,
193 method: &str,
194 payload: serde_json::Value,
195 ) -> Result<serde_json::Value> {
196 (**self).execute_value(method, payload).await
197 }
198
199 async fn execute_value_traced(
200 &self,
201 method: &str,
202 payload: serde_json::Value,
203 ) -> Result<(serde_json::Value, Arc<str>)> {
204 (**self).execute_value_traced(method, payload).await
205 }
206
207 async fn execute_streamed(
208 &self,
209 method: &str,
210 payload: serde_json::Value,
211 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
212 (**self).execute_streamed(method, payload).await
213 }
214
215 async fn execute_streamed_with_body(
216 &self,
217 method: &str,
218 payload: serde_json::Value,
219 body_rx: mpsc::Receiver<Bytes>,
220 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
221 (**self)
222 .execute_streamed_with_body(method, payload, body_rx)
223 .await
224 }
225
226 async fn execute_streamed_with_parts(
227 &self,
228 method: &str,
229 payload: serde_json::Value,
230 parts_rx: mpsc::Receiver<RequestPart>,
231 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
232 (**self)
233 .execute_streamed_with_parts(method, payload, parts_rx)
234 .await
235 }
236}