bext-php 0.2.0

Embedded PHP runtime for bext — custom SAPI linking libphp via Rust FFI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! PHP Worker Pool — dedicated OS threads for PHP script execution.
//!
//! Supports two modes:
//! 1. Classic mode: one `php_execute_script()` per HTTP request
//! 2. Worker mode:  boot a worker script once, dispatch requests to its
//!    `bext_handle_request()` loop (eliminates framework bootstrap)
//!
//! Architecture mirrors `bext-core::jsc_ssr::pool::JscRenderPool`.

use super::context::RequestCtx;
use super::ffi;
use std::cell::RefCell;
use std::ffi::CString;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

// ─── Thread-local worker state (for worker mode) ─────────────────────────

/// Opaque pointer to a heap-allocated `RequestCtx`, safe to send through channels.
///
/// # Safety
///
/// Ownership is transferred linearly: the producer creates a `Box<RequestCtx>`,
/// converts it to a raw pointer, wraps it in `SendPtr`, and sends it through a
/// bounded channel.  The consumer receives exclusive ownership and must either
/// convert it back to `Box<RequestCtx>` via `Box::from_raw` or ensure the C
/// side doesn't access it concurrently.  The pointer is never aliased — only
/// one thread holds it at any time.
pub(crate) struct SendPtr(pub(crate) *mut u8);
unsafe impl Send for SendPtr {}

/// Per-thread state used by the FFI callbacks in worker mode.
pub(crate) struct WorkerThreadState {
    /// Receives request context pointers from the pool dispatcher.
    pub(crate) request_rx: flume::Receiver<SendPtr>,
    /// Signals that the current request is complete.
    pub(crate) done_tx: flume::Sender<()>,
}

thread_local! {
    pub static WORKER_THREAD_STATE: RefCell<Option<WorkerThreadState>> = const { RefCell::new(None) };
}

// ─── Request / Response types ────────────────────────────────────────────

/// A PHP execution request dispatched to a worker.
pub enum PhpRequest {
    /// Execute a PHP script and return the output.
    Execute(Box<PhpExecuteRequest>),
    Shutdown,
}

/// Inner data for a PHP execute request (boxed to reduce enum size).
pub struct PhpExecuteRequest {
    pub script_path: String,
    pub method: String,
    pub uri: String,
    pub query_string: String,
    pub content_type: Option<String>,
    pub body: Vec<u8>,
    pub cookies: Option<String>,
    pub headers: Vec<(String, String)>,
    pub remote_addr: Option<String>,
    pub server_name: Option<String>,
    pub server_port: u16,
    pub https: bool,
    pub reply: flume::Sender<PhpResponse>,
}

/// Response from a PHP worker.
#[derive(Debug, Clone)]
pub enum PhpResponse {
    Ok {
        status: u16,
        body: Vec<u8>,
        headers: Vec<(String, String)>,
        exec_time_us: u64,
    },
    Error(String),
}

/// Pool-level statistics.
#[derive(Debug, Clone, Default)]
pub struct PhpPoolStats {
    pub workers: u32,
    pub active: u32,
    pub total_requests: u64,
    pub total_errors: u64,
    pub avg_exec_time_us: u64,
}

// ─── Execution mode ──────────────────────────────────────────────────────

/// How PHP scripts are executed.
#[derive(Debug, Clone)]
pub enum PhpMode {
    /// One `php_execute_script()` per request. Simple, compatible with everything.
    Classic,
    /// Boot a worker script once; dispatch requests to its `bext_handle_request()` loop.
    /// Eliminates per-request framework bootstrap (~3ms for Laravel).
    Worker {
        /// Path to the worker PHP script.
        script: String,
    },
}

// ─── Pool ────────────────────────────────────────────────────────────────

pub struct PhpPool {
    sender: flume::Sender<PhpRequest>,
    workers: Vec<std::thread::JoinHandle<()>>,
    active: Arc<AtomicU32>,
    total_requests: Arc<AtomicU64>,
    total_errors: Arc<AtomicU64>,
    total_exec_time_us: Arc<AtomicU64>,
    worker_count: u32,
    mode: PhpMode,
}

