1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use crate::actor::start_actor;
use crate::{Actor, Addr, Context};
use anyhow::Result;
use fnv::FnvHasher;
use futures::channel::oneshot;
use futures::lock::Mutex;
use futures::FutureExt;
use once_cell::sync::OnceCell;
use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
#[async_trait::async_trait]
pub trait Service: Actor + Default {
async fn from_registry() -> Result<Addr<Self>> {
static REGISTRY: OnceCell<
Mutex<HashMap<TypeId, Box<dyn Any + Send>, BuildHasherDefault<FnvHasher>>>,
> = OnceCell::new();
let registry = REGISTRY.get_or_init(Default::default);
let mut registry = registry.lock().await;
match registry.get_mut(&TypeId::of::<Self>()) {
Some(addr) => Ok(addr.downcast_ref::<Addr<Self>>().unwrap().clone()),
None => {
let (tx_exit, rx_exit) = oneshot::channel();
let rx_exit = rx_exit.shared();
let (ctx, rx, tx) = Context::new(Some(rx_exit));
registry.insert(TypeId::of::<Self>(), Box::new(ctx.address()));
drop(registry);
start_actor(ctx.clone(), rx, tx_exit, Self::default()).await?;
Ok(Addr {
actor_id: ctx.actor_id(),
tx,
rx_exit: ctx.rx_exit.clone(),
})
}
}
}
}
thread_local! {
static LOCAL_REGISTRY: RefCell<HashMap<TypeId, Box<dyn Any + Send>, BuildHasherDefault<FnvHasher>>> = Default::default();
}
#[async_trait::async_trait]
pub trait LocalService: Actor + Default {
async fn from_registry() -> Result<Addr<Self>> {
let res = LOCAL_REGISTRY.with(|registry| {
registry
.borrow_mut()
.get_mut(&TypeId::of::<Self>())
.map(|addr| addr.downcast_ref::<Addr<Self>>().unwrap().clone())
});
match res {
Some(addr) => Ok(addr),
None => {
let addr = {
let (tx_exit, rx_exit) = oneshot::channel();
let rx_exit = rx_exit.shared();
let (ctx, rx, tx) = Context::new(Some(rx_exit));
start_actor(ctx.clone(), rx, tx_exit, Self::default()).await?;
Addr {
actor_id: ctx.actor_id(),
tx,
rx_exit: ctx.rx_exit.clone(),
}
};
LOCAL_REGISTRY.with(|registry| {
registry
.borrow_mut()
.insert(TypeId::of::<Self>(), Box::new(addr.clone()));
});
Ok(addr)
}
}
}
}