coerce_rt/actor/
context.rs1use crate::actor::scheduler::{ActorScheduler, ActorType, GetActor, RegisterActor};
2use crate::actor::{Actor, ActorId, ActorRef, ActorRefErr, BoxedActorRef};
3
4lazy_static! {
5 static ref CURRENT_CONTEXT: ActorContext = { ActorContext::new() };
6}
7
8#[derive(Clone)]
9pub struct ActorContext {
10 scheduler: ActorRef<ActorScheduler>,
11}
12
13impl ActorContext {
14 pub fn new() -> ActorContext {
15 ActorContext {
16 scheduler: ActorScheduler::new(),
17 }
18 }
19
20 pub fn current_context() -> ActorContext {
21 CURRENT_CONTEXT.clone()
22 }
23
24 pub async fn new_tracked_actor<A: Actor>(
25 &mut self,
26 actor: A,
27 ) -> Result<ActorRef<A>, ActorRefErr>
28 where
29 A: 'static + Sync + Send,
30 {
31 self.new_actor(actor, ActorType::Tracked).await
32 }
33
34 pub async fn new_anon_actor<A: Actor>(&mut self, actor: A) -> Result<ActorRef<A>, ActorRefErr>
35 where
36 A: 'static + Sync + Send,
37 {
38 self.new_actor(actor, ActorType::Anonymous).await
39 }
40
41 pub async fn new_actor<A: Actor>(
42 &mut self,
43 actor: A,
44 actor_type: ActorType,
45 ) -> Result<ActorRef<A>, ActorRefErr>
46 where
47 A: 'static + Sync + Send,
48 {
49 let (tx, rx) = tokio::sync::oneshot::channel();
50 let actor_ref = self
51 .scheduler
52 .send(RegisterActor(actor, actor_type, tx))
53 .await;
54
55 match rx.await {
56 Ok(true) => actor_ref,
57 _ => Err(ActorRefErr::ActorUnavailable),
58 }
59 }
60
61 pub async fn get_tracked_actor<A: Actor>(&mut self, id: ActorId) -> Option<ActorRef<A>>
62 where
63 A: 'static + Sync + Send,
64 {
65 match self.scheduler.send(GetActor::new(id)).await {
66 Ok(a) => a,
67 Err(_) => None,
68 }
69 }
70}
71
72#[derive(Debug, Eq, PartialEq, Clone)]
73pub enum ActorStatus {
74 Starting,
75 Started,
76 Stopping,
77 Stopped,
78}
79
80pub struct ActorHandlerContext {
81 id: ActorId,
82 status: ActorStatus,
83 boxed_ref: BoxedActorRef,
84}
85
86impl ActorHandlerContext {
87 pub fn new(id: ActorId, status: ActorStatus, boxed_ref: BoxedActorRef) -> ActorHandlerContext {
88 ActorHandlerContext {
89 id,
90 status,
91 boxed_ref,
92 }
93 }
94
95 pub fn id(&self) -> &ActorId {
96 &self.id
97 }
98
99 pub fn set_status(&mut self, state: ActorStatus) {
100 self.status = state
101 }
102
103 pub fn get_status(&self) -> &ActorStatus {
104 &self.status
105 }
106
107 pub(super) fn actor_ref<A: Actor>(&self) -> ActorRef<A>
108 where
109 A: 'static + Sync + Send,
110 {
111 ActorRef::from(self.boxed_ref.clone())
112 }
113}