Skip to main content

rocketmq_runtime/task/
service_task.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::future::Future;
16use std::sync::atomic::AtomicBool;
17use std::sync::atomic::AtomicU64;
18use std::sync::atomic::Ordering;
19use std::sync::Arc;
20use std::time::Duration;
21use std::time::Instant;
22
23use parking_lot::Mutex;
24use tokio::sync::Notify;
25use tokio::time::timeout;
26use tracing::info;
27use tracing::warn;
28
29use crate::config::DEFAULT_SHUTDOWN_TIMEOUT;
30use crate::shutdown_deadline::ABORT_CONFIRMATION_TIMEOUT;
31use crate::RuntimeError;
32use crate::RuntimeResult;
33use crate::ShutdownDeadline;
34use crate::ShutdownReport;
35use crate::TaskGroup;
36use crate::TaskId;
37
38/// Lifecycle state of a [`ServiceManager`] and the loop it runs.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum ServiceTaskState {
41    /// The service has never been started.
42    NotStarted,
43    /// `start` accepted the request and is spawning the loop.
44    Starting,
45    /// The loop is running.
46    Running,
47    /// A stop was requested and the loop has not finished yet.
48    Stopping,
49    /// The loop finished, or shutdown completed.
50    Stopped,
51}
52
53impl ServiceTaskState {
54    const fn as_bits(self) -> u64 {
55        match self {
56            Self::NotStarted => 0,
57            Self::Starting => 1,
58            Self::Running => 2,
59            Self::Stopping => 3,
60            Self::Stopped => 4,
61        }
62    }
63
64    const fn from_bits(bits: u64) -> Self {
65        match bits {
66            0 => Self::NotStarted,
67            1 => Self::Starting,
68            2 => Self::Running,
69            3 => Self::Stopping,
70            _ => Self::Stopped,
71        }
72    }
73}
74
75const STATE_BITS: u32 = 8;
76const STATE_MASK: u64 = (1 << STATE_BITS) - 1;
77const GENERATION_MASK: u64 = u64::MAX >> STATE_BITS;
78
79fn pack(generation: u64, state: ServiceTaskState) -> u64 {
80    (generation << STATE_BITS) | state.as_bits()
81}
82
83fn generation_of(word: u64) -> u64 {
84    word >> STATE_BITS
85}
86
87fn state_of(word: u64) -> ServiceTaskState {
88    ServiceTaskState::from_bits(word & STATE_MASK)
89}
90
91/// Control state shared by a [`ServiceManager`] and the loop it runs.
92///
93/// One atomic word holds the state together with the generation of the
94/// current run. `start` begins a new generation, so a loop left over from an
95/// earlier run that outlived its shutdown sees itself as stopped and cannot
96/// overwrite the state of the run that replaced it.
97#[derive(Debug)]
98struct ServiceSignals {
99    word: AtomicU64,
100    has_notified: AtomicBool,
101    wait_point: Notify,
102}
103
104impl ServiceSignals {
105    fn new() -> Self {
106        Self {
107            word: AtomicU64::new(pack(0, ServiceTaskState::NotStarted)),
108            has_notified: AtomicBool::new(false),
109            wait_point: Notify::new(),
110        }
111    }
112
113    fn state(&self) -> ServiceTaskState {
114        state_of(self.word.load(Ordering::Acquire))
115    }
116
117    /// Starts a new generation from `NotStarted` or `Stopped`.
118    ///
119    /// Returns the replaced word and the new generation, or the current state
120    /// when a run is still active.
121    fn begin_start(&self) -> Result<(u64, u64), ServiceTaskState> {
122        let mut word = self.word.load(Ordering::Acquire);
123        loop {
124            let state = state_of(word);
125            if !matches!(state, ServiceTaskState::NotStarted | ServiceTaskState::Stopped) {
126                return Err(state);
127            }
128            let generation = generation_of(word).wrapping_add(1) & GENERATION_MASK;
129            match self.word.compare_exchange_weak(
130                word,
131                pack(generation, ServiceTaskState::Starting),
132                Ordering::AcqRel,
133                Ordering::Acquire,
134            ) {
135                Ok(_) => return Ok((word, generation)),
136                Err(actual) => word = actual,
137            }
138        }
139    }
140
141    /// Moves `generation` from `from` to `to`; does nothing if either changed.
142    fn transition(&self, generation: u64, from: ServiceTaskState, to: ServiceTaskState) -> bool {
143        self.word
144            .compare_exchange(
145                pack(generation, from),
146                pack(generation, to),
147                Ordering::AcqRel,
148                Ordering::Acquire,
149            )
150            .is_ok()
151    }
152
153    /// Marks `generation` stopped unless a newer run already replaced it.
154    fn finish(&self, generation: u64) -> bool {
155        self.word
156            .fetch_update(Ordering::AcqRel, Ordering::Acquire, |word| {
157                (generation_of(word) == generation).then(|| pack(generation, ServiceTaskState::Stopped))
158            })
159            .is_ok()
160    }
161
162    /// Requests a stop of the current run and returns its state and generation.
163    fn request_stop(&self) -> (ServiceTaskState, u64) {
164        let mut word = self.word.load(Ordering::Acquire);
165        loop {
166            let state = state_of(word);
167            let generation = generation_of(word);
168            if !matches!(state, ServiceTaskState::Starting | ServiceTaskState::Running) {
169                return (state, generation);
170            }
171            match self.word.compare_exchange_weak(
172                word,
173                pack(generation, ServiceTaskState::Stopping),
174                Ordering::AcqRel,
175                Ordering::Acquire,
176            ) {
177                Ok(_) => return (state, generation),
178                Err(actual) => word = actual,
179            }
180        }
181    }
182
183    fn is_stopped_for(&self, generation: u64) -> bool {
184        let word = self.word.load(Ordering::Acquire);
185        generation_of(word) != generation
186            || matches!(state_of(word), ServiceTaskState::Stopping | ServiceTaskState::Stopped)
187    }
188
189    fn wakeup(&self) {
190        if self
191            .has_notified
192            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
193            .is_ok()
194        {
195            self.wait_point.notify_one();
196        }
197    }
198}
199
200/// Stops the run it belongs to when the loop returns or is aborted.
201struct StopOnExit {
202    signals: Arc<ServiceSignals>,
203    generation: u64,
204}
205
206impl Drop for StopOnExit {
207    fn drop(&mut self) {
208        if self.signals.finish(self.generation) {
209            self.signals.has_notified.store(false, Ordering::Release);
210        }
211    }
212}
213
214/// Control handle passed to [`ServiceTask::run`].
215pub struct ServiceTaskContext {
216    signals: Arc<ServiceSignals>,
217    generation: u64,
218}
219
220impl ServiceTaskContext {
221    /// Creates a context that is not stopped and has no pending wakeup.
222    ///
223    /// [`ServiceManager`] creates the context it passes to [`ServiceTask::run`];
224    /// this constructor lets a test drive a service loop directly.
225    pub fn new() -> Self {
226        Self {
227            signals: Arc::new(ServiceSignals::new()),
228            generation: 0,
229        }
230    }
231
232    /// Returns whether this run was asked to stop, or was replaced by a newer run.
233    pub fn is_stopped(&self) -> bool {
234        self.signals.is_stopped_for(self.generation)
235    }
236
237    /// Waits until woken up or until `interval` elapses.
238    ///
239    /// Returns at once when a wakeup is already pending. Always returns
240    /// `true`, after which the loop does its `on_wait_end` work.
241    pub async fn wait_for_running(&self, interval: Duration) -> bool {
242        if self
243            .signals
244            .has_notified
245            .compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
246            .is_ok()
247        {
248            return true;
249        }
250
251        // A timeout is the normal way to leave the wait.
252        let _ = timeout(interval, self.signals.wait_point.notified()).await;
253        self.signals.has_notified.store(false, Ordering::Release);
254        true
255    }
256
257    /// Wakes the loop if it is waiting, or makes its next wait return at once.
258    pub fn wakeup(&self) {
259        self.signals.wakeup();
260    }
261}
262
263impl Default for ServiceTaskContext {
264    fn default() -> Self {
265        Self::new()
266    }
267}
268
269/// Defines service task behavior.
270#[trait_variant::make(Send)]
271pub trait ServiceTask: Sync {
272    /// Get the service name
273    fn get_service_name(&self) -> String;
274
275    /// implement the service logic here
276    async fn run(&self, context: &ServiceTaskContext);
277
278    /// override for custom behavior
279    async fn on_wait_end(&self) {
280        async {}
281    }
282}
283
284/// Runs a [`ServiceTask`] loop as a service task of an owned task group.
285///
286/// Each run is spawned in a `rocketmq.service-manager` child of the task group
287/// given at construction, so the owner's shutdown report and diagnostics
288/// include it. A stopped manager can be started again.
289///
290/// Shutdown waits no longer than the earliest of the deadline passed to
291/// [`Self::shutdown_until`] and the deadline installed on the parent task
292/// group by an owner that is shutting down. When neither exists, it uses the
293/// runtime's default shutdown budget. An interrupting shutdown is the one
294/// exception: it gives the aborted loop at least one second to confirm its
295/// destruction, so with less than a second left it can return up to one
296/// second after that deadline.
297pub struct ServiceManager<T: ServiceTask + 'static> {
298    service: Arc<T>,
299    signals: Arc<ServiceSignals>,
300    task_handle: Mutex<Option<ServiceTaskHandle>>,
301    last_task_group_shutdown_report: Mutex<Option<ShutdownReport>>,
302    parent_task_group: TaskGroup,
303}
304
305struct ServiceTaskHandle {
306    task_id: TaskId,
307    task_group: TaskGroup,
308}
309
310impl ServiceTaskHandle {
311    async fn shutdown(self, deadline: ShutdownDeadline, interrupt: bool, service_name: &str) -> ShutdownReport {
312        let report = if interrupt {
313            // The abort needs a window to confirm even after the deadline passed.
314            let confirmation = deadline.remaining().max(ABORT_CONFIRMATION_TIMEOUT);
315            if !self.task_group.abort_task_and_wait(self.task_id, confirmation).await {
316                warn!(
317                    "Service thread {} interrupt did not finish before timeout",
318                    service_name
319                );
320            }
321            self.task_group.shutdown(Duration::ZERO).await
322        } else if self.task_group.wait_task(self.task_id, deadline.remaining()).await {
323            self.task_group.shutdown_until(deadline).await
324        } else {
325            warn!("Service thread {} shutdown timeout", service_name);
326            self.task_group.shutdown(Duration::ZERO).await
327        };
328        if !report.is_healthy() {
329            warn!(
330                "Service thread {} shutdown report is unhealthy: {}",
331                service_name,
332                report.to_json()
333            );
334        }
335        report
336    }
337}
338
339fn spawn_service_task<F>(
340    parent_task_group: &TaskGroup,
341    task_name: String,
342    future: F,
343) -> RuntimeResult<ServiceTaskHandle>
344where
345    F: Future<Output = ()> + Send + 'static,
346{
347    let task_group = parent_task_group.component("rocketmq.service-manager");
348    let task_id = task_group
349        .spawn_service(task_name, future)
350        .map_err(|error| RuntimeError::within(crate::RuntimeOperation::SpawnServiceTask, error))?;
351    Ok(ServiceTaskHandle { task_id, task_group })
352}
353
354impl<T: ServiceTask> AsRef<T> for ServiceManager<T> {
355    fn as_ref(&self) -> &T {
356        &self.service
357    }
358}
359
360impl<T: ServiceTask + 'static> ServiceManager<T> {
361    /// Creates a manager whose runs are owned by `parent_task_group`.
362    pub fn new_with_task_group(service: T, parent_task_group: TaskGroup) -> Self {
363        Self::new_arc_with_task_group(Arc::new(service), parent_task_group)
364    }
365
366    /// Creates a manager for a shared service whose runs are owned by
367    /// `parent_task_group`.
368    pub fn new_arc_with_task_group(service: Arc<T>, parent_task_group: TaskGroup) -> Self {
369        Self {
370            service,
371            signals: Arc::new(ServiceSignals::new()),
372            task_handle: Mutex::new(None),
373            last_task_group_shutdown_report: Mutex::new(None),
374            parent_task_group,
375        }
376    }
377
378    /// Starts a run of the service loop.
379    ///
380    /// Starting a manager whose loop is still active only logs a warning.
381    ///
382    /// # Errors
383    ///
384    /// Returns an error if the parent task group no longer accepts work.
385    pub async fn start(&self) -> RuntimeResult<()> {
386        let service_name = self.service.get_service_name();
387        let (replaced, generation) = match self.signals.begin_start() {
388            Ok(started) => started,
389            Err(state) => {
390                warn!(
391                    "Service thread {} is already started, current_state: {:?}",
392                    service_name, state
393                );
394                return Ok(());
395            }
396        };
397        info!("Try to start service thread: {}", service_name);
398
399        let service = self.service.clone();
400        let signals = self.signals.clone();
401        // The service loop is created on the heap by the worker's first poll. An
402        // inline loop would make this future as large as the service's state,
403        // and unoptimized builds copy it at every hop down to the task group.
404        let future = async move {
405            Box::pin(Self::run_internal(service, signals, generation)).await;
406        };
407        let handle = match spawn_service_task(&self.parent_task_group, service_name.clone(), future) {
408            Ok(handle) => handle,
409            Err(error) => {
410                // Nothing was spawned, so restore the state this start replaced.
411                let _ = self.signals.word.compare_exchange(
412                    pack(generation, ServiceTaskState::Starting),
413                    replaced,
414                    Ordering::AcqRel,
415                    Ordering::Acquire,
416                );
417                return Err(error);
418            }
419        };
420
421        // A run that ended on its own leaves its task group behind; release it.
422        let previous = self.task_handle.lock().replace(handle);
423        if let Some(previous) = previous {
424            let _ = previous.task_group.shutdown_now();
425        }
426        self.signals
427            .transition(generation, ServiceTaskState::Starting, ServiceTaskState::Running);
428
429        info!("Started service thread: {}", service_name);
430        Ok(())
431    }
432
433    async fn run_internal(service: Arc<T>, signals: Arc<ServiceSignals>, generation: u64) {
434        let service_name = service.get_service_name();
435        let _stop_on_exit = StopOnExit {
436            signals: signals.clone(),
437            generation,
438        };
439        info!("Service thread {} is running", service_name);
440        signals.transition(generation, ServiceTaskState::Starting, ServiceTaskState::Running);
441
442        let context = ServiceTaskContext { signals, generation };
443        service.run(&context).await;
444
445        info!("Service thread {} has stopped", service_name);
446    }
447
448    /// Stops the service and waits for its loop.
449    ///
450    /// The wait ends at the deadline installed on the parent task group, or
451    /// after the runtime's default shutdown budget when there is none. A loop
452    /// still running then is aborted.
453    ///
454    /// # Errors
455    ///
456    /// Currently always succeeds; the result is kept for callers that
457    /// propagate shutdown failures.
458    pub async fn shutdown(&self) -> RuntimeResult<()> {
459        self.shutdown_inner(false, None).await
460    }
461
462    /// Stops the service like [`Self::shutdown`], aborting the loop at once
463    /// when `interrupt` is set.
464    ///
465    /// # Errors
466    ///
467    /// Currently always succeeds; the result is kept for callers that
468    /// propagate shutdown failures.
469    pub async fn shutdown_with_interrupt(&self, interrupt: bool) -> RuntimeResult<()> {
470        self.shutdown_inner(interrupt, None).await
471    }
472
473    /// Stops the service and waits for its loop no later than `deadline`.
474    ///
475    /// # Errors
476    ///
477    /// Currently always succeeds; the result is kept for callers that
478    /// propagate shutdown failures.
479    pub async fn shutdown_until(&self, deadline: ShutdownDeadline) -> RuntimeResult<()> {
480        self.shutdown_inner(false, Some(deadline)).await
481    }
482
483    /// Stops the service no later than `deadline`, aborting the loop at once
484    /// when `interrupt` is set.
485    ///
486    /// An interrupted loop is given at least one second to confirm the abort,
487    /// so when less than a second of `deadline` remains the call can return up
488    /// to one second after it.
489    ///
490    /// # Errors
491    ///
492    /// Currently always succeeds; the result is kept for callers that
493    /// propagate shutdown failures.
494    pub async fn shutdown_with_interrupt_until(
495        &self,
496        interrupt: bool,
497        deadline: ShutdownDeadline,
498    ) -> RuntimeResult<()> {
499        self.shutdown_inner(interrupt, Some(deadline)).await
500    }
501
502    async fn shutdown_inner(&self, interrupt: bool, requested: Option<ShutdownDeadline>) -> RuntimeResult<()> {
503        let service_name = self.service.get_service_name();
504        let handle = self.task_handle.lock().take();
505        let (state, generation) = self.signals.request_stop();
506        if handle.is_none()
507            && !matches!(
508                state,
509                ServiceTaskState::Starting | ServiceTaskState::Running | ServiceTaskState::Stopping
510            )
511        {
512            warn!("Service thread {} is not running", service_name);
513            return Ok(());
514        }
515
516        info!("Shutdown thread[{}] interrupt={}", service_name, interrupt);
517        self.signals.wakeup();
518
519        let deadline = self.shutdown_deadline(requested);
520        let begin_time = Instant::now();
521        if let Some(handle) = handle {
522            let report = handle.shutdown(deadline, interrupt, &service_name).await;
523            *self.last_task_group_shutdown_report.lock() = Some(report);
524        }
525        info!(
526            "Join thread[{}], elapsed time: {}ms",
527            service_name,
528            begin_time.elapsed().as_millis()
529        );
530
531        self.signals.finish(generation);
532        Ok(())
533    }
534
535    fn shutdown_deadline(&self, requested: Option<ShutdownDeadline>) -> ShutdownDeadline {
536        match (requested, self.parent_task_group.shutdown_deadline()) {
537            (Some(requested), Some(installed)) => requested.earliest(installed),
538            (Some(deadline), None) | (None, Some(deadline)) => deadline,
539            (None, None) => ShutdownDeadline::after(DEFAULT_SHUTDOWN_TIMEOUT),
540        }
541    }
542
543    /// Asks the loop to stop without waiting for it.
544    pub fn make_stop(&self) {
545        let (state, _) = self.signals.request_stop();
546        if matches!(state, ServiceTaskState::Starting | ServiceTaskState::Running) {
547            info!("Make stop thread[{}]", self.service.get_service_name());
548        }
549    }
550
551    /// Wakes the loop if it is waiting, or makes its next wait return at once.
552    pub fn wakeup(&self) {
553        self.signals.wakeup();
554    }
555
556    /// Returns the current lifecycle state.
557    pub fn get_lifecycle_state(&self) -> ServiceTaskState {
558        self.signals.state()
559    }
560
561    /// Returns the shutdown report of the task group used by the last stopped run.
562    pub fn last_task_group_shutdown_report(&self) -> Option<ShutdownReport> {
563        self.last_task_group_shutdown_report.lock().clone()
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use std::future;
570    use std::sync::atomic::AtomicBool;
571    use std::sync::atomic::AtomicUsize;
572    use std::sync::atomic::Ordering;
573    use std::sync::Arc;
574
575    use tokio::sync::Notify;
576    use tokio::time::Duration;
577
578    use super::*;
579    use crate::RuntimeContext;
580
581    /// Counts loop iterations and signals each one.
582    struct CountingService {
583        iterations: Arc<AtomicUsize>,
584        iterated: Arc<Notify>,
585    }
586
587    impl ServiceTask for CountingService {
588        fn get_service_name(&self) -> String {
589            "counting-service".to_string()
590        }
591
592        async fn run(&self, context: &ServiceTaskContext) {
593            while !context.is_stopped() {
594                context.wait_for_running(Duration::from_secs(60)).await;
595                self.on_wait_end().await;
596            }
597        }
598
599        async fn on_wait_end(&self) {
600            self.iterations.fetch_add(1, Ordering::AcqRel);
601            self.iterated.notify_one();
602        }
603    }
604
605    struct PendingService {
606        entered: Arc<Notify>,
607        dropped: Arc<AtomicBool>,
608    }
609
610    struct DropMarker {
611        dropped: Arc<AtomicBool>,
612    }
613
614    impl Drop for DropMarker {
615        fn drop(&mut self) {
616            self.dropped.store(true, Ordering::Release);
617        }
618    }
619
620    impl ServiceTask for PendingService {
621        fn get_service_name(&self) -> String {
622            "pending-service".to_string()
623        }
624
625        async fn run(&self, _context: &ServiceTaskContext) {
626            let _marker = DropMarker {
627                dropped: Arc::clone(&self.dropped),
628            };
629            self.entered.notify_one();
630            future::pending::<()>().await;
631        }
632    }
633
634    fn counting_service() -> (CountingService, Arc<AtomicUsize>, Arc<Notify>) {
635        let iterations = Arc::new(AtomicUsize::new(0));
636        let iterated = Arc::new(Notify::new());
637        (
638            CountingService {
639                iterations: iterations.clone(),
640                iterated: iterated.clone(),
641            },
642            iterations,
643            iterated,
644        )
645    }
646
647    /// Returns a service that never stops on its own, with its entry signal
648    /// and a flag set when its loop future is dropped.
649    fn pending_service() -> (PendingService, Arc<Notify>, Arc<AtomicBool>) {
650        let entered = Arc::new(Notify::new());
651        let dropped = Arc::new(AtomicBool::new(false));
652        (
653            PendingService {
654                entered: entered.clone(),
655                dropped: dropped.clone(),
656            },
657            entered,
658            dropped,
659        )
660    }
661
662    #[tokio::test]
663    async fn service_runs_under_its_parent_task_group() {
664        let context = RuntimeContext::from_current("service-manager-parent-test");
665        let service_context = context.service_context("service-manager-service");
666        let (service, _, _) = counting_service();
667        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
668
669        manager.start().await.unwrap();
670        assert_eq!(service_context.task_group().component_count(), 1);
671        manager.shutdown().await.unwrap();
672        let child_report = manager
673            .last_task_group_shutdown_report()
674            .expect("service manager shutdown report should exist");
675        assert_eq!(child_report.name, "rocketmq.service-manager");
676        assert!(child_report.is_healthy(), "{}", child_report.to_json());
677
678        let report = service_context.task_group().shutdown(Duration::from_secs(1)).await;
679        assert!(report.is_healthy(), "{}", report.to_json());
680        assert!(report.children.is_empty(), "{}", report.to_json());
681    }
682
683    #[tokio::test]
684    async fn lifecycle_moves_through_running_and_stopped() {
685        let context = RuntimeContext::from_current("service-manager-lifecycle-test");
686        let service_context = context.service_context("service-manager-lifecycle");
687        let (service, iterations, iterated) = counting_service();
688        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
689        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::NotStarted);
690
691        manager.start().await.unwrap();
692        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Running);
693
694        let iteration = iterated.notified();
695        manager.wakeup();
696        iteration.await;
697        assert!(iterations.load(Ordering::Acquire) >= 1);
698
699        manager.shutdown().await.unwrap();
700        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Stopped);
701    }
702
703    #[tokio::test]
704    async fn second_start_while_running_is_ignored() {
705        let context = RuntimeContext::from_current("service-manager-multi-start-test");
706        let service_context = context.service_context("service-manager-multi-start");
707        let (service, _, _) = counting_service();
708        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
709
710        manager.start().await.unwrap();
711        manager.start().await.unwrap();
712        assert_eq!(service_context.task_group().component_count(), 1);
713        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Running);
714
715        manager.shutdown().await.unwrap();
716        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Stopped);
717    }
718
719    #[tokio::test]
720    async fn stopped_manager_can_start_again() {
721        let context = RuntimeContext::from_current("service-manager-restart-test");
722        let service_context = context.service_context("service-manager-restart");
723        let (service, _, _) = counting_service();
724        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
725
726        manager.start().await.unwrap();
727        manager.shutdown().await.unwrap();
728        manager.start().await.unwrap();
729        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Running);
730        manager.shutdown().await.unwrap();
731        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Stopped);
732
733        let report = service_context.task_group().shutdown(Duration::from_secs(1)).await;
734        assert!(report.is_healthy(), "{}", report.to_json());
735    }
736
737    #[tokio::test]
738    async fn make_stop_ends_the_loop_without_shutdown() {
739        let context = RuntimeContext::from_current("service-manager-make-stop-test");
740        let service_context = context.service_context("service-manager-make-stop");
741        let (service, _, _) = counting_service();
742        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
743
744        manager.start().await.unwrap();
745        manager.make_stop();
746        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Stopping);
747        manager.wakeup();
748
749        let report = service_context.task_group().shutdown(Duration::from_secs(1)).await;
750        assert!(report.is_healthy(), "{}", report.to_json());
751        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Stopped);
752    }
753
754    #[tokio::test]
755    async fn shutdown_deadline_aborts_a_loop_that_does_not_stop() {
756        let context = RuntimeContext::from_current("service-manager-deadline-test");
757        let service_context = context.service_context("service-manager-deadline");
758        let (service, entered, dropped) = pending_service();
759        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
760
761        manager.start().await.unwrap();
762        entered.notified().await;
763        let started = std::time::Instant::now();
764        manager
765            .shutdown_until(ShutdownDeadline::after(Duration::from_millis(20)))
766            .await
767            .unwrap();
768
769        assert!(
770            started.elapsed() < Duration::from_secs(5),
771            "shutdown should stop at the deadline instead of a fixed join time"
772        );
773        assert!(
774            dropped.load(Ordering::Acquire),
775            "service future should be dropped after the deadline aborts the task"
776        );
777        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Stopped);
778        let report = manager
779            .last_task_group_shutdown_report()
780            .expect("service task group shutdown report should be recorded");
781        assert!(!report.is_healthy(), "{}", report.to_json());
782        assert_eq!(report.aborted, 1, "{}", report.to_json());
783        assert_eq!(report.timed_out, 1, "{}", report.to_json());
784    }
785
786    #[tokio::test]
787    async fn shutdown_follows_the_deadline_installed_by_the_parent_owner() {
788        let context = RuntimeContext::from_current("service-manager-installed-deadline-test");
789        let service_context = context.service_context("service-manager-installed-deadline");
790        let (service, entered, dropped) = pending_service();
791        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
792        manager.start().await.unwrap();
793        entered.notified().await;
794
795        let started = std::time::Instant::now();
796        // The owner installs its deadline when the shutdown call is made, so
797        // the manager's unbounded shutdown below inherits it.
798        let owner_shutdown = service_context.task_group().shutdown(Duration::from_millis(20));
799        let (report, stopped) = tokio::join!(owner_shutdown, manager.shutdown());
800        stopped.unwrap();
801
802        assert!(
803            started.elapsed() < Duration::from_secs(5),
804            "an unbounded shutdown call should inherit the owner's deadline"
805        );
806        assert!(dropped.load(Ordering::Acquire));
807        assert!(!report.is_healthy(), "{}", report.to_json());
808    }
809
810    #[tokio::test]
811    async fn interrupt_aborts_the_loop_at_once() {
812        let context = RuntimeContext::from_current("service-manager-interrupt-test");
813        let service_context = context.service_context("service-manager-interrupt");
814        let (service, entered, dropped) = pending_service();
815        let manager = ServiceManager::new_with_task_group(service, service_context.task_group().clone());
816
817        manager.start().await.unwrap();
818        entered.notified().await;
819        manager.shutdown_with_interrupt(true).await.unwrap();
820
821        assert!(dropped.load(Ordering::Acquire));
822        assert_eq!(manager.get_lifecycle_state(), ServiceTaskState::Stopped);
823    }
824
825    #[test]
826    fn a_replaced_run_sees_itself_stopped() {
827        let signals = Arc::new(ServiceSignals::new());
828        let (_, first) = signals.begin_start().expect("first run starts");
829        let old = ServiceTaskContext {
830            signals: signals.clone(),
831            generation: first,
832        };
833        signals.transition(first, ServiceTaskState::Starting, ServiceTaskState::Running);
834        assert!(!old.is_stopped());
835
836        signals.request_stop();
837        assert!(signals.finish(first));
838        let (_, second) = signals.begin_start().expect("second run starts");
839        signals.transition(second, ServiceTaskState::Starting, ServiceTaskState::Running);
840
841        assert!(old.is_stopped(), "a loop from the first run must not keep running");
842        assert!(!signals.finish(first), "the first run must not stop the second");
843        assert_eq!(signals.state(), ServiceTaskState::Running);
844    }
845
846    #[tokio::test]
847    async fn standalone_context_returns_at_once_for_a_pending_wakeup() {
848        let context = ServiceTaskContext::new();
849        assert!(!context.is_stopped());
850        context.wakeup();
851        assert!(context.wait_for_running(Duration::from_secs(60)).await);
852    }
853}