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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use crate::{
handles::{handle_notifier_pair, ServiceHandles},
initializer::{BoxedServiceInitializer, ServiceInitializationError, ServiceInitializer},
};
use futures::future::join_all;
use std::sync::Arc;
use tari_shutdown::ShutdownSignal;
use tokio::runtime;
pub struct StackBuilder {
initializers: Vec<BoxedServiceInitializer>,
executor: runtime::Handle,
shutdown_signal: ShutdownSignal,
}
impl StackBuilder {
pub fn new(executor: runtime::Handle, shutdown_signal: ShutdownSignal) -> Self {
Self {
initializers: Vec::new(),
executor,
shutdown_signal,
}
}
}
impl StackBuilder {
pub fn add_initializer<I>(self, initializer: I) -> Self
where
I: ServiceInitializer + Send + 'static,
I::Future: Send + 'static,
{
self.add_initializer_boxed(initializer.boxed())
}
pub fn add_initializer_boxed(mut self, initializer: BoxedServiceInitializer) -> Self {
self.initializers.push(initializer);
self
}
pub async fn finish(self) -> Result<Arc<ServiceHandles>, ServiceInitializationError> {
let (notifier, handles_fut) = handle_notifier_pair();
let StackBuilder {
executor,
shutdown_signal,
initializers,
} = self;
let init_futures = initializers.into_iter().map(|mut init| {
ServiceInitializer::initialize(
&mut init,
executor.clone(),
handles_fut.clone(),
shutdown_signal.clone(),
)
});
for result in join_all(init_futures).await {
result?;
}
notifier.notify();
Ok(handles_fut.into_inner())
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{handles::ServiceHandlesFuture, initializer::ServiceInitializer};
use futures::{executor::block_on, future, Future};
use std::sync::atomic::{AtomicUsize, Ordering};
use tari_shutdown::Shutdown;
use tokio::runtime::Runtime;
use tower::service_fn;
#[test]
fn service_defn_simple() {
let rt = Runtime::new().unwrap();
let simple_initializer = |executor: runtime::Handle, _: ServiceHandlesFuture, _: ShutdownSignal| {
executor.spawn(future::ready(()));
future::ok(())
};
let shutdown = Shutdown::new();
let handles = block_on(
StackBuilder::new(rt.handle().clone(), shutdown.to_signal())
.add_initializer(simple_initializer)
.finish(),
);
assert!(handles.is_ok());
}
#[derive(Clone)]
struct DummyServiceHandle(usize);
struct DummyInitializer {
state: Arc<AtomicUsize>,
}
impl DummyInitializer {
fn new(state: Arc<AtomicUsize>) -> Self {
Self { state }
}
}
impl ServiceInitializer for DummyInitializer {
type Future = impl Future<Output = Result<(), ServiceInitializationError>>;
fn initialize(
&mut self,
executor: runtime::Handle,
handles_fut: ServiceHandlesFuture,
_shutdown: ShutdownSignal,
) -> Self::Future
{
executor.spawn(future::ready(()));
handles_fut.register(DummyServiceHandle(123));
executor.spawn(async move {
let final_handles = handles_fut.await;
let handle = final_handles.get_handle::<DummyServiceHandle>().unwrap();
assert_eq!(handle.0, 123);
service_fn(|_: ()| future::ok::<_, ()>(handle.0));
});
self.state.fetch_add(1, Ordering::AcqRel);
future::ready(Ok(()))
}
}
#[test]
fn service_stack_new() {
let rt = Runtime::new().unwrap();
let shared_state = Arc::new(AtomicUsize::new(0));
let shutdown = Shutdown::new();
let initializer = DummyInitializer::new(Arc::clone(&shared_state));
let handles = block_on(
StackBuilder::new(rt.handle().clone(), shutdown.to_signal())
.add_initializer(initializer)
.finish(),
)
.unwrap();
handles.get_handle::<DummyServiceHandle>().unwrap();
assert_eq!(shared_state.load(Ordering::SeqCst), 1);
}
}