use crate::console::ConsoleInternals as _;
use std::ffi::OsString;
use std::net::SocketAddr;
use std::process::ExitCode;
use std::sync::Arc;
use super::connections::LimitedListener;
use super::{Application, LoggingError, shutdown_signal};
use crate::config::dotenv;
use crate::console::markup::clean;
use crate::console::{CommandsInternals as _, Console};
use crate::context::{App, Context, Internals};
use crate::error::ErrorInternals as _;
use crate::errors::panic;
use axum::serve::ListenerExt as _;
use futures_util::{FutureExt, future::FusedFuture};
impl Application {
pub fn run(self) -> ExitCode {
let mut arguments = std::env::args_os();
let program = arguments.next().unwrap_or_else(|| OsString::from("app"));
self.run_with(program, arguments.collect())
}
fn run_with(self, program: OsString, arguments: Vec<OsString>) -> ExitCode {
if tokio::runtime::Handle::try_current().is_ok() {
Console::terminal().error(
"`Application::run` starts its own async runtime, so call it from a synchronous `fn main`; \
inside a runtime, use `Application::serve`",
);
return ExitCode::FAILURE;
}
unsafe { dotenv::export(&self.dotenv) };
let _logs = match self.init_logging() {
Ok(logs) => Some(logs),
Err(LoggingError::AlreadyInstalled) => None,
Err(error) => {
let error: &(dyn std::error::Error + 'static) = &error;
let causes = std::iter::successors(Some(error), |cause| cause.source());
Console::terminal().error(clean(&crate::error::join_causes(causes)));
return ExitCode::FAILURE;
}
};
let runtime = match tokio::runtime::Runtime::new() {
Ok(runtime) => runtime,
Err(error) => {
Console::terminal().error(format!("failed to start the async runtime: {error}"));
return ExitCode::FAILURE;
}
};
let mut console = Console::terminal();
let code = runtime.block_on(self.run_and_finish(program, arguments, &mut console, shutdown_signal()));
runtime.shutdown_timeout(CLOSING);
ExitCode::from(code)
}
async fn run_and_finish(
&self,
program: OsString,
arguments: Vec<OsString>,
console: &mut Console,
interrupted: impl Future<Output = ()>,
) -> u8 {
let code = self.run_command(program, arguments, console).await;
finish(&self.shared, interrupted).await;
code
}
pub(crate) async fn run_command(
&self,
program: OsString,
mut arguments: Vec<OsString>,
console: &mut Console,
) -> u8 {
let started = std::time::Instant::now();
let context = Context::new(Arc::clone(&self.shared), None);
context
.clone()
.scope(async {
let result = panic::catch(async {
self.boot().await?;
default_to_serve(&mut arguments);
let _ = context.local::<CommandApplication>().0.set(self.clone());
let _ = context.local::<crate::console::Invoker>().0.set(self.invoke());
let code = self
.shared
.part::<crate::console::Commands>()
.run(program, arguments, console)
.await?;
console.ensure_written()?;
Ok(code)
})
.await;
let span = crate::console::command_span(&context).entered();
let code = match result {
Ok(code) => {
if code != 0 {
crate::foundation::telemetry::fail(
&span,
&crate::foundation::telemetry::Summary::exit_code(i64::from(code)),
);
}
code
}
Err(error) => {
let code = self.command_failed(&error, console);
if code != 0 {
crate::foundation::telemetry::fail(&span, &error);
}
code
}
};
span.record("process.exit.code", i64::from(code));
tracing::debug!(
target: super::telemetry::COMMAND_TARGET,
exit_code = code,
duration_ms = crate::foundation::telemetry::duration_ms(started.elapsed()),
"Command finished",
);
code
})
.await
}
fn command_failed(&self, error: &crate::Error, console: &mut Console) -> u8 {
if matches!(
error.downcast_ref::<crate::console::PromptError>(),
Some(crate::console::PromptError::Cancelled)
) {
return 130;
}
if crate::console::OutputClosed::is(error) {
return 141;
}
self.shared.reporter.report_for_console(error);
console.error(clean(&format!("{error:#}")));
1
}
pub async fn serve(self, address: impl tokio::net::ToSocketAddrs) -> std::io::Result<()> {
self.serve_with_output(address, &mut Console::terminal()).await
}
pub(super) async fn serve_with_output(
self,
address: impl tokio::net::ToSocketAddrs,
console: &mut Console,
) -> std::io::Result<()> {
let shared = Arc::clone(&self.shared);
let result = async {
self.check_auth_pages().map_err(std::io::Error::other)?;
self.boot()
.await
.map_err(|error| std::io::Error::other(error.for_boot("the application failed to boot")))?;
let listener = tokio::net::TcpListener::bind(address).await?;
self.serve_on(listener, console, shutdown_signal()).await
}
.await;
finish(&shared, shutdown_signal()).await;
result
}
async fn serve_on(
self,
listener: tokio::net::TcpListener,
console: &mut Console,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> std::io::Result<()> {
let address = listener.local_addr()?;
let grace = self.config().server.shutdown_timeout;
let max_connections = self.config().server.max_connections;
let shared = Arc::clone(&self.shared);
crate::task::ticks::start(
&Context::new(Arc::clone(&self.shared), None),
crate::foundation::Host::Server,
);
console.info(format!("Server running at `http://{address}`. Press Ctrl+C to stop."));
let (stopping, stopped) = tokio::sync::oneshot::channel();
let listener = LimitedListener::new(listener, max_connections).tap_io(|_| ());
let server = axum::serve(
listener,
self.router.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async move {
shutdown.await;
shared.shutdown.begin();
let _ = stopping.send(());
});
let deadline = async {
if stopped.await.is_ok() {
console.info(format!("Stopping. Waiting up to {grace} for requests in progress."));
tokio::time::sleep(*grace).await;
} else {
std::future::pending::<()>().await;
}
};
let mut server = std::pin::pin!(server.into_future().fuse());
tokio::select! {
result = async {
let result = server.as_mut().await;
if result.is_err() { self.shared.shutdown.cut_off(); }
self.shared.shutdown.background_finished().await;
self.shared.part::<crate::task::ticks::Ticking>().finish(&self.shared).await;
close_database(&self.shared).await;
result
} => result,
() = deadline => {
console.warn(format!("Stopped with work still in progress after {grace}."));
self.shared.shutdown.cut_off();
let database = close_database(&self.shared);
let _ = tokio::time::timeout(CLOSING, async {
let connections = async {
if !server.is_terminated() { let _ = server.await; }
};
let _ = tokio::join!(connections, self.shared.shutdown.background_finished(), database);
}).await;
Ok(())
}
}
}
}
fn close_database(shared: &App) -> impl Future<Output = ()> + Send + use<> {
#[cfg(feature = "database")]
let closing = shared
.services
.built::<crate::db::DatabaseManager>()
.map(|manager| manager.shutdown());
#[cfg(not(feature = "database"))]
let _ = shared;
async move {
#[cfg(feature = "database")]
if let Some(closing) = closing {
closing.await;
}
}
}
async fn finish(shared: &Arc<App>, interrupted: impl Future<Output = ()>) {
if shared.shutdown.is_stopping() {
return;
}
shared.shutdown.begin();
let grace = shared.config.server.shutdown_timeout;
let mut deadline = tokio::time::Instant::now() + *grace;
let finished = tokio::select! {
biased;
() = shared.shutdown.background_finished() => true,
() = tokio::time::sleep_until(deadline) => {
tracing::warn!(target: super::telemetry::COMMAND_TARGET, "Cutting off background work still in progress after {grace}");
false
}
() = interrupted => {
tracing::warn!(target: super::telemetry::COMMAND_TARGET, "Interrupted: cutting off background work still in progress");
false
}
};
let finished = finished
&& tokio::time::timeout_at(deadline, shared.part::<crate::task::ticks::Ticking>().finish(shared))
.await
.inspect_err(|_| {
tracing::warn!(target: super::telemetry::COMMAND_TARGET, "Cutting off shutdown ticks still running after {grace}");
})
.is_ok();
if !finished {
shared.shutdown.cut_off();
deadline = tokio::time::Instant::now() + CLOSING;
let _ = tokio::time::timeout_at(deadline, shared.shutdown.background_finished()).await;
}
if tokio::time::timeout_at(deadline, close_database(shared)).await.is_err() {
tracing::warn!(target: "laravel::db", "Database shutdown deadline expired with connections still checked out");
}
}
fn default_to_serve(arguments: &mut Vec<OsString>) {
let input = arguments
.iter()
.position(|argument| !crate::console::is_global_option(argument));
if input.is_none_or(|index| {
arguments[index].to_str().is_some_and(|argument| {
argument.starts_with('-') && !matches!(argument, "-h" | "--help" | "-V" | "--version")
})
}) {
arguments.insert(input.unwrap_or(arguments.len()), OsString::from("serve"));
}
}
const CLOSING: std::time::Duration = std::time::Duration::from_secs(1);
#[cfg(test)]
mod tests {
use super::*;
use crate::config::logging::LogChannel;
use crate::event::{self, Event};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::Notify;
use crate::console::clap;
use crate::container::Inject;
use futures_util::future::BoxFuture;
struct Work(std::sync::Mutex<Option<BoxFuture<'static, crate::Result<()>>>>);
#[derive(clap::Parser)]
#[command(name = "work")]
struct WorkCommand;
#[crate::console::command]
impl WorkCommand {
async fn handle(self, work: Inject<Work>) -> crate::Result<()> {
let work = work.0.lock().unwrap().take().expect("each test starts its work once");
crate::task::background(work)?;
Ok(())
}
}
fn working(
work: impl Future<Output = crate::Result<()>> + Send + 'static,
) -> crate::foundation::ApplicationBuilder {
let work = Work(std::sync::Mutex::new(Some(Box::pin(work))));
Application::configure()
.replace_env(crate::config::Env::default())
.with_services(|services| {
services.instance(work);
})
.with_commands(|commands, _| {
commands.add::<WorkCommand>();
})
}
async fn run_and_finish(
app: &Application,
command: &str,
interrupted: impl Future<Output = ()> + Send + 'static,
) -> (u8, Duration) {
let app = app.clone();
let command = OsString::from(command);
let started = Instant::now();
let mut run = tokio::spawn(async move {
app.run_and_finish("app".into(), vec![command], &mut Console::captured(), interrupted)
.await
});
let result = tokio::time::timeout(Duration::from_secs(5), &mut run).await;
if result.is_err() {
run.abort();
}
let code = result
.expect("finishing a command is bounded")
.expect("finishing did not panic");
(code, started.elapsed())
}
struct Dropped(Arc<AtomicUsize>);
impl Drop for Dropped {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_command_waits_for_its_background_work_before_finishing() {
let finished = Arc::new(AtomicUsize::new(0));
let app = working({
let finished = Arc::clone(&finished);
async move {
tokio::time::sleep(Duration::from_millis(100)).await;
assert_eq!(crate::config().app.name, "Laravel");
finished.store(1, Ordering::SeqCst);
Ok(())
}
})
.create();
let (code, _) = run_and_finish(&app, "work", std::future::pending()).await;
assert_eq!(code, 0);
assert_eq!(finished.load(Ordering::SeqCst), 1);
let error = app
.scope(async || crate::task::background(async { Ok(()) }))
.await
.unwrap_err();
assert!(error.to_string().contains("shutting down"));
}
#[tokio::test(flavor = "multi_thread")]
async fn background_failures_are_reported_without_changing_the_exit_code() {
let reported = Arc::new(std::sync::Mutex::new(Vec::new()));
let app = working(async {
tokio::task::yield_now().await;
Err(anyhow::anyhow!("metrics are down").into())
})
.with_errors({
let reported = Arc::clone(&reported);
move |errors, _| {
errors.report_all(move |error| reported.lock().unwrap().push(error.to_string()));
}
})
.create();
let (code, _) = run_and_finish(&app, "work", std::future::pending()).await;
assert_eq!(code, 0);
assert_eq!(*reported.lock().unwrap(), ["metrics are down"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn hung_background_work_is_cut_off_at_the_deadline_or_when_interrupted() {
for interrupt in [false, true] {
let dropped = Arc::new(AtomicUsize::new(0));
let payload = Dropped(Arc::clone(&dropped));
let app = working(async move {
let _payload = payload;
std::future::pending::<crate::Result<()>>().await
})
.with_config(move |config, _| {
config.server.shutdown_timeout = if interrupt {
Duration::from_secs(60).into()
} else {
Duration::from_millis(200).into()
};
})
.create();
let interrupted = async move {
if interrupt {
tokio::time::sleep(Duration::from_millis(100)).await;
} else {
std::future::pending::<()>().await;
}
};
let (code, elapsed) = run_and_finish(&app, "work", interrupted).await;
assert_eq!(code, 0);
assert_eq!(dropped.load(Ordering::SeqCst), 1, "cut-off work is dropped");
assert!(
elapsed >= Duration::from_millis(100),
"waits until cut off: {elapsed:?}"
);
assert!(elapsed < Duration::from_secs(2), "cuts off promptly: {elapsed:?}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn commands_without_background_work_finish_immediately() {
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_config(|config, _| config.server.shutdown_timeout = Duration::from_secs(60).into())
.with_routing(|routing, _| {
routing.web(|route| {
route.get("/", || async { "Home" });
});
})
.create();
let (code, elapsed) = run_and_finish(&app, "route:list", std::future::pending()).await;
assert_eq!(code, 0);
assert!(elapsed < Duration::from_secs(1), "{elapsed:?}");
}
#[tokio::test]
async fn commands_end_quietly_once_nothing_reads_their_output() {
let app = Application::configure()
.replace_env(crate::config::Env::default())
.create();
let mut console = Console::with_closed_stdout();
let code = app
.run_command("app".into(), vec!["route:list".into(), "--json".into()], &mut console)
.await;
assert_eq!(code, 141);
assert_eq!(console.into_output().1, "", "nothing is written to stderr");
}
#[test]
fn failures_after_stdout_closes_still_print_their_message() {
let app = Application::configure()
.replace_env(crate::config::Env::default())
.create();
let mut console = Console::with_closed_stdout();
console.line("a row nobody reads");
let failure = crate::Error::from(std::io::Error::other("The import failed."));
assert_eq!(app.command_failed(&failure, &mut console), 1);
assert_eq!(console.into_output().1, "The import failed.\n");
}
#[test]
fn other_broken_pipes_are_failures() {
let app = Application::configure()
.replace_env(crate::config::Env::default())
.create();
let mut console = Console::captured();
let child = std::io::Error::from(std::io::ErrorKind::BrokenPipe);
assert_eq!(app.command_failed(&crate::Error::from(child), &mut console), 1);
assert!(console.into_output().1.to_lowercase().contains("broken pipe"));
}
#[test]
fn a_builder_whose_application_cant_start_exits_with_a_failure() {
let code = Application::configure()
.replace_env(crate::config::Env::from_iter([("APP_DEBUG", "maybe")]))
.run();
assert_eq!(code, ExitCode::FAILURE);
}
#[test]
fn the_process_stops_when_its_log_files_cant_be_written() {
let file = std::env::temp_dir().join(format!("laravel-unwritable-logs-{}", std::process::id()));
std::fs::write(&file, "").unwrap();
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_config({
let file = file.clone();
move |config, _| {
config.app.base_path = file;
config.logging.channels = vec![LogChannel::stderr(), LogChannel::daily()];
}
})
.create();
let code = app.run_with("app".into(), vec!["route:list".into()]);
let _ = std::fs::remove_file(file);
assert_eq!(code, ExitCode::FAILURE);
}
#[derive(clap::Parser)]
#[command(name = "block")]
struct BlockCommand;
#[crate::console::command]
impl BlockCommand {
async fn handle(self) {
drop(tokio::task::spawn_blocking(|| {
loop {
std::thread::park();
}
}));
}
}
#[test]
fn the_process_exits_without_waiting_for_blocking_work_that_never_returns() {
if std::env::var_os("LARAVEL_TEST_BLOCKING_EXIT").is_some() {
std::thread::spawn(|| {
std::thread::sleep(Duration::from_secs(30));
std::process::exit(101);
});
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_config(|config, _| config.logging.channels = Vec::new())
.with_commands(|commands, _| {
commands.add::<BlockCommand>();
})
.create();
assert_eq!(app.run_with("app".into(), vec!["block".into()]), ExitCode::SUCCESS);
return;
}
let output = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"foundation::console::tests::the_process_exits_without_waiting_for_blocking_work_that_never_returns",
])
.env("LARAVEL_TEST_BLOCKING_EXIT", "1")
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn nested_and_test_commands_leave_background_work_running() {
let release = Arc::new(Notify::new());
let finished = Arc::new(AtomicUsize::new(0));
let app = working({
let release = Arc::clone(&release);
let finished = Arc::clone(&finished);
async move {
release.notified().await;
finished.store(1, Ordering::SeqCst);
Ok(())
}
})
.create();
let code = tokio::time::timeout(
Duration::from_secs(5),
app.run_command("app".into(), vec!["work".into()], &mut Console::captured()),
)
.await
.expect("nested commands do not wait for background work");
assert_eq!(code, 0);
assert_eq!(finished.load(Ordering::SeqCst), 0);
assert!(!app.shared.shutdown.is_stopping());
release.notify_one();
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn server_drains_database_work_before_closing_pools_and_bounds_external_leases() -> crate::Result<()> {
use crate::config::database::ConnectionConfig;
use crate::db::{DatabaseManager, sqlx::Sqlite};
for held_lease in [false, true] {
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_config(|config, _| {
config.server.shutdown_timeout = Duration::from_millis(200).into();
config
.database
.connections
.insert("sqlite".into(), ConnectionConfig::new("sqlite::memory:"));
config.database.default = "sqlite".into();
})
.create();
let manager = app.resolve::<DatabaseManager>().await;
let connection = manager.default_connection()?.typed::<Sqlite>()?;
let pool = connection.native_pool().await?;
let lease = if held_lease { Some(pool.acquire().await?) } else { None };
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let finished = Arc::new(AtomicUsize::new(0));
app.scope({
let entered = Arc::clone(&entered);
let release = Arc::clone(&release);
let finished = Arc::clone(&finished);
async move || {
crate::task::background(async move {
let mut tx = connection.begin().await?;
entered.notify_one();
release.notified().await;
assert_eq!(tx.query("SELECT 42").scalar::<i64>().await?, Some(42));
tx.commit().await?;
assert_eq!(connection.query("SELECT 17").scalar::<i64>().await?, Some(17));
finished.store(1, Ordering::SeqCst);
Ok(())
})
}
})
.await?;
tokio::time::timeout(Duration::from_secs(5), entered.notified())
.await
.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let observer = app.clone();
let (stop, stopped) = tokio::sync::oneshot::channel();
let mut server = tokio::spawn(async move {
app.serve_on(listener, &mut Console::captured(), async {
let _ = stopped.await;
})
.await
});
stop.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(5), observer.shared.shutdown.begun())
.await
.unwrap();
assert!(
!pool.is_closed(),
"in-flight work may still acquire database connections"
);
release.notify_one();
let result = tokio::time::timeout(Duration::from_secs(4), &mut server).await;
if result.is_err() {
server.abort();
}
result
.expect("held native leases cannot hang server shutdown")
.unwrap()?;
assert_eq!(finished.load(Ordering::SeqCst), 1);
assert!(pool.is_closed());
drop(lease);
tokio::time::timeout(Duration::from_secs(5), manager.shutdown())
.await
.unwrap();
assert_eq!(pool.size(), 0);
}
Ok(())
}
#[cfg(feature = "database-sqlite")]
#[tokio::test(flavor = "multi_thread")]
async fn a_command_closes_database_pools_after_its_background_work() -> crate::Result<()> {
use crate::config::database::ConnectionConfig;
use crate::db::{DatabaseManager, sqlx::Sqlite};
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let finished = Arc::new(AtomicUsize::new(0));
let app = working({
let entered = Arc::clone(&entered);
let release = Arc::clone(&release);
let finished = Arc::clone(&finished);
async move {
let connection = crate::resolve::<DatabaseManager>()
.await?
.default_connection()?
.typed::<Sqlite>()?;
let mut tx = connection.begin().await?;
entered.notify_one();
release.notified().await;
assert_eq!(tx.query("SELECT 42").scalar::<i64>().await?, Some(42));
tx.commit().await?;
assert_eq!(connection.query("SELECT 17").scalar::<i64>().await?, Some(17));
finished.store(1, Ordering::SeqCst);
Ok(())
}
})
.with_config(|config, _| {
config
.database
.connections
.insert("sqlite".into(), ConnectionConfig::new("sqlite::memory:"));
config.database.default = "sqlite".into();
})
.create();
let pool = app
.resolve::<DatabaseManager>()
.await
.default_connection()?
.typed::<Sqlite>()?
.native_pool()
.await?;
let finishing = run_and_finish(&app, "work", std::future::pending());
let ((code, _), ()) = tokio::join!(finishing, async {
tokio::time::timeout(Duration::from_secs(5), entered.notified())
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(5), app.shared.shutdown.begun())
.await
.unwrap();
assert!(
!pool.is_closed(),
"background work may still acquire database connections"
);
release.notify_one();
});
assert_eq!(code, 0);
assert_eq!(finished.load(Ordering::SeqCst), 1);
assert!(pool.is_closed());
Ok(())
}
#[tokio::test]
async fn an_idle_server_waits_for_background_work_then_enforces_its_deadline() {
for (complete, event) in [(true, true), (false, true), (true, false), (false, false)] {
struct Payload(Arc<AtomicUsize>);
impl Drop for Payload {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let dropped = Arc::new(AtomicUsize::new(0));
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_config(|config, _| {
config.server.shutdown_timeout = Duration::from_millis(200).into();
})
.with_events({
let entered = Arc::clone(&entered);
let release = Arc::clone(&release);
move |events, _| {
events.listen(move |event: Event<Payload>| {
let entered = Arc::clone(&entered);
let release = Arc::clone(&release);
async move {
entered.notify_one();
release.notified().await;
drop(event);
}
});
}
})
.create();
app.scope(async || {
let payload = Payload(Arc::clone(&dropped));
if event {
event::dispatch_background(payload).unwrap();
} else {
let entered = Arc::clone(&entered);
let release = Arc::clone(&release);
crate::task::background(async move {
entered.notify_one();
release.notified().await;
drop(payload);
Ok(())
})
.unwrap();
}
})
.await;
tokio::time::timeout(Duration::from_secs(5), entered.notified())
.await
.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let observer = app.clone();
let (stop, stopped) = tokio::sync::oneshot::channel();
let mut server = tokio::spawn(async move {
app.serve_on(listener, &mut Console::captured(), async {
let _ = stopped.await;
})
.await
});
stop.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(5), observer.shared.shutdown.begun())
.await
.unwrap();
let error = observer
.scope(async || crate::task::background(async { Ok(()) }))
.await
.unwrap_err();
assert!(error.to_string().contains("shutting down"));
assert!(!server.is_finished(), "background work holds the idle server open");
if complete {
release.notify_one();
}
let result = tokio::time::timeout(Duration::from_secs(5), &mut server).await;
if result.is_err() {
server.abort();
}
result
.expect("shutdown is bounded")
.expect("server did not panic")
.unwrap();
assert_eq!(dropped.load(Ordering::SeqCst), 1);
}
}
fn serving(
app: Application,
) -> (
tokio::sync::oneshot::Sender<()>,
tokio::task::JoinHandle<std::io::Result<()>>,
) {
let (stop, stopped) = tokio::sync::oneshot::channel();
let server = tokio::spawn(async move {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
app.serve_on(listener, &mut Console::captured(), async {
let _ = stopped.await;
})
.await
});
(stop, server)
}
async fn stopped(server: tokio::task::JoinHandle<std::io::Result<()>>) -> std::io::Result<()> {
tokio::time::timeout(Duration::from_secs(5), server)
.await
.expect("shutdown is bounded")
.expect("server did not panic")
}
#[tokio::test]
async fn connections_past_the_limit_wait_until_an_open_one_closes() {
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
async fn request(address: SocketAddr) -> tokio::net::TcpStream {
let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();
stream
.write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
.await
.unwrap();
stream
}
async fn status_line(stream: &mut tokio::net::TcpStream, wait: Duration) -> Option<String> {
let mut buffer = [0; 12];
tokio::time::timeout(wait, stream.read_exact(&mut buffer))
.await
.ok()?
.unwrap();
Some(String::from_utf8_lossy(&buffer).into_owned())
}
for (max, waits) in [(1, true), (0, false)] {
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_config(move |config, _| config.server.max_connections = max)
.create();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
let server = tokio::spawn(async move {
app.serve_on(listener, &mut Console::captured(), async {
let _ = stopped.await;
})
.await
});
let mut first = request(address).await;
let status = status_line(&mut first, Duration::from_secs(5)).await;
assert_eq!(status.as_deref(), Some("HTTP/1.1 404"));
let mut second = request(address).await;
let early = status_line(&mut second, Duration::from_millis(300)).await;
assert_eq!(early.is_none(), waits, "max_connections = {max}");
if waits {
drop(first);
let status = status_line(&mut second, Duration::from_secs(5)).await;
assert_eq!(status.as_deref(), Some("HTTP/1.1 404"));
}
drop(second);
stop.send(()).unwrap();
tokio::time::timeout(Duration::from_secs(5), server)
.await
.expect("shutdown is bounded")
.unwrap()
.unwrap();
}
}
#[tokio::test]
async fn serving_repeats_ticks_through_failures_then_runs_shutdown_ticks_once() {
use crate::time::ToSpan;
struct Ticked(AtomicUsize);
let reported = Arc::new(AtomicUsize::new(0));
let flushed = Arc::new(AtomicUsize::new(0));
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_services(|services| {
services.instance(Ticked(AtomicUsize::new(0)));
})
.with_errors({
let reported = Arc::clone(&reported);
move |errors, _| {
errors.report_all(move |error| {
assert!(error.to_string().contains("tick error"));
assert_eq!(
crate::context::get::<String>("job").as_deref(),
Some("count"),
"reported in the tick's context"
);
reported.fetch_add(1, Ordering::SeqCst);
});
}
})
.with_ticks({
let flushed = Arc::clone(&flushed);
move |ticks, _| {
ticks
.every(20.milliseconds(), |ticked: Inject<Ticked>| async move {
crate::context::add("job", "count");
ticked.0.fetch_add(1, Ordering::SeqCst);
Err::<(), _>(crate::error::fail("tick error"))
})
.immediately();
ticks
.every(1.hour(), move || {
let flushed = Arc::clone(&flushed);
async move {
flushed.fetch_add(1, Ordering::SeqCst);
}
})
.run_on_shutdown();
}
})
.create();
let ticked = app.resolve::<Ticked>().await;
let (stop, server) = serving(app);
tokio::time::timeout(Duration::from_secs(5), async {
while reported.load(Ordering::SeqCst) < 3 {
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.expect("failing ticks keep repeating");
assert_eq!(flushed.load(Ordering::SeqCst), 0);
stop.send(()).unwrap();
stopped(server).await.unwrap();
assert_eq!(flushed.load(Ordering::SeqCst), 1);
let total = ticked.0.load(Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(60)).await;
assert_eq!(ticked.0.load(Ordering::SeqCst), total, "ticks stop with the server");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_worker_runs_the_ticks_its_host_allows_then_their_shutdown_ticks() {
use crate::foundation::Host;
use crate::time::ToSpan;
#[derive(clap::Parser)]
#[command(name = "hosting")]
struct Hosting;
#[crate::console::command]
impl Hosting {
async fn handle(self, events: Inject<Events>) {
crate::task::ticks::start(
&Context::expect("hosting"),
Host::Worker {
connection: "redis".to_owned(),
queues: vec!["high".to_owned()],
},
);
while events.0.lock().unwrap().is_empty() {
tokio::time::sleep(Duration::from_millis(5)).await;
}
}
}
#[derive(Default)]
struct Events(std::sync::Mutex<Vec<String>>);
impl Events {
fn push(&self, event: impl Into<String>) {
self.0.lock().unwrap().push(event.into());
}
}
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_services(|services| {
services.instance(Events::default());
})
.with_commands(|commands, _| {
commands.add::<Hosting>();
})
.with_ticks(|ticks, _| {
ticks
.every(1.hour(), |events: Inject<Events>| async move { events.push("server") })
.immediately()
.when(Host::is_server)
.run_on_shutdown();
ticks
.every(1.hour(), |events: Inject<Events>| async move {
events.push(format!("{:?}", crate::foundation::host()))
})
.immediately()
.when(Host::is_worker);
ticks
.every(1.hour(), |events: Inject<Events>| async move {
events.push("high worker stopping")
})
.when(|host| matches!(host, Host::Worker { queues, .. } if queues == &["high"]))
.run_on_shutdown();
})
.create();
let (code, _) = run_and_finish(&app, "hosting", std::future::pending()).await;
assert_eq!(code, 0);
let events = app.resolve::<Events>().await;
assert_eq!(
*events.0.lock().unwrap(),
[
r#"Some(Worker { connection: "redis", queues: ["high"] })"#,
"high worker stopping"
],
);
assert!(app.host().is_some_and(|host| host.is_worker()));
}
#[tokio::test]
async fn shutdown_ticks_flush_what_background_work_from_requests_buffered() {
use crate::time::ToSpan;
struct Buffer(AtomicUsize);
let flushed = Arc::new(std::sync::Mutex::new(Vec::new()));
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_services(|services| {
services.instance(Buffer(AtomicUsize::new(0)));
})
.with_ticks({
let flushed = Arc::clone(&flushed);
move |ticks, _| {
ticks
.every(1.hour(), move |buffer: Inject<Buffer>| {
let flushed = Arc::clone(&flushed);
async move { flushed.lock().unwrap().push(buffer.0.swap(0, Ordering::SeqCst)) }
})
.run_on_shutdown();
}
})
.create();
let buffer = app.resolve::<Buffer>().await;
app.scope(async || {
crate::task::background(async {
tokio::time::sleep(Duration::from_millis(100)).await;
crate::resolve::<Buffer>().await?.0.fetch_add(1, Ordering::SeqCst);
Ok(())
})
.unwrap();
})
.await;
let (stop, server) = serving(app);
tokio::time::sleep(Duration::from_millis(20)).await;
stop.send(()).unwrap();
stopped(server).await.unwrap();
assert_eq!(
*flushed.lock().unwrap(),
[1],
"the shutdown tick flushed the background work's count"
);
assert_eq!(buffer.0.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn shutdown_waits_for_a_tick_in_progress_within_its_deadline() {
use crate::time::ToSpan;
for complete in [true, false] {
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
let app = Application::configure()
.replace_env(crate::config::Env::default())
.with_config(|config, _| {
config.server.shutdown_timeout = Duration::from_millis(200).into();
})
.with_ticks({
let (entered, release, events) = (Arc::clone(&entered), Arc::clone(&release), Arc::clone(&events));
move |ticks, _| {
let held = Arc::clone(&events);
ticks
.every(1.hour(), move || {
let (entered, release, events) =
(Arc::clone(&entered), Arc::clone(&release), Arc::clone(&held));
async move {
entered.notify_one();
release.notified().await;
events.lock().unwrap().push("held");
}
})
.immediately();
ticks
.every(1.hour(), move || {
let events = Arc::clone(&events);
async move { events.lock().unwrap().push("final") }
})
.run_on_shutdown();
}
})
.create();
let (stop, mut server) = serving(app);
tokio::time::timeout(Duration::from_secs(5), entered.notified())
.await
.unwrap();
stop.send(()).unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(!server.is_finished(), "a tick in progress holds the server open");
if complete {
release.notify_one();
}
let result = tokio::time::timeout(Duration::from_secs(5), &mut server).await;
if result.is_err() {
server.abort();
}
result.expect("shutdown is bounded").unwrap().unwrap();
let expected: &[&str] = if complete { &["held", "final"] } else { &[] };
assert_eq!(*events.lock().unwrap(), expected);
}
}
}
#[derive(Default)]
struct CommandApplication(std::sync::OnceLock<Application>);
impl Application {
fn invoke(&self) -> crate::console::Invoke {
let app = self.clone();
crate::console::Invoke(Arc::new(move |arguments, console| {
let app = app.clone();
Box::pin(async move { app.run_command(OsString::from("app"), arguments, console).await })
}))
}
#[doc(hidden)]
#[must_use]
#[track_caller]
pub fn __of_command() -> Self {
Context::expect("a command's `&Application` argument")
.local::<CommandApplication>()
.0
.get()
.cloned()
.expect("a command takes `&Application` only when the application runs it")
}
}