Skip to main content

hyperlane_plugin_shutdown/
impl.rs

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