Skip to main content

kompact/runtime/
system.rs

1use super::*;
2
3#[cfg(feature = "type_erasure")]
4use crate::utils::erased::CreateErased;
5use crate::{
6    config::Config,
7    supervision::{ComponentSupervisor, ListenEvent, SupervisionPort, SupervisorMsg},
8    timer::timer_manager::{CanCancelTimers, TimerRefFactory},
9    utils::BlockingFutureExt,
10};
11#[cfg(feature = "distributed")]
12use crate::{
13    messaging::{
14        DispatchEnvelope,
15        MsgEnvelope,
16        PathResolvable,
17        RegistrationEnvelope,
18        RegistrationError,
19        RegistrationResult,
20    },
21    routing::groups::StorePolicy,
22};
23use oncemutex::{OnceMutex, OnceMutexGuard};
24use std::{
25    any::{Any, TypeId},
26    fmt,
27    future::Future,
28    sync::Mutex,
29    time::{Duration, Instant},
30};
31
32use futures::FutureExt;
33use snafu::ResultExt;
34
35const STARTUP_POLL_INTERVAL: Duration = Duration::from_millis(50);
36
37/// A Kompact system is a collection of components and services
38///
39/// An instance of `KompactSystem` is created from a [KompactConfig](KompactConfig)
40/// via the [build](KompactConfig::build) function.
41///
42/// It is possible to run more than one Kompact system in a single process.
43/// This allows different settings to be used for different component groups, for example.
44/// It can also be used for testing communication in unit or integration tests.
45///
46/// # Note
47///
48/// For some schedulers it can happen that components may switch from one system's scheduler to the
49/// other's when running multiple systems in the same process and communicating between them via channels
50/// or actor references.
51/// Generally, this shouldn't be an issue, but it can invalidate assumptions on thread assignments, so it's
52/// important to be aware of. If this behaviour needs to be avoided at all costs, one can either use a scheduler
53/// that doesn't use thread-local variables to determine the target queue
54/// (e.g., [`crossbeam_channel_pool`](executors::crossbeam_channel_pool)),
55/// or limit cross-system communication to network-only,
56/// incurring the associated serialisation/deserialisations costs.
57///
58/// # Example
59///
60/// Build a system with default settings with:
61///
62/// ```
63/// use kompact::prelude::*;
64///
65/// let system = KompactConfig::default().build().wait().expect("system");
66/// # system.shutdown().wait().expect("shutdown");
67/// ```
68#[derive(Clone)]
69pub struct KompactSystem {
70    inner: Arc<KompactRuntime>,
71    config: Arc<Config>,
72    scheduler: Box<dyn Scheduler>,
73}
74
75struct PendingKompactSystem {
76    system: KompactSystem,
77    deadletter_ready: KFuture<()>,
78    dispatcher_ready: KFuture<()>,
79}
80
81impl PendingKompactSystem {
82    /// Wait until the internal components have announced readiness.
83    ///
84    /// The deadletter box and dispatcher are started on Kompact scheduler threads
85    /// before this future is polled. The future waits for their readiness promises
86    /// without entering a nested executor, and periodically wakes up to report a
87    /// poisoned runtime instead of waiting forever.
88    async fn await_ready(self) -> Result<KompactSystem, KompactError> {
89        let PendingKompactSystem {
90            system,
91            deadletter_ready,
92            dispatcher_ready,
93        } = self;
94        Self::await_component_ready(&system, deadletter_ready).await?;
95        Self::await_component_ready(&system, dispatcher_ready).await?;
96        Ok(system)
97    }
98
99    async fn await_component_ready(
100        system: &KompactSystem,
101        mut ready: KFuture<()>,
102    ) -> Result<(), KompactError> {
103        loop {
104            if system.inner.is_poisoned() {
105                return Err(KompactError::Poisoned);
106            }
107            match async_std::future::timeout(STARTUP_POLL_INTERVAL, &mut ready).await {
108                Ok(Ok(())) => return Ok(()),
109                Ok(Err(e)) => return Err(KompactError::from_other(e)),
110                // This is only the periodic timeout; keep waiting after checking poison above.
111                Err(_timeout) => continue,
112            }
113        }
114    }
115}
116
117impl KompactSystem {
118    pub(crate) fn build_from_config(
119        conf: KompactConfig,
120    ) -> impl Future<Output = Result<Self, KompactError>> + Unpin + 'static {
121        async move {
122            let pending = Self::prepare_new(conf)?;
123            pending.await_ready().await
124        }
125        .boxed_local()
126    }
127
128    fn load_config(conf: &KompactConfig) -> Result<Config, KompactError> {
129        let mut config = Config::new();
130        for source in &conf.config_sources {
131            let next = source.load()?;
132            config.merge(next);
133        }
134        Ok(config)
135    }
136
137    /// Use the [build](KompactConfig::build) method instead.
138    fn prepare_new(mut conf: KompactConfig) -> Result<PendingKompactSystem, KompactError> {
139        let config = Self::load_config(&conf)?;
140        conf.override_from_config(&config)?;
141
142        let scheduler = (*conf.scheduler_builder)(conf.threads);
143        let sc_builder = conf.sc_builder.clone();
144
145        let runtime = Arc::new(KompactRuntime::new(conf));
146        let sys = KompactSystem {
147            inner: runtime,
148            config: Arc::new(config),
149            scheduler,
150        };
151        let (dead_prom, dead_f) = utils::promise();
152        let (disp_prom, disp_f) = utils::promise();
153        let system_components = (*sc_builder)(&sys, dead_prom, disp_prom);
154        let supervisor = sys.create_unsupervised(ComponentSupervisor::new);
155        let ic = InternalComponents::new(supervisor, system_components);
156        sys.inner.set_internal_components(ic);
157        sys.inner.start_internal_components(&sys);
158        Ok(PendingKompactSystem {
159            system: sys,
160            deadletter_ready: dead_f,
161            dispatcher_ready: disp_f,
162        })
163    }
164
165    #[allow(dead_code)]
166    // Only used in testing
167    pub(crate) fn get_system_components(&self) -> &dyn SystemComponents {
168        self.inner.get_internal_components().get_system_components()
169    }
170
171    pub(crate) fn dispatcher_ref(&self) -> DispatcherRef {
172        self.inner.assert_active();
173        self.inner.dispatcher_ref()
174    }
175
176    pub(crate) fn schedule(&self, c: Arc<dyn CoreContainer>) -> () {
177        self.scheduler.schedule(c);
178    }
179
180    /// Get a reference to the system-wide Kompact logger
181    ///
182    /// # Example
183    ///
184    /// ```
185    /// # use kompact::prelude::*;
186    /// # let system = KompactConfig::default().build().wait().expect("system");
187    /// info!(system.logger(), "Hello World from the system logger!");
188    /// # system.shutdown().wait().expect("shutdown");
189    /// ```
190    pub fn logger(&self) -> &KompactLogger {
191        &self.inner.logger
192    }
193
194    /// Get a reference to the system configuration
195    ///
196    /// Use [load_config_str](KompactConfig::load_config_str) or
197    /// [load_config_file](KompactConfig::load_config_file)
198    /// to load values into the config object.
199    ///
200    /// # Example
201    ///
202    /// ```
203    /// use kompact::prelude::*;
204    /// let default_values = r#"a = 7"#;
205    /// let mut conf = KompactConfig::default();
206    /// conf.load_config_str(default_values);
207    /// let system = conf.build().wait().expect("system");
208    /// assert_eq!(Some(7i64), system.config()["a"].as_i64());
209    /// ```
210    pub fn config(&self) -> &Config {
211        self.config.as_ref()
212    }
213
214    /// Get a owned reference to the system configuration
215    pub fn config_owned(&self) -> Arc<Config> {
216        self.config.clone()
217    }
218
219    /// Returns the current time according to the system timer.
220    pub fn now(&self) -> Instant {
221        self.inner.assert_not_poisoned();
222        self.inner.timer_ref().now()
223    }
224
225    pub(crate) fn poison(&self) {
226        self.inner.poison();
227        self.scheduler.poison();
228    }
229
230    /// Create a new component
231    ///
232    /// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),
233    /// which is the initialised to form a [Component](Component).
234    /// Since components are shared between threads, the created component
235    /// is wrapped into an [Arc](std::sync::Arc).
236    ///
237    /// Newly created components are not started automatically.
238    /// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)
239    /// to start a newly created component, once it is connected properly.
240    ///
241    /// If you need address this component via the network, see the [register](KompactSystem::register) function.
242    ///
243    /// # Example
244    ///
245    /// ```
246    /// # use kompact::prelude::*;
247    /// # use kompact::doctest_helpers::*;
248    /// # let system = KompactConfig::default().build().wait().expect("system");
249    /// let c = system.create(TestComponent1::new);
250    /// # system.shutdown().wait().expect("shutdown");
251    /// ```
252    pub fn create<C, F>(&self, f: F) -> Arc<Component<C>>
253    where
254        F: FnOnce() -> C,
255        C: ComponentDefinition + 'static,
256    {
257        self.inner.assert_active();
258        let c = Arc::new(Component::new(self.clone(), f(), self.supervision_port()));
259        {
260            let mut mutable_core = c.mutable_core.lock().unwrap();
261            let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
262            mutable_core.definition.setup(c.clone());
263            c.core().set_component(cc);
264        }
265        c
266    }
267
268    /// Create a new component from type-erased definition
269    ///
270    /// Since components are shared between threads, the created component
271    /// is internally wrapped into an [Arc](std::sync::Arc).
272    ///
273    /// Newly created components are not started automatically.
274    /// Use [start](KompactSystem::start) or
275    /// [start_notify](KompactSystem::start_notify) to start a newly
276    /// created component, once it is connected properly.
277    ///
278    /// If you need address this component via the network, see the [register](KompactSystem::register) function.
279    ///
280    /// # Example
281    ///
282    /// ```
283    /// # use kompact::prelude::*;
284    /// # use kompact::doctest_helpers::*;
285    /// # let system = KompactConfig::default().build().wait().expect("system");
286    /// let c = system.create_erased(Box::new(TestComponent1::new()));
287    /// # system.shutdown().wait().expect("shutdown");
288    /// ```
289    #[cfg(feature = "type_erasure")]
290    #[inline(always)]
291    pub fn create_erased<M: MessageBounds>(
292        &self,
293        a: Box<dyn CreateErased<M>>,
294    ) -> Arc<dyn AbstractComponent<Message = M>> {
295        a.create_in(self)
296    }
297
298    /// Create a new system component
299    ///
300    /// You *must* use this instead of [create](KompactSystem::create) to create
301    /// a new system component.
302    /// During system initialisation the supervisor is not available, yet,
303    /// so normal [create](KompactSystem::create) calls will panic!
304    pub fn create_unsupervised<C, F>(&self, f: F) -> Arc<Component<C>>
305    where
306        F: FnOnce() -> C,
307        C: ComponentDefinition + 'static,
308    {
309        let c = Arc::new(Component::without_supervisor(self.clone(), f()));
310        {
311            let mut mutable_core = c.mutable_core.lock().unwrap();
312            mutable_core.definition.setup(c.clone());
313            let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
314            c.core().set_component(cc);
315        }
316        c
317    }
318
319    /// Create a new component, which runs on its own dedicated thread.
320    ///
321    /// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),
322    /// which is the initialised to form a [Component](Component).
323    /// Since components are shared between threads, the created component
324    /// is wrapped into an [Arc](std::sync::Arc).
325    ///
326    /// A dedicated thread is assigned to this component, which sleeps when the component has no work.
327    ///
328    /// Newly created components are not started automatically.
329    /// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)
330    /// to start a newly created component, once it is connected properly.
331    ///
332    /// If you need address this component via the network, see the [register](KompactSystem::register) function.
333    pub fn create_dedicated<C, F>(&self, f: F) -> Arc<Component<C>>
334    where
335        F: FnOnce() -> C,
336        C: ComponentDefinition + 'static,
337    {
338        self.inner.assert_active();
339        let (scheduler, promise) =
340            dedicated_scheduler::DedicatedThreadScheduler::new().expect("Scheduler");
341        let c = Arc::new(Component::with_dedicated_scheduler(
342            self.clone(),
343            f(),
344            self.supervision_port(),
345            scheduler,
346        ));
347        {
348            let mut mutable_core = c.mutable_core.lock().unwrap();
349            let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
350            mutable_core.definition.setup(c.clone());
351            c.core().set_component(cc);
352        }
353        promise.fulfil(c.clone()).expect("Should accept component");
354        c
355    }
356
357    /// Create a new component, which runs on its own dedicated thread and is pinned to certain CPU core.
358    ///
359    /// This functionality is only available with feature `thread_pinning`.
360    ///
361    /// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),
362    /// which is the initialised to form a [Component](Component).
363    /// Since components are shared between threads, the created component
364    /// is wrapped into an [Arc](std::sync::Arc).
365    ///
366    /// A dedicated thread is assigned to this component, which sleeps when the component has no work.
367    /// The thread is also pinned to the given `core_id`, allowing static, manual, NUMA aware component assignments.
368    ///
369    /// Newly created components are not started automatically.
370    /// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)
371    /// to start a newly created component, once it is connected properly.
372    ///
373    /// If you need address this component via the network, see the [register](KompactSystem::register) function.
374    #[cfg(feature = "thread_pinning")]
375    pub fn create_dedicated_pinned<C, F>(&self, f: F, core_id: CoreId) -> Arc<Component<C>>
376    where
377        F: FnOnce() -> C,
378        C: ComponentDefinition + 'static,
379    {
380        self.inner.assert_active();
381        let (scheduler, promise) =
382            dedicated_scheduler::DedicatedThreadScheduler::pinned(core_id).expect("Scheduler");
383        let c = Arc::new(Component::with_dedicated_scheduler(
384            self.clone(),
385            f(),
386            self.supervision_port(),
387            scheduler,
388        ));
389        {
390            let mut mutable_core = c.mutable_core.lock().unwrap();
391            let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
392            mutable_core.definition.setup(c.clone());
393            c.core().set_component(cc);
394        }
395        promise.fulfil(c.clone()).expect("Should accept component");
396        c
397    }
398
399    /// Create a new system component, which runs on its own dedicated thread.
400    ///
401    /// A dedicated thread is assigned to this component, which sleeps when the component has no work.
402    ///
403    /// You *must* use this instead of [create_dedicated](KompactSystem::create_dedicated) to create
404    /// a new system component on its own thread.
405    /// During system initialisation the supervisor is not available, yet,
406    /// so normal [create](KompactSystem::create) calls will panic!
407    pub fn create_dedicated_unsupervised<C, F>(&self, f: F) -> Arc<Component<C>>
408    where
409        F: FnOnce() -> C,
410        C: ComponentDefinition + 'static,
411    {
412        let (scheduler, promise) =
413            dedicated_scheduler::DedicatedThreadScheduler::new().expect("Scheduler");
414        let c = Arc::new(Component::without_supervisor_with_dedicated_scheduler(
415            self.clone(),
416            f(),
417            scheduler,
418        ));
419        {
420            let mut mutable_core = c.mutable_core.lock().unwrap();
421            mutable_core.definition.setup(c.clone());
422            let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
423            c.core().set_component(cc);
424        }
425        promise.fulfil(c.clone()).expect("Should accept component");
426        c
427    }
428
429    /// Create a new system component, which runs on its own dedicated thread.
430    ///
431    /// A dedicated thread is assigned to this component, which sleeps when the component has no work.
432    /// The thread is also pinned to the given `core_id`, allowing static, manual, NUMA aware component assignments.
433    ///
434    /// You *must* use this instead of [create_dedicated_pinned](KompactSystem::create_dedicated_pinned) to create
435    /// a new system component on its own thread.
436    /// During system initialisation the supervisor is not available, yet,
437    /// so normal [create](KompactSystem::create) calls will panic!
438    #[cfg(feature = "thread_pinning")]
439    pub fn create_dedicated_pinned_unsupervised<C, F>(
440        &self,
441        f: F,
442        core_id: CoreId,
443    ) -> Arc<Component<C>>
444    where
445        F: FnOnce() -> C,
446        C: ComponentDefinition + 'static,
447    {
448        let (scheduler, promise) =
449            dedicated_scheduler::DedicatedThreadScheduler::pinned(core_id).expect("Scheduler");
450        let c = Arc::new(Component::without_supervisor_with_dedicated_scheduler(
451            self.clone(),
452            f(),
453            scheduler,
454        ));
455        {
456            let mut mutable_core = c.mutable_core.lock().unwrap();
457            mutable_core.definition.setup(c.clone());
458            let cc: Arc<dyn CoreContainer> = c.clone() as Arc<dyn CoreContainer>;
459            c.core().set_component(cc);
460        }
461        promise.fulfil(c.clone()).expect("Should accept component");
462        c
463    }
464
465    /// Attempts to register `c` with the dispatcher using its unique id
466    ///
467    /// The returned future will contain the unique id [ActorPath](ActorPath)
468    /// for the given component, once it is completed by the dispatcher.
469    ///
470    /// Once the future completes, the component can be addressed via the network,
471    /// even if it has not been started, yet (in which case messages will simply be queued up).
472    ///
473    /// # Example
474    ///
475    /// ```
476    /// use kompact::prelude::*;
477    /// # use kompact::doctest_helpers::*;
478    /// use std::time::Duration;
479    /// let system = KompactConfig::default().build().wait().expect("KompactSystem");
480    /// let c = system.create(TestComponent1::new);
481    /// system.register(&c).wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1");
482    /// # system.shutdown().wait().expect("shutdown");
483    /// ```
484    #[cfg(feature = "distributed")]
485    pub fn register(&self, c: &dyn UniqueRegistrable) -> KFuture<RegistrationResult> {
486        self.inner.assert_active();
487        let id = c.component_id();
488        let id_path = PathResolvable::ActorId(id);
489        self.inner.register_by_path(c.dyn_ref(), false, id_path) // never update unique registrations
490    }
491
492    /// Creates a new component and registers it with the dispatcher
493    ///
494    /// This function is simply a convenience shortcut for
495    /// [create](KompactSystem::create) followed by [register](KompactSystem::register),
496    /// as this combination is very common in networked Kompact systems.
497    ///
498    /// # Example
499    ///
500    /// ```
501    /// use kompact::prelude::*;
502    /// # use kompact::doctest_helpers::*;
503    /// use std::time::Duration;
504    /// let system = KompactConfig::default().build().wait().expect("KompactSystem");
505    /// let (c, registration_future) = system.create_and_register(TestComponent1::new);
506    /// registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1");
507    /// # system.shutdown().wait().expect("shutdown");
508    /// ```
509    #[cfg(feature = "distributed")]
510    pub fn create_and_register<C, F>(
511        &self,
512        f: F,
513    ) -> (Arc<Component<C>>, KFuture<RegistrationResult>)
514    where
515        F: FnOnce() -> C,
516        C: ComponentDefinition + 'static,
517    {
518        // it will already check this twice...don't check it a third time
519        // self.inner.assert_active();
520        let c = self.create(f);
521        let r = self.register(&c);
522        (c, r)
523    }
524
525    /// Attempts to register the provided component with a human-readable alias.
526    ///
527    /// The returned future will contain the named [ActorPath](ActorPath)
528    /// for the given alias, once it is completed by the dispatcher.
529    ///
530    /// Alias registration will fail if a previous registration already exists.
531    /// Use [update_alias_registration](KompactSystem::update_alias_registration) to override an existing registration.
532    ///
533    /// # Note
534    ///
535    /// While aliases are easier to read, lookup by unique ids is significantly more efficient.
536    /// However, named aliases allow services to be taken over by another component when the original registrant failed,
537    /// something that is not possible with unique paths. Thus, this kind of addressing lends itself to lookup-service
538    /// style components, for example.
539    ///
540    /// # Example
541    ///
542    /// ```
543    /// use kompact::prelude::*;
544    /// # use kompact::doctest_helpers::*;
545    /// use std::time::Duration;
546    /// let system = KompactConfig::default().build().wait().expect("KompactSystem");
547    /// let (c, unique_registration_future) = system.create_and_register(TestComponent1::new);
548    /// unique_registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1");
549    /// let alias_registration_future = system.register_by_alias(&c, "test");
550    /// alias_registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1 by alias");
551    /// # system.shutdown().wait().expect("shutdown");
552    /// ```
553    #[cfg(feature = "distributed")]
554    pub fn register_by_alias<A>(
555        &self,
556        c: &dyn DynActorRefFactory,
557        alias: A,
558    ) -> KFuture<RegistrationResult>
559    where
560        A: Into<String>,
561    {
562        self.inner.assert_active();
563        self.inner
564            .register_by_alias(c.dyn_ref(), false, alias.into())
565    }
566
567    /// Attempts to register the provided component with a human-readable alias.
568    ///
569    /// The returned future will contain the named [ActorPath](ActorPath)
570    /// for the given alias, once it is completed by the dispatcher.
571    ///
572    /// This registration will replace any previous registration, if it exists.
573    ///
574    /// # Note
575    ///
576    /// While aliases are easier to read, lookup by unique ids is significantly more efficient.
577    /// However, named aliases allow services to be taken over by another component when the original registrant failed,
578    /// something that is not possible with unique paths. Thus, this kind of addressing lends itself to lookup-service
579    /// style components, for example.
580    ///
581    /// # Example
582    ///
583    /// ```
584    /// use kompact::prelude::*;
585    /// # use kompact::doctest_helpers::*;
586    /// use std::time::Duration;
587    /// let system = KompactConfig::default().build().wait().expect("KompactSystem");
588    /// let (c, unique_registration_future) = system.create_and_register(TestComponent1::new);
589    /// unique_registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1");
590    /// let alias_registration_future = system.update_alias_registration(&c, "test");
591    /// alias_registration_future.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1 by alias");
592    /// let alias_reregistration_future = system.update_alias_registration(&c, "test");
593    /// alias_reregistration_future.wait_expect(Duration::from_millis(1000), "Failed to override TestComponent1 registration by alias");
594    /// # system.shutdown().wait().expect("shutdown");
595    /// ```
596    #[cfg(feature = "distributed")]
597    pub fn update_alias_registration<A>(
598        &self,
599        c: &dyn DynActorRefFactory,
600        alias: A,
601    ) -> KFuture<RegistrationResult>
602    where
603        A: Into<String>,
604    {
605        self.inner.assert_active();
606        self.inner
607            .register_by_alias(c.dyn_ref(), true, alias.into())
608    }
609
610    /// Attempts to set the routing policy at `path`
611    ///
612    /// Setting a routing policy at a path "a" will include
613    /// all actors paths registered under paths of the form "a/..."
614    /// to be included as members of the routing group that the policy applies to.
615    ///
616    /// Having an explicit routing policy at a path will cause routing over group
617    /// members, even if no routing marker (e.g., "a/*" or "a/?" is given).
618    ///
619    /// Overriding an existing actor or policy at the given path will fail,
620    /// unless `update` is set to `true`.
621    ///
622    /// Provided routing policies can be found in the [routing::groups](crate::routing::groups) module.
623    ///
624    /// # Example
625    ///
626    /// ```
627    /// use kompact::prelude::*;
628    /// use kompact::routing::groups::*;
629    /// # use kompact::doctest_helpers::*;
630    /// use std::time::Duration;
631    /// let system = KompactConfig::default().build().wait().expect("KompactSystem");
632    /// let policy_registration_future = system.set_routing_policy(BroadcastRouting::default(), "broadcast-me", false);
633    /// let broadcast_path = policy_registration_future.wait_expect(Duration::from_millis(1000), "Failed to set broadcast policy");
634    /// let c1 = system.create(TestComponent1::new);
635    /// let c2 = system.create(TestComponent1::new);
636    /// let alias_registration_future1 = system.register_by_alias(&c1, "broadcast-me/test1");
637    /// let alias_registration_future2 = system.register_by_alias(&c2, "broadcast-me/something/test2");
638    /// alias_registration_future1.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent1 by alias");
639    /// alias_registration_future2.wait_expect(Duration::from_millis(1000), "Failed to register TestComponent2 by alias");
640    /// // sending to broadcast_path now will send to c1 and c2
641    /// # system.shutdown().wait().expect("shutdown");
642    /// ```
643    #[cfg(feature = "distributed")]
644    pub fn set_routing_policy<P>(
645        &self,
646        policy: P,
647        path: &str,
648        update: bool,
649    ) -> KFuture<RegistrationResult>
650    where
651        P: Into<StorePolicy>,
652    {
653        self.inner.assert_active();
654        self.inner.set_routing_policy(policy.into(), path, update)
655    }
656
657    /// Start a component
658    ///
659    /// A component only handles events/messages once it is started.
660    /// In particular, a component that isn't started shouldn't be scheduled and thus
661    /// access to its definition should always succeed,
662    /// for example via [on_definition](Component::on_definition).
663    ///
664    /// # Example
665    ///
666    /// ```
667    /// # use kompact::prelude::*;
668    /// # use kompact::doctest_helpers::*;
669    /// # let system = KompactConfig::default().build().wait().expect("system");
670    /// let c = system.create(TestComponent1::new);
671    /// system.start(&c);
672    /// # system.shutdown().wait().expect("shutdown");
673    /// ```
674    pub fn start(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> () {
675        self.inner.assert_not_poisoned();
676        c.enqueue_control(ControlEvent::Start);
677    }
678
679    /// Allows backend crates to interact with the concrete dispatcher definition.
680    ///
681    /// The callback receives the dispatcher definition erased as [`Any`].
682    /// Backend crates can downcast it to their concrete dispatcher type in order to
683    /// wire backend-specific ports or query backend-specific state.
684    #[cfg(feature = "distributed")]
685    pub fn with_dispatcher_definition<F>(&self, f: F) -> ()
686    where
687        F: FnOnce(&mut dyn Any),
688    {
689        self.inner.with_dispatcher_definition(f);
690    }
691
692    /// Start a component and complete a future once it has started
693    ///
694    /// When the returned future completes, the component is guaranteed to have started.
695    /// However, it is not guaranteed to be in an active state,
696    /// as it could already have been stopped or could have failed since.
697    ///
698    /// A component only handles events/messages once it is started.
699    /// In particular, a component that isn't started shouldn't be scheduled and thus
700    /// access to its definition should always succeed,
701    /// for example via [on_definition](Component::on_definition).
702    ///
703    /// # Example
704    ///
705    /// ```
706    /// # use kompact::prelude::*;
707    /// # use kompact::doctest_helpers::*;
708    /// use std::time::Duration;
709    /// # let system = KompactConfig::default().build().wait().expect("system");
710    /// let c = system.create(TestComponent1::new);
711    /// system.start_notify(&c)
712    ///       .wait_timeout(Duration::from_millis(1000))
713    ///       .expect("TestComponent1 never started!");
714    /// # system.shutdown().wait().expect("shutdown");
715    /// ```
716    pub fn start_notify(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> KFuture<()> {
717        self.inner.assert_active();
718        let (p, f) = utils::promise();
719        let amp = Arc::new(Mutex::new(p));
720        self.supervision_port()
721            .enqueue(SupervisorMsg::Listen(amp, ListenEvent::Started(c.id())));
722        c.enqueue_control(ControlEvent::Start);
723        f
724    }
725
726    /// Stop a component
727    ///
728    /// A component does not handle any events/messages while it is stopped,
729    /// but it does not get deallocated either. It can be started again later with
730    /// [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify).
731    ///
732    /// A component that is stopped shouldn't be scheduled and thus
733    /// access to its definition should always succeed,
734    /// for example via [on_definition](Component::on_definition).
735    ///
736    /// # Example
737    ///
738    /// ```
739    /// # use kompact::prelude::*;
740    /// # use kompact::doctest_helpers::*;
741    /// use std::time::Duration;
742    /// # let system = KompactConfig::default().build().wait().expect("system");
743    /// let c = system.create(TestComponent1::new);
744    /// system.start_notify(&c)
745    ///       .wait_timeout(Duration::from_millis(1000))
746    ///       .expect("TestComponent1 never started!");
747    /// system.stop(&c);
748    /// # system.shutdown().wait().expect("shutdown");
749    /// ```
750    pub fn stop(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> () {
751        self.inner.assert_active();
752        c.enqueue_control(ControlEvent::Stop);
753    }
754
755    /// Stop a component and complete a future once it has stopped
756    ///
757    /// When the returned future completes, the component is guaranteed to have stopped.
758    /// However, it is not guaranteed to be in a passive state,
759    /// as it could already have been started again since.
760    ///
761    /// A component does not handle any events/messages while it is stopped,
762    /// but it does not get deallocated either. It can be started again later with
763    /// [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify).
764    ///
765    /// A component that is stopped shouldn't be scheduled and thus
766    /// access to its definition should always succeed,
767    /// for example via [on_definition](Component::on_definition).
768    ///
769    /// # Example
770    ///
771    /// ```
772    /// # use kompact::prelude::*;
773    /// # use kompact::doctest_helpers::*;
774    /// use std::time::Duration;
775    /// # let system = KompactConfig::default().build().wait().expect("system");
776    /// let c = system.create(TestComponent1::new);
777    /// system.start_notify(&c)
778    ///       .wait_timeout(Duration::from_millis(1000))
779    ///       .expect("TestComponent1 never started!");
780    /// system.stop_notify(&c)
781    ///       .wait_timeout(Duration::from_millis(1000))
782    ///       .expect("TestComponent1 never stopped!");
783    /// system.start_notify(&c)
784    ///       .wait_timeout(Duration::from_millis(1000))
785    ///       .expect("TestComponent1 never re-started!");
786    /// # system.shutdown().wait().expect("shutdown");
787    /// ```
788    pub fn stop_notify(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> KFuture<()> {
789        self.inner.assert_active();
790        let (p, f) = utils::promise();
791        let amp = Arc::new(Mutex::new(p));
792        self.supervision_port()
793            .enqueue(SupervisorMsg::Listen(amp, ListenEvent::Stopped(c.id())));
794        c.enqueue_control(ControlEvent::Stop);
795        f
796    }
797
798    /// Stop and deallocate a component
799    ///
800    /// The supervisor will attempt to deallocate `c` once it is stopped.
801    /// However, if there are still outstanding references somewhere else in the system
802    /// this will fail, of course. In that case the supervisor leaves a debug message
803    /// in the logging output, so that this circumstance can be discovered if necessary.
804    ///
805    /// # Example
806    ///
807    /// ```
808    /// # use kompact::prelude::*;
809    /// # use kompact::doctest_helpers::*;
810    /// use std::time::Duration;
811    /// # let system = KompactConfig::default().build().wait().expect("system");
812    /// let c = system.create(TestComponent1::new);
813    /// system.start_notify(&c)
814    ///       .wait_timeout(Duration::from_millis(1000))
815    ///       .expect("TestComponent1 never started!");
816    /// system.kill(c);
817    /// # system.shutdown().wait().expect("shutdown");
818    /// ```
819    pub fn kill(&self, c: Arc<impl AbstractComponent + ?Sized>) -> () {
820        self.inner.assert_active();
821        c.enqueue_control(ControlEvent::Kill);
822    }
823
824    /// Stop and deallocate a component, and complete a future once it has stopped
825    ///
826    /// The supervisor will attempt to deallocate `c` once it is stopped.
827    /// However, if there are still outstanding references somewhere else in the system
828    /// this will fail, of course. In that case the supervisor leaves a debug message
829    /// in the logging output, so that this circumstance can be discovered if necessary.
830    ///
831    /// # Note
832    ///
833    /// The completion of the future indicates that the component has been stopped,
834    /// *not* that it has been deallocated.
835    ///
836    /// If, for some reason, you really need to know when it has been deallocated,
837    /// you need to hold on to a copy of the component, use [try_unwrap](std::sync::Arc::try_unwrap)
838    /// and then call `drop` once you are successful.
839    ///
840    /// # Example
841    ///
842    /// ```
843    /// # use kompact::prelude::*;
844    /// # use kompact::doctest_helpers::*;
845    /// use std::time::Duration;
846    /// # let system = KompactConfig::default().build().wait().expect("system");
847    /// let c = system.create(TestComponent1::new);
848    /// system.start_notify(&c)
849    ///       .wait_timeout(Duration::from_millis(1000))
850    ///       .expect("TestComponent1 never started!");
851    /// system.kill_notify(c)
852    ///       .wait_timeout(Duration::from_millis(1000))
853    ///       .expect("TestComponent1 never stopped!");
854    /// # system.shutdown().wait().expect("shutdown");
855    /// ```
856    pub fn kill_notify(&self, c: Arc<impl AbstractComponent + ?Sized>) -> KFuture<()> {
857        self.inner.assert_active();
858        let (p, f) = utils::promise();
859        let amp = Arc::new(Mutex::new(p));
860        self.supervision_port()
861            .enqueue(SupervisorMsg::Listen(amp, ListenEvent::Destroyed(c.id())));
862        c.enqueue_control(ControlEvent::Kill);
863        f
864    }
865
866    /// Trigger an indication `event` on a shared `port`
867    ///
868    /// This can be used to send events to component without connecting a channel.
869    /// You only nneed to acquire port reference via [share](prelude::RequiredPort::share).
870    pub fn trigger_i<P>(&self, event: P::Indication, port: &RequiredRef<P>)
871    where
872        P: Port + 'static,
873    {
874        self.inner.assert_active();
875        port.enqueue(event);
876    }
877
878    /// Trigger a request `event` on a shared `port`
879    ///
880    /// This can be used to send events to component without connecting a channel.
881    /// You only nneed to acquire port reference via [share](prelude::ProvidedPort::share).
882    pub fn trigger_r<P>(&self, msg: P::Request, port: &ProvidedRef<P>)
883    where
884        P: Port + 'static,
885    {
886        self.inner.assert_active();
887        port.enqueue(msg);
888    }
889
890    /// Return the configured thoughput value
891    ///
892    /// See also [throughput](KompactConfig::throughput).
893    pub fn throughput(&self) -> usize {
894        self.inner.throughput
895    }
896
897    /// Return the configured maximum number of messages per scheduling
898    ///
899    /// This value is based on [throughput](KompactConfig::throughput)
900    /// and [msg_priority](KompactConfig::msg_priority).
901    pub fn max_messages(&self) -> usize {
902        self.inner.max_messages
903    }
904
905    /// Return a future that completes when the Kompact system is terminated.
906    ///
907    /// The returned future observes system state and completes once the system is
908    /// destroyed or faulty. Async callers should `.await` it, while synchronous
909    /// callers can use [`BlockingFutureExt::wait`](crate::prelude::BlockingFutureExt::wait).
910    ///
911    /// # Note
912    ///
913    /// Don't use this method for any measurements,
914    /// as its implementation currently does not include any
915    /// notification logic. It simply checks its internal state
916    /// every second or so, so there might be quite some delay
917    /// until a shutdown is detected.
918    pub fn terminated(&self) -> impl Future<Output = ()> + Unpin + 'static {
919        let runtime = self.inner.clone();
920        async move {
921            loop {
922                if lifecycle::is_destroyed(runtime.state()) || lifecycle::is_faulty(runtime.state())
923                {
924                    return;
925                }
926                async_std::task::sleep(std::time::Duration::from_secs(1)).await;
927            }
928        }
929        .boxed_local()
930    }
931
932    /// Wait for the Kompact system to be terminated
933    ///
934    /// Suspends this thread until the system is terminated
935    /// from some other thread, such as its own threadpool,
936    /// for example.
937    ///
938    /// Use [`terminated`](KompactSystem::terminated) for the future-returning API.
939    ///
940    /// # Note
941    ///
942    /// Don't use this method for any measurements,
943    /// as its implementation currently does not include any
944    /// notification logic. It simply checks its internal state
945    /// every second or so, so there might be quite some delay
946    /// until a shutdown is detected.
947    pub fn await_termination(self) {
948        self.terminated().wait();
949    }
950
951    /// Shutdown the Kompact system.
952    ///
953    /// Stops all components and then stops the scheduler.
954    ///
955    /// This function may fail to stop in time (or at all),
956    /// if components hang on to scheduler threads indefinitely.
957    ///
958    /// This function returns a future. Async callers should `.await` it, while
959    /// synchronous callers can use [`BlockingFutureExt::wait`](crate::prelude::BlockingFutureExt::wait).
960    /// The shutdown sequence awaits component shutdown without entering a nested
961    /// executor. Scheduler implementations can also provide a non-blocking
962    /// shutdown future via [`Scheduler::shutdown_notify`].
963    ///
964    /// # Example
965    ///
966    /// ```
967    /// use kompact::prelude::*;
968    ///
969    /// let system = KompactConfig::default().build().wait().expect("system");
970    /// system.shutdown().wait().expect("shutdown");
971    /// ```
972    pub fn shutdown(
973        self,
974    ) -> impl Future<Output = Result<(), ShutdownError>> + Send + Unpin + 'static {
975        async move {
976            self.inner.assert_active();
977            self.inner.shutdown_notify(&self).await?;
978            self.scheduler
979                .shutdown_notify()
980                .await
981                .context(shutdown_error::SchedulerSnafu)?;
982            Ok(())
983        }
984        .boxed()
985    }
986
987    /// Kill the Kompact system
988    ///
989    /// Similar to `shutdown()` except the Network will not be gracefully disconnected, making this
990    /// shutdown more immediate and brutal.
991    ///
992    /// Remote systems will perceive this system as crashed.
993    pub fn kill_system(self) -> Result<(), ShutdownError> {
994        self.inner.assert_active();
995        self.inner.kill(&self)?;
996        self.scheduler
997            .shutdown()
998            .context(shutdown_error::SchedulerSnafu)?;
999        Ok(())
1000    }
1001
1002    /// Start shutting down the Kompact system from within a component.
1003    ///
1004    /// This is a fire-and-forget helper for lifecycle and message handlers that
1005    /// cannot consume their system handle. Use [`shutdown`](KompactSystem::shutdown)
1006    /// when you own the system and want to wait for shutdown to finish.
1007    ///
1008    /// Shutdown may fail to stop in time (or at all),
1009    /// if components hang on to scheduler threads indefinitely.
1010    ///
1011    /// # Example
1012    ///
1013    /// ```
1014    /// use kompact::prelude::*;
1015    ///
1016    /// #[derive(ComponentDefinition, Actor)]
1017    /// struct Stopper {
1018    ///    ctx: ComponentContext<Self>,
1019    /// }
1020    /// impl Stopper {
1021    ///     fn new() -> Stopper {
1022    ///         Stopper {
1023    ///             ctx: ComponentContext::uninitialised(),
1024    ///         }
1025    ///     }
1026    /// }
1027    /// impl ComponentLifecycle for Stopper {
1028    ///    fn on_start(&mut self) -> HandlerResult {
1029    ///        self.ctx().system().shutdown_async();
1030    ///        Handled::OK
1031    ///     }
1032    /// }
1033    /// let system = KompactConfig::default().build().wait().expect("system");
1034    /// let c = system.create(Stopper::new);
1035    /// system.start(&c);
1036    /// system.await_termination();
1037    /// ```
1038    pub fn shutdown_async(&self) -> () {
1039        let sys = self.clone();
1040        async_std::task::spawn(async move {
1041            let logger = sys.inner.logger().clone();
1042            if let Err(error) = sys.shutdown().await {
1043                error!(logger, "async system shutdown failed"; "error" => format!("{}", error));
1044            }
1045        });
1046    }
1047
1048    #[cfg(feature = "distributed")]
1049    /// Return the system path of this Kompact system
1050    ///
1051    /// The system path forms a prefix for every [ActorPath](prelude::ActorPath).
1052    pub fn system_path(&self) -> SystemPath {
1053        self.inner.assert_active();
1054        self.inner.system_path()
1055    }
1056
1057    #[cfg(feature = "distributed")]
1058    /// Generate an unique path for the given component
1059    ///
1060    /// Produces a unique id [ActorPath](prelude::ActorPath) for `component`
1061    /// using the system path of this system.
1062    ///
1063    /// The returned `ActorPath` is only useful if the component was first [registered](KompactSystem::register),
1064    /// otherwise all messages sent to it will land in the system's deadletter box.
1065    ///
1066    /// # Note
1067    ///
1068    /// If you pass in a component from a different system, you will get
1069    /// a perfectly valid `ActorPath` instance, but which can not receive any messages,
1070    /// unless you also registered the component with this system's dispatcher.
1071    /// Suffice to say, crossing system boundaries in this manner is not recommended.
1072    pub fn actor_path_for(&self, component: &Arc<impl AbstractComponent + ?Sized>) -> ActorPath {
1073        ActorPath::Unique(UniquePath::with_system(self.system_path(), component.id()))
1074    }
1075
1076    /// Run a Future on this system's executor pool and return a handle to the result
1077    ///
1078    /// Handles can be awaited like any other future.
1079    ///
1080    /// # Note
1081    ///
1082    /// The current API is not as efficient as calling [FuturesExecutor::spawn](executors::FuturesExecutor::spawn)
1083    /// directly, due to some trait object indirection in Kompact systems.
1084    /// Thus, if performance is important, it is recommended to maintain a (non trait-object) handle
1085    /// to the actual `Executor` pool being used and call its `spawn` function instead.
1086    /// This API is really just a somewhat roundabout convenience for doing the same.
1087    pub fn spawn<R: Send + 'static>(
1088        &self,
1089        future: impl futures::Future<Output = R> + 'static + Send,
1090    ) -> JoinHandle<R> {
1091        // Having to use the channel here kinda sucks,
1092        // since the executor pool could do this without.
1093        // But there doesn't seem to be any way to pass the
1094        // required generic types through the `dyn Scheduler`
1095        // trait object :(
1096        let (tx, rx) = futures::channel::oneshot::channel();
1097        let unit_future = async move {
1098            let res = future.await;
1099            let _ignore = tx.send(res); // if it can't send the handle was dropped, which is fine
1100        };
1101        self.scheduler.spawn(Box::pin(unit_future));
1102        rx
1103    }
1104
1105    pub(crate) fn supervision_port(&self) -> ProvidedRef<SupervisionPort> {
1106        self.inner.supervision_port()
1107    }
1108
1109    #[cfg(feature = "distributed")]
1110    /// The remote path for the deadletter box
1111    pub fn deadletter_path(&self) -> ActorPath {
1112        ActorPath::Named(NamedPath::with_system(self.system_path(), Vec::new()))
1113    }
1114}
1115
1116impl ActorRefFactory for KompactSystem {
1117    type Message = Never;
1118
1119    /// Returns a reference to the deadletter box
1120    fn actor_ref(&self) -> ActorRef<Never> {
1121        self.inner.assert_active();
1122        self.inner.deadletter_ref()
1123    }
1124}
1125
1126impl SystemHandle for KompactSystem {
1127    fn now(&self) -> Instant {
1128        KompactSystem::now(self)
1129    }
1130
1131    fn create<C, F>(&self, f: F) -> Arc<Component<C>>
1132    where
1133        F: FnOnce() -> C,
1134        C: ComponentDefinition + 'static,
1135    {
1136        KompactSystem::create(self, f)
1137    }
1138
1139    #[cfg(feature = "type_erasure")]
1140    fn create_erased<M: MessageBounds>(
1141        &self,
1142        a: Box<dyn CreateErased<M>>,
1143    ) -> Arc<dyn AbstractComponent<Message = M>> {
1144        KompactSystem::create_erased(self, a)
1145    }
1146
1147    fn start(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> () {
1148        KompactSystem::start(self, c)
1149    }
1150
1151    fn start_notify(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> KFuture<()> {
1152        KompactSystem::start_notify(self, c)
1153    }
1154
1155    fn stop(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> () {
1156        KompactSystem::stop(self, c)
1157    }
1158
1159    fn stop_notify(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> KFuture<()> {
1160        KompactSystem::stop_notify(self, c)
1161    }
1162
1163    fn kill(&self, c: Arc<impl AbstractComponent + ?Sized>) -> () {
1164        KompactSystem::kill(self, c)
1165    }
1166
1167    fn kill_notify(&self, c: Arc<impl AbstractComponent + ?Sized>) -> KFuture<()> {
1168        KompactSystem::kill_notify(self, c)
1169    }
1170
1171    fn throughput(&self) -> usize {
1172        KompactSystem::throughput(self)
1173    }
1174
1175    fn max_messages(&self) -> usize {
1176        KompactSystem::max_messages(self)
1177    }
1178
1179    fn shutdown_async(&self) -> () {
1180        KompactSystem::shutdown_async(self)
1181    }
1182
1183    fn deadletter_ref(&self) -> ActorRef<Never> {
1184        self.actor_ref()
1185    }
1186
1187    fn spawn<R: Send + 'static>(
1188        &self,
1189        future: impl futures::Future<Output = R> + 'static + Send,
1190    ) -> JoinHandle<R> {
1191        KompactSystem::spawn(self, future)
1192    }
1193}
1194
1195#[cfg(feature = "distributed")]
1196impl Dispatching for KompactSystem {
1197    fn dispatcher_ref(&self) -> DispatcherRef {
1198        self.inner.assert_active();
1199        self.inner.dispatcher_ref()
1200    }
1201}
1202
1203#[cfg(feature = "distributed")]
1204impl DistributedSystemHandle for KompactSystem {
1205    fn register(&self, c: &dyn UniqueRegistrable) -> KFuture<RegistrationResult> {
1206        self.register(c)
1207    }
1208
1209    fn create_and_register<C, F>(&self, f: F) -> (Arc<Component<C>>, KFuture<RegistrationResult>)
1210    where
1211        F: FnOnce() -> C,
1212        C: ComponentDefinition + 'static,
1213    {
1214        self.create_and_register(f)
1215    }
1216
1217    fn register_by_alias<A>(
1218        &self,
1219        c: &dyn DynActorRefFactory,
1220        alias: A,
1221    ) -> KFuture<RegistrationResult>
1222    where
1223        A: Into<String>,
1224    {
1225        self.register_by_alias(c, alias)
1226    }
1227
1228    fn update_alias_registration<A>(
1229        &self,
1230        c: &dyn DynActorRefFactory,
1231        alias: A,
1232    ) -> KFuture<RegistrationResult>
1233    where
1234        A: Into<String>,
1235    {
1236        self.update_alias_registration(c, alias)
1237    }
1238
1239    fn set_routing_policy<P>(
1240        &self,
1241        policy: P,
1242        path: &str,
1243        update: bool,
1244    ) -> KFuture<RegistrationResult>
1245    where
1246        P: Into<StorePolicy>,
1247    {
1248        self.set_routing_policy(policy, path, update)
1249    }
1250
1251    fn system_path(&self) -> SystemPath {
1252        self.system_path()
1253    }
1254}
1255
1256#[cfg(feature = "distributed")]
1257impl ActorPathFactory for KompactSystem {
1258    fn actor_path(&self) -> ActorPath {
1259        self.deadletter_path()
1260    }
1261}
1262
1263impl TimerRefFactory for KompactSystem {
1264    fn timer_ref(&self) -> timer::TimerRef {
1265        self.inner.assert_not_poisoned();
1266        self.inner.timer_ref()
1267    }
1268}
1269
1270/// A limited version of a [KompactSystem](KompactSystem)
1271///
1272/// This is meant for use from within components, where blocking APIs
1273/// are unacceptable.
1274pub trait SystemHandle: CanCancelTimers {
1275    /// Returns the current time according to the system timer.
1276    fn now(&self) -> Instant;
1277
1278    /// Create a new component
1279    ///
1280    /// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),
1281    /// which is the initialised to form a [Component](Component).
1282    /// Since components are shared between threads, the created component
1283    /// is wrapped into an [Arc](std::sync::Arc).
1284    ///
1285    /// Newly created components are not started automatically.
1286    /// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)
1287    /// to start a newly created component, once it is connected properly.
1288    ///
1289    /// If you need address this component via the network, see the [register](KompactSystem::register) function.
1290    ///
1291    /// # Example
1292    ///
1293    /// ```
1294    /// # use kompact::prelude::*;
1295    /// # use kompact::doctest_helpers::*;
1296    /// # let system = KompactConfig::default().build().wait().expect("system");
1297    /// let c = system.create(TestComponent1::new);
1298    /// # system.shutdown().wait().expect("shutdown");
1299    /// ```
1300    fn create<C, F>(&self, f: F) -> Arc<Component<C>>
1301    where
1302        F: FnOnce() -> C,
1303        C: ComponentDefinition + 'static;
1304
1305    /// Create a new component from type-erased component definition
1306    ///
1307    /// Since components are shared between threads, the created component
1308    /// is internally wrapped into an [Arc](std::sync::Arc).
1309    ///
1310    /// Newly created components are not started automatically.
1311    /// Use [start](KompactSystem::start) or
1312    /// [start_notify](KompactSystem::start_notify) to start a newly
1313    /// created component, once it is connected properly.
1314    ///
1315    /// If you need address this component via the network, see the [register](KompactSystem::register) function.
1316    ///
1317    /// # Example
1318    ///
1319    /// ```
1320    /// # use kompact::prelude::*;
1321    /// # use kompact::doctest_helpers::*;
1322    /// # let system = KompactConfig::default().build().wait().expect("system");
1323    /// let c = system.create_erased(Box::new(TestComponent1::new()));
1324    /// # system.shutdown().wait().expect("shutdown");
1325    /// ```
1326    #[cfg(feature = "type_erasure")]
1327    fn create_erased<M: MessageBounds>(
1328        &self,
1329        a: Box<dyn CreateErased<M>>,
1330    ) -> Arc<dyn AbstractComponent<Message = M>>;
1331
1332    /// Start a component
1333    ///
1334    /// A component only handles events/messages once it is started.
1335    /// In particular, a component that isn't started shouldn't be scheduled and thus
1336    /// access to its definition should always succeed,
1337    /// for example via [on_definition](Component::on_definition).
1338    ///
1339    /// # Example
1340    ///
1341    /// ```
1342    /// # use kompact::prelude::*;
1343    /// # use kompact::doctest_helpers::*;
1344    /// # let system = KompactConfig::default().build().wait().expect("system");
1345    /// let c = system.create(TestComponent1::new);
1346    /// system.start(&c);
1347    /// # system.shutdown().wait().expect("shutdown");
1348    /// ```
1349    fn start(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> ();
1350
1351    /// Start a component and complete a future once it has started
1352    ///
1353    /// When the returned future completes, the component is guaranteed to have started.
1354    /// However, it is not guaranteed to be in an active state,
1355    /// as it could already have been stopped or could have failed since.
1356    ///
1357    /// A component only handles events/messages once it is started.
1358    /// In particular, a component that isn't started shouldn't be scheduled and thus
1359    /// access to its definition should always succeed,
1360    /// for example via [on_definition](Component::on_definition).
1361    ///
1362    /// # Example
1363    ///
1364    /// ```
1365    /// # use kompact::prelude::*;
1366    /// # use kompact::doctest_helpers::*;
1367    /// use std::time::Duration;
1368    /// # let system = KompactConfig::default().build().wait().expect("system");
1369    /// let c = system.create(TestComponent1::new);
1370    /// system.start_notify(&c)
1371    ///       .wait_timeout(Duration::from_millis(1000))
1372    ///       .expect("TestComponent1 never started!");
1373    /// # system.shutdown().wait().expect("shutdown");
1374    /// ```
1375    fn start_notify(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> KFuture<()>;
1376
1377    /// Stop a component
1378    ///
1379    /// A component does not handle any events/messages while it is stopped,
1380    /// but it does not get deallocated either. It can be started again later with
1381    /// [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify).
1382    ///
1383    /// A component that is stopped shouldn't be scheduled and thus
1384    /// access to its definition should always succeed,
1385    /// for example via [on_definition](Component::on_definition).
1386    ///
1387    /// # Example
1388    ///
1389    /// ```
1390    /// # use kompact::prelude::*;
1391    /// # use kompact::doctest_helpers::*;
1392    /// use std::time::Duration;
1393    /// # let system = KompactConfig::default().build().wait().expect("system");
1394    /// let c = system.create(TestComponent1::new);
1395    /// system.start_notify(&c)
1396    ///       .wait_timeout(Duration::from_millis(1000))
1397    ///       .expect("TestComponent1 never started!");
1398    /// system.stop(&c);
1399    /// # system.shutdown().wait().expect("shutdown");
1400    /// ```
1401    fn stop(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> ();
1402
1403    /// Stop a component and complete a future once it has stopped
1404    ///
1405    /// When the returned future completes, the component is guaranteed to have stopped.
1406    /// However, it is not guaranteed to be in a passive state,
1407    /// as it could already have been started again since.
1408    ///
1409    /// A component does not handle any events/messages while it is stopped,
1410    /// but it does not get deallocated either. It can be started again later with
1411    /// [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify).
1412    ///
1413    /// A component that is stopped shouldn't be scheduled and thus
1414    /// access to its definition should always succeed,
1415    /// for example via [on_definition](Component::on_definition).
1416    ///
1417    /// # Example
1418    ///
1419    /// ```
1420    /// # use kompact::prelude::*;
1421    /// # use kompact::doctest_helpers::*;
1422    /// use std::time::Duration;
1423    /// # let system = KompactConfig::default().build().wait().expect("system");
1424    /// let c = system.create(TestComponent1::new);
1425    /// system.start_notify(&c)
1426    ///       .wait_timeout(Duration::from_millis(1000))
1427    ///       .expect("TestComponent1 never started!");
1428    /// system.stop_notify(&c)
1429    ///       .wait_timeout(Duration::from_millis(1000))
1430    ///       .expect("TestComponent1 never stopped!");
1431    /// system.start_notify(&c)
1432    ///       .wait_timeout(Duration::from_millis(1000))
1433    ///       .expect("TestComponent1 never re-started!");
1434    /// # system.shutdown().wait().expect("shutdown");
1435    /// ```
1436    fn stop_notify(&self, c: &Arc<impl AbstractComponent + ?Sized>) -> KFuture<()>;
1437
1438    /// Stop and deallocate a component
1439    ///
1440    /// The supervisor will attempt to deallocate `c` once it is stopped.
1441    /// However, if there are still outstanding references somewhere else in the system
1442    /// this will fail, of course. In that case the supervisor leaves a debug message
1443    /// in the logging output, so that this circumstance can be discovered if necessary.
1444    ///
1445    /// # Example
1446    ///
1447    /// ```
1448    /// # use kompact::prelude::*;
1449    /// # use kompact::doctest_helpers::*;
1450    /// use std::time::Duration;
1451    /// # let system = KompactConfig::default().build().wait().expect("system");
1452    /// let c = system.create(TestComponent1::new);
1453    /// system.start_notify(&c)
1454    ///       .wait_timeout(Duration::from_millis(1000))
1455    ///       .expect("TestComponent1 never started!");
1456    /// system.kill(c);
1457    /// # system.shutdown().wait().expect("shutdown");
1458    /// ```
1459    fn kill(&self, c: Arc<impl AbstractComponent + ?Sized>) -> ();
1460
1461    /// Stop and deallocate a component, and complete a future once it has stopped
1462    ///
1463    /// The supervisor will attempt to deallocate `c` once it is stopped.
1464    /// However, if there are still outstanding references somewhere else in the system
1465    /// this will fail, of course. In that case the supervisor leaves a debug message
1466    /// in the logging output, so that this circumstance can be discovered if necessary.
1467    ///
1468    /// # Note
1469    ///
1470    /// The completion of the future indicates that the component has been stopped,
1471    /// *not* that it has been deallocated.
1472    ///
1473    /// If, for some reason, you really need to know when it has been deallocated,
1474    /// you need to hold on to a copy of the component, use [try_unwrap](std::sync::Arc::try_unwrap)
1475    /// and then call `drop` once you are successful.
1476    ///
1477    /// # Example
1478    ///
1479    /// ```
1480    /// # use kompact::prelude::*;
1481    /// # use kompact::doctest_helpers::*;
1482    /// use std::time::Duration;
1483    /// # let system = KompactConfig::default().build().wait().expect("system");
1484    /// let c = system.create(TestComponent1::new);
1485    /// system.start_notify(&c)
1486    ///       .wait_timeout(Duration::from_millis(1000))
1487    ///       .expect("TestComponent1 never started!");
1488    /// system.kill_notify(c)
1489    ///       .wait_timeout(Duration::from_millis(1000))
1490    ///       .expect("TestComponent1 never stopped!");
1491    /// # system.shutdown().wait().expect("shutdown");
1492    /// ```
1493    fn kill_notify(&self, c: Arc<impl AbstractComponent + ?Sized>) -> KFuture<()>;
1494
1495    /// Return the configured thoughput value
1496    ///
1497    /// See also [throughput](KompactConfig::throughput).
1498    fn throughput(&self) -> usize;
1499
1500    /// Return the configured maximum number of messages per scheduling
1501    ///
1502    /// This value is based on [throughput](KompactConfig::throughput)
1503    /// and [msg_priority](KompactConfig::msg_priority).
1504    fn max_messages(&self) -> usize;
1505
1506    /// Start shutting down the Kompact system from within a component.
1507    ///
1508    /// This is a fire-and-forget helper for lifecycle and message handlers that
1509    /// cannot consume their system handle. Use [`shutdown`](KompactSystem::shutdown)
1510    /// when you own the system and want to wait for shutdown to finish.
1511    ///
1512    /// Shutdown may fail to stop in time (or at all),
1513    /// if components hang on to scheduler threads indefinitely.
1514    ///
1515    /// # Example
1516    ///
1517    /// ```
1518    /// use kompact::prelude::*;
1519    ///
1520    /// #[derive(ComponentDefinition, Actor)]
1521    /// struct Stopper {
1522    ///    ctx: ComponentContext<Self>,
1523    /// }
1524    /// impl Stopper {
1525    ///     fn new() -> Stopper {
1526    ///         Stopper {
1527    ///             ctx: ComponentContext::uninitialised(),
1528    ///         }
1529    ///     }
1530    /// }
1531    /// impl ComponentLifecycle for Stopper {
1532    ///    fn on_start(&mut self) -> HandlerResult {
1533    ///        self.ctx().system().shutdown_async();
1534    ///        Handled::OK
1535    ///     }
1536    /// }
1537    /// let system = KompactConfig::default().build().wait().expect("system");
1538    /// let c = system.create(Stopper::new);
1539    /// system.start(&c);
1540    /// system.await_termination();
1541    /// ```
1542    fn shutdown_async(&self) -> ();
1543
1544    /// Returns a reference to the system's deadletter box
1545    fn deadletter_ref(&self) -> ActorRef<Never>;
1546
1547    /// Run a Future on this system's executor pool and return a handle to the result
1548    ///
1549    /// Handles can be awaited like any other future.
1550    fn spawn<R: Send + 'static>(
1551        &self,
1552        future: impl futures::Future<Output = R> + 'static + Send,
1553    ) -> JoinHandle<R>;
1554}
1555
1556/// Distributed-only extensions for a [SystemHandle].
1557#[cfg(feature = "distributed")]
1558pub trait DistributedSystemHandle: SystemHandle + Dispatching {
1559    /// Attempts to register `c` with the dispatcher using its unique id.
1560    fn register(&self, c: &dyn UniqueRegistrable) -> KFuture<RegistrationResult>;
1561
1562    /// Creates a new component and registers it with the dispatcher.
1563    fn create_and_register<C, F>(&self, f: F) -> (Arc<Component<C>>, KFuture<RegistrationResult>)
1564    where
1565        F: FnOnce() -> C,
1566        C: ComponentDefinition + 'static;
1567
1568    /// Attempts to register the provided component with a human-readable alias.
1569    fn register_by_alias<A>(
1570        &self,
1571        c: &dyn DynActorRefFactory,
1572        alias: A,
1573    ) -> KFuture<RegistrationResult>
1574    where
1575        A: Into<String>;
1576
1577    /// Attempts to update the registration for the given alias.
1578    fn update_alias_registration<A>(
1579        &self,
1580        c: &dyn DynActorRefFactory,
1581        alias: A,
1582    ) -> KFuture<RegistrationResult>
1583    where
1584        A: Into<String>;
1585
1586    /// Attempts to set the routing policy at `path`.
1587    fn set_routing_policy<P>(
1588        &self,
1589        policy: P,
1590        path: &str,
1591        update: bool,
1592    ) -> KFuture<RegistrationResult>
1593    where
1594        P: Into<StorePolicy>;
1595
1596    /// Return the system path of this Kompact system.
1597    fn system_path(&self) -> SystemPath;
1598}
1599
1600/// A trait to provide custom implementations of all system components
1601pub trait SystemComponents: Send + Sync + 'static {
1602    /// Return a reference to this deadletter box
1603    fn deadletter_ref(&self) -> ActorRef<Never>;
1604    /// Return a reference to this dispatcher
1605    fn dispatcher_ref(&self) -> DispatcherRef;
1606    /// Return a system path for this dispatcher
1607    fn system_path(&self) -> SystemPath;
1608    /// Start all the system components
1609    fn start(&self, _system: &KompactSystem) -> ();
1610    /// Stop all the system components
1611    fn stop(&self, _system: &KompactSystem) -> ();
1612    /// Stop all the system components and complete once shutdown has finished
1613    fn stop_notify<'a>(
1614        &'a self,
1615        system: &'a KompactSystem,
1616    ) -> futures::future::BoxFuture<'a, Result<(), SystemComponentsShutdownError>>;
1617    /// Stop all the system components as fast as possible, no graceful shutdown
1618    fn kill(&self, _system: &KompactSystem) -> ();
1619    /// Allow downcasting to concrete type
1620    fn type_id(&self) -> TypeId {
1621        TypeId::of::<Self>()
1622    }
1623    /// Allow backend crates to interact with the concrete dispatcher definition.
1624    ///
1625    /// This takes a boxed callback instead of `impl FnOnce(...)`, because
1626    /// `SystemComponents` is used behind a trait object and generic methods would
1627    /// make the trait non-object-safe.
1628    fn with_dispatcher_definition_dyn<'a>(&self, f: DispatcherDefinitionCallback<'a>) -> ();
1629
1630    /// Convenience wrapper for callers that work with a concrete system-components type.
1631    fn with_dispatcher_definition<F>(&self, f: F) -> ()
1632    where
1633        Self: Sized,
1634        F: FnOnce(&mut dyn Any),
1635    {
1636        self.with_dispatcher_definition_dyn(Box::new(f))
1637    }
1638}
1639
1640pub(crate) type DispatcherDefinitionCallback<'a> = Box<dyn FnOnce(&mut dyn Any) + 'a>;
1641
1642impl dyn SystemComponents {
1643    // Implementation copied from std::any::Any
1644    /// Allow downcasting to concrete type
1645    pub fn downcast<T: SystemComponents>(&self) -> Option<&T> {
1646        // Get `TypeId` of the type this function is instantiated with.
1647        let t = TypeId::of::<T>();
1648
1649        // Get `TypeId` of the type in the trait object (`self`).
1650        let concrete = self.type_id();
1651
1652        // Compare both `TypeId`s on equality.
1653        if t == concrete {
1654            // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
1655            // that check for memory safety because we have implemented Any for all types; no other
1656            // impls can exist as they would conflict with our impl.
1657            unsafe { Some(&*(self as *const dyn SystemComponents as *const T)) }
1658        } else {
1659            None
1660        }
1661    }
1662}
1663
1664/// Extra trait for timers to implement
1665pub trait TimerComponent: TimerRefFactory + Send + Sync {
1666    /// Stop the underlying timer thread
1667    fn shutdown(&self) -> Result<(), TimerShutdownError>;
1668
1669    /// Stop the underlying timer thread from an async shutdown path
1670    fn shutdown_notify<'a>(
1671        &'a self,
1672    ) -> futures::future::BoxFuture<'a, Result<(), TimerShutdownError>>;
1673}
1674
1675struct InternalComponents {
1676    supervisor: Arc<Component<ComponentSupervisor>>,
1677    supervision_port: ProvidedRef<SupervisionPort>,
1678    system_components: Box<dyn SystemComponents>,
1679}
1680
1681impl InternalComponents {
1682    fn new(
1683        supervisor: Arc<Component<ComponentSupervisor>>,
1684        system_components: Box<dyn SystemComponents>,
1685    ) -> InternalComponents {
1686        let supervision_port = supervisor.on_definition(|s| s.supervision.share());
1687        InternalComponents {
1688            supervisor,
1689            supervision_port,
1690            system_components,
1691        }
1692    }
1693
1694    fn start(&self, system: &KompactSystem) -> () {
1695        self.system_components.start(system);
1696        system.start(&self.supervisor);
1697    }
1698
1699    fn deadletter_ref(&self) -> ActorRef<Never> {
1700        self.system_components.deadletter_ref()
1701    }
1702
1703    fn dispatcher_ref(&self) -> DispatcherRef {
1704        self.system_components.dispatcher_ref()
1705    }
1706
1707    #[cfg(feature = "distributed")]
1708    fn with_dispatcher_definition<F>(&self, f: F) -> ()
1709    where
1710        F: FnOnce(&mut dyn Any),
1711    {
1712        self.system_components
1713            .with_dispatcher_definition_dyn(Box::new(f))
1714    }
1715
1716    #[cfg(feature = "distributed")]
1717    fn system_path(&self) -> SystemPath {
1718        self.system_components.system_path()
1719    }
1720
1721    fn supervision_port(&self) -> ProvidedRef<SupervisionPort> {
1722        self.supervision_port.clone()
1723    }
1724
1725    fn stop_notify<'a>(
1726        &'a self,
1727        system: &'a KompactSystem,
1728    ) -> futures::future::BoxFuture<'a, Result<(), SystemComponentsShutdownError>> {
1729        async move {
1730            let (p, f) = utils::promise();
1731            self.supervision_port
1732                .enqueue(SupervisorMsg::Shutdown(Arc::new(Mutex::new(p))));
1733            f.await
1734                .boxed()
1735                .with_context(|_| system_components_shutdown_error::SourceSnafu {
1736                    message: "supervisor shutdown promise was dropped".to_string(),
1737                })?;
1738            self.system_components.stop_notify(system).await
1739        }
1740        .boxed()
1741    }
1742
1743    fn kill(&self, system: &KompactSystem) -> () {
1744        let (p, f) = utils::promise();
1745        self.supervision_port
1746            .enqueue(SupervisorMsg::Shutdown(Arc::new(Mutex::new(p))));
1747        f.wait();
1748        self.system_components.kill(system);
1749    }
1750
1751    #[allow(unknown_lints, clippy::explicit_auto_deref)]
1752    pub(crate) fn get_system_components(&self) -> &dyn SystemComponents {
1753        &*self.system_components
1754    }
1755}
1756
1757struct KompactRuntime {
1758    label: String,
1759    throughput: usize,
1760    max_messages: usize,
1761    timer: Box<dyn TimerComponent>,
1762    internal_components: OnceMutex<Option<InternalComponents>>,
1763    logger: KompactLogger,
1764    state: AtomicUsize,
1765}
1766
1767impl KompactRuntime {
1768    fn new(conf: KompactConfig) -> Self {
1769        let mm = conf.max_messages();
1770        let logger = match conf.root_logger {
1771            Some(log) => log.new(o!("system" => conf.label.clone())),
1772            None => default_logger().new(o!("system" => conf.label.clone())),
1773        };
1774        KompactRuntime {
1775            label: conf.label,
1776            throughput: conf.throughput,
1777            max_messages: mm,
1778            timer: (conf.timer_builder)(),
1779            internal_components: OnceMutex::new(None),
1780            logger,
1781            state: lifecycle::initial_state(),
1782        }
1783    }
1784
1785    fn set_internal_components(&self, internal_components: InternalComponents) -> () {
1786        let guard_opt: Option<OnceMutexGuard<'_, Option<InternalComponents>>> =
1787            self.internal_components.lock();
1788        if let Some(mut guard) = guard_opt {
1789            *guard = Some(internal_components);
1790        } else {
1791            panic!("KompactRuntime was already initialised!");
1792        }
1793    }
1794
1795    fn start_internal_components(&self, system: &KompactSystem) -> () {
1796        match *self.internal_components {
1797            Some(ref ic) => {
1798                ic.start(system);
1799                lifecycle::set_active(self.state());
1800            }
1801            None => panic!("KompactRuntime was not properly initialised!"),
1802        }
1803    }
1804
1805    pub(crate) fn get_internal_components(&self) -> &InternalComponents {
1806        match *self.internal_components {
1807            Some(ref ic) => ic,
1808            None => panic!("KompactRuntime was not properly initialised!"),
1809        }
1810    }
1811
1812    #[allow(dead_code)]
1813    fn logger(&self) -> &KompactLogger {
1814        &self.logger
1815    }
1816
1817    /// Registers an actor with a path at the dispatcher
1818    #[cfg(feature = "distributed")]
1819    fn register_by_path(
1820        &self,
1821        actor_ref: DynActorRef,
1822        update: bool,
1823        path: PathResolvable,
1824    ) -> KFuture<RegistrationResult> {
1825        debug!(self.logger(), "Requesting actor registration at {:?}", path);
1826        let (promise, future) = utils::promise();
1827        let dispatcher = self.dispatcher_ref();
1828        let envelope = MsgEnvelope::Typed(DispatchEnvelope::Registration(
1829            RegistrationEnvelope::actor_with_promise(actor_ref, path, update, promise),
1830        ));
1831        dispatcher.enqueue(envelope);
1832        future
1833    }
1834
1835    /// Registers an actor with an alias at the dispatcher
1836    #[cfg(feature = "distributed")]
1837    fn register_by_alias(
1838        &self,
1839        actor_ref: DynActorRef,
1840        update: bool,
1841        alias: String,
1842    ) -> KFuture<RegistrationResult> {
1843        debug!(
1844            self.logger(),
1845            "Requesting actor alias registration for {:?}", alias
1846        );
1847        let path = PathResolvable::Alias(alias);
1848        self.register_by_path(actor_ref, update, path)
1849    }
1850
1851    #[cfg(feature = "distributed")]
1852    fn set_routing_policy(
1853        &self,
1854        policy: StorePolicy,
1855        path: &str,
1856        update: bool,
1857    ) -> KFuture<RegistrationResult> {
1858        debug!(
1859            self.logger(),
1860            "Requesting policy registration at {:?}", path
1861        );
1862        let (promise, future) = utils::promise();
1863        let parsed_path = crate::actors::parse_path(path);
1864        match crate::actors::validate_insert_path(&parsed_path) {
1865            Ok(_) => {
1866                let dispatcher = self.dispatcher_ref();
1867                let envelope =
1868                    RegistrationEnvelope::policy_with_promise(policy, parsed_path, update, promise);
1869                let msg = MsgEnvelope::Typed(DispatchEnvelope::Registration(envelope));
1870                dispatcher.enqueue(msg);
1871            }
1872            Err(e) => {
1873                promise
1874                    .fulfil(Err(RegistrationError::InvalidPath(e)))
1875                    .expect("should fulfil promise");
1876            }
1877        }
1878        future
1879    }
1880
1881    fn deadletter_ref(&self) -> ActorRef<Never> {
1882        match *self.internal_components {
1883            Some(ref sc) => sc.deadletter_ref(),
1884            None => panic!("KompactRuntime was not properly initialised!"),
1885        }
1886    }
1887
1888    fn dispatcher_ref(&self) -> DispatcherRef {
1889        match *self.internal_components {
1890            Some(ref sc) => sc.dispatcher_ref(),
1891            None => panic!("KompactRuntime was not properly initialised!"),
1892        }
1893    }
1894
1895    #[cfg(feature = "distributed")]
1896    fn with_dispatcher_definition<F>(&self, f: F) -> ()
1897    where
1898        F: FnOnce(&mut dyn Any),
1899    {
1900        match *self.internal_components {
1901            Some(ref sc) => sc.with_dispatcher_definition(f),
1902            None => panic!("KompactRuntime was not properly initialised!"),
1903        }
1904    }
1905
1906    #[cfg(feature = "distributed")]
1907    fn system_path(&self) -> SystemPath {
1908        match *self.internal_components {
1909            Some(ref sc) => sc.system_path(),
1910            None => panic!("KompactRuntime was not properly initialised!"),
1911        }
1912    }
1913
1914    fn supervision_port(&self) -> ProvidedRef<SupervisionPort> {
1915        match *self.internal_components {
1916            Some(ref ic) => ic.supervision_port(),
1917            None => panic!("KompactRuntime was not properly initialised!"),
1918        }
1919    }
1920
1921    fn timer_ref(&self) -> timer::TimerRef {
1922        self.timer.timer_ref()
1923    }
1924
1925    fn shutdown_notify<'a>(
1926        &'a self,
1927        system: &'a KompactSystem,
1928    ) -> futures::future::BoxFuture<'a, Result<(), ShutdownError>> {
1929        async move {
1930            let ic = (*self.internal_components)
1931                .as_ref()
1932                .expect("KompactRuntime was not initialised at shutdown!");
1933            let components_result = ic
1934                .stop_notify(system)
1935                .await
1936                .context(shutdown_error::SystemComponentsSnafu)
1937                .map_err(ShutdownError::from);
1938            let timer_result = self
1939                .timer
1940                .shutdown_notify()
1941                .await
1942                .context(shutdown_error::TimerSnafu)
1943                .map_err(ShutdownError::from);
1944            lifecycle::set_destroyed(self.state());
1945            components_result.and(timer_result)
1946        }
1947        .boxed()
1948    }
1949
1950    fn kill(&self, system: &KompactSystem) -> Result<(), ShutdownError> {
1951        let ic = (*self.internal_components)
1952            .as_ref()
1953            .expect("KompactRuntime was not initialised at shutdown!");
1954        ic.kill(system);
1955        let result = self
1956            .timer
1957            .shutdown()
1958            .context(shutdown_error::TimerSnafu)
1959            .map_err(ShutdownError::from);
1960        lifecycle::set_destroyed(self.state());
1961        result
1962    }
1963
1964    pub(crate) fn poison(&self) {
1965        lifecycle::set_faulty(self.state());
1966        let _ = self.timer.shutdown();
1967    }
1968
1969    fn state(&self) -> &AtomicUsize {
1970        &self.state
1971    }
1972
1973    fn is_active(&self) -> bool {
1974        lifecycle::is_active(self.state())
1975    }
1976
1977    fn is_poisoned(&self) -> bool {
1978        lifecycle::is_faulty(self.state())
1979    }
1980
1981    fn assert_active(&self) {
1982        assert!(self.is_active(), "KompactRuntime was not in active state!");
1983    }
1984
1985    fn assert_not_poisoned(&self) {
1986        assert!(!self.is_poisoned(), "KompactRuntime was poisoned!");
1987    }
1988}
1989
1990impl fmt::Debug for KompactRuntime {
1991    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1992        write!(f, "KompactRuntime({})", self.label)
1993    }
1994}