hyperlane_plugin_shutdown/
impl.rs1use super::*;
2
3impl Default for ShutdownConfig {
5 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
16impl ShutdownConfig {
18 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 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
47impl Drop for ShutdownGuard {
49 #[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
61impl Default for ShutdownCoordinator {
63 fn default() -> Self {
65 Self::new(ShutdownConfig::default())
66 }
67}
68
69impl ShutdownCoordinator {
71 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 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 #[inline]
151 pub fn get_config(&self) -> &ShutdownConfig {
152 let Self { inner } = self;
153 &inner.core.config
154 }
155
156 #[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 #[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 #[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 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 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 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 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
330impl ShutdownPlugin {
332 pub fn init(coordinator: ShutdownCoordinator) -> &'static Self {
342 SHUTDOWN_PLUGIN.get_or_init(|| Self { coordinator })
343 }
344
345 pub fn get() -> Option<&'static Self> {
351 SHUTDOWN_PLUGIN.get()
352 }
353
354 pub fn get_coordinator(&self) -> &ShutdownCoordinator {
360 &self.coordinator
361 }
362}