use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use bytes::Bytes;
use tokio::sync::mpsc;
use crate::response::ResponseChunk;
#[async_trait]
pub trait Executor: Send + Sync + 'static {
async fn execute(&self, payload: Bytes) -> Result<Bytes> {
self.execute_method("dispatch", payload).await
}
async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes>;
async fn execute_value(
&self,
method: &str,
payload: serde_json::Value,
) -> Result<serde_json::Value> {
let bytes = serde_json::to_vec(&payload)?;
let result = self.execute_method(method, Bytes::from(bytes)).await?;
Ok(serde_json::from_slice(&result)?)
}
async fn execute_value_traced(
&self,
method: &str,
payload: serde_json::Value,
) -> Result<(serde_json::Value, Arc<str>)> {
let value = self.execute_value(method, payload).await?;
Ok((value, Arc::from("")))
}
async fn execute_streamed(
&self,
method: &str,
payload: serde_json::Value,
) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
let (value, id) = self.execute_value_traced(method, payload).await?;
let (tx, rx) = mpsc::channel(4);
let _ = tx.send(ResponseChunk::Return(value)).await;
let _ = tx.send(ResponseChunk::End).await;
Ok((rx, id))
}
async fn execute_streamed_with_body(
&self,
method: &str,
payload: serde_json::Value,
body_rx: mpsc::Receiver<Bytes>,
) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
drop(body_rx);
self.execute_streamed(method, payload).await
}
}
pub async fn value_to_chunks(value: serde_json::Value, tx: &mpsc::Sender<ResponseChunk>) {
let status =
u16::try_from(value.get("status").and_then(|v| v.as_u64()).unwrap_or(200)).unwrap_or(200);
let headers: HashMap<String, String> = value
.get("headers")
.and_then(|v| v.as_object())
.map(|obj| {
obj.iter()
.filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
.collect()
})
.unwrap_or_default();
let _ = tx.send(ResponseChunk::Headers { status, headers }).await;
let body_str = value
.get("body")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let body_encoding = value
.get("body_encoding")
.and_then(|v| v.as_str())
.map(str::to_string);
let body_bytes: Bytes = if body_encoding.as_deref() == Some("base64") {
use base64::Engine;
match base64::engine::general_purpose::STANDARD.decode(&body_str) {
Ok(b) => Bytes::from(b),
Err(e) => {
tracing::error!(error = ?e, "value_to_chunks: base64 decode failed");
Bytes::new()
}
}
} else {
Bytes::from(body_str.into_bytes())
};
if !body_bytes.is_empty() {
let _ = tx.send(ResponseChunk::Body(body_bytes)).await;
}
let _ = tx.send(ResponseChunk::End).await;
}
#[async_trait]
impl<T: Executor + ?Sized> Executor for Arc<T> {
async fn execute(&self, payload: Bytes) -> Result<Bytes> {
(**self).execute(payload).await
}
async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
(**self).execute_method(method, payload).await
}
async fn execute_value(
&self,
method: &str,
payload: serde_json::Value,
) -> Result<serde_json::Value> {
(**self).execute_value(method, payload).await
}
async fn execute_value_traced(
&self,
method: &str,
payload: serde_json::Value,
) -> Result<(serde_json::Value, Arc<str>)> {
(**self).execute_value_traced(method, payload).await
}
async fn execute_streamed(
&self,
method: &str,
payload: serde_json::Value,
) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
(**self).execute_streamed(method, payload).await
}
async fn execute_streamed_with_body(
&self,
method: &str,
payload: serde_json::Value,
body_rx: mpsc::Receiver<Bytes>,
) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
(**self)
.execute_streamed_with_body(method, payload, body_rx)
.await
}
}