Minimize main logic

Signed-off-by: eternal-flame-AD <yume@yumechi.jp>
This commit is contained in:
ゆめ 2024-10-16 18:17:30 -05:00
parent ab15f3e3ff
commit c67e647b11
No known key found for this signature in database
2 changed files with 50 additions and 36 deletions

View file

@ -48,42 +48,15 @@ async fn main() {
)
.await;
let (jh, handle) = serve::serve(
serve::run(
state.clone(),
serve::start(
state,
&args.listen,
args.tls_cert.as_deref(),
args.tls_key.as_deref(),
)
.await,
)
.await;
let mut gc_ticker = tokio::time::interval(std::time::Duration::from_secs(300));
gc_ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("Failed to register SIGTERM handler");
tokio::spawn(async move {
loop {
gc_ticker.tick().await;
state
.client_pool_ref()
.gc(std::time::Duration::from_secs(120));
}
});
tokio::select! {
res = jh => {
if let Err(e) = res {
log::error!("Server error: {}", e);
}
}
_ = tokio::signal::ctrl_c() => {
log::info!("Gracefully shutting down...");
handle.graceful_shutdown(Some(std::time::Duration::from_secs(30)));
}
_ = sigterm.recv() => {
log::info!("Received SIGTERM, shutting down...");
handle.graceful_shutdown(Some(std::time::Duration::from_secs(30)));
}
}
}

View file

@ -24,7 +24,7 @@ pub const HAS_TLS_FEATURE: bool = cfg!(feature = "tls");
/// - `tls_key`: The path to the TLS key file
///
/// Use [`tokio::select`] to listen on multiple addresses
pub async fn serve<
pub async fn start<
S: HasAppState<E> + Evaluator<E> + Send + Sync + 'static,
E: IntoResponse + Send + Sync + 'static,
>(
@ -80,3 +80,44 @@ pub async fn serve<
}
}
}
/// Run the server until exit
pub async fn run<
S: HasAppState<E> + Evaluator<E> + Send + Sync + 'static,
E: IntoResponse + Send + Sync + 'static,
>(
state: S,
handle: (JoinHandle<Result<(), std::io::Error>>, Handle),
) {
let (jh, handle) = handle;
let mut gc_ticker = tokio::time::interval(std::time::Duration::from_secs(300));
gc_ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.expect("Failed to register SIGTERM handler");
tokio::spawn(async move {
loop {
gc_ticker.tick().await;
state
.client_pool_ref()
.gc(std::time::Duration::from_secs(120));
}
});
tokio::select! {
res = jh => {
if let Err(e) = res {
log::error!("Server error: {}", e);
}
}
_ = tokio::signal::ctrl_c() => {
log::info!("Gracefully shutting down...");
handle.graceful_shutdown(Some(std::time::Duration::from_secs(30)));
}
_ = sigterm.recv() => {
log::info!("Received SIGTERM, shutting down...");
handle.graceful_shutdown(Some(std::time::Duration::from_secs(30)));
}
}
}