forked from Trustless-OSS/Toss-Backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycle.rs
More file actions
75 lines (59 loc) · 1.81 KB
/
Copy pathlifecycle.rs
File metadata and controls
75 lines (59 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use tracing::{info, warn};
static SHUTTING_DOWN: AtomicBool = AtomicBool::new(false);
static ACTIVE_REQUESTS: AtomicUsize = AtomicUsize::new(0);
pub fn is_shutting_down() -> bool {
SHUTTING_DOWN.load(Ordering::SeqCst)
}
pub fn begin_shutdown() {
if SHUTTING_DOWN.swap(true, Ordering::SeqCst) {
return;
}
info!("Shutdown initiated; new requests should be rejected");
}
pub fn track_active_request() {
ACTIVE_REQUESTS.fetch_add(1, Ordering::SeqCst);
}
pub fn untrack_active_request() {
let current = ACTIVE_REQUESTS.load(Ordering::SeqCst);
if current > 0 {
ACTIVE_REQUESTS.fetch_sub(1, Ordering::SeqCst);
}
}
pub fn get_active_request_count() -> usize {
ACTIVE_REQUESTS.load(Ordering::SeqCst)
}
pub async fn wait_for_active_requests(timeout_ms: u64) {
if get_active_request_count() == 0 {
return;
}
let start = std::time::Instant::now();
while get_active_request_count() > 0 {
if start.elapsed().as_millis() >= timeout_ms as u128 {
warn!(
active_requests = get_active_request_count(),
timeout_ms, "Timed out waiting for active requests"
);
return;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
pub async fn shutdown_signal() {
let ctrl_c = async {
let _ = tokio::signal::ctrl_c().await;
};
#[cfg(unix)]
let terminate = async {
use tokio::signal::unix::{signal, SignalKind};
if let Ok(mut stream) = signal(SignalKind::terminate()) {
let _ = stream.recv().await;
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {}
_ = terminate => {}
}
}