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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use std::cell::Cell;
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;
use tokio::runtime::{Builder, Runtime};
use tokio::sync::oneshot::{self, Sender};
#[derive(Clone, Debug)]
pub struct ShutGuard(Arc<Sender<()>>);
thread_local! {
static SHUT_GUARD: Cell<Option<ShutGuard>> = Cell::new(None);
}
fn with_shut_guard<R, F: FnOnce() -> R>(g: Option<ShutGuard>, f: F) -> R {
SHUT_GUARD.with(|c| {
assert!(c.replace(g).is_none());
struct Guard<'a>(&'a Cell<Option<ShutGuard>>);
impl Drop for Guard<'_> {
fn drop(&mut self) {
self.0.take();
}
}
let _g = Guard(c);
f()
})
}
pub fn shut_guard() -> Option<ShutGuard> {
SHUT_GUARD.with(|c| {
let g = c.take();
c.set(g.clone());
g
})
}
#[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 From<Config> for Builder {
fn from(cfg: Config) -> Builder {
let mut builder = Builder::new_multi_thread();
let threads = cfg.core_threads.unwrap_or_else(num_cpus::get);
builder.worker_threads(threads);
let max = match cfg.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 + 1
);
threads + 1
}
Some(max) => max,
};
builder.max_blocking_threads(max);
builder.thread_name(cfg.thread_name);
builder
}
}
#[non_exhaustive]
#[allow(clippy::type_complexity)]
pub enum Tokio<O, C> {
#[cfg(feature = "multithreaded")]
Default,
SingleThreaded,
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 {
#[cfg(feature = "multithreaded")]
Tokio::Default => Runtime::new().map_err(AnyError::from),
Tokio::SingleThreaded => Builder::new_current_thread()
.enable_all()
.build()
.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();
postprocess(builder)
}
}
}
}
#[cfg(feature = "multithreaded")]
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::<()>();
let shutdown_guard = Arc::new(Mutex::new(Some(ShutGuard(Arc::new(terminate_send)))));
let shutdown_guard_main = Arc::clone(&shutdown_guard);
let shutdown_guard_drain = Arc::clone(&shutdown_guard);
#[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);
let shut_guard = shutdown_guard.lock().unwrap().clone();
with_shut_guard(shut_guard, || {
if let Some(handle) = locked.as_ref() {
trace!("Wrapping hooks into tokio handle");
let _guard = handle.enter();
inner();
trace!("Leaving tokio handle");
} else {
drop(locked);
trace!("Running hooks without tokio handle, not available yet");
inner();
}
})
});
ext
.config_validator(init)
.around_hooks(around_hooks)
.on_terminate(move || {
trace!("Removing global shutdown guard (others might be present in resources)");
shutdown_guard_drain.lock().unwrap().take();
})
.run_around(move |spirit, inner| -> Result<(), AnyError> {
let runtime = runtime.lock().unwrap().take().expect("Run even before config");
debug!("Running with tokio runtime");
let _guard = runtime.enter();
let shut_guard = shutdown_guard_main.lock().unwrap().clone();
let result = with_shut_guard(shut_guard, 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");
runtime.shutdown_background();
spirit.terminate();
}
result
})
}
}