use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::OnceLock;
use encore_sdk_core::Runtime as CoreRuntime;
use tokio::sync::watch;
pub use encore_sdk_core::shutdown::ShutdownResult;
static COOPERATIVE: AtomicBool = AtomicBool::new(false);
static DRAINED: AtomicBool = AtomicBool::new(false);
fn signalled() -> &'static watch::Sender<bool> {
static SIGNALLED: OnceLock<watch::Sender<bool>> = OnceLock::new();
SIGNALLED.get_or_init(|| watch::channel(false).0)
}
pub fn signal() -> impl Future<Output = ()> + Send + 'static {
COOPERATIVE.store(true, Ordering::SeqCst);
crate::runtime::core();
let mut rx = signalled().subscribe();
async move {
_ = rx.wait_for(|signalled| *signalled).await;
}
}
pub async fn drained() -> ShutdownResult {
DRAINED.store(true, Ordering::SeqCst);
let core = crate::runtime::core();
begin(core, false);
core.shutdown_controller().mark_application_drained();
completed(core).await
}
fn begin(core: &CoreRuntime, cooperative: bool) {
let _guard = core.tokio_handle().enter();
core.shutdown_controller().begin(cooperative);
}
async fn completed(core: &CoreRuntime) -> ShutdownResult {
let result = core
.shutdown_controller()
.completed()
.await
.unwrap_or_else(|err| {
tracing::error!("failed to await shutdown completion: {err}");
ShutdownResult::Failed
});
crate::console_log::flush();
result
}
pub(crate) fn watch(core: &'static CoreRuntime) {
use encore_sdk_core::encore::runtime::v1::environment::Type;
let testing = core
.config_proto()
.environment
.as_ref()
.is_some_and(|env| env.env_type() == Type::Test);
if testing {
return;
}
let _guard = core.tokio_handle().enter();
let handle = match encore_sdk_core::shutdown::watch(core.shutdown_config().clone()) {
Ok(handle) => handle,
Err(err) => {
tracing::error!("not listening for shutdown signals: {err}");
return;
}
};
core.tokio_handle().spawn(async move {
handle.cancelled().await;
begin(core, COOPERATIVE.load(Ordering::SeqCst));
signalled().send_replace(true);
let result = completed(core).await;
if !DRAINED.load(Ordering::SeqCst) {
std::process::exit(result.code());
}
});
}