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 [`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 [`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 [`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 [`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 [`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 [`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/// Blanket impl: an `Arc<dyn Executor>` is also an `Executor`.
181#[async_trait]
182impl<T: Executor + ?Sized> Executor for Arc<T> {
183    async fn execute(&self, payload: Bytes) -> Result<Bytes> {
184        (**self).execute(payload).await
185    }
186
187    async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
188        (**self).execute_method(method, payload).await
189    }
190
191    async fn execute_value(
192        &self,
193        method: &str,
194        payload: serde_json::Value,
195    ) -> Result<serde_json::Value> {
196        (**self).execute_value(method, payload).await
197    }
198
199    async fn execute_value_traced(
200        &self,
201        method: &str,
202        payload: serde_json::Value,
203    ) -> Result<(serde_json::Value, Arc<str>)> {
204        (**self).execute_value_traced(method, payload).await
205    }
206
207    async fn execute_streamed(
208        &self,
209        method: &str,
210        payload: serde_json::Value,
211    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
212        (**self).execute_streamed(method, payload).await
213    }
214
215    async fn execute_streamed_with_body(
216        &self,
217        method: &str,
218        payload: serde_json::Value,
219        body_rx: mpsc::Receiver<Bytes>,
220    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
221        (**self)
222            .execute_streamed_with_body(method, payload, body_rx)
223            .await
224    }
225
226    async fn execute_streamed_with_parts(
227        &self,
228        method: &str,
229        payload: serde_json::Value,
230        parts_rx: mpsc::Receiver<RequestPart>,
231    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
232        (**self)
233            .execute_streamed_with_parts(method, payload, parts_rx)
234            .await
235    }
236}