use crate::notify::{self, Notifier, Receiver};
use ext_php_rs::{
boxed::ZBox,
call_user_func,
exception::{throw_object, PhpException},
ffi::zend_resource,
prelude::*,
types::{ZendObject, Zval},
zend::{ClassEntry, ExecutorGlobals, Function},
};
use lazy_static::lazy_static;
use std::{
cell::RefCell,
collections::HashMap,
ffi::{c_char, c_int, c_void},
future::Future,
io, ptr,
sync::{
atomic::{AtomicU64, Ordering},
mpsc, Arc, Condvar, Mutex, OnceLock,
},
time::{Duration, Instant},
};
use tokio::runtime::{Handle, Runtime};
lazy_static! {
pub static ref RUNTIME: Runtime = {
#[cfg(unix)]
RUNTIME_PID.store(std::process::id().into(), Ordering::SeqCst);
Runtime::new().expect("Could not allocate runtime")
};
}
#[cfg(unix)]
static RUNTIME_PID: AtomicU64 = AtomicU64::new(0);
static REQUEST_END: OnceLock<c_int> = OnceLock::new();
extern "C" fn request_end(_: *mut zend_resource) {
EventLoop::shutdown();
}
extern "C" {
fn zend_register_list_destructors_ex(
ld: Option<extern "C" fn(*mut zend_resource)>,
pld: Option<extern "C" fn(*mut zend_resource)>,
type_name: *const c_char,
module_number: c_int,
) -> c_int;
fn zend_register_resource(rsrc_pointer: *mut c_void, rsrc_type: c_int) -> *mut zend_resource;
}
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
thread_local! {
static EVENTLOOP: RefCell<Option<EventLoop>> = const { RefCell::new(None) };
}
struct Slot<T> {
state: Mutex<SlotState<T>>,
ready: Condvar,
}
enum SlotState<T> {
Running,
Completed(T),
Panicked,
Taken,
}
const PANICKED: &str = "php-tokio: the future panicked";
impl<T> Slot<T> {
fn new() -> Self {
Self {
state: Mutex::new(SlotState::Running),
ready: Condvar::new(),
}
}
fn set(&self, value: T) {
*self.state.lock().unwrap() = SlotState::Completed(value);
self.ready.notify_all();
}
fn finish(&self) {
let mut state = self.state.lock().unwrap();
if matches!(*state, SlotState::Running) {
*state = SlotState::Panicked;
}
self.ready.notify_all();
}
fn wait(&self) -> Option<T> {
let mut state = self.state.lock().unwrap();
while matches!(*state, SlotState::Running) {
state = self.ready.wait(state).unwrap();
}
match std::mem::replace(&mut *state, SlotState::Taken) {
SlotState::Completed(value) => Some(value),
_ => None,
}
}
}
struct Completion<T> {
id: u64,
slot: Arc<Slot<T>>,
completions: mpsc::Sender<u64>,
notifier: Arc<Notifier>,
}
impl<T> Drop for Completion<T> {
fn drop(&mut self) {
self.slot.finish();
let _ = self.completions.send(self.id);
self.notifier.notify();
}
}
#[derive(Default)]
struct Tasks {
state: Mutex<TasksState>,
borrowing_ended: Condvar,
}
#[derive(Default)]
struct TasksState {
running: usize,
borrowing: usize,
release: Option<Runtime>,
}
struct Task {
tasks: Arc<Tasks>,
borrowing: bool,
}
impl Tasks {
fn start(self: &Arc<Self>, borrowing: bool) -> Task {
let mut state = self.state.lock().unwrap();
state.running += 1;
state.borrowing += usize::from(borrowing);
Task {
tasks: self.clone(),
borrowing,
}
}
fn wait_borrowing(&self) {
let mut state = self.state.lock().unwrap();
while state.borrowing > 0 {
state = self.borrowing_ended.wait(state).unwrap();
}
}
fn release(&self, runtime: Runtime) {
let mut state = self.state.lock().unwrap();
if state.running == 0 {
drop(state);
drop(runtime);
} else {
state.release = Some(runtime);
}
}
}
impl Drop for Task {
fn drop(&mut self) {
let runtime = {
let mut state = self.tasks.state.lock().unwrap();
state.running -= 1;
state.borrowing -= usize::from(self.borrowing);
self.tasks.borrowing_ended.notify_all();
if state.running == 0 {
state.release.take()
} else {
None
}
};
if let Some(runtime) = runtime {
runtime.shutdown_background();
}
}
}
const SOCKET_ERROR: &str = "Could not create the notification socket";
#[cfg(unix)]
const PENDING_ACROSS_FORK: &str =
"php-tokio: this call was pending when the process forked, and can only complete in the parent";
#[cfg(unix)]
const FORKED: &str = "php-tokio cannot be used after fork: Tokio's threads are not inherited";
#[cfg(unix)]
const FORKED_RUNTIME: &str =
"php-tokio: init() cannot be used after fork, as the shared runtime's threads are not inherited: use init_with()";
pub struct EventLoop {
#[cfg(unix)]
pid: u32,
suspensions: HashMap<u64, Zval>,
completions: mpsc::Sender<u64>,
completed: mpsc::Receiver<u64>,
notifier: Arc<Notifier>,
receiver: Receiver,
handle: Handle,
runtime: Option<Runtime>,
tasks: Arc<Tasks>,
get_current_suspension: Function,
}
impl EventLoop {
pub fn init() -> PhpResult<Zval> {
Self::initialize(|| Ok(None))
}
pub fn init_with(runtime: impl FnOnce() -> io::Result<Runtime>) -> PhpResult<Zval> {
Self::initialize(|| runtime().map(Some))
}
fn initialize(runtime: impl FnOnce() -> io::Result<Option<Runtime>>) -> PhpResult<Zval> {
EVENTLOOP.with_borrow_mut(|e| {
let event_loop = match e {
None => {
let runtime = runtime()
.map_err(|err| format!("Could not build the Tokio runtime: {}", err))?;
e.insert(Self::new(runtime)?)
}
Some(event_loop) => event_loop,
};
event_loop.check_owned()?;
event_loop.receiver.php_stream()
})
}
pub fn suspend_on<T: Send + 'static, F: Future<Output = T> + Send + 'static>(future: F) -> T {
let (id, suspension, slot) =
Self::spawn(future, true).unwrap_or_else(|err| panic!("{}", err));
#[cfg(unix)]
let pid = std::process::id();
let interrupted = match Self::suspend(id, &suspension) {
Suspended::Resumed | Suspended::Failed(_) => false,
Suspended::Exited => true,
Suspended::Threw(exception) => {
rethrow(exception);
true
}
};
#[cfg(unix)]
if interrupted && pid != std::process::id() {
panic!("{}", PENDING_ACROSS_FORK);
}
#[cfg(not(unix))]
let _ = interrupted;
slot.wait().unwrap_or_else(|| panic!("{}", PANICKED))
}
pub fn try_suspend_on<T: Send + 'static, F: Future<Output = T> + Send + 'static>(
future: F,
) -> PhpResult<Option<T>> {
let (id, suspension, slot) = Self::spawn(future, false)?;
match Self::suspend(id, &suspension) {
Suspended::Resumed => slot.wait().map(Some).ok_or_else(|| PANICKED.into()),
Suspended::Failed(err) => Err(format!("Could not suspend the caller: {}", err).into()),
Suspended::Exited => Ok(None),
Suspended::Threw(exception) => {
Err(PhpException::from("Interrupted by an exception").with_object(zval(exception)))
}
}
}
fn spawn<T: Send + 'static, F: Future<Output = T> + Send + 'static>(
future: F,
borrowing: bool,
) -> Result<(u64, Zval, Arc<Slot<T>>), String> {
EVENTLOOP.with_borrow_mut(|c| {
let c = c
.as_mut()
.ok_or("php-tokio's EventLoop::init() must be called first")?;
c.check_owned()?;
let suspension = call_user_func!(c.get_current_suspension)
.ok()
.filter(|_| !ExecutorGlobals::has_exception())
.ok_or("Could not get the current suspension")?;
let id = NEXT_ID.fetch_add(1, Ordering::SeqCst);
c.suspensions.insert(id, suspension.shallow_clone());
let slot = Arc::new(Slot::new());
let task = c.tasks.start(borrowing);
let completion = Completion {
id,
slot: slot.clone(),
completions: c.completions.clone(),
notifier: c.notifier.clone(),
};
c.handle.spawn(async move {
let _task = task;
let completion = completion;
completion.slot.set(future.await);
});
Ok((id, suspension, slot))
})
}
fn suspend(id: u64, suspension: &Zval) -> Suspended {
let suspended = suspension.try_call_method("suspend", vec![]);
let result = if exit_pending() {
Suspended::Exited
} else if let Some(exception) = ExecutorGlobals::take_exception() {
Suspended::Threw(exception)
} else {
match suspended {
Ok(_) => return Suspended::Resumed,
Err(err) => Suspended::Failed(err),
}
};
EVENTLOOP.with_borrow_mut(|c| {
if let Some(c) = c.as_mut() {
c.suspensions.remove(&id);
}
});
result
}
pub fn wakeup() -> PhpResult<()> {
let ready = EVENTLOOP.with_borrow_mut(|c| -> PhpResult<Vec<Zval>> {
let c = c
.as_mut()
.ok_or("php-tokio's EventLoop::init() must be called first")?;
#[cfg(unix)]
if c.check_owned().is_err() {
return Ok(vec![]);
}
c.receiver.drain();
c.notifier.rearm();
Ok(c.completed
.try_iter()
.filter_map(|id| c.suspensions.remove(&id))
.collect())
})?;
resume(ready)
}
pub fn drain(timeout: Duration) -> PhpResult<()> {
let deadline = Instant::now() + timeout;
let ready = EVENTLOOP.with_borrow_mut(|c| {
let Some(c) = c.as_mut().filter(|c| c.check_owned().is_ok()) else {
return vec![];
};
let mut ready = vec![];
while !c.suspensions.is_empty() {
match c
.completed
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
{
Ok(id) => ready.extend(c.suspensions.remove(&id)),
Err(_) => break,
}
}
c.receiver.drain();
c.notifier.rearm();
ready.extend(
c.completed
.try_iter()
.filter_map(|id| c.suspensions.remove(&id)),
);
ready
});
resume(ready)
}
pub fn pending() -> usize {
EVENTLOOP.with_borrow(|c| {
c.as_ref()
.filter(|c| c.check_owned().is_ok())
.map_or(0, |c| c.suspensions.len())
})
}
pub fn shutdown() {
let event_loop = EVENTLOOP.with_borrow_mut(Option::take);
if let Some(mut event_loop) = event_loop {
#[cfg(unix)]
if event_loop.check_owned().is_err() {
std::mem::forget(event_loop);
return;
}
event_loop.tasks.wait_borrowing();
if let Some(runtime) = event_loop.runtime.take() {
event_loop.tasks.release(runtime);
}
}
}
fn new(runtime: Option<Runtime>) -> PhpResult<Self> {
let (completions, completed) = mpsc::channel();
let (notifier, receiver) = notify::channel().map_err(|e| format!("{SOCKET_ERROR}: {e}"))?;
for name in ["Revolt\\EventLoop", "Revolt\\EventLoop\\Suspension"] {
if ClassEntry::try_find(name).is_none() {
return Err(format!("\\{} does not exist", name).into());
}
}
let request_end = *REQUEST_END.get_or_init(|| unsafe {
zend_register_list_destructors_ex(Some(request_end), None, c"php-tokio".as_ptr(), 0)
});
unsafe { zend_register_resource(ptr::null_mut(), request_end) };
Ok(Self {
#[cfg(unix)]
pid: std::process::id(),
suspensions: HashMap::new(),
completions,
completed,
notifier: Arc::new(notifier),
receiver,
handle: match &runtime {
Some(runtime) => runtime.handle().clone(),
None => shared_runtime()?,
},
runtime,
tasks: Arc::default(),
get_current_suspension: Function::try_from_method(
"\\Revolt\\EventLoop",
"getSuspension",
)
.ok_or("\\Revolt\\EventLoop::getSuspension does not exist")?,
})
}
}
fn shared_runtime() -> Result<Handle, &'static str> {
let handle = RUNTIME.handle().clone();
#[cfg(unix)]
if RUNTIME_PID.load(Ordering::SeqCst) != u64::from(std::process::id()) {
return Err(FORKED_RUNTIME);
}
Ok(handle)
}
impl EventLoop {
#[cfg(unix)]
fn check_owned(&self) -> Result<(), &'static str> {
if self.pid == std::process::id() {
Ok(())
} else {
Err(FORKED)
}
}
#[cfg(not(unix))]
fn check_owned(&self) -> Result<(), &'static str> {
Ok(())
}
}
enum Suspended {
Resumed,
Exited,
Threw(ZBox<ZendObject>),
Failed(ext_php_rs::error::Error),
}
fn zval(mut object: ZBox<ZendObject>) -> Zval {
let mut zval = Zval::new();
zval.set_object(&mut object);
zval
}
fn rethrow(exception: ZBox<ZendObject>) {
let _ = throw_object(zval(exception));
}
extern "C" {
fn zend_is_unwind_exit(ex: *const ext_php_rs::ffi::zend_object) -> bool;
fn zend_is_graceful_exit(ex: *const ext_php_rs::ffi::zend_object) -> bool;
}
fn exit_pending() -> bool {
let exception = ExecutorGlobals::get().exception;
!exception.is_null()
&& unsafe { zend_is_unwind_exit(exception) || zend_is_graceful_exit(exception) }
}
fn resume(ready: Vec<Zval>) -> PhpResult<()> {
let mut first = None;
for suspension in ready {
let _ = suspension.try_call_method("resume", vec![]);
if let Some(exception) = ExecutorGlobals::take_exception() {
first.get_or_insert(exception);
}
}
if let Some(exception) = first {
rethrow(exception);
}
Ok(())
}