Skip to main content

folk_api/
executor.rs

1//! The `Executor` trait — how plugins send work to PHP workers.
2//!
3//! `folk-core` provides the concrete implementation, backed by the worker pool.
4
5use 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/// Sends a serialized payload to a PHP worker and returns the response.
16///
17/// Plugins call this; they never see the worker pool directly.
18#[async_trait]
19pub trait Executor: Send + Sync + 'static {
20    /// Send `payload` to a worker and return the response bytes.
21    /// Uses the RPC method name "dispatch" by default.
22    async fn execute(&self, payload: Bytes) -> Result<Bytes> {
23        self.execute_method("dispatch", payload).await
24    }
25
26    /// Send `payload` to a worker using a specific RPC method name.
27    async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes>;
28
29    /// Send structured data directly (no serialization).
30    ///
31    /// The default implementation falls back to JSON serialization
32    /// via [`Self::execute_method`]. Extension runtimes override this to
33    /// pass values through the channel without JSON encode/decode.
34    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    /// Like [`Self::execute_value`], but also returns the `request_id` under which the
45    /// request was executed — the same id exposed to PHP via `folk_request_id()`.
46    ///
47    /// Plugins that maintain an access log (e.g. HTTP) use this to record the id
48    /// for log correlation. The default implementation calls [`Self::execute_value`]
49    /// and returns an empty id (runtimes that don't track one).
50    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    /// Send a request and receive the response as a stream of [`ResponseChunk`]s.
60    ///
61    /// The returned receiver emits zero or more [`ResponseChunk::Body`] chunks
62    /// preceded by a [`ResponseChunk::Headers`] chunk, and terminated by
63    /// [`ResponseChunk::End`]. The `Arc<str>` is the `request_id` (UUID v7) for
64    /// log correlation — the same id exposed to PHP via `folk_request_id()`.
65    ///
66    /// Callers must drain the receiver to completion (`End` or channel close) to
67    /// allow the worker to accept the next request.
68    ///
69    /// The default implementation wraps [`Self::execute_value_traced`] into a
70    /// single-shot stream for runtimes that do not support true streaming. The
71    /// value is emitted verbatim as a [`ResponseChunk::Return`] — consumers
72    /// (HTTP / gRPC / jobs) interpret it themselves.
73    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    /// Like [`Self::execute_streamed`], but the request body is delivered to PHP as a
86    /// stream of [`Bytes`] chunks rather than embedded in `payload`.
87    ///
88    /// `body_rx` yields raw body chunks as they arrive from the transport; PHP
89    /// pulls them via `folk_read()` / `folk_read_all()`. The channel closing
90    /// signals end-of-body. This is the request-side counterpart to the
91    /// [`ResponseChunk`] response stream.
92    ///
93    /// The default implementation does not support request body streaming: it
94    /// discards `body_rx` and delegates to [`Self::execute_streamed`]. Runtimes backed
95    /// by a real worker pool override this to thread `body_rx` to the worker.
96    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    /// Like [`execute_streamed_with_body`], but the request body is a parsed
107    /// `multipart/form-data` stream rather than opaque bytes.
108    ///
109    /// `parts_rx` yields [`RequestPart`]s (Start / Data / End per field); PHP
110    /// pulls them via `folk_next_part()` + `folk_part_read()`. The channel
111    /// closing signals "no more parts".
112    ///
113    /// The default implementation discards `parts_rx` and delegates to
114    /// [`execute_streamed`]; the worker-pool runtime overrides it.
115    ///
116    /// [`execute_streamed_with_body`]: Self::execute_streamed_with_body
117    /// [`execute_streamed`]: Self::execute_streamed
118    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
129/// Convert a single-shot PHP response Value into a stream of ResponseChunks.
130///
131/// Sends `Headers`, optionally `Body`, then `End`. Errors are logged and
132/// result in an empty body.
133pub 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    // Ordered pairs, expanding array-valued headers (e.g. multiple Set-Cookie)
138    // into one entry each so they are not folded into a single value (#86).
139    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
188/// Drain a [`ResponseChunk`] stream into a single `serde_json::Value`.
189///
190/// The inverse of [`value_to_chunks`], used by the non-streaming callers (gRPC,
191/// jobs, and the backward-compat `execute` path). The result depends on how the
192/// worker finalised the request:
193///
194/// * [`ResponseChunk::Return`] — the value is returned **verbatim** (gRPC/jobs
195///   need their payload intact, not coerced into the HTTP shape);
196/// * [`ResponseChunk::Error`] — propagated as an `Err`;
197/// * a `Headers`/`Body` stream with no explicit `Return` is reconstructed into
198///   the legacy `{status, headers, body}` shape for backward compatibility.
199pub 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    // Reconstruct the legacy Value format that HTTP plugin / callers expect.
226    // A header seen once maps to a string; a repeated header (e.g. Set-Cookie)
227    // maps to an array so no value is lost (#86).
228    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/// An [`Executor`] that has no PHP runtime behind it.
251///
252/// Installed in the **master** process's [`PluginContext`](crate::PluginContext)
253/// (phase 79): the master supervises and owns shared state but never executes
254/// PHP. A `MasterOnly` plugin should never call its executor; if it does, every
255/// method logs an error and returns `Err` rather than silently doing nothing —
256/// surfacing the misuse (a plugin dispatching PHP while placed in the master)
257/// loudly but without crashing the supervisor.
258#[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/// Blanket impl: an `Arc<dyn Executor>` is also an `Executor`.
281#[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}