use std::sync::OnceLock;
use futures_util::FutureExt as _;
use tokio::runtime::Runtime;
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
pub(crate) fn try_ffi_runtime() -> eggfetch_core::Result<&'static Runtime> {
if let Some(rt) = RUNTIME.get() {
return Ok(rt);
}
let rt = Runtime::new().map_err(|e| {
eggfetch_core::Error::Io(std::sync::Arc::new(std::io::Error::other(format!(
"failed to create eggfetch-ffi tokio runtime: {e}"
))))
})?;
Ok(RUNTIME.get_or_init(|| rt))
}
pub(crate) fn blocking_send<
F: std::future::Future<Output = T> + Send + 'static,
T: Send + 'static,
>(
future: F,
) -> eggfetch_core::Result<T> {
match tokio::runtime::Handle::try_current() {
Ok(handle)
if matches!(
handle.runtime_flavor(),
tokio::runtime::RuntimeFlavor::MultiThread
) =>
{
Ok(tokio::task::block_in_place(move || handle.block_on(future)))
}
_ => {
let rt = try_ffi_runtime()?;
let (tx, rx) = std::sync::mpsc::channel();
rt.spawn(async move {
let outcome = std::panic::AssertUnwindSafe(future).catch_unwind().await;
let to_send = match outcome {
Ok(val) => Ok(val),
Err(payload) => {
let msg = if let Some(s) = payload.downcast_ref::<&str>() {
*s
} else if let Some(s) = payload.downcast_ref::<String>() {
s.as_str()
} else {
"task panicked"
};
Err(eggfetch_core::Error::Io(std::sync::Arc::new(
std::io::Error::other(format!(
"eggfetch-ffi blocking_send: task panicked: {msg}"
)),
)))
}
};
let _ = tx.send(to_send);
});
rx.recv().unwrap_or_else(|e| {
Err(eggfetch_core::Error::Io(std::sync::Arc::new(
std::io::Error::other(format!(
"eggfetch-ffi blocking_send: runtime task dropped ({e})"
)),
)))
})
}
}
}