php_tokio/event_loop.rs
1// Copyright 2023-2024 Daniil Gentili
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::notify::{self, Notifier, Receiver};
16use ext_php_rs::{
17 boxed::ZBox,
18 call_user_func,
19 exception::{throw_object, PhpException},
20 prelude::*,
21 types::{ZendObject, Zval},
22 zend::{ClassEntry, ExecutorGlobals, Function},
23};
24use lazy_static::lazy_static;
25use std::{
26 cell::RefCell,
27 collections::HashMap,
28 future::Future,
29 io,
30 sync::{
31 atomic::{AtomicU64, Ordering},
32 mpsc, Arc, Condvar, Mutex,
33 },
34 time::{Duration, Instant},
35};
36use tokio::runtime::{Handle, Runtime};
37
38lazy_static! {
39 /// The runtime of the event loops initialized with `EventLoop::init()`, shared by every
40 /// request of the process.
41 pub static ref RUNTIME: Runtime = {
42 #[cfg(unix)]
43 RUNTIME_PID.store(std::process::id().into(), Ordering::SeqCst);
44 Runtime::new().expect("Could not allocate runtime")
45 };
46}
47
48/// The process that created `RUNTIME`: its threads aren't inherited by forked children.
49#[cfg(unix)]
50static RUNTIME_PID: AtomicU64 = AtomicU64::new(0);
51
52/// The ID of the next caller, unique in the process: a caller of an event loop that was shut down
53/// can still be interrupted, and unregister itself, once a new event loop is initialized.
54static NEXT_ID: AtomicU64 = AtomicU64::new(0);
55
56thread_local! {
57 static EVENTLOOP: RefCell<Option<EventLoop>> = const { RefCell::new(None) };
58}
59
60/// The result of a future, handed over from a Tokio thread to the PHP thread.
61struct Slot<T> {
62 state: Mutex<SlotState<T>>,
63 ready: Condvar,
64}
65
66enum SlotState<T> {
67 Running,
68 Completed(T),
69 /// The future panicked (Tokio caught the panic): it has no result.
70 Panicked,
71 /// The result was taken.
72 Taken,
73}
74
75/// The message of the error of a caller whose future panicked.
76const PANICKED: &str = "php-tokio: the future panicked";
77
78impl<T> Slot<T> {
79 fn new() -> Self {
80 Self {
81 state: Mutex::new(SlotState::Running),
82 ready: Condvar::new(),
83 }
84 }
85
86 fn set(&self, value: T) {
87 *self.state.lock().unwrap() = SlotState::Completed(value);
88 self.ready.notify_all();
89 }
90
91 /// Called once the future is over: if it has no result, it panicked.
92 fn finish(&self) {
93 let mut state = self.state.lock().unwrap();
94 if matches!(*state, SlotState::Running) {
95 *state = SlotState::Panicked;
96 }
97 self.ready.notify_all();
98 }
99
100 /// Blocks until the future is over, returning its result, or None if it panicked.
101 fn wait(&self) -> Option<T> {
102 let mut state = self.state.lock().unwrap();
103 while matches!(*state, SlotState::Running) {
104 state = self.ready.wait(state).unwrap();
105 }
106 match std::mem::replace(&mut *state, SlotState::Taken) {
107 SlotState::Completed(value) => Some(value),
108 _ => None,
109 }
110 }
111}
112
113/// Owned by a future's task: once the future is over, completed or panicked, publishes its end
114/// and wakes PHP up. Its caller is resumed either way.
115struct Completion<T> {
116 id: u64,
117 slot: Arc<Slot<T>>,
118 completions: mpsc::Sender<u64>,
119 notifier: Arc<Notifier>,
120}
121
122impl<T> Drop for Completion<T> {
123 fn drop(&mut self) {
124 self.slot.finish();
125 // Only the ID crosses threads, never a PHP value.
126 let _ = self.completions.send(self.id);
127 self.notifier.notify();
128 }
129}
130
131/// The futures of an event loop's `suspend_on()` and `try_suspend_on()`.
132///
133/// A runtime that the event loop owns (`EventLoop::init_with()`) is released once none of them
134/// runs any more: dropping it earlier would cancel them, and a caller of `suspend_on()`
135/// interrupted by an exception waits for its future, which may borrow from the caller's stack, to
136/// complete.
137///
138/// `shutdown()` waits for the futures of `suspend_on()`: after a fatal error, PHP frees the
139/// memory of the suspended callers without unwinding them.
140#[derive(Default)]
141struct Tasks {
142 state: Mutex<TasksState>,
143 /// Notified when a future of `suspend_on()` ends.
144 borrowing_ended: Condvar,
145}
146
147#[derive(Default)]
148struct TasksState {
149 running: usize,
150 /// The futures of `suspend_on()` among them: they may borrow from their callers.
151 borrowing: usize,
152 /// The runtime to release once `running` is 0.
153 release: Option<Runtime>,
154}
155
156/// Held by a running future, until it is dropped.
157struct Task {
158 tasks: Arc<Tasks>,
159 borrowing: bool,
160}
161
162impl Tasks {
163 fn start(self: &Arc<Self>, borrowing: bool) -> Task {
164 let mut state = self.state.lock().unwrap();
165 state.running += 1;
166 state.borrowing += usize::from(borrowing);
167 Task {
168 tasks: self.clone(),
169 borrowing,
170 }
171 }
172
173 /// Blocks until the futures of `suspend_on()` ended.
174 fn wait_borrowing(&self) {
175 let mut state = self.state.lock().unwrap();
176 while state.borrowing > 0 {
177 state = self.borrowing_ended.wait(state).unwrap();
178 }
179 }
180
181 /// Releases the runtime on the PHP thread if none of the futures runs, else lets the last
182 /// one release it.
183 fn release(&self, runtime: Runtime) {
184 let mut state = self.state.lock().unwrap();
185 if state.running == 0 {
186 drop(state);
187 drop(runtime);
188 } else {
189 state.release = Some(runtime);
190 }
191 }
192}
193
194impl Drop for Task {
195 fn drop(&mut self) {
196 let runtime = {
197 let mut state = self.tasks.state.lock().unwrap();
198 state.running -= 1;
199 state.borrowing -= usize::from(self.borrowing);
200 self.tasks.borrowing_ended.notify_all();
201 if state.running == 0 {
202 state.release.take()
203 } else {
204 None
205 }
206 };
207 // On one of the runtime's own threads: it can't wait for them to stop.
208 if let Some(runtime) = runtime {
209 runtime.shutdown_background();
210 }
211 }
212}
213
214/// Tokio's threads don't survive a fork: only the process that initialized an event loop can use
215/// it.
216const SOCKET_ERROR: &str = "Could not create the notification socket";
217
218#[cfg(unix)]
219const PENDING_ACROSS_FORK: &str =
220 "php-tokio: this call was pending when the process forked, and can only complete in the parent";
221
222#[cfg(unix)]
223const FORKED: &str = "php-tokio cannot be used after fork: Tokio's threads are not inherited";
224
225#[cfg(unix)]
226const FORKED_RUNTIME: &str =
227 "php-tokio: init() cannot be used after fork, as the shared runtime's threads are not inherited: use init_with()";
228
229pub struct EventLoop {
230 /// The process that initialized the event loop.
231 #[cfg(unix)]
232 pid: u32,
233
234 /// The suspensions of the callers waiting for a future, by ID. PHP values never leave the
235 /// PHP thread: only the IDs of the completed futures cross threads.
236 suspensions: HashMap<u64, Zval>,
237 /// The IDs of the completed futures.
238 completions: mpsc::Sender<u64>,
239 completed: mpsc::Receiver<u64>,
240
241 /// Wakes PHP up when futures complete: shared by every future.
242 notifier: Arc<Notifier>,
243 receiver: Receiver,
244
245 /// Where the futures run.
246 handle: Handle,
247 /// The runtime from `init_with()`, released by `shutdown()`.
248 runtime: Option<Runtime>,
249 tasks: Arc<Tasks>,
250
251 get_current_suspension: Function,
252}
253
254impl EventLoop {
255 /// Initializes the event loop, returning the stream to watch for readability, calling
256 /// `wakeup()` when it is readable:
257 ///
258 /// ```php
259 /// $stream = Extension::init();
260 /// Revolt\EventLoop::onReadable($stream, fn () => Extension::wakeup());
261 /// ```
262 ///
263 /// The stream is the same every time: don't close it before `shutdown()` (on Windows, closing
264 /// a socket stream shuts the socket down). The futures run on `RUNTIME`, shared by every
265 /// request.
266 pub fn init() -> PhpResult<Zval> {
267 Self::initialize(|| Ok(None))
268 }
269
270 /// Initializes the event loop like `init()`, with the futures running on the runtime that
271 /// `runtime` builds, for example to choose its threads:
272 ///
273 /// ```no_run
274 /// // In a PHP method.
275 /// php_tokio::EventLoop::init_with(|| {
276 /// tokio::runtime::Builder::new_multi_thread()
277 /// .worker_threads(1)
278 /// .enable_all()
279 /// .build()
280 /// })
281 /// # ;
282 /// ```
283 ///
284 /// `runtime` is only called if the event loop isn't initialized yet. The event loop owns the
285 /// runtime: `shutdown()` releases it, once the futures of `suspend_on()` and
286 /// `try_suspend_on()` running on it completed.
287 pub fn init_with(runtime: impl FnOnce() -> io::Result<Runtime>) -> PhpResult<Zval> {
288 Self::initialize(|| runtime().map(Some))
289 }
290
291 fn initialize(runtime: impl FnOnce() -> io::Result<Option<Runtime>>) -> PhpResult<Zval> {
292 EVENTLOOP.with_borrow_mut(|e| {
293 let event_loop = match e {
294 None => {
295 let runtime = runtime()
296 .map_err(|err| format!("Could not build the Tokio runtime: {}", err))?;
297 e.insert(Self::new(runtime)?)
298 }
299 Some(event_loop) => event_loop,
300 };
301 event_loop.check_owned()?;
302 event_loop.receiver.php_stream()
303 })
304 }
305
306 /// Suspends the current fiber until `future` completes, returning its result.
307 ///
308 /// If the fiber is interrupted by an exception (an event-loop error thrown into `{main}`, or
309 /// the fiber being destroyed), this waits for the future anyway, blocking the PHP thread, and
310 /// returns its result with the exception pending: the future may borrow from the caller's
311 /// stack (see `php_async_impl`). For the same reason, `shutdown()` waits for the future.
312 ///
313 /// Panics if the event loop is not initialized, or if the future panicked.
314 pub fn suspend_on<T: Send + 'static, F: Future<Output = T> + Send + 'static>(future: F) -> T {
315 // What's going on here? Unsafe borrows???
316 // NO: this is actually 100% safe, and here's why.
317 //
318 // Rust thinks we're Sending the Future to another thread (tokio's event loop),
319 // where it may be used even after its lifetime expires in the main (PHP) thread.
320 //
321 // In reality, the Future is only used by Tokio until the result is ready.
322 //
323 // Rust does not understand that when we suspend the current fiber in suspend_on,
324 // we basically keep alive the the entire stack,
325 // including the Rust stack and the Future on it, until the result of the future is ready.
326 //
327 // Once the result of the Future is ready, tokio doesn't need it anymore,
328 // the suspend_on function is resumed, and we safely drop the Future upon exiting.
329 //
330 // This only holds if suspend_on never returns (or unwinds) before the future has
331 // completed: nothing below may panic once the future is spawned, and if the caller
332 // is not resumed by wakeup(), we wait for the future before returning. If PHP frees the
333 // caller without unwinding it (a fatal error), shutdown() waits for the future.
334 let (id, suspension, slot) =
335 Self::spawn(future, true).unwrap_or_else(|err| panic!("{}", err));
336 #[cfg(unix)]
337 let pid = std::process::id();
338 let interrupted = match Self::suspend(id, &suspension) {
339 Suspended::Resumed | Suspended::Failed(_) => false,
340 // Pending for the caller.
341 Suspended::Exited => true,
342 Suspended::Threw(exception) => {
343 rethrow(exception);
344 true
345 }
346 };
347 // In a process forked meanwhile (whose copy of the fiber PHP destroys), the future never
348 // completes: it runs on Tokio's threads, in the parent. Nothing here uses what it borrows,
349 // so unwind rather than wait forever: ext-php-rs throws nothing over the pending exception.
350 #[cfg(unix)]
351 if interrupted && pid != std::process::id() {
352 panic!("{}", PENDING_ACROSS_FORK);
353 }
354 #[cfg(not(unix))]
355 let _ = interrupted;
356 // Resumed by wakeup() once the future completed, this doesn't block; interrupted, this
357 // waits for the future.
358 slot.wait().unwrap_or_else(|| panic!("{}", PANICKED))
359 }
360
361 /// Like `suspend_on()`, but fails instead of panicking, and never waits for the future if
362 /// the fiber is interrupted: the future completes on its own. It must therefore own all its
363 /// data: never pass it anything borrowed with `borrow_unchecked`.
364 ///
365 /// Interrupted by an exception, returns it, unchanged. Interrupted by an exit (`exit()`, or
366 /// PHP destroying the fiber, at the end of the request or once nothing references it),
367 /// returns `None`: the exit stays pending, as PHP must keep unwinding the fiber, so nothing
368 /// may be thrown. Return any value then: PHP discards it.
369 ///
370 /// Fails if the future panicked.
371 pub fn try_suspend_on<T: Send + 'static, F: Future<Output = T> + Send + 'static>(
372 future: F,
373 ) -> PhpResult<Option<T>> {
374 let (id, suspension, slot) = Self::spawn(future, false)?;
375 match Self::suspend(id, &suspension) {
376 // Resumed by wakeup() or drain() once the future ended: this doesn't block.
377 Suspended::Resumed => slot.wait().map(Some).ok_or_else(|| PANICKED.into()),
378 Suspended::Failed(err) => Err(format!("Could not suspend the caller: {}", err).into()),
379 Suspended::Exited => Ok(None),
380 Suspended::Threw(exception) => {
381 Err(PhpException::from("Interrupted by an exception").with_object(zval(exception)))
382 }
383 }
384 }
385
386 /// Spawns `future`, registering the caller's suspension. `borrowing`: the future may borrow
387 /// from the caller (`suspend_on()`).
388 fn spawn<T: Send + 'static, F: Future<Output = T> + Send + 'static>(
389 future: F,
390 borrowing: bool,
391 ) -> Result<(u64, Zval, Arc<Slot<T>>), String> {
392 EVENTLOOP.with_borrow_mut(|c| {
393 let c = c
394 .as_mut()
395 .ok_or("php-tokio's EventLoop::init() must be called first")?;
396 c.check_owned()?;
397 // An exception thrown by getSuspension() stays pending, as the previous one.
398 let suspension = call_user_func!(c.get_current_suspension)
399 .ok()
400 .filter(|_| !ExecutorGlobals::has_exception())
401 .ok_or("Could not get the current suspension")?;
402 let id = NEXT_ID.fetch_add(1, Ordering::SeqCst);
403 c.suspensions.insert(id, suspension.shallow_clone());
404
405 let slot = Arc::new(Slot::new());
406 let task = c.tasks.start(borrowing);
407 let completion = Completion {
408 id,
409 slot: slot.clone(),
410 completions: c.completions.clone(),
411 notifier: c.notifier.clone(),
412 };
413 c.handle.spawn(async move {
414 // Dropped in reverse order: the future, then the completion, then the task.
415 let _task = task;
416 let completion = completion;
417 completion.slot.set(future.await);
418 });
419 Ok((id, suspension, slot))
420 })
421 }
422
423 /// Suspends the caller until wakeup() or drain() resumes it. Interrupted, unregisters it.
424 fn suspend(id: u64, suspension: &Zval) -> Suspended {
425 // try_call_method returns Ok even when suspend() throws: the exception is left pending.
426 let suspended = suspension.try_call_method("suspend", vec![]);
427 let result = if exit_pending() {
428 Suspended::Exited
429 } else if let Some(exception) = ExecutorGlobals::take_exception() {
430 Suspended::Threw(exception)
431 } else {
432 match suspended {
433 Ok(_) => return Suspended::Resumed,
434 Err(err) => Suspended::Failed(err),
435 }
436 };
437 EVENTLOOP.with_borrow_mut(|c| {
438 if let Some(c) = c.as_mut() {
439 c.suspensions.remove(&id);
440 }
441 });
442 result
443 }
444
445 /// Resumes the callers whose future completed.
446 ///
447 /// In a process forked from the one that initialized the event loop, does nothing: the
448 /// notification socket is shared with the parent, whose notifications must stay there.
449 pub fn wakeup() -> PhpResult<()> {
450 let ready = EVENTLOOP.with_borrow_mut(|c| -> PhpResult<Vec<Zval>> {
451 let c = c
452 .as_mut()
453 .ok_or("php-tokio's EventLoop::init() must be called first")?;
454 #[cfg(unix)]
455 if c.check_owned().is_err() {
456 return Ok(vec![]);
457 }
458 c.receiver.drain();
459 c.notifier.rearm();
460 Ok(c.completed
461 .try_iter()
462 .filter_map(|id| c.suspensions.remove(&id))
463 .collect())
464 })?;
465 resume(ready)
466 }
467
468 /// Waits up to `timeout` for the futures of the suspended callers to complete, and resumes
469 /// the callers whose future completed, like `wakeup()`. This doesn't run the PHP event loop:
470 /// the resumed callers continue once it runs.
471 ///
472 /// Use it before `shutdown()` when the pending futures are about to complete (their work was
473 /// finished or rejected), so that their callers are resumed.
474 pub fn drain(timeout: Duration) -> PhpResult<()> {
475 let deadline = Instant::now() + timeout;
476 let ready = EVENTLOOP.with_borrow_mut(|c| {
477 let Some(c) = c.as_mut().filter(|c| c.check_owned().is_ok()) else {
478 return vec![];
479 };
480 let mut ready = vec![];
481 while !c.suspensions.is_empty() {
482 match c
483 .completed
484 .recv_timeout(deadline.saturating_duration_since(Instant::now()))
485 {
486 Ok(id) => ready.extend(c.suspensions.remove(&id)),
487 Err(_) => break,
488 }
489 }
490 // As wakeup() does: the completions published meanwhile are collected next.
491 c.receiver.drain();
492 c.notifier.rearm();
493 ready.extend(
494 c.completed
495 .try_iter()
496 .filter_map(|id| c.suspensions.remove(&id)),
497 );
498 ready
499 });
500 resume(ready)
501 }
502
503 /// The number of suspended callers.
504 pub fn pending() -> usize {
505 EVENTLOOP.with_borrow(|c| {
506 c.as_ref()
507 .filter(|c| c.check_owned().is_ok())
508 .map_or(0, |c| c.suspensions.len())
509 })
510 }
511
512 /// Releases the event loop. Callers still suspended are never resumed: their suspensions are
513 /// released here, on the PHP thread. A runtime from `init_with()` is released once the
514 /// futures running on it completed.
515 ///
516 /// Blocks until the futures of `suspend_on()` completed: they may borrow from their callers,
517 /// whose memory PHP frees without unwinding them after a fatal error (or a timeout). Call it
518 /// at the end of every request (RSHUTDOWN), which runs before PHP frees that memory.
519 pub fn shutdown() {
520 let event_loop = EVENTLOOP.with_borrow_mut(Option::take);
521 if let Some(mut event_loop) = event_loop {
522 #[cfg(unix)]
523 if event_loop.check_owned().is_err() {
524 // Inherited across fork: the parent owns the socket and the runtime.
525 std::mem::forget(event_loop);
526 return;
527 }
528 event_loop.tasks.wait_borrowing();
529 if let Some(runtime) = event_loop.runtime.take() {
530 event_loop.tasks.release(runtime);
531 }
532 }
533 }
534
535 fn new(runtime: Option<Runtime>) -> PhpResult<Self> {
536 let (completions, completed) = mpsc::channel();
537 // On one line: on Windows, which can't run out of descriptors, the closure never runs.
538 let (notifier, receiver) = notify::channel().map_err(|e| format!("{SOCKET_ERROR}: {e}"))?;
539
540 // Autoloaded if needed.
541 for name in ["Revolt\\EventLoop", "Revolt\\EventLoop\\Suspension"] {
542 if ClassEntry::try_find(name).is_none() {
543 return Err(format!("\\{} does not exist", name).into());
544 }
545 }
546
547 Ok(Self {
548 #[cfg(unix)]
549 pid: std::process::id(),
550 suspensions: HashMap::new(),
551 completions,
552 completed,
553 notifier: Arc::new(notifier),
554 receiver,
555 handle: match &runtime {
556 Some(runtime) => runtime.handle().clone(),
557 None => shared_runtime()?,
558 },
559 runtime,
560 tasks: Arc::default(),
561 get_current_suspension: Function::try_from_method(
562 "\\Revolt\\EventLoop",
563 "getSuspension",
564 )
565 .ok_or("\\Revolt\\EventLoop::getSuspension does not exist")?,
566 })
567 }
568}
569
570/// `RUNTIME`'s handle, unless `RUNTIME` was created before a fork, without its threads.
571fn shared_runtime() -> Result<Handle, &'static str> {
572 let handle = RUNTIME.handle().clone();
573 #[cfg(unix)]
574 if RUNTIME_PID.load(Ordering::SeqCst) != u64::from(std::process::id()) {
575 return Err(FORKED_RUNTIME);
576 }
577 Ok(handle)
578}
579
580impl EventLoop {
581 /// Fails in a process forked from the one that initialized the event loop.
582 #[cfg(unix)]
583 fn check_owned(&self) -> Result<(), &'static str> {
584 if self.pid == std::process::id() {
585 Ok(())
586 } else {
587 Err(FORKED)
588 }
589 }
590
591 /// Windows has no fork.
592 #[cfg(not(unix))]
593 fn check_owned(&self) -> Result<(), &'static str> {
594 Ok(())
595 }
596}
597
598/// How a caller's suspension ended.
599enum Suspended {
600 /// By wakeup() or drain(), once its future completed.
601 Resumed,
602 /// By an exit, left pending (see exit_pending()).
603 Exited,
604 /// By an exception, taken.
605 Threw(ZBox<ZendObject>),
606 /// Without suspending.
607 Failed(ext_php_rs::error::Error),
608}
609
610/// `object` as a zval, holding its reference.
611fn zval(mut object: ZBox<ZendObject>) -> Zval {
612 let mut zval = Zval::new();
613 // Adds a reference: dropping the box releases its own.
614 zval.set_object(&mut object);
615 zval
616}
617
618/// Throws an exception taken with take_exception() again.
619fn rethrow(exception: ZBox<ZendObject>) {
620 // Fails only for a zval that isn't an object.
621 let _ = throw_object(zval(exception));
622}
623
624extern "C" {
625 fn zend_is_unwind_exit(ex: *const ext_php_rs::ffi::zend_object) -> bool;
626 fn zend_is_graceful_exit(ex: *const ext_php_rs::ffi::zend_object) -> bool;
627}
628
629/// Whether the pending exception is an exit: `exit()` (unwind exit), or PHP destroying a fiber
630/// (graceful exit). Neither is a Throwable, and PHP must keep unwinding: it can't be taken and
631/// thrown again, nor replaced by another exception.
632fn exit_pending() -> bool {
633 let exception = ExecutorGlobals::get().exception;
634 !exception.is_null()
635 && unsafe { zend_is_unwind_exit(exception) || zend_is_graceful_exit(exception) }
636}
637
638/// Resumes the callers, outside the event loop's borrow: resuming can re-enter php-tokio.
639fn resume(ready: Vec<Zval>) -> PhpResult<()> {
640 let mut first = None;
641 for suspension in ready {
642 let _ = suspension.try_call_method("resume", vec![]);
643 // An exception thrown by resume() is left pending, and PHP calls nothing while one is:
644 // take it to resume the others, and rethrow the first one.
645 if let Some(exception) = ExecutorGlobals::take_exception() {
646 first.get_or_insert(exception);
647 }
648 }
649 if let Some(exception) = first {
650 rethrow(exception);
651 }
652 Ok(())
653}