Skip to main content

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