folk_core/runtime.rs
1//! Abstraction over how PHP workers are spawned.
2//!
3//! `WorkerPool` does not know what a PHP process is. It asks the
4//! `Runtime` to spawn a worker; the runtime returns a `WorkerHandle` which
5//! gives the pool a way to execute requests and to terminate the worker.
6//!
7//! In phase 23 (extension mode), the runtime spawns OS threads that run PHP
8//! inside the same process. Communication is via channels (zero IPC).
9
10use anyhow::Result;
11use async_trait::async_trait;
12
13/// A handle to a spawned worker.
14///
15/// The pool dispatches requests via `execute` and controls lifecycle via
16/// `ready` and `terminate`.
17#[async_trait]
18pub trait WorkerHandle: Send + 'static {
19 /// Worker identifier (thread ID, PID, or synthetic).
20 fn id(&self) -> u32;
21
22 /// Wait for the worker to signal readiness.
23 /// Returns once the worker has booted and is ready to accept requests.
24 async fn ready(&mut self) -> Result<()>;
25
26 /// Execute a single request: send structured data, receive result.
27 async fn execute(
28 &mut self,
29 method: &str,
30 payload: serde_json::Value,
31 ) -> Result<serde_json::Value>;
32
33 /// Terminate the worker. Implementations should signal shutdown and
34 /// wait for the worker to exit.
35 async fn terminate(&mut self) -> Result<()>;
36
37 /// Whether this worker can be recycled (terminated and respawned).
38 /// Returns `false` for the main thread worker which cannot be restarted.
39 fn is_recyclable(&self) -> bool {
40 true
41 }
42}
43
44/// Spawns workers per a runtime-specific strategy.
45#[async_trait]
46pub trait Runtime: Send + Sync + 'static {
47 /// Spawn a single worker and return a handle.
48 ///
49 /// The caller must call `ready()` before dispatching requests.
50 async fn spawn(&self) -> Result<Box<dyn WorkerHandle>>;
51}
52
53// --- MockRuntime: in-memory runtime for tests ---
54
55type MockResponder =
56 std::sync::Arc<dyn Fn(&str, &serde_json::Value) -> Result<serde_json::Value> + Send + Sync>;
57
58/// In-memory runtime used in tests. Each spawned worker echoes requests back.
59pub struct MockRuntime {
60 responder: MockResponder,
61 next_id: std::sync::atomic::AtomicU32,
62}
63
64impl MockRuntime {
65 /// Create a mock runtime that echoes the payload back as the result.
66 pub fn echo() -> Self {
67 Self {
68 responder: std::sync::Arc::new(|_method, payload| Ok(payload.clone())),
69 next_id: std::sync::atomic::AtomicU32::new(10000),
70 }
71 }
72}
73
74#[async_trait]
75impl Runtime for MockRuntime {
76 async fn spawn(&self) -> Result<Box<dyn WorkerHandle>> {
77 let id = self
78 .next_id
79 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
80 Ok(Box::new(MockWorker {
81 id,
82 responder: self.responder.clone(),
83 terminated: false,
84 }))
85 }
86}
87
88/// In-memory worker used by `MockRuntime`.
89pub struct MockWorker {
90 id: u32,
91 responder: MockResponder,
92 terminated: bool,
93}
94
95#[async_trait]
96impl WorkerHandle for MockWorker {
97 fn id(&self) -> u32 {
98 self.id
99 }
100
101 async fn ready(&mut self) -> Result<()> {
102 Ok(())
103 }
104
105 async fn execute(
106 &mut self,
107 method: &str,
108 payload: serde_json::Value,
109 ) -> Result<serde_json::Value> {
110 if self.terminated {
111 anyhow::bail!("worker terminated");
112 }
113 (self.responder)(method, &payload)
114 }
115
116 async fn terminate(&mut self) -> Result<()> {
117 self.terminated = true;
118 Ok(())
119 }
120}