use std::sync::{Once, OnceLock};
use encore_sdk_core::Runtime as CoreRuntime;
static RUNTIME: OnceLock<CoreRuntime> = OnceLock::new();
pub(crate) fn core() -> &'static CoreRuntime {
static WATCH: Once = Once::new();
let core = RUNTIME.get_or_init(|| {
let test_runner = crate::testing::runner_detected();
std::thread::scope(|scope| scope.spawn(move || build(test_runner)).join())
.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
});
WATCH.call_once(|| {
crate::shutdown::watch(core);
if core.system_test().is_some() {
encore_sdk_core::system_test::set_test_context(crate::testing::outgoing_if_known);
}
});
core
}
pub(crate) fn initialized() -> Option<&'static CoreRuntime> {
RUNTIME.get()
}
pub(crate) fn configured() -> Option<&'static CoreRuntime> {
if RUNTIME.get().is_some() || encore_sdk_core::configured_in_env() {
Some(core())
} else {
None
}
}
fn build(test_runner: bool) -> CoreRuntime {
CoreRuntime::builder()
.with_test_runner(test_runner)
.with_test_mode_from_env()
.with_exec_mode_from_env()
.with_runtime_config_from_env()
.build()
.unwrap_or_else(|e| {
use std::io::Write;
let _ = writeln!(
std::io::stderr(),
"encore: failed to initialize the SDK runtime: {e:#}"
);
std::process::exit(1);
})
}
pub fn initialize() {
core();
crate::pubsub::start_registered();
}
pub fn tokio_handle() -> tokio::runtime::Handle {
core().tokio_handle().clone()
}
pub fn run_blocking() {
crate::pubsub::start_registered();
let handle = tokio_handle();
handle.block_on(crate::shutdown::signal());
let result = handle.block_on(crate::shutdown::drained());
std::process::exit(result.code());
}