Skip to main content

jax_daemon/process/
utils.rs

1use std::time::Duration;
2
3use tokio::signal::unix::{signal, SignalKind};
4use tokio::sync::watch;
5use tokio::task::JoinHandle;
6
7// NOTE (amiller68): i hate a utils file ... but damn these are useful
8
9const REQUEST_GRACE_PERIOD: Duration = Duration::from_secs(10);
10
11/// Spawns a task that listens for SIGINT and SIGTERM and sends a shutdown signal via a watch.
12///
13/// Returns the join handle, the sender (for programmatic shutdown), and the receiver.
14pub fn graceful_shutdown_blocker() -> (JoinHandle<()>, watch::Sender<()>, watch::Receiver<()>) {
15    let mut sigint = signal(SignalKind::interrupt()).unwrap();
16    let mut sigterm = signal(SignalKind::terminate()).unwrap();
17
18    let (tx, rx) = tokio::sync::watch::channel(());
19    let signal_tx = tx.clone();
20
21    let handle = tokio::spawn(async move {
22        tokio::select! {
23            _ = sigint.recv() => {
24                tracing::debug!("gracefully exiting immediately on SIGINT");
25            }
26            _ = sigterm.recv() => {
27                tokio::time::sleep(REQUEST_GRACE_PERIOD).await;
28                tracing::debug!("initiaing graceful shutdown with delay on SIGTERM");
29            }
30        }
31
32        // Time to start signaling any services that care about gracefully shutting down that the
33        // time is at hand.
34        let _ = signal_tx.send(());
35    });
36
37    (handle, tx, rx)
38}
39
40/// Registers a panic hook that logs panics using the `tracing` crate
41pub fn register_panic_logger() {
42    std::panic::set_hook(Box::new(|panic| match panic.location() {
43        Some(loc) => {
44            tracing::error!(
45                message = %panic,
46                panic.file = loc.file(),
47                panic.line = loc.line(),
48                panic.column = loc.column(),
49            );
50        }
51        None => tracing::error!(message = %panic),
52    }));
53}
54
55pub fn report_build_info() {
56    let build = common::prelude::build_info();
57
58    tracing::info!(
59        build_profile = ?build.build_profile,
60        features = ?build.build_features,
61        version = ?build.version,
62        "service starting up"
63    );
64}