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