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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! `bext-php` — embedded PHP runtime for the bext server.
//!
//! Provides in-process PHP execution via a custom SAPI that bridges PHP's
//! I/O to Rust.  Architecture follows the same pattern as FrankenPHP
//! (custom SAPI + worker threads) but uses Rust FFI instead of Go/CGo.
//!
//! ## How it works
//!
//! 1. `build.rs` compiles `sapi/bext_php_sapi.c` and links against `libphp`
//!    (PHP compiled with `--enable-embed --enable-zts`).
//!
//! 2. The C SAPI implements PHP's `sapi_module_struct` callbacks, forwarding
//!    all I/O (output writes, POST reads, cookies, headers) to Rust via
//!    `extern "C"` functions defined in `ffi.rs`.
//!
//! 3. `PhpPool` manages N OS threads, each registered with PHP's TSRM.
//!    Requests are dispatched via bounded channels (same as `JscRenderPool`).
//!
//! 4. `PhpState` is the top-level handle added to bext-server's `AppState`.
//!    It manages initialization, pool lifecycle, and graceful shutdown.
//!
//! ## Requirements
//!
//! - PHP 8.2+ compiled with `--enable-embed --enable-zts`
//! - `php-config` in PATH (or set `BEXT_PHP_CONFIG`)
//! - Linux (primary target) or macOS
//!
//! ## Configuration
//!
//! ```toml
//! [php]
//! enabled = true
//! document_root = "./public"
//! workers = 4
//!
//! [php.ini]
//! memory_limit = "256M"
//! opcache.enable = "1"
//! opcache.jit = "1255"
//! ```

pub mod bridge;
pub mod config;
pub mod context;
mod ffi;
pub mod pool;

use std::ffi::CString;
use std::sync::Arc;

pub use config::PhpConfig;
pub use pool::{PhpPool, PhpPoolStats, PhpResponse};

// ---------------------------------------------------------------------------
// PhpState — central handle for the PHP runtime (mirrors EbpfState)
// ---------------------------------------------------------------------------

/// Central state for the embedded PHP runtime.
///
/// Manages the PHP module lifecycle and worker pool. Added to bext-server's
/// `AppState` behind `#[cfg(feature = "php")]`.
pub struct PhpState {
    pool: Option<Arc<PhpPool>>,
    config: PhpConfig,
}

impl PhpState {
    /// Initialize the PHP runtime and create the worker pool.
    ///
    /// Returns `Ok` even if PHP is disabled by config (pool will be None).
    pub fn init(config: PhpConfig) -> anyhow::Result<Self> {
        if !config.enabled {
            tracing::info!("PHP runtime disabled by configuration");
            return Ok(Self { pool: None, config });
        }

        // Verify document root exists
        let doc_root = std::path::Path::new(&config.document_root);
        if !doc_root.is_dir() {
            tracing::warn!(
                path = %config.document_root,
                "PHP document_root does not exist; PHP requests will return 404"
            );
        }

        // Build INI entries
        let ini_str = config.ini_entries_string();
        let c_ini =
            CString::new(ini_str).map_err(|e| anyhow::anyhow!("Invalid INI string: {}", e))?;

        // Initialize PHP module (one-time, process-wide)
        let ret = unsafe { ffi::bext_php_module_init(c_ini.as_ptr()) };
        if ret != 0 {
            return Err(anyhow::anyhow!(
                "PHP module initialization failed (bext_php_module_init returned {})",
                ret
            ));
        }

        let worker_count = config.effective_workers();
        let mode_label = if config.is_worker_mode() {
            "worker"
        } else {
            "classic"
        };
        tracing::info!(
            workers = worker_count,
            mode = mode_label,
            document_root = %config.document_root,
            "PHP runtime initialized"
        );

        // Create pool in the appropriate mode.
        // is_worker_mode() returns false on NTS PHP even if worker_script is set.
        let pool = if config.is_worker_mode() {
            let script = config.worker_script.as_ref().unwrap().clone();
            PhpPool::worker(worker_count, script, config.max_requests)
        } else {
            PhpPool::with_max_requests(worker_count, config.max_requests)
        }
        .map_err(|e| anyhow::anyhow!("Failed to create PHP pool: {}", e))?;

        Ok(Self {
            pool: Some(Arc::new(pool)),
            config,
        })
    }

