1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! Safe bridge for executing async work from synchronous Lua callbacks.
//!
//! Lua callbacks run synchronously on whatever thread invokes
//! `lua.call`. When invoked from a tokio task (e.g., via
//! `tokio::task::spawn_blocking` or directly from `eggsec::dispatch`),
//! `tokio::runtime::Handle::current().block_on` may panic with
//! "cannot execute blocking call inside blocking context".
//!
//! [`block_on_async`] handles both cases:
//! - If a tokio runtime is currently active, it delegates to the handle.
//! - Otherwise, it constructs an ephemeral current-thread runtime.
//!
//! This avoids the panic and removes the need for callers to manage
//! runtime lifecycle.
/// Run an async future to completion from a synchronous context.
///
/// Returns the future's output. If no tokio runtime is active in the
/// current thread, a dedicated current-thread runtime is constructed
/// and torn down on completion.
///
/// Fallible variant of [`block_on_async`]: runtime-construction failure
/// is returned to the caller instead of panicking. Prefer this in new
/// code so Lua callbacks can surface the error via `mlua::Error`.
pub fn try_block_on_async<F>(fut: F) -> std::io::Result<F::Output>
where
F: std::future::Future,
{
match tokio::runtime::Handle::try_current() {
Ok(handle) => Ok(handle.block_on(fut)),
Err(_) => {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?;
Ok(rt.block_on(fut))
}
}
}
/// Run an async future to completion from a synchronous context.
///
/// Returns the future's output. If no tokio runtime is active in the
/// current thread, a dedicated current-thread runtime is constructed
/// and torn down on completion.
///
/// # Panics
///
/// Panics only if the ephemeral runtime cannot be constructed. The
/// builder uses a fixed, valid configuration, so construction fails
/// solely on process-global resource exhaustion (unrecoverable); the
/// failure is logged before panicking. Callers that must handle the
/// error should use [`try_block_on_async`] instead.
pub fn block_on_async<F>(fut: F) -> F::Output
where
F: std::future::Future,
{
match try_block_on_async(fut) {
Ok(output) => output,
Err(e) => {
tracing::error!(
"failed to construct dedicated runtime for NSE async bridge: {}",
e
);
panic!(
"failed to construct dedicated runtime for NSE async bridge: {}",
e
);
}
}
}