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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use std::sync::{Arc, Mutex, PoisonError};
use err_context::prelude::*;
use err_context::AnyError;
use log::{debug, trace, warn};
use serde::de::DeserializeOwned;
#[cfg(feature = "rt-from-cfg")]
use serde::{Deserialize, Serialize};
use spirit::extension::{Extensible, Extension};
use spirit::validation::Action;
#[cfg(all(feature = "cfg-help", feature = "rt-from-cfg"))]
use structdoc::StructDoc;
use structopt::StructOpt;
#[cfg(feature = "rt-from-cfg")]
use tokio::runtime::Builder;
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
#[cfg(feature = "rt-from-cfg")]
const DEFAULT_MAX_THREADS: usize = 512;
#[cfg(feature = "rt-from-cfg")]
const THREAD_NAME: &str = "tokio-runtime-worker";
#[cfg(feature = "rt-from-cfg")]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)]
#[serde(rename_all = "kebab-case", default)]
#[cfg_attr(feature = "cfg-help", derive(StructDoc))]
#[non_exhaustive]
pub struct Config {
#[serde(skip_serializing_if = "Option::is_none")]
pub core_threads: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_threads: Option<usize>,
pub thread_name: String,
}
#[cfg(feature = "rt-from-cfg")]
impl Default for Config {
fn default() -> Self {
Config {
core_threads: None,
max_threads: None,
thread_name: THREAD_NAME.to_owned(),
}
}
}
#[cfg(feature = "rt-from-cfg")]
impl Into<Builder> for Config {
fn into(self) -> Builder {
let mut builder = Builder::new();
let threads = self.core_threads.unwrap_or_else(num_cpus::get);
builder.core_threads(threads);
let max = match self.max_threads {
None if threads >= DEFAULT_MAX_THREADS => {
warn!(
"Increasing max threads from implicit {} to {} to match core threads",
DEFAULT_MAX_THREADS, threads
);
threads
}
None => DEFAULT_MAX_THREADS,
Some(max_threads) if max_threads < threads => {
warn!(
"Incrementing max threads from configured {} to {} to match core threads",
max_threads, threads
);
threads
}
Some(max) => max,
};
builder.max_threads(max);
builder.thread_name(self.thread_name);
builder
}
}
#[non_exhaustive]
#[allow(clippy::type_complexity)]
pub enum Tokio<O, C> {
Default,
Custom(Box<dyn FnMut(&O, &Arc<C>) -> Result<Runtime, AnyError> + Send>),
#[cfg(feature = "rt-from-cfg")]
FromCfg(
Box<dyn FnMut(&O, &C) -> Config + Send>,
Box<dyn FnMut(Builder) -> Result<Runtime, AnyError> + Send>,
),
}
impl<O, C> Tokio<O, C> {
#[cfg(feature = "rt-from-cfg")]
pub fn from_cfg<E>(mut extractor: E) -> Self
where
E: FnMut(&C) -> Config + Send + 'static,
{
let extractor = move |_opts: &O, cfg: &C| extractor(&cfg);
let finish = |mut builder: Builder| -> Result<Runtime, AnyError> { Ok(builder.build()?) };
Tokio::FromCfg(Box::new(extractor), Box::new(finish))
}
pub fn create(&mut self, opts: &O, cfg: &Arc<C>) -> Result<Runtime, AnyError> {
match self {
Tokio::Default => Runtime::new().map_err(AnyError::from),
Tokio::Custom(ctor) => ctor(opts, cfg),
#[cfg(feature = "rt-from-cfg")]
Tokio::FromCfg(extractor, postprocess) => {
let cfg = extractor(opts, cfg);
let mut builder: Builder = cfg.into();
builder.enable_all().threaded_scheduler();
postprocess(builder)
}
}
}
}
impl<O, C> Default for Tokio<O, C> {
fn default() -> Self {
Tokio::Default
}
}
impl<E> Extension<E> for Tokio<E::Opts, E::Config>
where
E: Extensible<Ok = E>,
E::Config: DeserializeOwned + Send + Sync + 'static,
E::Opts: StructOpt + Send + Sync + 'static,
{
fn apply(mut self, ext: E) -> Result<E, AnyError> {
trace!("Wrapping in tokio runtime");
let runtime = Arc::new(Mutex::new(None));
let handle = Arc::new(Mutex::new(None));
let init = {
let mut initialized = false;
let runtime = Arc::clone(&runtime);
let handle = Arc::clone(&handle);
#[cfg(feature = "rt-from-cfg")]
let mut prev_cfg = None;
move |_: &_, cfg: &Arc<_>, opts: &_| -> Result<Action, AnyError> {
if initialized {
#[cfg(feature = "rt-from-cfg")]
if let Tokio::FromCfg(extract, _) = &mut self {
let prev = prev_cfg
.as_ref()
.expect("Should have stored config on init");
let new = extract(opts, &cfg);
if prev != &new {
warn!("Tokio configuration differs, but can't be reloaded at run time");
}
}
} else {
debug!("Creating the tokio runtime");
let new_runtime = self.create(opts, &cfg).context("Tokio runtime creation")?;
let new_handle = new_runtime.handle().clone();
*runtime.lock().unwrap() = Some(new_runtime);
*handle.lock().unwrap() = Some(new_handle);
initialized = true;
#[cfg(feature = "rt-from-cfg")]
if let Tokio::FromCfg(extract, _) = &mut self {
prev_cfg = Some(extract(opts, &cfg));
}
}
Ok(Action::new())
}
};
let (terminate_send, terminate_recv) = oneshot::channel();
#[allow(clippy::type_complexity)]
let around_hooks: Box<dyn for<'a> FnMut(Box<dyn FnOnce() + 'a>) + Send> =
Box::new(move |inner| {
let locked = handle
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(handle) = locked.as_ref() {
trace!("Wrapping hooks into tokio handle");
handle.enter(inner);
trace!("Leaving tokio handle");
} else {
drop(locked);
trace!("Running hooks without tokio handle, not available yet");
inner();
}
});
ext
.on_terminate(|| {
let _ = terminate_send.send(());
})
.config_validator(init)
.around_hooks(around_hooks)
.run_around(move |spirit, inner| -> Result<(), AnyError> {
let mut runtime = runtime.lock().unwrap().take().expect("Run even before config");
debug!("Running with tokio handle");
let result = runtime.enter(inner);
debug!("Inner bodies ended");
if result.is_ok() {
debug!("Waiting for spirit to terminate");
let _ = runtime.block_on(terminate_recv);
debug!("Spirit signalled termination to runtime");
drop(runtime);
} else {
warn!("Tokio runtime initialization body returned an error, trying to shut everything down gracefully");
runtime.shutdown_background();
spirit.terminate();
}
result
})
}
}