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