1use async_trait::async_trait;
2use parking_lot::Mutex;
3use std::sync::{
4 Arc,
5 atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
6};
7use std::time::Duration;
8use tokio::sync::{Notify, oneshot};
9use tokio::task::JoinHandle;
10use tokio_util::sync::CancellationToken;
11
12type LcResult<T = ()> = std::result::Result<T, LifecycleError>;
16
17type TaskResult<T = ()> = anyhow::Result<T>;
19
20type ReadyFn<T> = fn(
22 Arc<T>,
23 CancellationToken,
24 ReadySignal,
25)
26 -> std::pin::Pin<Box<dyn std::future::Future<Output = TaskResult<()>> + Send>>;
27
28pub const DEFAULT_READY_WARN_AFTER: Duration = Duration::from_secs(60);
33
34#[inline]
36fn duration_to_ms(d: Duration) -> u64 {
37 u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44#[repr(u8)]
45pub enum Status {
46 Stopped,
47 Starting,
48 Running,
49 Stopping,
50}
51
52impl Status {
53 #[inline]
54 #[must_use]
55 pub const fn as_u8(self) -> u8 {
56 match self {
57 Status::Stopped => 0,
58 Status::Starting => 1,
59 Status::Running => 2,
60 Status::Stopping => 3,
61 }
62 }
63 #[inline]
64 #[must_use]
65 pub const fn from_u8(x: u8) -> Self {
66 match x {
67 1 => Status::Starting,
68 2 => Status::Running,
69 3 => Status::Stopping,
70 _ => Status::Stopped,
71 }
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum StopReason {
78 Finished,
79 Cancelled,
80 Timeout,
81}
82
83pub struct ReadySignal(oneshot::Sender<()>);
87
88impl ReadySignal {
89 #[inline]
90 pub fn notify(self) {
91 if self.0.send(()).is_err() {
92 tracing::debug!("ReadySignal::notify: receiver already dropped");
93 }
94 }
95 #[inline]
97 #[must_use]
98 pub fn from_sender(sender: tokio::sync::oneshot::Sender<()>) -> Self {
99 ReadySignal(sender)
100 }
101}
102
103#[async_trait]
108pub trait Runnable: Send + Sync + 'static {
109 async fn run(self: Arc<Self>, cancel: CancellationToken) -> TaskResult<()>;
111}
112
113#[derive(Debug, thiserror::Error)]
117pub enum LifecycleError {
118 #[error("already started")]
119 AlreadyStarted,
120}
121
122pub struct Lifecycle {
131 name: &'static str,
132 status: Arc<AtomicU8>,
133 handle: Mutex<Option<JoinHandle<()>>>,
134 cancel: Mutex<Option<CancellationToken>>,
135 finished: Arc<AtomicBool>,
137 was_cancelled: Arc<AtomicBool>,
139 finished_notify: Arc<Notify>,
141 ready_warn_after_ms: AtomicU64,
144}
145
146impl Lifecycle {
147 #[must_use]
148 pub fn new_named(name: &'static str) -> Self {
149 Self {
150 name,
151 status: Arc::new(AtomicU8::new(Status::Stopped.as_u8())),
152 handle: Mutex::new(None),
153 cancel: Mutex::new(None),
154 finished: Arc::new(AtomicBool::new(false)),
155 was_cancelled: Arc::new(AtomicBool::new(false)),
156 finished_notify: Arc::new(Notify::new()),
157 ready_warn_after_ms: AtomicU64::new(duration_to_ms(DEFAULT_READY_WARN_AFTER)),
158 }
159 }
160
161 #[must_use]
162 pub fn new() -> Self {
163 Self::new_named("lifecycle")
164 }
165
166 #[must_use]
169 pub fn with_ready_warn_after(self, after: Duration) -> Self {
170 self.set_ready_warn_after(after);
171 self
172 }
173
174 pub fn set_ready_warn_after(&self, after: Duration) {
177 self.ready_warn_after_ms
178 .store(duration_to_ms(after), Ordering::Relaxed);
179 }
180
181 #[inline]
183 #[must_use]
184 pub fn ready_warn_after(&self) -> Duration {
185 Duration::from_millis(self.ready_warn_after_ms.load(Ordering::Relaxed))
186 }
187
188 #[inline]
189 pub fn name(&self) -> &'static str {
190 self.name
191 }
192
193 #[inline]
196 fn load_status(&self) -> Status {
197 Status::from_u8(self.status.load(Ordering::Acquire))
198 }
199
200 #[inline]
201 fn store_status(&self, s: Status) {
202 self.status.store(s.as_u8(), Ordering::Release);
203 }
204
205 #[tracing::instrument(skip(self, make), level = "debug")]
215 pub fn start<F, Fut>(&self, make: F) -> LcResult
216 where
217 F: FnOnce(CancellationToken) -> Fut + Send + 'static,
218 Fut: std::future::Future<Output = TaskResult<()>> + Send + 'static,
219 {
220 self.start_core(CancellationToken::new(), move |tok, _| make(tok), false)
221 }
222
223 #[tracing::instrument(skip(self, make, token), level = "debug")]
228 pub fn start_with_token<F, Fut>(&self, token: CancellationToken, make: F) -> LcResult
229 where
230 F: FnOnce(CancellationToken) -> Fut + Send + 'static,
231 Fut: std::future::Future<Output = TaskResult<()>> + Send + 'static,
232 {
233 self.start_core(token, move |tok, _| make(tok), false)
234 }
235
236 #[tracing::instrument(skip(self, make), level = "debug")]
241 pub fn start_with_ready<F, Fut>(&self, make: F) -> LcResult
242 where
243 F: FnOnce(CancellationToken, ReadySignal) -> Fut + Send + 'static,
244 Fut: std::future::Future<Output = TaskResult<()>> + Send + 'static,
245 {
246 self.start_core(
247 CancellationToken::new(),
248 move |tok, rdy| async move {
249 let Some(rdy) = rdy else {
250 return Err(anyhow::anyhow!("ReadySignal must be present"));
251 };
252 make(tok, rdy).await
253 },
254 true,
255 )
256 }
257
258 #[tracing::instrument(skip(self, make, token), level = "debug")]
263 pub fn start_with_ready_and_token<F, Fut>(&self, token: CancellationToken, make: F) -> LcResult
264 where
265 F: FnOnce(CancellationToken, ReadySignal) -> Fut + Send + 'static,
266 Fut: std::future::Future<Output = TaskResult<()>> + Send + 'static,
267 {
268 self.start_core(
269 token,
270 move |tok, rdy| async move {
271 let Some(rdy) = rdy else {
272 return Err(anyhow::anyhow!("ReadySignal must be present"));
273 };
274 make(tok, rdy).await
275 },
276 true,
277 )
278 }
279
280 fn start_core<F, Fut>(&self, token: CancellationToken, make: F, ready_mode: bool) -> LcResult
285 where
286 F: Send + 'static + FnOnce(CancellationToken, Option<ReadySignal>) -> Fut,
287 Fut: std::future::Future<Output = TaskResult<()>> + Send + 'static,
288 {
289 let cas_ok = self
291 .status
292 .compare_exchange(
293 Status::Stopped.as_u8(),
294 Status::Starting.as_u8(),
295 Ordering::AcqRel,
296 Ordering::Acquire,
297 )
298 .is_ok();
299 if !cas_ok {
300 return Err(LifecycleError::AlreadyStarted);
301 }
302
303 self.finished.store(false, Ordering::Release);
304 self.was_cancelled.store(false, Ordering::Release);
305
306 {
308 let mut c = self.cancel.lock();
309 *c = Some(token.clone());
310 }
311
312 let (ready_tx, ready_rx) = oneshot::channel::<()>();
315 if ready_mode {
316 let status_on_ready = self.status.clone();
317 let ready_warn_after = self.ready_warn_after();
318 let ready_name = self.name;
319 tokio::spawn(async move {
320 let mut ready_rx = ready_rx;
321 let ready_result = match tokio::time::timeout(ready_warn_after, &mut ready_rx).await
322 {
323 Ok(result) => result,
324 Err(_elapsed) => {
325 if Status::from_u8(status_on_ready.load(Ordering::Acquire))
328 == Status::Starting
329 {
330 tracing::error!(
331 gear = %ready_name,
332 timeout_secs = ready_warn_after.as_secs(),
333 "gear did not signal readiness within the deadline; still Starting"
334 );
335 }
336 ready_rx.await
337 }
338 };
339 match ready_result {
340 Ok(()) => {
341 _ = status_on_ready.compare_exchange(
342 Status::Starting.as_u8(),
343 Status::Running.as_u8(),
344 Ordering::AcqRel,
345 Ordering::Acquire,
346 );
347 tracing::debug!("lifecycle status -> running (ready)");
348 }
349 Err(_) => {
350 if Status::from_u8(status_on_ready.load(Ordering::Acquire))
355 == Status::Starting
356 {
357 tracing::warn!(
358 gear = %ready_name,
359 "ready signal dropped before notifying; staying in Starting until finish"
360 );
361 }
362 }
363 }
364 });
365 } else {
366 self.store_status(Status::Running);
367 tracing::debug!("lifecycle status -> running");
368 }
369
370 let finished_flag = self.finished.clone();
371 let finished_notify = self.finished_notify.clone();
372 let status_on_finish = self.status.clone();
373
374 let gear_name = self.name;
376 let task_id = format!("{gear_name}-{self:p}");
377 let handle = tokio::spawn(async move {
378 tracing::debug!(task_id = %task_id, gear = %gear_name, "lifecycle task starting");
379 let res = make(token, ready_mode.then(|| ReadySignal(ready_tx))).await;
380 if let Err(e) = res {
381 tracing::error!(error=%e, task_id=%task_id, gear = %gear_name, "lifecycle task error");
382 }
383 finished_flag.store(true, Ordering::Release);
384 finished_notify.notify_waiters();
385 status_on_finish.store(Status::Stopped.as_u8(), Ordering::Release);
386 tracing::debug!(task_id=%task_id, gear = %gear_name, "lifecycle task finished");
387 });
388
389 {
391 let mut h = self.handle.lock();
392 *h = Some(handle);
393 }
394
395 Ok(())
396 }
397
398 #[tracing::instrument(skip(self, timeout), level = "debug")]
403 pub async fn stop(&self, timeout: Duration) -> LcResult<StopReason> {
404 let gear_name = self.name;
405 let task_id = format!("{gear_name}-{self:p}");
406 let st = self.load_status();
407 if !matches!(st, Status::Starting | Status::Running | Status::Stopping) {
408 return Ok(StopReason::Finished);
410 }
411
412 self.store_status(Status::Stopping);
413
414 if let Some(tok) = { self.cancel.lock().take() } {
416 self.was_cancelled.store(true, Ordering::Release);
417 tok.cancel();
418 }
419
420 let finished_flag = self.finished.clone();
422 let notify = self.finished_notify.clone();
423 let finished_wait = async move {
424 if finished_flag.load(Ordering::Acquire) {
425 return;
426 }
427 notify.notified().await;
428 };
429
430 let reason = tokio::select! {
431 () = finished_wait => {
432 if self.was_cancelled.load(Ordering::Acquire) {
433 StopReason::Cancelled
434 } else {
435 StopReason::Finished
436 }
437 }
438 () = tokio::time::sleep(timeout) => StopReason::Timeout,
439 };
440
441 let handle_opt = { self.handle.lock().take() };
443 if let Some(handle) = handle_opt {
444 if matches!(reason, StopReason::Timeout) && !handle.is_finished() {
445 tracing::warn!("lifecycle stop timed out; aborting task");
446 handle.abort();
447 }
448
449 match handle.await {
450 Ok(()) => {
451 tracing::debug!(task_id = %task_id, gear = %gear_name, "lifecycle task completed successfully");
452 }
453 Err(e) if e.is_cancelled() => {
454 tracing::debug!(task_id = %task_id, gear = %gear_name, "lifecycle task was cancelled/aborted");
455 }
456 Err(e) if e.is_panic() => {
457 match e.try_into_panic() {
459 Ok(panic_payload) => {
460 let panic_msg = panic_payload
461 .downcast_ref::<&str>()
462 .copied()
463 .map(str::to_owned)
464 .or_else(|| panic_payload.downcast_ref::<String>().cloned())
465 .unwrap_or_else(|| "unknown panic".to_owned());
466
467 tracing::error!(
468 task_id = %task_id,
469 gear = %gear_name,
470 panic_message = %panic_msg,
471 "lifecycle task panicked - this indicates a serious bug"
472 );
473 }
474 _ => {
475 tracing::error!(
476 task_id = %task_id,
477 gear = %gear_name,
478 "lifecycle task panicked (could not extract panic message)"
479 );
480 }
481 }
482 }
483 Err(e) => {
484 tracing::warn!(task_id = %task_id, gear = %gear_name, error = %e, "lifecycle task join error");
485 }
486 }
487
488 self.finished.store(true, Ordering::Release);
489 self.finished_notify.notify_waiters();
490 }
491
492 self.store_status(Status::Stopped);
493 tracing::info!(?reason, "lifecycle stopped");
494 Ok(reason)
495 }
496
497 #[inline]
499 #[must_use]
500 pub fn status(&self) -> Status {
501 self.load_status()
502 }
503
504 #[inline]
506 pub fn is_running(&self) -> bool {
507 matches!(self.status(), Status::Starting | Status::Running)
508 }
509
510 #[inline]
512 #[must_use]
513 pub fn try_start<F, Fut>(&self, make: F) -> bool
514 where
515 F: FnOnce(CancellationToken) -> Fut + Send + 'static,
516 Fut: std::future::Future<Output = TaskResult<()>> + Send + 'static,
517 {
518 self.start(make).is_ok()
519 }
520
521 pub async fn wait_stopped(&self) {
523 if self.finished.load(Ordering::Acquire) {
524 return;
525 }
526 self.finished_notify.notified().await;
527 }
528}
529
530impl Default for Lifecycle {
531 fn default() -> Self {
532 Self::new()
533 }
534}
535
536impl Drop for Lifecycle {
537 fn drop(&mut self) {
539 if let Some(tok) = self.cancel.get_mut().take() {
540 tok.cancel();
541 }
542 if let Some(handle) = self.handle.get_mut().take() {
543 handle.abort();
544 }
545 }
546}
547
548#[must_use]
552pub struct WithLifecycle<T: Runnable> {
553 inner: Arc<T>,
554 lc: Arc<Lifecycle>,
555 pub(crate) stop_timeout: Duration,
557 stop_timeout_fn: Option<fn(&T) -> Duration>,
558 await_ready: bool,
560 has_ready_handler: bool,
561 run_ready_fn: Option<ReadyFn<T>>,
562 ready_warn_after: Duration,
564}
565
566impl<T: Runnable> WithLifecycle<T> {
567 pub fn new(inner: T) -> Self {
568 Self {
569 inner: Arc::new(inner),
570 lc: Arc::new(Lifecycle::new_named(std::any::type_name::<T>())),
571 stop_timeout: Duration::from_secs(30),
572 stop_timeout_fn: None,
573 await_ready: false,
574 has_ready_handler: false,
575 run_ready_fn: None,
576 ready_warn_after: DEFAULT_READY_WARN_AFTER,
577 }
578 }
579
580 pub fn from_arc(inner: Arc<T>) -> Self {
581 Self {
582 inner,
583 lc: Arc::new(Lifecycle::new_named(std::any::type_name::<T>())),
584 stop_timeout: Duration::from_secs(30),
585 stop_timeout_fn: None,
586 await_ready: false,
587 has_ready_handler: false,
588 run_ready_fn: None,
589 ready_warn_after: DEFAULT_READY_WARN_AFTER,
590 }
591 }
592
593 pub fn new_with_name(inner: T, name: &'static str) -> Self {
594 Self {
595 inner: Arc::new(inner),
596 lc: Arc::new(Lifecycle::new_named(name)),
597 stop_timeout: Duration::from_secs(30),
598 stop_timeout_fn: None,
599 await_ready: false,
600 has_ready_handler: false,
601 run_ready_fn: None,
602 ready_warn_after: DEFAULT_READY_WARN_AFTER,
603 }
604 }
605
606 pub fn from_arc_with_name(inner: Arc<T>, name: &'static str) -> Self {
607 Self {
608 inner,
609 lc: Arc::new(Lifecycle::new_named(name)),
610 stop_timeout: Duration::from_secs(30),
611 stop_timeout_fn: None,
612 await_ready: false,
613 has_ready_handler: false,
614 run_ready_fn: None,
615 ready_warn_after: DEFAULT_READY_WARN_AFTER,
616 }
617 }
618
619 pub fn with_stop_timeout(mut self, d: Duration) -> Self {
637 self.stop_timeout = d;
638 self.stop_timeout_fn = None;
639 self
640 }
641
642 pub fn with_stop_timeout_fn(mut self, provider: fn(&T) -> Duration) -> Self {
645 self.stop_timeout_fn = Some(provider);
646 self
647 }
648
649 pub fn with_ready_warn_after(mut self, after: Duration) -> Self {
653 self.ready_warn_after = after;
654 self
655 }
656
657 #[inline]
658 #[must_use]
659 pub fn status(&self) -> Status {
660 self.lc.status()
661 }
662
663 #[inline]
664 #[must_use]
665 pub fn inner(&self) -> &T {
666 self.inner.as_ref()
667 }
668
669 #[inline]
671 #[must_use]
672 pub fn inner_arc(&self) -> Arc<T> {
673 self.inner.clone()
674 }
675
676 pub fn with_ready_mode(
678 mut self,
679 await_ready: bool,
680 has_ready_handler: bool,
681 run_ready_fn: Option<ReadyFn<T>>,
682 ) -> Self {
683 self.await_ready = await_ready;
684 self.has_ready_handler = has_ready_handler;
685 self.run_ready_fn = run_ready_fn;
686 self
687 }
688}
689
690impl<T: Runnable + Default> Default for WithLifecycle<T> {
691 fn default() -> Self {
692 Self::new(T::default())
693 }
694}
695
696#[async_trait]
697impl<T: Runnable> crate::contracts::RunnableCapability for WithLifecycle<T> {
698 #[tracing::instrument(skip(self, external_cancel), level = "debug")]
699 async fn start(&self, external_cancel: CancellationToken) -> TaskResult<()> {
700 let inner = self.inner.clone();
701 let composed = external_cancel.child_token();
702
703 self.lc.set_ready_warn_after(self.ready_warn_after);
706
707 if !self.await_ready {
708 self.lc
709 .start_with_token(composed, move |cancel| inner.run(cancel))
710 .map_err(anyhow::Error::from)
711 } else if self.has_ready_handler {
712 let f = self.run_ready_fn.ok_or_else(|| {
713 anyhow::anyhow!("run_ready_fn must be set when has_ready_handler")
714 })?;
715 self.lc
716 .start_with_ready_and_token(composed, move |cancel, ready| f(inner, cancel, ready))
717 .map_err(anyhow::Error::from)
718 } else {
719 self.lc
720 .start_with_ready_and_token(composed, move |cancel, ready| async move {
721 ready.notify();
723 inner.run(cancel).await
724 })
725 .map_err(anyhow::Error::from)
726 }
727 }
728
729 #[tracing::instrument(skip(self, deadline_token), level = "debug")]
739 async fn stop(&self, deadline_token: CancellationToken) -> TaskResult<()> {
740 let timeout = self
741 .stop_timeout_fn
742 .map_or(self.stop_timeout, |provider| provider(&self.inner));
743 tokio::select! {
744 res = self.lc.stop(timeout) => {
745 _ = res.map_err(anyhow::Error::from)?;
746 Ok(())
747 }
748 () = deadline_token.cancelled() => {
749 tracing::debug!("Hard-stop deadline reached, aborting lifecycle");
751 _ = self.lc.stop(Duration::from_millis(0)).await?;
752 Ok(())
753 }
754 }
755 }
756}
757
758impl<T: Runnable> Drop for WithLifecycle<T> {
759 fn drop(&mut self) {
761 if Arc::strong_count(&self.lc) == 1 {
762 if let Some(tok) = self.lc.cancel.lock().as_ref() {
763 tok.cancel();
764 }
765 if let Some(handle) = self.lc.handle.lock().as_ref() {
766 handle.abort();
767 }
768 }
769 }
770}
771
772#[cfg(test)]
775#[cfg_attr(coverage_nightly, coverage(off))]
776mod tests {
777 use super::*;
778 use std::sync::atomic::{AtomicU32, Ordering as AOrd};
779 use tokio::time::{Duration, sleep};
780
781 struct TestRunnable {
782 counter: AtomicU32,
783 }
784
785 impl TestRunnable {
786 fn new() -> Self {
787 Self {
788 counter: AtomicU32::new(0),
789 }
790 }
791 fn count(&self) -> u32 {
792 self.counter.load(AOrd::Relaxed)
793 }
794 }
795
796 #[async_trait::async_trait]
797 impl Runnable for TestRunnable {
798 async fn run(self: Arc<Self>, cancel: CancellationToken) -> TaskResult<()> {
799 let mut interval = tokio::time::interval(Duration::from_millis(10));
800 loop {
801 tokio::select! {
802 _ = interval.tick() => { self.counter.fetch_add(1, AOrd::Relaxed); }
803 () = cancel.cancelled() => break,
804 }
805 }
806 Ok(())
807 }
808 }
809
810 #[tokio::test]
811 async fn lifecycle_basic() {
812 let lc = Arc::new(Lifecycle::new());
813 assert_eq!(lc.status(), Status::Stopped);
814
815 let result = lc.start(|cancel| async move {
816 cancel.cancelled().await;
817 Ok(())
818 });
819 assert!(result.is_ok());
820
821 let stop_result = lc.stop(Duration::from_millis(100)).await;
822 assert!(stop_result.is_ok());
823 assert_eq!(lc.status(), Status::Stopped);
824 }
825
826 #[tokio::test]
827 async fn with_lifecycle_wrapper_basics() {
828 let runnable = TestRunnable::new();
829 let wrapper = WithLifecycle::new(runnable);
830
831 assert_eq!(wrapper.status(), Status::Stopped);
832 assert_eq!(wrapper.inner().count(), 0);
833
834 let wrapper = wrapper.with_stop_timeout(Duration::from_mins(1));
835 assert_eq!(wrapper.stop_timeout.as_secs(), 60);
836 }
837
838 #[tokio::test]
839 async fn start_sets_running_immediately() {
840 let lc = Lifecycle::new();
841 lc.start(|cancel| async move {
842 cancel.cancelled().await;
843 Ok(())
844 })
845 .unwrap();
846
847 let s = lc.status();
848 assert!(matches!(s, Status::Running | Status::Starting));
849
850 let _ = lc.stop(Duration::from_millis(50)).await.unwrap();
851 assert_eq!(lc.status(), Status::Stopped);
852 }
853
854 #[tokio::test]
855 async fn start_with_ready_transitions_and_stop() {
856 let lc = Lifecycle::new();
857
858 let (ready_tx, ready_rx) = oneshot::channel::<()>();
859 lc.start_with_ready(move |cancel, ready| async move {
860 _ = ready_rx.await;
861 ready.notify();
862 cancel.cancelled().await;
863 Ok(())
864 })
865 .unwrap();
866
867 assert_eq!(lc.status(), Status::Starting);
868
869 _ = ready_tx.send(());
870 sleep(Duration::from_millis(10)).await;
871 assert_eq!(lc.status(), Status::Running);
872
873 let reason = lc.stop(Duration::from_millis(100)).await.unwrap();
874 assert!(matches!(
875 reason,
876 StopReason::Cancelled | StopReason::Finished
877 ));
878 assert_eq!(lc.status(), Status::Stopped);
879 }
880
881 #[tokio::test]
882 async fn stop_while_starting_before_ready() {
883 let lc = Lifecycle::new();
884
885 lc.start_with_ready(move |cancel, _ready| async move {
886 cancel.cancelled().await;
887 Ok(())
888 })
889 .unwrap();
890
891 assert_eq!(lc.status(), Status::Starting);
892
893 let reason = lc.stop(Duration::from_millis(100)).await.unwrap();
894 assert!(matches!(
895 reason,
896 StopReason::Cancelled | StopReason::Finished
897 ));
898 assert_eq!(lc.status(), Status::Stopped);
899 }
900
901 #[test]
902 fn ready_warn_after_preserves_the_inner_lifecycle() {
903 let wrapper = WithLifecycle::new_with_name(TestRunnable::new(), "configured");
904 let lifecycle = Arc::as_ptr(&wrapper.lc);
905 let wrapper = wrapper.with_ready_warn_after(Duration::from_secs(7));
906
907 assert_eq!(Arc::as_ptr(&wrapper.lc), lifecycle);
908 assert_eq!(wrapper.lc.name(), "configured");
909 assert_eq!(wrapper.ready_warn_after, Duration::from_secs(7));
910 }
911
912 #[tokio::test]
913 async fn ready_warn_after_on_active_lifecycle_does_not_panic() {
914 use crate::contracts::RunnableCapability;
915 let wrapper = WithLifecycle::new(TestRunnable::new());
918 wrapper.start(CancellationToken::new()).await.unwrap();
919 let wrapper = wrapper.with_ready_warn_after(Duration::from_secs(7));
920 assert_eq!(wrapper.ready_warn_after, Duration::from_secs(7));
921 wrapper.stop(CancellationToken::new()).await.unwrap();
922 }
923
924 #[tokio::test(start_paused = true)]
925 #[tracing_test::traced_test]
926 async fn dropped_ready_signal_logs_a_warning_and_stays_starting() {
927 let lc =
931 Lifecycle::new_named("dropped-ready").with_ready_warn_after(Duration::from_millis(30));
932 lc.start_with_ready(|cancel, ready| async move {
933 drop(ready);
934 cancel.cancelled().await;
935 Ok(())
936 })
937 .unwrap();
938
939 tokio::time::timeout(Duration::from_secs(1), async {
940 while !logs_contain("ready signal dropped before notifying") {
941 sleep(Duration::from_millis(1)).await;
942 }
943 })
944 .await
945 .expect("dropped readiness must be logged immediately");
946 logs_assert(|lines: &[&str]| {
947 if lines.iter().any(|line| {
948 line.contains("ready signal dropped before notifying")
949 && line.contains("WARN")
950 && line.contains("dropped-ready")
951 }) {
952 Ok(())
953 } else {
954 Err("dropped readiness must log a warning naming the gear".to_owned())
955 }
956 });
957 sleep(Duration::from_millis(80)).await;
959 assert!(!logs_contain(
960 "did not signal readiness within the deadline"
961 ));
962 assert_eq!(lc.status(), Status::Starting);
963
964 lc.stop(Duration::from_millis(100)).await.unwrap();
965 assert_eq!(lc.status(), Status::Stopped);
966 }
967
968 #[tokio::test(start_paused = true)]
969 #[tracing_test::traced_test]
970 async fn ready_warn_after_times_out_loudly_but_stays_starting() {
971 let lc = Lifecycle::new_named("slowpoke").with_ready_warn_after(Duration::from_millis(30));
974
975 lc.start_with_ready(move |cancel, ready| async move {
976 let _held = ready; cancel.cancelled().await;
978 Ok(())
979 })
980 .unwrap();
981
982 assert_eq!(lc.status(), Status::Starting);
983
984 sleep(Duration::from_millis(80)).await;
985
986 logs_assert(|lines: &[&str]| {
989 if lines.iter().any(|line| {
990 line.contains("did not signal readiness within the deadline")
991 && line.contains("ERROR")
992 && line.contains("slowpoke")
993 }) {
994 Ok(())
995 } else {
996 Err("expired readiness warning must log an ERROR naming the gear".to_owned())
997 }
998 });
999 assert_eq!(
1000 lc.status(),
1001 Status::Starting,
1002 "must remain Starting, not fatal"
1003 );
1004
1005 let _ = lc.stop(Duration::from_millis(100)).await.unwrap();
1006 assert_eq!(lc.status(), Status::Stopped);
1007 }
1008
1009 #[tokio::test(start_paused = true)]
1010 #[tracing_test::traced_test]
1011 async fn ready_after_deadline_transitions_to_running() {
1012 let lc = Lifecycle::new_named("late-ready").with_ready_warn_after(Duration::from_secs(1));
1013 let (ready_tx, ready_rx) = oneshot::channel::<()>();
1014 lc.start_with_ready(move |cancel, ready| async move {
1015 ready_rx.await.unwrap();
1016 ready.notify();
1017 cancel.cancelled().await;
1018 Ok(())
1019 })
1020 .unwrap();
1021
1022 sleep(Duration::from_secs(2)).await;
1023 assert!(logs_contain("did not signal readiness within the deadline"));
1024 assert_eq!(lc.status(), Status::Starting);
1025
1026 ready_tx.send(()).unwrap();
1027 tokio::time::timeout(Duration::from_secs(1), async {
1028 while lc.status() != Status::Running {
1029 sleep(Duration::from_millis(1)).await;
1030 }
1031 })
1032 .await
1033 .expect("late readiness must transition to Running");
1034
1035 lc.stop(Duration::from_millis(100)).await.unwrap();
1036 assert_eq!(lc.status(), Status::Stopped);
1037 }
1038
1039 #[tokio::test(start_paused = true)]
1040 #[tracing_test::traced_test]
1041 async fn ready_before_deadline_does_not_time_out() {
1042 let lc = Lifecycle::new().with_ready_warn_after(Duration::from_secs(5));
1045
1046 let (ready_tx, ready_rx) = oneshot::channel::<()>();
1047 lc.start_with_ready(move |cancel, ready| async move {
1048 ready_rx.await.unwrap();
1049 ready.notify();
1050 cancel.cancelled().await;
1051 Ok(())
1052 })
1053 .unwrap();
1054
1055 assert_eq!(lc.status(), Status::Starting);
1056 ready_tx.send(()).unwrap();
1057 sleep(Duration::from_millis(20)).await;
1058 assert_eq!(lc.status(), Status::Running);
1059
1060 sleep(Duration::from_secs(6)).await;
1061 assert_eq!(lc.status(), Status::Running);
1062 assert!(!logs_contain(
1063 "did not signal readiness within the deadline"
1064 ));
1065
1066 lc.stop(Duration::from_millis(100)).await.unwrap();
1067 assert_eq!(lc.status(), Status::Stopped);
1068 }
1069
1070 #[tokio::test]
1071 async fn timeout_path_aborts_and_notifies() {
1072 let lc = Lifecycle::new();
1073
1074 lc.start(|_cancel| async move {
1075 loop {
1076 sleep(Duration::from_secs(1000)).await;
1077 }
1078 #[allow(unreachable_code)]
1079 Ok::<_, anyhow::Error>(())
1080 })
1081 .unwrap();
1082
1083 let reason = lc.stop(Duration::from_millis(30)).await.unwrap();
1084 assert_eq!(reason, StopReason::Timeout);
1085 assert_eq!(lc.status(), Status::Stopped);
1086 }
1087
1088 #[tokio::test]
1089 async fn try_start_and_second_start_fails() {
1090 let lc = Lifecycle::new();
1091
1092 assert!(lc.try_start(|cancel| async move {
1093 cancel.cancelled().await;
1094 Ok(())
1095 }));
1096
1097 let err = lc.start(|_c| async { Ok(()) }).unwrap_err();
1098 match err {
1099 LifecycleError::AlreadyStarted => {}
1100 }
1101
1102 let _ = lc.stop(Duration::from_millis(80)).await.unwrap();
1103 assert_eq!(lc.status(), Status::Stopped);
1104 }
1105
1106 #[tokio::test]
1107 async fn stop_is_idempotent_and_safe_concurrent() {
1108 let lc = Arc::new(Lifecycle::new());
1109
1110 lc.start(|cancel| async move {
1111 cancel.cancelled().await;
1112 Ok(())
1113 })
1114 .unwrap();
1115
1116 let a = lc.clone();
1117 let b = lc.clone();
1118 let (r1, r2) = tokio::join!(
1119 async move { a.stop(Duration::from_millis(80)).await },
1120 async move { b.stop(Duration::from_millis(80)).await },
1121 );
1122
1123 let r1 = r1.unwrap();
1124 let r2 = r2.unwrap();
1125 assert!(matches!(
1126 r1,
1127 StopReason::Finished | StopReason::Cancelled | StopReason::Timeout
1128 ));
1129 assert!(matches!(
1130 r2,
1131 StopReason::Finished | StopReason::Cancelled | StopReason::Timeout
1132 ));
1133 assert_eq!(lc.status(), Status::Stopped);
1134 }
1135
1136 #[tokio::test]
1137 async fn stateful_wrapper_start_stop_roundtrip() {
1138 use crate::contracts::RunnableCapability;
1139
1140 let wrapper = WithLifecycle::new(TestRunnable::new());
1141 assert_eq!(wrapper.status(), Status::Stopped);
1142
1143 wrapper.start(CancellationToken::new()).await.unwrap();
1144 assert!(wrapper.lc.is_running());
1145
1146 wrapper.stop(CancellationToken::new()).await.unwrap();
1147 assert_eq!(wrapper.status(), Status::Stopped);
1148 }
1149
1150 #[tokio::test]
1151 async fn with_lifecycle_double_start_fails() {
1152 use crate::contracts::RunnableCapability;
1153
1154 let wrapper = WithLifecycle::new(TestRunnable::new());
1155 let cancel = CancellationToken::new();
1156 wrapper.start(cancel.clone()).await.unwrap();
1157 let err = wrapper.start(cancel).await;
1158 assert!(err.is_err());
1159 wrapper.stop(CancellationToken::new()).await.unwrap();
1160 }
1161
1162 #[tokio::test]
1163 async fn with_lifecycle_concurrent_stop_calls() {
1164 use crate::contracts::RunnableCapability;
1165 let wrapper = Arc::new(WithLifecycle::new(TestRunnable::new()));
1166 wrapper.start(CancellationToken::new()).await.unwrap();
1167 let a = wrapper.clone();
1168 let b = wrapper.clone();
1169 let (r1, r2) = tokio::join!(
1170 async move { a.stop(CancellationToken::new()).await },
1171 async move { b.stop(CancellationToken::new()).await },
1172 );
1173 assert!(r1.is_ok());
1174 assert!(r2.is_ok());
1175 assert_eq!(wrapper.status(), Status::Stopped);
1176 }
1177
1178 #[tokio::test]
1179 async fn lifecycle_handles_panics_properly() {
1180 let lc = Lifecycle::new();
1181
1182 lc.start(|_cancel| async {
1184 panic!("test panic message");
1185 })
1186 .unwrap();
1187
1188 tokio::time::sleep(Duration::from_millis(50)).await;
1190
1191 let reason = lc.stop(Duration::from_secs(1)).await.unwrap();
1193
1194 assert!(matches!(
1197 reason,
1198 StopReason::Finished | StopReason::Cancelled | StopReason::Timeout
1199 ));
1200 assert_eq!(lc.status(), Status::Stopped);
1201 }
1202
1203 #[tokio::test]
1204 async fn lifecycle_task_naming_and_logging() {
1205 let lc = Lifecycle::new();
1206
1207 lc.start(|cancel| async move {
1209 cancel.cancelled().await;
1210 Ok(())
1211 })
1212 .unwrap();
1213
1214 assert!(lc.is_running());
1216
1217 let reason = lc.stop(Duration::from_millis(100)).await.unwrap();
1219 assert!(matches!(
1220 reason,
1221 StopReason::Cancelled | StopReason::Finished
1222 ));
1223 assert_eq!(lc.status(), Status::Stopped);
1224 }
1225
1226 #[tokio::test]
1227 async fn lifecycle_join_handles_all_tasks() {
1228 let lc = Arc::new(Lifecycle::new());
1229
1230 lc.start(|cancel| async move {
1232 tokio::time::sleep(Duration::from_millis(10)).await;
1233 cancel.cancelled().await;
1234 Ok(())
1235 })
1236 .unwrap();
1237
1238 let start = std::time::Instant::now();
1240 let reason = lc.stop(Duration::from_millis(200)).await.unwrap();
1241 let elapsed = start.elapsed();
1242
1243 assert!(elapsed >= Duration::from_millis(10));
1245 assert!(matches!(
1246 reason,
1247 StopReason::Cancelled | StopReason::Finished
1248 ));
1249 assert_eq!(lc.status(), Status::Stopped);
1250 }
1251}