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::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 [`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 [`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 [`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 [`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 [`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 [`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
107/// Convert a single-shot PHP response Value into a stream of ResponseChunks.
108///
109/// Sends `Headers`, optionally `Body`, then `End`. Errors are logged and
110/// result in an empty body.
111pub async fn value_to_chunks(value: serde_json::Value, tx: &mpsc::Sender<ResponseChunk>) {
112    let status =
113        u16::try_from(value.get("status").and_then(|v| v.as_u64()).unwrap_or(200)).unwrap_or(200);
114
115    let headers: HashMap<String, String> = value
116        .get("headers")
117        .and_then(|v| v.as_object())
118        .map(|obj| {
119            obj.iter()
120                .filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string())))
121                .collect()
122        })
123        .unwrap_or_default();
124
125    let _ = tx.send(ResponseChunk::Headers { status, headers }).await;
126
127    let body_str = value
128        .get("body")
129        .and_then(|v| v.as_str())
130        .unwrap_or("")
131        .to_string();
132    let body_encoding = value
133        .get("body_encoding")
134        .and_then(|v| v.as_str())
135        .map(str::to_string);
136
137    let body_bytes: Bytes = if body_encoding.as_deref() == Some("base64") {
138        use base64::Engine;
139        match base64::engine::general_purpose::STANDARD.decode(&body_str) {
140            Ok(b) => Bytes::from(b),
141            Err(e) => {
142                tracing::error!(error = ?e, "value_to_chunks: base64 decode failed");
143                Bytes::new()
144            }
145        }
146    } else {
147        Bytes::from(body_str.into_bytes())
148    };
149
150    if !body_bytes.is_empty() {
151        let _ = tx.send(ResponseChunk::Body(body_bytes)).await;
152    }
153
154    let _ = tx.send(ResponseChunk::End).await;
155}
156
157/// Blanket impl: an `Arc<dyn Executor>` is also an `Executor`.
158#[async_trait]
159impl<T: Executor + ?Sized> Executor for Arc<T> {
160    async fn execute(&self, payload: Bytes) -> Result<Bytes> {
161        (**self).execute(payload).await
162    }
163
164    async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
165        (**self).execute_method(method, payload).await
166    }
167
168    async fn execute_value(
169        &self,
170        method: &str,
171        payload: serde_json::Value,
172    ) -> Result<serde_json::Value> {
173        (**self).execute_value(method, payload).await
174    }
175
176    async fn execute_value_traced(
177        &self,
178        method: &str,
179        payload: serde_json::Value,
180    ) -> Result<(serde_json::Value, Arc<str>)> {
181        (**self).execute_value_traced(method, payload).await
182    }
183
184    async fn execute_streamed(
185        &self,
186        method: &str,
187        payload: serde_json::Value,
188    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
189        (**self).execute_streamed(method, payload).await
190    }
191
192    async fn execute_streamed_with_body(
193        &self,
194        method: &str,
195        payload: serde_json::Value,
196        body_rx: mpsc::Receiver<Bytes>,
197    ) -> Result<(mpsc::Receiver<ResponseChunk>, Arc<str>)> {
198        (**self)
199            .execute_streamed_with_body(method, payload, body_rx)
200            .await
201    }
202}