use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use bytes::Bytes;
use tokio::sync::mpsc;
use crate::request::RequestPart;
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
}
async fn execute_streamed_with_parts(
&self,
method: &str,
payload: serde_json::Value,
parts_rx: mpsc::Receiver<RequestPart>,
) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
drop(parts_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 mut headers: Vec<(String, String)> = Vec::new();
if let Some(obj) = value.get("headers").and_then(|v| v.as_object()) {
for (k, v) in obj {
match v {
serde_json::Value::String(s) => headers.push((k.clone(), s.clone())),
serde_json::Value::Array(items) => {
for item in items {
if let Some(s) = item.as_str() {
headers.push((k.clone(), s.to_string()));
}
}
}
_ => {}
}
}
}
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;
}
pub async fn chunks_to_value(rx: &mut mpsc::Receiver<ResponseChunk>) -> Result<serde_json::Value> {
let mut status: u16 = 200;
let mut headers: Vec<(String, String)> = Vec::new();
let mut body_bytes: Vec<u8> = Vec::new();
let mut return_value: Option<serde_json::Value> = None;
while let Some(chunk) = rx.recv().await {
match chunk {
ResponseChunk::Headers {
status: s,
headers: h,
} => {
status = s;
headers = h;
}
ResponseChunk::Body(b) => body_bytes.extend_from_slice(&b),
ResponseChunk::Return(v) => return_value = Some(v),
ResponseChunk::Error(e) => return Err(anyhow::Error::new(e)),
ResponseChunk::End => break,
}
}
if let Some(value) = return_value {
return Ok(value);
}
let mut headers_map: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
for (k, v) in headers {
match headers_map.get_mut(&k) {
Some(serde_json::Value::Array(arr)) => arr.push(serde_json::Value::String(v)),
Some(existing) => {
let prev = existing.take();
*existing = serde_json::Value::Array(vec![prev, serde_json::Value::String(v)]);
}
None => {
headers_map.insert(k, serde_json::Value::String(v));
}
}
}
let headers_value = serde_json::Value::Object(headers_map);
Ok(serde_json::json!({
"status": status,
"headers": headers_value,
"body": String::from_utf8_lossy(&body_bytes),
}))
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoopExecutor;
impl NoopExecutor {
fn refuse<T>() -> Result<T> {
tracing::error!(
"NoopExecutor called in the master process: a plugin dispatched PHP \
but ran with role=Master (no PHP runtime). Check its placement()."
);
Err(anyhow::anyhow!(
"no PHP runtime in the master process (NoopExecutor)"
))
}
}
#[async_trait]
impl Executor for NoopExecutor {
async fn execute_method(&self, _method: &str, _payload: Bytes) -> Result<Bytes> {
Self::refuse()
}
}
#[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
}
async fn execute_streamed_with_parts(
&self,
method: &str,
payload: serde_json::Value,
parts_rx: mpsc::Receiver<RequestPart>,
) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
(**self)
.execute_streamed_with_parts(method, payload, parts_rx)
.await
}
}