    /// Whether the PHP runtime is active (enabled + initialized).
    pub fn is_active(&self) -> bool {
        self.pool.is_some()
    }

    /// Get a reference to the worker pool (if active).
    pub fn pool(&self) -> Option<&Arc<PhpPool>> {
        self.pool.as_ref()
    }

    /// Get the PHP configuration.
    pub fn config(&self) -> &PhpConfig {
        &self.config
    }

    /// Execute a PHP request through the pool.
    ///
    /// Resolves the script path from the request URI, then dispatches to a
    /// worker.  Returns `None` if PHP is not active or the path doesn't
    /// resolve to a PHP file.
    #[allow(clippy::too_many_arguments)]
    pub fn execute(
        &self,
        request_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,
    ) -> Option<PhpResponse> {
        let pool = self.pool.as_ref()?;

        // Enforce max body size
        if body.len() > self.config.max_body_bytes {
            return Some(PhpResponse::Error(format!(
                "Request body too large ({} bytes, max {})",
                body.len(),
                self.config.max_body_bytes,
            )));
        }

        // In worker mode, the worker script handles all routing internally.
        // In classic mode, resolve the request path to a filesystem script.
        let script_path = if self.config.is_worker_mode() {
            // Worker mode: send all PHP requests to the worker pool.
            // The script_path is ignored by the worker (it's already running).
            self.config.worker_script.clone().unwrap_or_default()
        } else {
            self.config.resolve_script(request_path)?
        };

        match pool.execute(
            script_path,
            method.to_string(),
            uri.to_string(),
            query_string.to_string(),
            content_type.map(|s| s.to_string()),
            body,
            cookies.map(|s| s.to_string()),
            headers,
            remote_addr.map(|s| s.to_string()),
            server_name.map(|s| s.to_string()),
            server_port,
            https,
        ) {
            Ok(resp) => Some(resp),
            Err(e) => {
                tracing::error!(path = %request_path, error = %e, "PHP execution failed");
                // Return generic error to client — full details logged server-side
                Some(PhpResponse::Error("PHP execution failed".into()))
            }
        }
    }

    /// Get pool statistics.
    pub fn stats(&self) -> PhpPoolStats {
        self.pool.as_ref().map(|p| p.stats()).unwrap_or_default()
    }

    /// Get status summary as JSON.
    pub fn status_json(&self) -> serde_json::Value {
        let stats = self.stats();
        serde_json::json!({
            "active": self.is_active(),
            "document_root": self.config.document_root,
            "workers": stats.workers,
            "workers_busy": stats.active,
            "total_requests": stats.total_requests,
            "total_errors": stats.total_errors,
            "avg_exec_time_us": stats.avg_exec_time_us,
        })
    }

    /// Get Prometheus metrics.
    pub fn prometheus_metrics(&self) -> String {
        if !self.is_active() {
            return String::new();
        }
        let stats = self.stats();
        format!(
            "# HELP bext_php_workers Number of PHP worker threads\n\
             # TYPE bext_php_workers gauge\n\
             bext_php_workers {}\n\
             # HELP bext_php_workers_active Currently busy PHP workers\n\
             # TYPE bext_php_workers_active gauge\n\
             bext_php_workers_active {}\n\
             # HELP bext_php_requests_total Total PHP requests processed\n\
             # TYPE bext_php_requests_total counter\n\
             bext_php_requests_total {}\n\
             # HELP bext_php_errors_total Total PHP execution errors\n\
             # TYPE bext_php_errors_total counter\n\
             bext_php_errors_total {}\n\
             # HELP bext_php_exec_time_avg_us Average PHP execution time (microseconds)\n\
             # TYPE bext_php_exec_time_avg_us gauge\n\
             bext_php_exec_time_avg_us {}\n",
            stats.workers,
            stats.active,
            stats.total_requests,
            stats.total_errors,
            stats.avg_exec_time_us,
        )
    }
}