impl PhpPool {
    /// Create a classic-mode pool.
    pub fn new(worker_count: usize) -> Result<Self, String> {
        Self::create(worker_count, 0, PhpMode::Classic, None)
    }

    /// Create a classic-mode pool with per-worker request lifecycle limit.
    pub fn with_max_requests(worker_count: usize, max_requests: u64) -> Result<Self, String> {
        Self::create(worker_count, max_requests, PhpMode::Classic, None)
    }

    /// Create a worker-mode pool. The worker script boots the framework
    /// once and calls `bext_handle_request($callback)` in a loop.
    pub fn worker(
        worker_count: usize,
        worker_script: String,
        max_requests: u64,
    ) -> Result<Self, String> {
        Self::create(
            worker_count,
            max_requests,
            PhpMode::Worker {
                script: worker_script.clone(),
            },
            Some(worker_script),
        )
    }

    fn create(
        worker_count: usize,
        max_requests: u64,
        mode: PhpMode,
        worker_script: Option<String>,
    ) -> Result<Self, String> {
        // Queue depth = 128 × worker count.  Requests beyond this will block
        // the caller (backpressure), matching PHP-FPM's behavior under load.
        let (sender, receiver) = flume::bounded::<PhpRequest>(worker_count.max(1) * 128);
        let active = Arc::new(AtomicU32::new(0));
        let total_requests = Arc::new(AtomicU64::new(0));
        let total_errors = Arc::new(AtomicU64::new(0));
        let total_exec_time_us = Arc::new(AtomicU64::new(0));

        let mut workers = Vec::with_capacity(worker_count);

        for i in 0..worker_count {
            let rx = receiver.clone();
            let active = Arc::clone(&active);
            let total_requests = Arc::clone(&total_requests);
            let total_errors = Arc::clone(&total_errors);
            let total_exec_time_us = Arc::clone(&total_exec_time_us);
            let ws = worker_script.clone();

            let handle = std::thread::Builder::new()
                .name(format!("bext-php-{}", i))
                // PHP 8.4's stack checker (zend.max_allowed_stack_size) auto-detects
                // from getrlimit which reports the MAIN thread's limit, not ours.
                // Use 16MB to ensure plenty of room for PHP's compiler + JIT.
                .stack_size(16 * 1024 * 1024)
                .spawn(move || {
                    // Wrap in catch_unwind for crash recovery
                    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        if let Some(ref script) = ws {
                            worker_mode_loop(
                                i,
                                rx,
                                active,
                                total_requests,
                                total_errors,
                                total_exec_time_us,
                                script,
                                max_requests,
                            );
                        } else {
                            classic_mode_loop(
                                i,
                                rx,
                                active,
                                total_requests,
                                total_errors,
                                total_exec_time_us,
                                max_requests,
                            );
                        }
                    }));
                    if let Err(e) = result {
                        let msg = if let Some(s) = e.downcast_ref::<String>() {
                            s.clone()
                        } else if let Some(s) = e.downcast_ref::<&str>() {
                            s.to_string()
                        } else {
                            "unknown panic".to_string()
                        };
                        tracing::error!(worker = i, error = %msg, "PHP worker panicked");
                    }
                })
                .map_err(|e| format!("Failed to spawn PHP worker {}: {}", i, e))?;

            workers.push(handle);
        }

        Ok(Self {
            sender,
            workers,
            active,
            total_requests,
            total_errors,
            total_exec_time_us,
            worker_count: worker_count as u32,
            mode,
        })
    }

    /// Execute a PHP request. Blocks until a worker completes.
    #[allow(clippy::too_many_arguments)]
    pub fn execute(
        &self,
        script_path: String,
        method: String,
        uri: String,
        query_string: String,
        content_type: Option<String>,
        body: Vec<u8>,
        cookies: Option<String>,
        headers: Vec<(String, String)>,
        remote_addr: Option<String>,
        server_name: Option<String>,
        server_port: u16,
        https: bool,
    ) -> Result<PhpResponse, String> {
        let (tx, rx) = flume::bounded(1);
        self.sender
            .send_timeout(
                PhpRequest::Execute(Box::new(PhpExecuteRequest {
                    script_path,
                    method,
                    uri,
                    query_string,
                    content_type,
                    body,
                    cookies,
                    headers,
                    remote_addr,
                    server_name,
                    server_port,
                    https,
                    reply: tx,
                })),
                Duration::from_secs(30),
            )
            .map_err(|_| "PHP pool queue timeout (30s)".to_string())?;
        rx.recv_timeout(Duration::from_secs(60))
            .map_err(|_| "PHP worker timeout (60s)".to_string())
    }

    pub fn healthy_workers(&self) -> u32 {
        self.workers.iter().filter(|h| !h.is_finished()).count() as u32
    }

    pub fn stats(&self) -> PhpPoolStats {
        let total = self.total_requests.load(Ordering::Relaxed);
        PhpPoolStats {
            workers: self.worker_count,
            active: self.active.load(Ordering::Relaxed),
            total_requests: total,
            total_errors: self.total_errors.load(Ordering::Relaxed),
            avg_exec_time_us: if total > 0 {
                self.total_exec_time_us.load(Ordering::Relaxed) / total
            } else {
                0
            },
        }
    }

    pub fn mode(&self) -> &PhpMode {
        &self.mode
    }

    pub fn shutdown(self) {
        for _ in &self.workers {
            let _ = self.sender.send(PhpRequest::Shutdown);
        }
        for handle in self.workers {
            let _ = handle.join();
        }
    }
}

