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::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/// Sends a serialized payload to a PHP worker and returns the response.
17///
18/// Plugins call this; they never see the worker pool directly.
19#[async_trait]
20pub trait Executor: Send + Sync + 'static {
21    /// Send `payload` to a worker and return the response bytes.
22    /// Uses the RPC method name "dispatch" by default.
23    async fn execute(&self, payload: Bytes) -> Result<Bytes> {
24        self.execute_method("dispatch", payload).await
25    }
26
27    /// Send `payload` to a worker using a specific RPC method name.
28    async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes>;
29
30    /// Send structured data directly (no serialization).
31    ///
32    /// The default implementation falls back to JSON serialization
33    /// via [`Self::execute_method`]. Extension runtimes override this to
34    /// pass values through the channel without JSON encode/decode.
35    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    /// Like [`Self::execute_value`], but also returns the `request_id` under which the
46    /// request was executed — the same id exposed to PHP via `folk_request_id()`.
47    ///
48    /// Plugins that maintain an access log (e.g. HTTP) use this to record the id
49    /// for log correlation. The default implementation calls [`Self::execute_value`]
50    /// and returns an empty id (runtimes that don't track one).
51    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    /// Send a request and receive the response as a stream of [`ResponseChunk`]s.
61    ///
62    /// The returned receiver emits zero or more [`ResponseChunk::Body`] chunks
63    /// preceded by a [`ResponseChunk::Headers`] chunk, and terminated by
64    /// [`ResponseChunk::End`]. The `Arc<str>` is the `request_id` (UUID v7) for
65    /// log correlation — the same id exposed to PHP via `folk_request_id()`.
66    ///
67    /// Callers must drain the receiver to completion (`End` or channel close) to
68    /// allow the worker to accept the next request.
69    ///
70    /// The default implementation wraps [`Self::execute_value_traced`] into a
71    /// single-shot stream for runtimes that do not support true streaming. The
72    /// value is emitted verbatim as a [`ResponseChunk::Return`] — consumers
73    /// (HTTP / gRPC / jobs) interpret it themselves.
74    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    /// Like [`Self::execute_streamed`], but the request body is delivered to PHP as a
87    /// stream of [`Bytes`] chunks rather than embedded in `payload`.
88    ///
89    /// `body_rx` yields raw body chunks as they arrive from the transport; PHP
90    /// pulls them via `folk_read()` / `folk_read_all()`. The channel closing
91    /// signals end-of-body. This is the request-side counterpart to the
92    /// [`ResponseChunk`] response stream.
93    ///
94    /// The default implementation does not support request body streaming: it
95    /// discards `body_rx` and delegates to [`Self::execute_streamed`]. Runtimes backed
96    /// by a real worker pool override this to thread `body_rx` to the worker.
97    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    /// Like [`execute_streamed_with_body`], but the request body is a parsed
108    /// `multipart/form-data` stream rather than opaque bytes.
109    ///
110    /// `parts_rx` yields [`RequestPart`]s (Start / Data / End per field); PHP
111    /// pulls them via `folk_next_part()` + `folk_part_read()`. The channel
112    /// closing signals "no more parts".
113    ///
114    /// The default implementation discards `parts_rx` and delegates to
115    /// [`execute_streamed`]; the worker-pool runtime overrides it.
116    ///
117    /// [`execute_streamed_with_body`]: Self::execute_streamed_with_body
118    /// [`execute_streamed`]: Self::execute_streamed
119    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
130/// Convert a single-shot PHP response Value into a stream of ResponseChunks.
131///
132/// Sends `Headers`, optionally `Body`, then `End`. Errors are logged and
133/// result in an empty body.
134pub 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/// Drain a [`ResponseChunk`] stream into a single `serde_json::Value`.
181///
182/// The inverse of [`value_to_chunks`], used by the non-streaming callers (gRPC,
183/// jobs, and the backward-compat `execute` path). The result depends on how the
184/// worker finalised the request:
185///
186/// * [`ResponseChunk::Return`] — the value is returned **verbatim** (gRPC/jobs
187///   need their payload intact, not coerced into the HTTP shape);
188/// * [`ResponseChunk::Error`] — propagated as an `Err`;
189/// * a `Headers`/`Body` stream with no explicit `Return` is reconstructed into
190///   the legacy `{status, headers, body}` shape for backward compatibility.
191pub async fn chunks_to_value(rx: &mut mpsc::Receiver<ResponseChunk>) -> Result<serde_json::Value> {
192    let mut status: u16 = 200;
193    let mut headers: HashMap<String, String> = HashMap::new();
194    let mut body_bytes: Vec<u8> = Vec::new();
195    let mut return_value: Option<serde_json::Value> = None;
196
197    while let Some(chunk) = rx.recv().await {
198        match chunk {
199            ResponseChunk::Headers {
200                status: s,
201                headers: h,
202            } => {
203                status = s;
204                headers = h;
205            }
206            ResponseChunk::Body(b) => body_bytes.extend_from_slice(&b),
207            ResponseChunk::Return(v) => return_value = Some(v),
208            ResponseChunk::Error(e) => return Err(anyhow::Error::new(e)),
209            ResponseChunk::End => break,
210        }
211    }
212
213    if let Some(value) = return_value {
214        return Ok(value);
215    }
216
217    // Reconstruct the legacy Value format that HTTP plugin / callers expect.
218    let headers_value: serde_json::Value = headers
219        .into_iter()
220        .map(|(k, v)| (k, serde_json::Value::String(v)))
221        .collect::<serde_json::Map<_, _>>()
222        .into();
223
224    Ok(serde_json::json!({
225        "status": status,
226        "headers": headers_value,
227        "body": String::from_utf8_lossy(&body_bytes),
228    }))
229}
230
231/// An [`Executor`] that has no PHP runtime behind it.
232///
233/// Installed in the **master** process's [`PluginContext`](crate::PluginContext)
234/// (phase 79): the master supervises and owns shared state but never executes
235/// PHP. A `MasterOnly` plugin should never call its executor; if it does, every
236/// method logs an error and returns `Err` rather than silently doing nothing —
237/// surfacing the misuse (a plugin dispatching PHP while placed in the master)
238/// loudly but without crashing the supervisor.
239#[derive(Debug, Clone, Copy, Default)]
240pub struct NoopExecutor;
241
242impl NoopExecutor {
243    fn refuse<T>() -> Result<T> {
244        tracing::error!(
245            "NoopExecutor called in the master process: a plugin dispatched PHP \
246             but ran with role=Master (no PHP runtime). Check its placement()."
247        );
248        Err(anyhow::anyhow!(
249            "no PHP runtime in the master process (NoopExecutor)"
250        ))
251    }
252}
253
254#[async_trait]
255impl Executor for NoopExecutor {
256    async fn execute_method(&self, _method: &str, _payload: Bytes) -> Result<Bytes> {
257        Self::refuse()
258    }
259}
260
261/// Blanket impl: an `Arc<dyn Executor>` is also an `Executor`.
262#[async_trait]
263impl<T: Executor + ?Sized> Executor for Arc<T> {
264    async fn execute(&self, payload: Bytes) -> Result<Bytes> {
265        (**self).execute(payload).await
266    }
267
268    async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
269        (**self).execute_method(method, payload).await
270    }
271
272    async fn execute_value(
273        &self,
274        method: &str,
275        payload: serde_json::Value,
276    ) -> Result<serde_json::Value> {
277        (**self).execute_value(method, payload).await
278    }
279
280    async fn execute_value_traced(
281        &self,
282        method: &str,
283        payload: serde_json::Value,
284    ) -> Result<(serde_json::Value, Arc<str>)> {
285        (**self).execute_value_traced(method, payload).await
286    }
287
288    async fn execute_streamed(
289        &self,
290        method: &str,
291        payload: serde_json::Value,
292    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
293        (**self).execute_streamed(method, payload).await
294    }
295
296    async fn execute_streamed_with_body(
297        &self,
298        method: &str,
299        payload: serde_json::Value,
300        body_rx: mpsc::Receiver<Bytes>,
301    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
302        (**self)
303            .execute_streamed_with_body(method, payload, body_rx)
304            .await
305    }
306
307    async fn execute_streamed_with_parts(
308        &self,
309        method: &str,
310        payload: serde_json::Value,
311        parts_rx: mpsc::Receiver<RequestPart>,
312    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
313        (**self)
314            .execute_streamed_with_parts(method, payload, parts_rx)
315            .await
316    }
317}