impl Drop for PhpState {
    fn drop(&mut self) {
        if self.pool.is_some() {
            // Pool threads will exit when the sender drops.
            // Then shut down PHP module.
            tracing::info!("Shutting down PHP runtime");

            // Take and drop the pool to trigger worker shutdown
            if let Some(pool) = self.pool.take() {
                // If we're the last Arc holder, shutdown cleanly
                if let Ok(pool) = Arc::try_unwrap(pool) {
                    pool.shutdown();
                }
            }

            unsafe {
                ffi::bext_php_module_shutdown();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ─── PhpState (disabled mode) ────────────────────────────────────────

    #[test]
    fn disabled_config_creates_inactive_state() {
        let config = PhpConfig {
            enabled: false,
            ..PhpConfig::default()
        };
        let state = PhpState::init(config).unwrap();
        assert!(!state.is_active());
        assert!(state.pool().is_none());
    }

    #[test]
    fn stats_default_is_zero() {
        let config = PhpConfig::default();
        let state = PhpState::init(config).unwrap();
        let stats = state.stats();
        assert_eq!(stats.workers, 0);
        assert_eq!(stats.active, 0);
        assert_eq!(stats.total_requests, 0);
        assert_eq!(stats.total_errors, 0);
        assert_eq!(stats.avg_exec_time_us, 0);
    }

    #[test]
    fn status_json_disabled() {
        let config = PhpConfig::default();
        let state = PhpState::init(config).unwrap();
        let json = state.status_json();
        assert_eq!(json["active"], false);
        assert_eq!(json["workers"], 0);
        assert_eq!(json["total_requests"], 0);
    }

    #[test]
    fn prometheus_empty_when_disabled() {
        let config = PhpConfig::default();
        let state = PhpState::init(config).unwrap();
        assert!(state.prometheus_metrics().is_empty());
    }

    #[test]
    fn execute_returns_none_when_disabled() {
        let config = PhpConfig::default();
        let state = PhpState::init(config).unwrap();
        let result = state.execute(
            "/index.php",
            "GET",
            "/index.php",
            "",
            None,
            Vec::new(),
            None,
            Vec::new(),
            None,
            None,
            80,
            false,
        );
        assert!(result.is_none());
    }

    #[test]
    fn config_accessor() {
        let config = PhpConfig {
            document_root: "/custom/root".into(),
            ..PhpConfig::default()
        };
        let state = PhpState::init(config).unwrap();
        assert_eq!(state.config().document_root, "/custom/root");
        assert!(!state.config().enabled);
    }

    // ─── PhpResponse ─────────────────────────────────────────────────────

    #[test]
    fn php_response_ok_clone() {
        let resp = PhpResponse::Ok {
            status: 200,
            body: b"<h1>Hello</h1>".to_vec(),
            headers: vec![("Content-Type".into(), "text/html".into())],
            exec_time_us: 1500,
        };
        let cloned = resp.clone();
        match cloned {
            PhpResponse::Ok {
                status,
                body,
                headers,
                exec_time_us,
            } => {
                assert_eq!(status, 200);
                assert_eq!(body, b"<h1>Hello</h1>");
                assert_eq!(headers.len(), 1);
                assert_eq!(exec_time_us, 1500);
            }
            PhpResponse::Error(_) => panic!("Expected Ok"),
        }
    }

    #[test]
    fn php_response_error_clone() {
        let resp = PhpResponse::Error("timeout".into());
        let cloned = resp.clone();
        match cloned {
            PhpResponse::Error(msg) => assert_eq!(msg, "timeout"),
            PhpResponse::Ok { .. } => panic!("Expected Error"),
        }
    }

    #[test]
    fn php_response_debug() {
        let resp = PhpResponse::Ok {
            status: 404,
            body: Vec::new(),
            headers: Vec::new(),
            exec_time_us: 0,
        };
        let debug = format!("{:?}", resp);
        assert!(debug.contains("404"));
    }

    // ─── PhpPoolStats ────────────────────────────────────────────────────

    #[test]
    fn pool_stats_default() {
        let stats = pool::PhpPoolStats::default();
        assert_eq!(stats.workers, 0);
        assert_eq!(stats.active, 0);
        assert_eq!(stats.total_requests, 0);
        assert_eq!(stats.total_errors, 0);
        assert_eq!(stats.avg_exec_time_us, 0);
    }

    #[test]
    fn pool_stats_debug() {
        let stats = pool::PhpPoolStats {
            workers: 4,
            active: 2,
            total_requests: 1000,
            total_errors: 5,
            avg_exec_time_us: 250,
        };
        let debug = format!("{:?}", stats);
        assert!(debug.contains("workers: 4"));
        assert!(debug.contains("total_requests: 1000"));
    }

    // ─── Body size enforcement ───────────────────────────────────────────

    #[test]
    fn execute_rejects_oversized_body() {
        // Create a config with enabled=false but check the body limit logic
        // by using a config with a small max_body_bytes
        let config = PhpConfig {
            enabled: false,
            max_body_bytes: 100,
            ..PhpConfig::default()
        };
        let state = PhpState::init(config).unwrap();
        // With PHP disabled, execute returns None (not active)
        // But we can test the config stores the limit
        assert_eq!(state.config().max_body_bytes, 100);
    }

    // ─── Prometheus format ───────────────────────────────────────────────

    #[test]
    fn prometheus_format_valid() {
        // When active, prometheus should produce valid format lines
        let config = PhpConfig::default();
        let state = PhpState::init(config).unwrap();
        // Disabled → empty
        let prom = state.prometheus_metrics();
        assert!(prom.is_empty());
    }

    // ─── Status JSON structure ───────────────────────────────────────────

    #[test]
    fn status_json_has_all_fields() {
        let config = PhpConfig::default();
        let state = PhpState::init(config).unwrap();
        let json = state.status_json();
        // All expected fields present
        assert!(json.get("active").is_some());
        assert!(json.get("document_root").is_some());
        assert!(json.get("workers").is_some());
        assert!(json.get("workers_busy").is_some());
        assert!(json.get("total_requests").is_some());
        assert!(json.get("total_errors").is_some());
        assert!(json.get("avg_exec_time_us").is_some());
    }

    // ─── Worker mode config propagation ──────────────────────────────────

    #[test]
    fn worker_mode_config_stored() {
        let config = PhpConfig {
            worker_script: Some("./worker.php".into()),
            ..PhpConfig::default()
        };
        let state = PhpState::init(config).unwrap();
        assert_eq!(
            state.config().worker_script.as_deref(),
            Some("./worker.php")
        );
    }

    #[test]
    fn cache_responses_config_stored() {
        let config = PhpConfig {
            cache_responses: false,
            ..PhpConfig::default()
        };
        let state = PhpState::init(config).unwrap();
        assert!(!state.config().cache_responses);
    }

    // ─── PhpMode enum ────────────────────────────────────────────────────

    #[test]
    fn php_mode_classic_debug() {
        let mode = pool::PhpMode::Classic;
        let debug = format!("{:?}", mode);
        assert_eq!(debug, "Classic");
    }

    #[test]
    fn php_mode_worker_debug() {
        let mode = pool::PhpMode::Worker {
            script: "/opt/app/worker.php".into(),
        };
        let debug = format!("{:?}", mode);
        assert!(debug.contains("Worker"));
        assert!(debug.contains("worker.php"));
    }

    #[test]
    fn php_mode_clone() {
        let mode = pool::PhpMode::Worker {
            script: "w.php".into(),
        };
        let cloned = mode.clone();
        match cloned {
            pool::PhpMode::Worker { script } => assert_eq!(script, "w.php"),
            _ => panic!("Expected Worker"),
        }
    }

    // ─── PhpResponse edge cases ──────────────────────────────────────────

    #[test]
    fn php_response_ok_empty_body() {
        let resp = PhpResponse::Ok {
            status: 204,
            body: Vec::new(),
            headers: Vec::new(),
            exec_time_us: 0,
        };
        match resp {
            PhpResponse::Ok { status, body, .. } => {
                assert_eq!(status, 204);
                assert!(body.is_empty());
            }
            _ => panic!("Expected Ok"),
        }
    }

    #[test]
    fn php_response_ok_large_body() {
        let body = vec![0x42u8; 10 * 1024 * 1024]; // 10MB
        let resp = PhpResponse::Ok {
            status: 200,
            body,
            headers: vec![("Content-Type".into(), "application/octet-stream".into())],
            exec_time_us: 5000,
        };
        match resp {
            PhpResponse::Ok { body, .. } => assert_eq!(body.len(), 10 * 1024 * 1024),
            _ => panic!("Expected Ok"),
        }
    }

    #[test]
    fn php_response_error_empty_message() {
        let resp = PhpResponse::Error(String::new());
        match resp {
            PhpResponse::Error(msg) => assert!(msg.is_empty()),
            _ => panic!("Expected Error"),
        }
    }

    #[test]
    fn php_response_ok_many_headers() {
        let headers: Vec<(String, String)> = (0..100)
            .map(|i| (format!("X-Header-{}", i), format!("value-{}", i)))
            .collect();
        let resp = PhpResponse::Ok {
            status: 200,
            body: b"ok".to_vec(),
            headers,
            exec_time_us: 10,
        };
        match resp {
            PhpResponse::Ok { headers, .. } => assert_eq!(headers.len(), 100),
            _ => panic!("Expected Ok"),
        }
    }

    #[test]
    fn php_response_5xx_status() {
        let resp = PhpResponse::Ok {
            status: 503,
            body: b"Service Unavailable".to_vec(),
            headers: Vec::new(),
            exec_time_us: 0,
        };
        match resp {
            PhpResponse::Ok { status, .. } => assert_eq!(status, 503),
            _ => panic!("Expected Ok"),
        }
    }

    // ─── Security tests ──────────────────────────────────────────────────

    #[test]
    fn execute_body_size_enforced() {
        let config = PhpConfig {
            max_body_bytes: 10,
            ..PhpConfig::default()
        };
        let state = PhpState::init(config).unwrap();
        // Body larger than max should return error (not panic)
        let result = state.execute(
            "/index.php",
            "POST",
            "/index.php",
            "",
            None,
            vec![0u8; 100], // 100 bytes > 10 byte limit
            None,
            Vec::new(),
            None,
            None,
            80,
            false,
        );
        // Disabled PHP returns None, but the config is stored
        assert_eq!(state.config().max_body_bytes, 10);
    }

    #[test]
    fn error_messages_generic() {
        // Verify that PhpResponse::Error from execute doesn't leak internals
        let resp = PhpResponse::Error("PHP execution failed".into());
        match resp {
            PhpResponse::Error(msg) => {
                assert!(!msg.contains("/home/"));
                assert!(!msg.contains("stack trace"));
                assert!(!msg.contains("Fatal error"));
            }
            _ => panic!("Expected Error"),
        }
    }

    #[test]
    fn bridge_no_jsc_returns_error() {
        // Without JSC pool registered, bridge should return error, not panic
        let result = crate::bridge::jsc_render("{}");
        assert!(result.contains("not available"));
    }

    #[test]
    fn bridge_no_php_returns_error() {
        let result = crate::bridge::php_call("GET", "/api/test", None);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not available"));
    }
}