const WORKER_RECV_TIMEOUT: Duration = Duration::from_secs(30);

// ─── Classic mode worker loop ────────────────────────────────────────────

fn classic_mode_loop(
    worker_id: usize,
    rx: flume::Receiver<PhpRequest>,
    active: Arc<AtomicU32>,
    total_requests: Arc<AtomicU64>,
    total_errors: Arc<AtomicU64>,
    total_exec_time_us: Arc<AtomicU64>,
    max_requests: u64,
) {
    tracing::info!(worker = worker_id, mode = "classic", "PHP worker started");
    let mut local_count: u64 = 0;

    loop {
        if max_requests > 0 && local_count >= max_requests {
            tracing::info!(
                worker = worker_id,
                requests = local_count,
                "PHP worker rotating"
            );
            break;
        }

        let request = match rx.recv_timeout(WORKER_RECV_TIMEOUT) {
            Ok(req) => req,
            Err(flume::RecvTimeoutError::Timeout) => continue,
            Err(flume::RecvTimeoutError::Disconnected) => break,
        };

        match request {
            PhpRequest::Shutdown => break,
            PhpRequest::Execute(req) => {
                active.fetch_add(1, Ordering::Relaxed);
                total_requests.fetch_add(1, Ordering::Relaxed);
                local_count += 1;

                let response = execute_classic(
                    &req.script_path,
                    &req.method,
                    &req.uri,
                    &req.query_string,
                    req.content_type.as_deref(),
                    req.body,
                    req.cookies.as_deref(),
                    req.headers,
                    req.remote_addr.as_deref(),
                    req.server_name.as_deref(),
                    req.server_port,
                    req.https,
                );

                match &response {
                    PhpResponse::Ok { exec_time_us, .. } => {
                        total_exec_time_us.fetch_add(*exec_time_us, Ordering::Relaxed);
                    }
                    PhpResponse::Error(_) => {
                        total_errors.fetch_add(1, Ordering::Relaxed);
                    }
                }

                let _ = req.reply.send(response);
                active.fetch_sub(1, Ordering::Relaxed);
            }
        }
    }

    tracing::info!(worker = worker_id, "PHP worker stopped");
}

