1use std::sync::Arc;
6
7use anyhow::Result;
8use async_trait::async_trait;
9use bytes::Bytes;
10use tokio::sync::mpsc;
11
12use crate::request::RequestPart;
13use crate::response::ResponseChunk;
14
15#[async_trait]
19pub trait Executor: Send + Sync + 'static {
20 async fn execute(&self, payload: Bytes) -> Result<Bytes> {
23 self.execute_method("dispatch", payload).await
24 }
25
26 async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes>;
28
29 async fn execute_value(
35 &self,
36 method: &str,
37 payload: serde_json::Value,
38 ) -> Result<serde_json::Value> {
39 let bytes = serde_json::to_vec(&payload)?;
40 let result = self.execute_method(method, Bytes::from(bytes)).await?;
41 Ok(serde_json::from_slice(&result)?)
42 }
43
44 async fn execute_value_traced(
51 &self,
52 method: &str,
53 payload: serde_json::Value,
54 ) -> Result<(serde_json::Value, Arc<str>)> {
55 let value = self.execute_value(method, payload).await?;
56 Ok((value, Arc::from("")))
57 }
58
59 async fn execute_streamed(
74 &self,
75 method: &str,
76 payload: serde_json::Value,
77 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
78 let (value, id) = self.execute_value_traced(method, payload).await?;
79 let (tx, rx) = mpsc::channel(4);
80 let _ = tx.send(ResponseChunk::Return(value)).await;
81 let _ = tx.send(ResponseChunk::End).await;
82 Ok((rx, id))
83 }
84
85 async fn execute_streamed_with_body(
97 &self,
98 method: &str,
99 payload: serde_json::Value,
100 body_rx: mpsc::Receiver<Bytes>,
101 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
102 drop(body_rx);
103 self.execute_streamed(method, payload).await
104 }
105
106 async fn execute_streamed_with_parts(
119 &self,
120 method: &str,
121 payload: serde_json::Value,
122 parts_rx: mpsc::Receiver<RequestPart>,
123 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
124 drop(parts_rx);
125 self.execute_streamed(method, payload).await
126 }
127}
128
129pub async fn value_to_chunks(value: serde_json::Value, tx: &mpsc::Sender<ResponseChunk>) {
134 let status =
135 u16::try_from(value.get("status").and_then(|v| v.as_u64()).unwrap_or(200)).unwrap_or(200);
136
137 let mut headers: Vec<(String, String)> = Vec::new();
140 if let Some(obj) = value.get("headers").and_then(|v| v.as_object()) {
141 for (k, v) in obj {
142 match v {
143 serde_json::Value::String(s) => headers.push((k.clone(), s.clone())),
144 serde_json::Value::Array(items) => {
145 for item in items {
146 if let Some(s) = item.as_str() {
147 headers.push((k.clone(), s.to_string()));
148 }
149 }
150 }
151 _ => {}
152 }
153 }
154 }
155
156 let _ = tx.send(ResponseChunk::Headers { status, headers }).await;
157
158 let body_str = value
159 .get("body")
160 .and_then(|v| v.as_str())
161 .unwrap_or("")
162 .to_string();
163 let body_encoding = value
164 .get("body_encoding")
165 .and_then(|v| v.as_str())
166 .map(str::to_string);
167
168 let body_bytes: Bytes = if body_encoding.as_deref() == Some("base64") {
169 use base64::Engine;
170 match base64::engine::general_purpose::STANDARD.decode(&body_str) {
171 Ok(b) => Bytes::from(b),
172 Err(e) => {
173 tracing::error!(error = ?e, "value_to_chunks: base64 decode failed");
174 Bytes::new()
175 }
176 }
177 } else {
178 Bytes::from(body_str.into_bytes())
179 };
180
181 if !body_bytes.is_empty() {
182 let _ = tx.send(ResponseChunk::Body(body_bytes)).await;
183 }
184
185 let _ = tx.send(ResponseChunk::End).await;
186}
187
188pub async fn chunks_to_value(rx: &mut mpsc::Receiver<ResponseChunk>) -> Result<serde_json::Value> {
200 let mut status: u16 = 200;
201 let mut headers: Vec<(String, String)> = Vec::new();
202 let mut body_bytes: Vec<u8> = Vec::new();
203 let mut return_value: Option<serde_json::Value> = None;
204
205 while let Some(chunk) = rx.recv().await {
206 match chunk {
207 ResponseChunk::Headers {
208 status: s,
209 headers: h,
210 } => {
211 status = s;
212 headers = h;
213 }
214 ResponseChunk::Body(b) => body_bytes.extend_from_slice(&b),
215 ResponseChunk::Return(v) => return_value = Some(v),
216 ResponseChunk::Error(e) => return Err(anyhow::Error::new(e)),
217 ResponseChunk::End => break,
218 }
219 }
220
221 if let Some(value) = return_value {
222 return Ok(value);
223 }
224
225 let mut headers_map: serde_json::Map<String, serde_json::Value> = serde_json::Map::new();
229 for (k, v) in headers {
230 match headers_map.get_mut(&k) {
231 Some(serde_json::Value::Array(arr)) => arr.push(serde_json::Value::String(v)),
232 Some(existing) => {
233 let prev = existing.take();
234 *existing = serde_json::Value::Array(vec![prev, serde_json::Value::String(v)]);
235 }
236 None => {
237 headers_map.insert(k, serde_json::Value::String(v));
238 }
239 }
240 }
241 let headers_value = serde_json::Value::Object(headers_map);
242
243 Ok(serde_json::json!({
244 "status": status,
245 "headers": headers_value,
246 "body": String::from_utf8_lossy(&body_bytes),
247 }))
248}
249
250#[derive(Debug, Clone, Copy, Default)]
259pub struct NoopExecutor;
260
261impl NoopExecutor {
262 fn refuse<T>() -> Result<T> {
263 tracing::error!(
264 "NoopExecutor called in the master process: a plugin dispatched PHP \
265 but ran with role=Master (no PHP runtime). Check its placement()."
266 );
267 Err(anyhow::anyhow!(
268 "no PHP runtime in the master process (NoopExecutor)"
269 ))
270 }
271}
272
273#[async_trait]
274impl Executor for NoopExecutor {
275 async fn execute_method(&self, _method: &str, _payload: Bytes) -> Result<Bytes> {
276 Self::refuse()
277 }
278}
279
280#[async_trait]
282impl<T: Executor + ?Sized> Executor for Arc<T> {
283 async fn execute(&self, payload: Bytes) -> Result<Bytes> {
284 (**self).execute(payload).await
285 }
286
287 async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
288 (**self).execute_method(method, payload).await
289 }
290
291 async fn execute_value(
292 &self,
293 method: &str,
294 payload: serde_json::Value,
295 ) -> Result<serde_json::Value> {
296 (**self).execute_value(method, payload).await
297 }
298
299 async fn execute_value_traced(
300 &self,
301 method: &str,
302 payload: serde_json::Value,
303 ) -> Result<(serde_json::Value, Arc<str>)> {
304 (**self).execute_value_traced(method, payload).await
305 }
306
307 async fn execute_streamed(
308 &self,
309 method: &str,
310 payload: serde_json::Value,
311 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
312 (**self).execute_streamed(method, payload).await
313 }
314
315 async fn execute_streamed_with_body(
316 &self,
317 method: &str,
318 payload: serde_json::Value,
319 body_rx: mpsc::Receiver<Bytes>,
320 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
321 (**self)
322 .execute_streamed_with_body(method, payload, body_rx)
323 .await
324 }
325
326 async fn execute_streamed_with_parts(
327 &self,
328 method: &str,
329 payload: serde_json::Value,
330 parts_rx: mpsc::Receiver<RequestPart>,
331 ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
332 (**self)
333 .execute_streamed_with_parts(method, payload, parts_rx)
334 .await
335 }
336}