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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
use super::*;
/// Default construction for [`ShutdownConfig`].
impl Default for ShutdownConfig {
/// Constructs a default [`ShutdownConfig`] with 30 s drain timeout and `SIGINT`/`SIGTERM` enabled.
fn default() -> Self {
Self {
drain_timeout_ms: DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS,
callback_timeout_ms: DEFAULT_SHUTDOWN_CALLBACK_TIMEOUT_MS,
handle_sigint: true,
handle_sigterm: true,
}
}
}
/// Inherent builders for [`ShutdownConfig`].
impl ShutdownConfig {
/// Sets the maximum in-flight drain timeout in milliseconds.
///
/// # Arguments
///
/// - `u64` - Drain timeout in milliseconds.
///
/// # Returns
///
/// - `Self` - Updated configuration.
pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: u64) -> Self {
self.set_drain_timeout_ms(drain_timeout_ms);
self
}
/// Sets the maximum timeout for each [`ShutdownCallback`] in milliseconds.
///
/// # Arguments
///
/// - `u64` - Per-callback timeout in milliseconds.
///
/// # Returns
///
/// - `Self` - Updated configuration.
pub fn with_callback_timeout_ms(mut self, callback_timeout_ms: u64) -> Self {
self.set_callback_timeout_ms(callback_timeout_ms);
self
}
}
/// Drop implementation for [`ShutdownGuard`].
impl Drop for ShutdownGuard {
/// Decrements the owning shard's lock-free in-flight counter and wakes drain waiters upon reaching zero.
#[inline]
fn drop(&mut self) {
let Self { shard } = self;
let prev: usize = shard.state.fetch_sub(1, Ordering::Release);
if prev == (SHUTDOWN_BIT | 1) {
fence(Ordering::SeqCst);
shard.core.drained_notify.notify_waiters();
}
}
}
/// Default construction for [`ShutdownCoordinator`].
impl Default for ShutdownCoordinator {
/// Constructs a default [`ShutdownCoordinator`].
fn default() -> Self {
Self::new(ShutdownConfig::default())
}
}
/// Inherent implementation of [`ShutdownCoordinator`].
impl ShutdownCoordinator {
/// Creates a new [`ShutdownCoordinator`] governed by `config`.
///
/// # Arguments
///
/// - `ShutdownConfig` - Drain timeout and signal handling settings.
///
/// # Returns
///
/// - `Self` - Ready shutdown coordinator.
pub fn new(config: ShutdownConfig) -> Self {
let core: Arc<ShutdownCore> = Arc::new(ShutdownCore {
config,
triggered: AtomicBool::new(false),
shards_armed: AtomicBool::new(false),
shutdown_notify: Notify::new(),
drained_notify: Notify::new(),
callbacks: Vec::new(),
});
let shards: Box<[Arc<ShutdownShard>; SHUTDOWN_SHARD_COUNT]> =
Box::new(from_fn(|_: usize| {
Arc::new(ShutdownShard {
state: AtomicUsize::new(0),
core: Arc::clone(&core),
})
}));
Self {
inner: Arc::new(ShutdownCoordinatorInner { core, shards }),
}
}
/// Registers an async [`ShutdownCallback`] executed in LIFO order during shutdown.
///
/// # Arguments
///
/// - `C` - Concrete [`ShutdownCallback`] implementation.
///
/// # Returns
///
/// - `Self` - New coordinator handle including the registered callback.
pub fn with_callback<C>(self, callback: C) -> Self
where
C: ShutdownCallback,
{
let in_flight_count: usize = self.in_flight();
let Self { inner } = self;
let mut callbacks: Vec<Arc<dyn ShutdownCallback>> = inner.core.callbacks.clone();
callbacks.push(Arc::new(callback));
let already_triggered: bool = inner.core.triggered.load(Ordering::Acquire);
let core: Arc<ShutdownCore> = Arc::new(ShutdownCore {
config: inner.core.config.clone(),
triggered: AtomicBool::new(already_triggered),
shards_armed: AtomicBool::new(already_triggered),
shutdown_notify: Notify::new(),
drained_notify: Notify::new(),
callbacks,
});
let base_bits: usize = if already_triggered { SHUTDOWN_BIT } else { 0 };
let shards: Box<[Arc<ShutdownShard>; SHUTDOWN_SHARD_COUNT]> =
Box::new(from_fn(|idx: usize| {
let initial: usize = if idx == 0 {
base_bits | in_flight_count
} else {
base_bits
};
Arc::new(ShutdownShard {
state: AtomicUsize::new(initial),
core: Arc::clone(&core),
})
}));
Self {
inner: Arc::new(ShutdownCoordinatorInner { core, shards }),
}
}
/// Returns the active [`ShutdownConfig`].
///
/// # Returns
///
/// - `&ShutdownConfig` - Active configuration.
#[inline]
pub fn get_config(&self) -> &ShutdownConfig {
let Self { inner } = self;
&inner.core.config
}
/// Reports whether shutdown has been triggered.
///
/// # Returns
///
/// - `bool` - `true` once shutdown has started.
#[inline]
pub fn is_shutting_down(&self) -> bool {
let Self { inner } = self;
inner.core.shards_armed.load(Ordering::Acquire)
}
/// Returns the current number of active [`ShutdownGuard`] instances across all shards.
///
/// # Returns
///
/// - `usize` - In-flight guard count.
#[inline]
pub fn in_flight(&self) -> usize {
let Self { inner } = self;
let mut total: usize = 0;
for shard in inner.shards.iter() {
total = total.saturating_add(shard.state.load(Ordering::Acquire) & IN_FLIGHT_MASK);
}
total
}
/// Acquires a lock-free RAII [`ShutdownGuard`] on the caller's thread-affine shard if shutdown has not yet started.
///
/// # Returns
///
/// - `Option<ShutdownGuard>` - Active guard, or `None` once shutdown has been triggered.
#[inline]
pub fn enter(&self) -> Option<ShutdownGuard> {
let Self { inner } = self;
let shard: &Arc<ShutdownShard> = &inner.shards[shutdown_shard_index()];
if (shard.state.load(Ordering::Relaxed) & SHUTDOWN_BIT) != 0 {
return None;
}
let prev: usize = shard.state.fetch_add(1, Ordering::Acquire);
if (prev & SHUTDOWN_BIT) != 0 {
let undo: usize = shard.state.fetch_sub(1, Ordering::Release);
if undo == (SHUTDOWN_BIT | 1) {
fence(Ordering::SeqCst);
shard.core.drained_notify.notify_waiters();
}
return None;
}
Some(ShutdownGuard {
shard: Arc::clone(shard),
})
}
/// Triggers shutdown immediately across all shards and wakes all tasks awaiting [`ShutdownCoordinator::wait_triggered`].
pub fn trigger(&self) {
let Self { inner } = self;
if inner.core.shards_armed.load(Ordering::Acquire) {
return;
}
let mut total_in_flight: usize = 0;
for shard in inner.shards.iter() {
let prev: usize = shard.state.fetch_or(SHUTDOWN_BIT, Ordering::AcqRel);
total_in_flight = total_in_flight.saturating_add(prev & IN_FLIGHT_MASK);
}
inner.core.shards_armed.store(true, Ordering::Release);
if !inner.core.triggered.swap(true, Ordering::AcqRel) {
inner.core.shutdown_notify.notify_waiters();
}
if total_in_flight == 0 {
inner.core.drained_notify.notify_waiters();
}
}
/// Waits asynchronously until [`ShutdownCoordinator::trigger`] is invoked.
pub async fn wait_triggered(&self) {
let Self { inner } = self;
if inner.core.triggered.load(Ordering::Acquire) {
return;
}
let mut notified: Pin<&mut Notified<'_>> = pin!(inner.core.shutdown_notify.notified());
notified.as_mut().enable();
if inner.core.triggered.load(Ordering::Acquire) {
return;
}
notified.await;
}
/// Executes full graceful drain, runs registered callbacks in LIFO order, and optionally stops `control`.
///
/// # Arguments
///
/// - `Option<ServerControlHook>` - Optional Hyperlane server control hook to shut down cleanly.
///
/// # Returns
///
/// - `ShutdownReport` - Detailed drain and callback outcome summary.
pub async fn execute_shutdown(&self, control: Option<ServerControlHook>) -> ShutdownReport {
let Self { inner } = self;
let started: Instant = Instant::now();
self.trigger();
let drain_budget: Duration =
Duration::from_millis(inner.core.config.get_drain_timeout_ms());
let drained_cleanly: bool = if self.in_flight() == 0 {
true
} else {
timeout(drain_budget, async {
loop {
let mut notified: Pin<&mut Notified<'_>> =
pin!(inner.core.drained_notify.notified());
notified.as_mut().enable();
fence(Ordering::SeqCst);
if self.in_flight() == 0 {
break;
}
notified.await;
}
})
.await
.is_ok()
};
let remaining_in_flight: usize = self.in_flight();
let cb_budget: Duration =
Duration::from_millis(inner.core.config.get_callback_timeout_ms().max(1));
let mut completed_callbacks: Vec<String> = Vec::with_capacity(inner.core.callbacks.len());
let mut timed_out_callbacks: Vec<String> = Vec::new();
for callback in inner.core.callbacks.iter().rev() {
let name: String = callback.name().to_owned();
if timeout(cb_budget, callback.on_shutdown()).await.is_ok() {
completed_callbacks.push(name);
} else {
timed_out_callbacks.push(name);
}
}
if let Some(hook) = control {
hook.shutdown().await;
}
ShutdownReport {
drained_cleanly,
remaining_in_flight,
completed_callbacks,
timed_out_callbacks,
elapsed_ms: started.elapsed().as_millis() as u64,
}
}
/// Arms a background Tokio task waiting for OS signals or manual [`ShutdownCoordinator::trigger`] to stop `control`.
///
/// # Arguments
///
/// - `ServerControlHook` - Hyperlane server control hook returned by `Server::run`.
///
/// # Returns
///
/// - `JoinHandle<ShutdownReport>` - Join handle resolving to the [`ShutdownReport`] once shutdown completes.
pub fn arm_signals(&self, control: ServerControlHook) -> JoinHandle<ShutdownReport> {
let coordinator: Self = self.clone();
spawn(async move {
let handle_sigint: bool = coordinator.get_config().get_handle_sigint();
let handle_sigterm: bool = coordinator.get_config().get_handle_sigterm();
select! {
_ = coordinator.wait_triggered() => {}
_ = async {
if handle_sigint {
let _: io::Result<()> = ctrl_c().await;
} else {
pending::<()>().await;
}
} => {}
_ = wait_sigterm(handle_sigterm) => {}
}
coordinator.execute_shutdown(Some(control)).await
})
}
}
/// Inherent implementation of [`ShutdownPlugin`].
impl ShutdownPlugin {
/// Initializes the global [`ShutdownPlugin`] once with `coordinator`.
///
/// # Arguments
///
/// - `ShutdownCoordinator` - Configured graceful shutdown coordinator.
///
/// # Returns
///
/// - `&'static Self` - Reference to the initialized global plugin.
pub fn init(coordinator: ShutdownCoordinator) -> &'static Self {
SHUTDOWN_PLUGIN.get_or_init(|| Self { coordinator })
}
/// Returns the initialized global [`ShutdownPlugin`], if initialized.
///
/// # Returns
///
/// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
pub fn get() -> Option<&'static Self> {
SHUTDOWN_PLUGIN.get()
}
/// Returns the shared [`ShutdownCoordinator`].
///
/// # Returns
///
/// - `&ShutdownCoordinator` - Active shutdown coordinator.
pub fn get_coordinator(&self) -> &ShutdownCoordinator {
&self.coordinator
}
}