// ─── Worker mode loop ────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn worker_mode_loop(
    worker_id: usize,
    rx: flume::Receiver<PhpRequest>,
    active: Arc<AtomicU32>,
    total_requests: Arc<AtomicU64>,
    total_errors: Arc<AtomicU64>,
    total_exec_time_us: Arc<AtomicU64>,
    worker_script: &str,
    _max_requests: u64,
) {
    tracing::info!(worker = worker_id, mode = "worker", script = %worker_script, "PHP worker started");

    // Create channels for the C↔Rust worker protocol:
    // - request_tx/rx: pool sends request ctx pointers to the C bext_handle_request()
    // - done_tx/rx: C signals request completion back to pool
    let (request_tx, request_rx) = flume::bounded::<SendPtr>(1);
    let (done_tx, done_rx) = flume::bounded::<()>(1);

    // Install thread-local state for FFI callbacks
    WORKER_THREAD_STATE.with(|state| {
        *state.borrow_mut() = Some(WorkerThreadState {
            request_rx,
            done_tx,
        });
    });

    // Boot the worker script in a background thread.
    // The script runs `while (bext_handle_request($cb)) { ... }` which blocks
    // in bext_sapi_worker_wait_request() until we send a request.
    let c_script = match CString::new(worker_script) {
        Ok(s) => s,
        Err(e) => {
            tracing::error!(worker = worker_id, error = %e, "Invalid worker script path");
            return;
        }
    };

    // Create a minimal initial context for the boot phase
    let mut boot_ctx = RequestCtx::new(Vec::new(), None, Vec::new(), None, None, 80, false);

    // Launch PHP execution on THIS thread (it will block in the bext_handle_request loop)
    // We use a separate thread to dispatch requests to it.
    let dispatcher_rx = rx;
    let dispatcher_active = active;
    let dispatcher_total_requests = total_requests;
    let dispatcher_total_errors = total_errors;
    let dispatcher_total_exec_time_us = total_exec_time_us;

    // Spawn a dispatcher thread that receives PhpRequests and feeds them to the worker
    let request_tx_clone = request_tx.clone();
    let dispatcher = std::thread::Builder::new()
        .name(format!("bext-php-{}-dispatch", worker_id))
        .spawn(move || {
            loop {
                // Drain any stale completion signal from a previous timed-out request.
                // After a timeout, the PHP worker may still complete and send on done_tx,
                // leaving a stale signal that would cause the next iteration to reclaim
                // the wrong ctx_ptr (use-after-free).
                while done_rx.try_recv().is_ok() {}

                let request = match dispatcher_rx.recv_timeout(WORKER_RECV_TIMEOUT) {
                    Ok(req) => req,
                    Err(flume::RecvTimeoutError::Timeout) => continue,
                    Err(flume::RecvTimeoutError::Disconnected) => break,
                };

                match request {
                    PhpRequest::Shutdown => {
                        // Signal the worker to exit by dropping the request channel
                        drop(request_tx_clone);
                        break;
                    }
                    PhpRequest::Execute(req) => {
                        dispatcher_active.fetch_add(1, Ordering::Relaxed);
                        dispatcher_total_requests.fetch_add(1, Ordering::Relaxed);
                        let start = Instant::now();

                        // Build a request context and send its pointer to the worker
                        let mut req_ctx = Box::new(RequestCtx::new(
                            req.body,
                            req.cookies.as_deref(),
                            req.headers,
                            req.remote_addr.as_deref(),
                            req.server_name.as_deref(),
                            req.server_port,
                            req.https,
                        ));
                        req_ctx.set_request_info(
                            &req.method,
                            &req.uri,
                            &req.query_string,
                            req.content_type.as_deref(),
                        );

                        let ctx_ptr = Box::into_raw(req_ctx) as *mut u8;

                        // Send to the PHP worker (blocks until bext_handle_request picks it up)
                        if request_tx_clone.send(SendPtr(ctx_ptr)).is_err() {
                            // Worker died — convert back to Box to drop
                            let _ = unsafe { Box::from_raw(ctx_ptr as *mut RequestCtx) };
                            let _ = req.reply.send(PhpResponse::Error("Worker died".into()));
                            dispatcher_active.fetch_sub(1, Ordering::Relaxed);
                            dispatcher_total_errors.fetch_add(1, Ordering::Relaxed);
                            break;
                        }

                        // Wait for the worker to finish processing
                        match done_rx.recv_timeout(Duration::from_secs(60)) {
                            Ok(()) => {
                                // Reclaim the context and extract the response
                                let req_ctx = unsafe { Box::from_raw(ctx_ptr as *mut RequestCtx) };
                                let exec_time_us = start.elapsed().as_micros() as u64;
                                dispatcher_total_exec_time_us
                                    .fetch_add(exec_time_us, Ordering::Relaxed);

                                let _ = req.reply.send(PhpResponse::Ok {
                                    status: req_ctx.status_code,
                                    body: req_ctx.output_buf,
                                    headers: req_ctx.response_headers,
                                    exec_time_us,
                                });
                            }
                            Err(_) => {
                                // On timeout, we intentionally do not free ctx_ptr to avoid double-free with the PHP worker thread. The worker will clean up when it completes.
                                let _ = req
                                    .reply
                                    .send(PhpResponse::Error("PHP worker timeout".into()));
                                dispatcher_total_errors.fetch_add(1, Ordering::Relaxed);
                            }
                        }

                        dispatcher_active.fetch_sub(1, Ordering::Relaxed);
                    }
                }
            }
        });

    let dispatcher = match dispatcher {
        Ok(handle) => Some(handle),
        Err(e) => {
            tracing::error!(worker = worker_id, error = %e, "Failed to spawn dispatcher thread");
            return;
        }
    };

    // Run the PHP worker script on this thread.
    // It will loop in bext_handle_request(), blocking on request_rx.
    let exit_status = unsafe {
        ffi::bext_php_execute_worker(
            &mut boot_ctx as *mut RequestCtx as *mut ffi::BextRequestCtx,
            c_script.as_ptr(),
        )
    };

    tracing::info!(worker = worker_id, exit_status, "PHP worker script exited");

    // Clean up: drop request_tx to unblock the dispatcher, then join it
    drop(request_tx);
    if let Some(d) = dispatcher {
        let _ = d.join();
    }

    // Clean up thread-local state
    WORKER_THREAD_STATE.with(|state| {
        *state.borrow_mut() = None;
    });
}

