Skip to main content

folk_core/
worker_pool.rs

1//! Worker pool: dispatches requests to PHP workers, manages slot lifecycle.
2//!
3//! See `folk-spec/spec/03-worker-lifecycle.md` for the design.
4
5use std::sync::Arc;
6use std::time::Duration;
7
8use anyhow::{Context, Result, anyhow};
9use async_trait::async_trait;
10use bytes::Bytes;
11use folk_api::Executor;
12use tokio::sync::{Semaphore, mpsc, oneshot, watch};
13use tokio::task::JoinHandle;
14use tracing::{debug, error, info, warn};
15
16use crate::config::WorkersConfig;
17use crate::runtime::{Runtime, WorkerHandle};
18use crate::worker_slot::SlotInfo;
19
20/// Pool errors. Plugins typically translate these into their own domain errors.
21#[derive(Debug, thiserror::Error)]
22pub enum WorkError {
23    #[error("all workers busy")]
24    Busy,
25    #[error("worker died during request")]
26    WorkerDied,
27    #[error("execution timed out")]
28    Timeout,
29    #[error("worker returned application error: {message}")]
30    Application { code: i32, message: String },
31    #[error("internal error: {0}")]
32    Internal(String),
33}
34
35/// One dispatch request: id, method name, payload + reply channel.
36struct DispatchRequest {
37    request_id: Arc<str>,
38    method: String,
39    payload: serde_json::Value,
40    reply: oneshot::Sender<Result<serde_json::Value>>,
41}
42
43/// Worker pool — the dispatch surface.
44pub struct WorkerPool {
45    request_tx: mpsc::Sender<DispatchRequest>,
46    semaphore: Arc<Semaphore>,
47    runtime: Arc<dyn Runtime>,
48    /// Monotonic reload generation. Bumped by `trigger_reload`; observed by
49    /// slot supervisors to recycle their workers after the current request.
50    reload_tx: watch::Sender<u64>,
51    _pool_task: JoinHandle<()>,
52}
53
54impl WorkerPool {
55    /// Construct a pool with `config.count` workers spawned via `runtime`.
56    ///
57    /// Returns once the pool task is started. Workers boot asynchronously
58    /// in the background.
59    pub fn new(runtime: Arc<dyn Runtime>, config: WorkersConfig) -> Result<Arc<Self>> {
60        let semaphore = Arc::new(Semaphore::new(config.count));
61        let (request_tx, request_rx) = mpsc::channel::<DispatchRequest>(1024);
62        let (reload_tx, reload_rx) = watch::channel(0u64);
63
64        let pool_task = tokio::spawn(pool_main(
65            runtime.clone(),
66            config,
67            request_rx,
68            semaphore.clone(),
69            reload_rx,
70        ));
71
72        Ok(Arc::new(Self {
73            request_tx,
74            semaphore,
75            runtime,
76            reload_tx,
77            _pool_task: pool_task,
78        }))
79    }
80
81    /// Trigger a hot reload: invalidate compiled-code caches, then signal all
82    /// recyclable workers to restart after their current request completes.
83    ///
84    /// Non-recyclable workers (the main PHP thread) keep running — see the
85    /// dev-mode docs for the implications.
86    pub async fn trigger_reload(&self) {
87        if let Err(e) = self.runtime.reload().await {
88            warn!(error = %e, "reload: cache invalidation failed; recycling anyway");
89        }
90        self.reload_tx.send_modify(|g| *g += 1);
91        let generation = *self.reload_tx.borrow();
92        info!(generation, "hot reload triggered; recycling workers");
93    }
94
95    /// Dispatch a Value-based request through the pool.
96    ///
97    /// Returns the response together with the `request_id` (a UUID v7) generated
98    /// for this request — the same id exposed to PHP via `folk_request_id()`.
99    async fn dispatch_value(
100        &self,
101        method: &str,
102        payload: serde_json::Value,
103    ) -> Result<(serde_json::Value, Arc<str>)> {
104        let permit = self
105            .semaphore
106            .clone()
107            .acquire_owned()
108            .await
109            .context("pool semaphore closed")?;
110
111        // UUID v7: time-ordered (sortable by creation time) and globally unique
112        // across instances and restarts — usable as a single correlation key in
113        // aggregated logs.
114        let request_id: Arc<str> = Arc::from(uuid::Uuid::now_v7().hyphenated().to_string());
115        let (reply_tx, reply_rx) = oneshot::channel();
116        self.request_tx
117            .send(DispatchRequest {
118                request_id: request_id.clone(),
119                method: method.to_string(),
120                payload,
121                reply: reply_tx,
122            })
123            .await
124            .map_err(|_| anyhow!("pool task gone"))?;
125
126        let result = reply_rx
127            .await
128            .map_err(|_| anyhow!("pool dropped reply channel"))?;
129
130        drop(permit);
131        result.map(|value| (value, request_id))
132    }
133}
134
135#[async_trait]
136impl Executor for WorkerPool {
137    async fn execute_method(&self, method: &str, payload: Bytes) -> Result<Bytes> {
138        debug!(
139            method,
140            payload_len = payload.len(),
141            "pool: execute_method called (bytes path)"
142        );
143        // Legacy path: parse JSON bytes → Value → dispatch → Value → serialize
144        let value: serde_json::Value =
145            serde_json::from_slice(&payload).context("pool: failed to parse payload as JSON")?;
146        let (result, _id) = self.dispatch_value(method, value).await?;
147        let bytes = serde_json::to_vec(&result).context("pool: failed to serialize response")?;
148        Ok(Bytes::from(bytes))
149    }
150
151    async fn execute_value(
152        &self,
153        method: &str,
154        payload: serde_json::Value,
155    ) -> Result<serde_json::Value> {
156        debug!(method, "pool: execute_value called (zero-copy path)");
157        let (value, _id) = self.dispatch_value(method, payload).await?;
158        Ok(value)
159    }
160
161    async fn execute_value_traced(
162        &self,
163        method: &str,
164        payload: serde_json::Value,
165    ) -> Result<(serde_json::Value, Arc<str>)> {
166        debug!(method, "pool: execute_value_traced called");
167        self.dispatch_value(method, payload).await
168    }
169}
170
171// ---- Pool task ---------------------------------------------------------------
172
173async fn pool_main(
174    runtime: Arc<dyn Runtime>,
175    config: WorkersConfig,
176    mut request_rx: mpsc::Receiver<DispatchRequest>,
177    _semaphore: Arc<Semaphore>,
178    reload_rx: watch::Receiver<u64>,
179) {
180    let mut slot_inboxes: Vec<mpsc::Sender<DispatchRequest>> = Vec::with_capacity(config.count);
181    let mut slot_supervisors: Vec<JoinHandle<()>> = Vec::with_capacity(config.count);
182
183    for slot_id in 0..config.count {
184        let (slot_tx, slot_rx) = mpsc::channel::<DispatchRequest>(8);
185        slot_inboxes.push(slot_tx);
186        let runtime_clone = runtime.clone();
187        let cfg_clone = config.clone();
188        let reload_clone = reload_rx.clone();
189        let supervisor = tokio::spawn(slot_supervisor(
190            slot_id,
191            runtime_clone,
192            cfg_clone,
193            slot_rx,
194            reload_clone,
195        ));
196        slot_supervisors.push(supervisor);
197    }
198
199    // Round-robin dispatch.
200    let mut next: usize = 0;
201    while let Some(req) = request_rx.recv().await {
202        let chosen = next % slot_inboxes.len();
203        next = next.wrapping_add(1);
204
205        if slot_inboxes[chosen].send(req).await.is_err() {
206            warn!(slot_id = chosen, "slot inbox closed; failed to dispatch");
207        }
208    }
209
210    info!("pool main loop exiting; awaiting supervisors");
211    for handle in slot_supervisors {
212        let _ = handle.await;
213    }
214}
215
216// ---- Slot supervisor ---------------------------------------------------------
217
218async fn slot_supervisor(
219    slot_id: usize,
220    runtime: Arc<dyn Runtime>,
221    config: WorkersConfig,
222    mut inbox: mpsc::Receiver<DispatchRequest>,
223    mut reload_rx: watch::Receiver<u64>,
224) {
225    let mut slot = SlotInfo::new();
226    let mut worker: Option<Box<dyn WorkerHandle>> = None;
227    // Reload generation this worker was booted at. When the pool's generation
228    // advances past this, the worker must be recycled to pick up new code.
229    let mut boot_generation: u64 = *reload_rx.borrow();
230
231    loop {
232        // Spawn a worker if we don't have one.
233        if worker.is_none() {
234            boot_generation = *reload_rx.borrow();
235            match boot_worker(&runtime, &config, &mut slot).await {
236                Ok(w) => worker = Some(w),
237                Err(e) => {
238                    error!(slot_id, error = ?e, "failed to boot worker, will retry");
239                    tokio::time::sleep(Duration::from_secs(1)).await;
240                    continue;
241                },
242            }
243        }
244
245        let recyclable = worker.as_ref().is_some_and(|w| w.is_recyclable());
246
247        // Wait for a request, a reload signal, or shutdown.
248        let req = tokio::select! {
249            biased;
250            // React to a reload while idle so workers restart promptly even
251            // without traffic. Skip for non-recyclable workers (main thread).
252            res = reload_rx.changed(), if recyclable => {
253                if res.is_err() {
254                    // Pool dropped the sender — treat as shutdown.
255                    info!(slot_id, "supervisor shutting down (reload channel closed)");
256                    if let Some(mut w) = worker.take() {
257                        let _ = w.terminate().await;
258                    }
259                    return;
260                }
261                if *reload_rx.borrow() > boot_generation {
262                    info!(slot_id, "recycling idle worker for hot reload");
263                    if let Some(mut w) = worker.take() {
264                        let _ = w.terminate().await;
265                    }
266                    slot = SlotInfo::new();
267                }
268                continue;
269            },
270            maybe_req = inbox.recv() => {
271                let Some(req) = maybe_req else {
272                    info!(slot_id, "supervisor shutting down (inbox closed)");
273                    if let Some(mut w) = worker.take() {
274                        if let Err(e) = w.terminate().await {
275                            warn!(slot_id, error = ?e, "terminate error during shutdown");
276                        }
277                    }
278                    return;
279                };
280                req
281            },
282        };
283
284        // Dispatch.
285        let Some(w) = worker.as_mut() else {
286            unreachable!()
287        };
288        slot.mark_busy();
289        let result = dispatch_one(
290            w.as_mut(),
291            &req.method,
292            req.payload,
293            req.request_id.clone(),
294            config.exec_timeout,
295        )
296        .await;
297        slot.mark_idle();
298
299        // Send reply.
300        let _ = req.reply.send(result.map_err(anyhow::Error::from));
301
302        // Recycle on reload (after the request completes) or per the lifecycle
303        // policies (max_jobs / ttl).
304        let reload_pending = *reload_rx.borrow() > boot_generation;
305        if reload_pending || slot.should_recycle(&config) {
306            if let Some(ref w) = worker {
307                if !w.is_recyclable() {
308                    debug!(slot_id, "skipping recycle for non-recyclable worker");
309                    continue;
310                }
311            }
312            let reason = if reload_pending {
313                "hot reload"
314            } else {
315                "lifecycle"
316            };
317            info!(
318                slot_id,
319                jobs = slot.jobs_handled,
320                reason,
321                "recycling worker"
322            );
323            if let Some(mut w) = worker.take() {
324                let _ = w.terminate().await;
325            }
326            slot = SlotInfo::new();
327        }
328    }
329}
330
331async fn boot_worker(
332    runtime: &Arc<dyn Runtime>,
333    config: &WorkersConfig,
334    slot: &mut SlotInfo,
335) -> Result<Box<dyn WorkerHandle>> {
336    debug!("boot_worker: spawning");
337    let mut handle = runtime.spawn().await.context("spawn")?;
338    debug!(id = handle.id(), "boot_worker: waiting for ready");
339
340    let timeout = tokio::time::timeout(config.boot_timeout, handle.ready());
341    match timeout.await {
342        Ok(Ok(())) => {
343            let id = handle.id();
344            slot.mark_ready(id);
345            debug!(id, "worker ready");
346            Ok(handle)
347        },
348        Ok(Err(e)) => {
349            let _ = handle.terminate().await;
350            Err(e).context("worker ready() failed during boot")
351        },
352        Err(_) => {
353            let _ = handle.terminate().await;
354            anyhow::bail!("worker boot timed out after {:?}", config.boot_timeout)
355        },
356    }
357}
358
359async fn dispatch_one(
360    worker: &mut dyn WorkerHandle,
361    method: &str,
362    payload: serde_json::Value,
363    request_id: Arc<str>,
364    exec_timeout: Duration,
365) -> Result<serde_json::Value, WorkError> {
366    let recv = tokio::time::timeout(exec_timeout, worker.execute(method, payload, request_id));
367    match recv.await {
368        Ok(Ok(result)) => Ok(result),
369        Ok(Err(e)) => Err(WorkError::Internal(e.to_string())),
370        Err(_) => Err(WorkError::Timeout),
371    }
372}