use std::time::Duration;
use servlet::{App, FailureKind, ecosystem::tokio, sync::oneshot, time::timeout};
use super::support::{config, failures};
#[tokio::test]
async fn successful_early_exit_is_a_startup_failure() {
let error = App::new("early")
.config(config())
.worker("short-lived", |ctx| async move {
ctx.ready();
Ok(())
})
.start()
.await
.err()
.unwrap();
assert!(
failures(error)
.iter()
.any(|failure| failure.component == "short-lived"
&& failure.kind == FailureKind::UnexpectedExit)
);
}
#[tokio::test]
async fn a_running_worker_error_stops_its_sibling_and_the_application() {
let (fail, failure) = oneshot::channel();
let (stopped, stopped_rx) = oneshot::channel();
let running = App::new("supervision")
.config(config())
.worker("failing", |ctx| async move {
ctx.ready();
failure.await.unwrap();
Err(std::io::Error::other("worker failure").into())
})
.worker("sibling", |ctx| async move {
ctx.ready();
ctx.shutdown().cancelled().await;
stopped.send(()).unwrap();
Ok(())
})
.start()
.await
.unwrap();
let handle = running.handle();
fail.send(()).unwrap();
let error = timeout(Duration::from_secs(2), running.wait())
.await
.unwrap()
.unwrap_err();
assert!(
failures(error)
.iter()
.any(|failure| failure.component == "failing"
&& matches!(failure.kind, FailureKind::Error(_)))
);
stopped_rx.await.unwrap();
assert!(!handle.is_ready());
assert_eq!(handle.phase(), servlet::Phase::Stopped);
}
#[tokio::test]
async fn a_worker_factory_panic_is_reported_and_cleanup_still_runs() {
let (cleaned, cleanup) = oneshot::channel();
let error = App::new("panic")
.config(config())
.worker(
"factory",
|_| -> std::future::Ready<servlet::task::Result> { panic!("factory panic") },
)
.cleanup("resource", || async move {
cleaned.send(()).unwrap();
Ok(())
})
.start()
.await
.err()
.unwrap();
assert!(
failures(error)
.iter()
.any(|failure| failure.component == "factory" && failure.kind == FailureKind::Panicked)
);
cleanup.await.unwrap();
}
#[tokio::test]
async fn a_panic_after_readiness_is_observed_without_manual_shutdown() {
let (panic_now, trigger) = oneshot::channel();
let running = App::new("panic-running")
.config(config())
.worker("worker", |ctx| async move {
ctx.ready();
trigger.await.unwrap();
panic!("future panic");
})
.start()
.await
.unwrap();
panic_now.send(()).unwrap();
let error = timeout(Duration::from_secs(2), running.wait())
.await
.unwrap()
.unwrap_err();
assert!(
failures(error)
.iter()
.any(|failure| failure.component == "worker" && failure.kind == FailureKind::Panicked)
);
}