// ─── Classic mode execution ──────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn execute_classic(
    script_path: &str,
    method: &str,
    uri: &str,
    query_string: &str,
    content_type: Option<&str>,
    body: Vec<u8>,
    cookies: Option<&str>,
    headers: Vec<(String, String)>,
    remote_addr: Option<&str>,
    server_name: Option<&str>,
    server_port: u16,
    https: bool,
) -> PhpResponse {
    let c_script = match CString::new(script_path) {
        Ok(s) => s,
        Err(e) => return PhpResponse::Error(format!("Invalid script path: {}", e)),
    };
    let c_method = match CString::new(method) {
        Ok(s) => s,
        Err(e) => return PhpResponse::Error(format!("Invalid method: {}", e)),
    };
    let c_uri = match CString::new(uri) {
        Ok(s) => s,
        Err(e) => return PhpResponse::Error(format!("Invalid URI: {}", e)),
    };
    let c_query = match CString::new(query_string) {
        Ok(s) => s,
        Err(e) => return PhpResponse::Error(format!("Invalid query string: {}", e)),
    };
    let c_content_type = content_type.and_then(|ct| CString::new(ct).ok());
    let content_length = body.len() as i64;

    let mut req_ctx = RequestCtx::new(
        body,
        cookies,
        headers,
        remote_addr,
        server_name,
        server_port,
        https,
    );

    let start = Instant::now();

    let status = unsafe {
        ffi::bext_php_execute_script(
            &mut req_ctx as *mut RequestCtx as *mut ffi::BextRequestCtx,
            c_script.as_ptr(),
            c_method.as_ptr(),
            c_uri.as_ptr(),
            c_query.as_ptr(),
            c_content_type
                .as_ref()
                .map(|c| c.as_ptr())
                .unwrap_or(std::ptr::null()),
            content_length,
        )
    };

    let exec_time_us = start.elapsed().as_micros() as u64;

    if status < 0 {
        return PhpResponse::Error("PHP execution failed (request startup error)".into());
    }

    PhpResponse::Ok {
        status: status as u16,
        body: req_ctx.output_buf,
        headers: req_ctx.response_headers,
        exec_time_us,
    }
}