1use std::any::{Any, TypeId};
2use std::collections::VecDeque;
3use std::sync::{Arc, atomic::AtomicBool, atomic::AtomicUsize, atomic::Ordering};
4use std::time::{Duration, Instant};
5use std::{cell::RefCell, fmt, future::Future, pin::Pin};
6
7use async_channel::{Receiver, Sender, unbounded};
8use parking_lot::{Mutex, RwLock};
9
10use crate::arbiter::Arbiter;
11use crate::pool::PoolMetrics;
12use crate::{BlockingResult, Builder, Handle, HashMap, Runner, SystemRunner, TaskCallbacks};
13
14static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0);
15
16thread_local!(
17 static PINGS: RefCell<HashMap<Id, VecDeque<PingRecord>>> = RefCell::new(HashMap::default());
18);
19
20#[derive(Default)]
21struct Arbiters {
22 all: HashMap<Id, Arbiter>,
23 list: Vec<Arbiter>,
24}
25
26#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
30pub struct Id(pub(crate) usize);
31
32pub struct System(pub(crate) Arc<SystemInner>);
40
41pub(crate) struct SystemInner {
42 id: usize,
43 arbiter: Arbiter,
44 pub(crate) config: SystemConfig,
45 sender: Sender<SystemCommand>,
46 receiver: Receiver<SystemCommand>,
47 storage: RwLock<HashMap<TypeId, Box<dyn Any + Sync + Send>>>,
48 arbiters: Mutex<Arbiters>,
49 signals: AtomicBool,
50 retired_pools: Mutex<PoolMetrics>,
52}
53
54#[derive(Clone)]
60pub struct SystemConfig {
61 pub(super) name: String,
62 pub(super) stack_size: usize,
63 pub(super) ping_interval: usize,
64 pub(super) ping_threshold: usize,
65 pub(super) latency_interval: usize,
66 pub(super) pool_limit: usize,
67 pub(super) pool_recv_timeout: Duration,
68 pub(super) timer_resolution: u8,
69 pub(super) testing: bool,
70 pub(super) task_callbacks: Option<fn() -> TaskCallbacks>,
71 pub(super) runner: Arc<dyn Runner>,
72}
73
74thread_local!(
75 static CURRENT: RefCell<Option<System>> = const { RefCell::new(None) };
76);
77
78impl Clone for System {
79 fn clone(&self) -> Self {
80 Self(self.0.clone())
81 }
82}
83
84impl SystemInner {
85 pub(crate) fn arbiters(&self) -> Vec<Arbiter> {
87 self.arbiters.lock().list.clone()
88 }
89}
90
91impl System {
92 pub(super) fn start(config: SystemConfig) -> (Self, oneshot::Receiver<i32>) {
94 let id = SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst);
95 let (sender, receiver) = unbounded();
96
97 let (arbiter, controller) = Arbiter::new_system(id, &config);
98
99 let mut arbiters = Arbiters::default();
100 arbiters.all.insert(arbiter.id(), arbiter.clone());
101 arbiters.list.push(arbiter.clone());
102
103 let sys = System(Arc::new(SystemInner {
104 id,
105 config,
106 arbiter,
107 sender,
108 receiver,
109 arbiters: Mutex::new(arbiters),
110 retired_pools: Mutex::new(PoolMetrics::default()),
111 storage: RwLock::new(HashMap::default()),
112 signals: AtomicBool::new(false),
113 }));
114 System::set_current(sys.clone());
115
116 let (stop_tx, stop) = oneshot::channel();
117
118 crate::spawn_detached(SystemSupport::new(&sys, stop_tx).run());
120 crate::spawn_detached(controller.run(sys.clone()));
121
122 (sys, stop)
123 }
124
125 pub fn build() -> Builder {
129 Builder::new()
130 }
131
132 #[allow(clippy::new_ret_no_self)]
133 pub fn new<R: Runner>(name: &str, runner: R) -> SystemRunner {
137 Self::build().name(name).build(runner)
138 }
139
140 #[allow(clippy::new_ret_no_self)]
141 pub fn with_config(name: &str, mut config: SystemConfig) -> SystemRunner {
146 name.clone_into(&mut config.name);
147 Self::build().name(name).build_with(config)
148 }
149
150 pub fn current() -> System {
156 CURRENT.with(|cell| match *cell.borrow() {
157 Some(ref sys) => sys.clone(),
158 None => panic!("System is not running"),
159 })
160 }
161
162 pub fn try_current() -> Option<System> {
164 CURRENT.with(|cell| cell.borrow().as_ref().map(Clone::clone))
165 }
166
167 #[doc(hidden)]
169 pub fn set_current(sys: System) {
170 crate::task::set_callbacks(sys.0.config.task_callbacks.map(|f| f()));
171 CURRENT.with(|s| {
172 *s.borrow_mut() = Some(sys);
173 });
174 }
175
176 pub(crate) fn register_arbiter(&self, arb: Arbiter) {
177 crate::task::set_callbacks(self.0.config.task_callbacks.map(|f| f()));
178 CURRENT.with(|s| {
179 *s.borrow_mut() = Some(self.clone());
180 });
181 let mut arbiters = self.0.arbiters.lock();
182 arbiters.all.insert(arb.id(), arb.clone());
183 arbiters.list.push(arb);
184 }
185
186 pub(crate) fn unregister_arbiter(&self, id: Id) {
187 crate::task::set_callbacks(None);
188 CURRENT.with(|s| {
189 *s.borrow_mut() = None;
190 });
191 let mut arbiters = self.0.arbiters.lock();
192 if let Some(hnd) = arbiters.all.remove(&id) {
193 for (idx, arb) in arbiters.list.iter().enumerate() {
194 if &hnd == arb {
195 arbiters.list.remove(idx);
196 break;
197 }
198 }
199 self.retire_pool(&hnd);
200 }
201 }
202
203 fn retire_pool(&self, arb: &Arbiter) {
206 if arb != &self.0.arbiter {
207 self.0.retired_pools.lock().add_totals(&arb.pool_metrics());
208 }
209 }
210
211 pub(super) fn remove_current() {
212 crate::task::set_callbacks(None);
213 CURRENT.with(|cell| {
214 cell.borrow_mut().take();
215 });
216 }
217
218 pub(super) fn take_arbiters(&self) -> Vec<Arbiter> {
220 let mut arbiters = self.0.arbiters.lock();
221 arbiters.all.clear();
222 let list = std::mem::take(&mut arbiters.list);
223 for arb in &list {
224 self.retire_pool(arb);
225 }
226 list
227 }
228
229 pub(super) fn stop_arbiters(&self) {
231 for arb in self.take_arbiters() {
232 arb.stop();
233 }
234 }
235
236 pub fn id(&self) -> Id {
238 Id(self.0.id)
239 }
240
241 pub fn name(&self) -> &str {
243 &self.0.config.name
244 }
245
246 pub fn stop(&self) {
250 self.stop_with_code(0);
251 }
252
253 pub fn stop_with_code(&self, code: i32) {
260 let _ = self.0.sender.try_send(SystemCommand::Exit(code));
261 }
262
263 pub fn signals(&self) -> bool {
265 self.0.signals.load(Ordering::Relaxed)
266 }
267
268 pub fn enable_signals(&self) {
274 if !self.signals() && crate::signals::start(self) {
275 self.0.signals.store(true, Ordering::Relaxed);
276 }
277 }
278
279 pub fn disable_signals(&self) {
281 if self.signals() {
282 crate::signals::stop(self);
283 self.0.signals.store(false, Ordering::Relaxed);
284 }
285 }
286
287 pub fn arbiter(&self) -> Arbiter {
289 self.0.arbiter.clone()
290 }
291
292 pub fn list_arbiters<F, R>(&self, f: F) -> R
299 where
300 F: FnOnce(&[Arbiter]) -> R,
301 {
302 f(&self.0.arbiters())
303 }
304
305 pub fn list_arbiter_pings<F>(mut f: F)
319 where
320 F: FnMut(&Arbiter, &mut VecDeque<PingRecord>),
321 {
322 PINGS.with(|pings| {
323 let mut p = pings.borrow_mut();
324 let sys = System::current();
325 let arbiters: Vec<_> = {
326 let arbiters = sys.0.arbiters.lock();
327 p.keys()
328 .filter_map(|id| arbiters.all.get(id).map(|arb| (*id, arb.clone())))
329 .collect()
330 };
331
332 for (id, arb) in &arbiters {
334 if let Some(recs) = p.get_mut(id) {
335 f(arb, recs);
336 }
337 }
338 });
339 }
340
341 #[doc(hidden)]
342 pub fn set_latency_callback<F>(f: F)
350 where
351 F: Fn(ntex_error::Backtrace, Option<&'static std::panic::Location<'static>>)
352 + Send
353 + Sync
354 + 'static,
355 {
356 crate::watchdog::set_latency_callback(Arc::new(f));
357 }
358
359 pub fn config(&self) -> SystemConfig {
361 self.0.config.clone()
362 }
363
364 #[inline]
365 pub fn handle(&self) -> Handle {
367 self.arbiter().handle().clone()
368 }
369
370 pub fn testing(&self) -> bool {
372 self.0.config.testing()
373 }
374
375 #[inline]
376 pub fn timer_resolution(&self) -> u8 {
380 self.0.config.timer_resolution()
381 }
382
383 pub fn spawn_blocking<F, R>(&self, f: F) -> BlockingResult<R>
397 where
398 F: FnOnce() -> R + Send + 'static,
399 R: Send + 'static,
400 {
401 Arbiter::with_current_pool(self.0.id, |pool| {
402 pool.unwrap_or(&self.0.arbiter.0.pool).execute(f)
403 })
404 }
405
406 pub fn pool_metrics(&self) -> PoolMetrics {
412 let mut metrics = self.0.arbiter.pool_metrics();
413 let arbiters = self.0.arbiters.lock();
414 for arb in &arbiters.list {
415 if arb != &self.0.arbiter {
416 metrics.add(&arb.pool_metrics());
417 }
418 }
419 metrics.add_totals(&self.0.retired_pools.lock());
420 metrics
421 }
422
423 pub(crate) fn with_current<F, R>(f: F) -> R
425 where
426 F: FnOnce(Option<&System>) -> R,
427 {
428 CURRENT.with(|cell| f(cell.borrow().as_ref()))
429 }
430
431 pub fn get_value<T>(&self, f: impl FnOnce() -> T) -> T
438 where
439 T: Clone + Send + Sync + 'static,
440 {
441 if let Some(boxed) = self.0.storage.read().get(&TypeId::of::<T>())
442 && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
443 {
444 val.clone()
445 } else {
446 let val = f();
447 self.0
448 .storage
449 .write()
450 .insert(TypeId::of::<T>(), Box::new(val.clone()));
451 val
452 }
453 }
454}
455
456impl SystemConfig {
457 #[inline]
458 pub fn testing(&self) -> bool {
460 self.testing
461 }
462
463 #[inline]
464 pub fn timer_resolution(&self) -> u8 {
468 self.timer_resolution
469 }
470
471 #[inline]
472 pub fn task_callbacks(&self) -> Option<fn() -> TaskCallbacks> {
476 self.task_callbacks
477 }
478}
479
480impl fmt::Debug for System {
481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482 f.debug_struct("System")
483 .field("id", &self.0.id)
484 .field("config", &self.0.config)
485 .field("signals", &self.signals())
486 .field("pool", &self.0.arbiter.0.pool)
487 .finish()
488 }
489}
490
491impl fmt::Debug for SystemConfig {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 f.debug_struct("SystemConfig")
494 .field("name", &self.name)
495 .field("testing", &self.testing)
496 .field("stack_size", &self.stack_size)
497 .field("timer_resolution", &self.timer_resolution)
498 .field("task_callbacks", &self.task_callbacks)
499 .finish()
500 }
501}
502
503#[derive(Debug)]
504pub(super) enum SystemCommand {
505 Exit(i32),
506}
507
508#[derive(Debug)]
509struct SystemSupport {
510 sys: System,
511 stop: Option<oneshot::Sender<i32>>,
512 commands: Receiver<SystemCommand>,
513 watchdog: Option<Arc<AtomicBool>>,
514}
515
516impl Drop for SystemSupport {
517 fn drop(&mut self) {
518 self.stop_watchdog();
519 }
520}
521
522impl SystemSupport {
523 fn new(sys: &System, stop: oneshot::Sender<i32>) -> Self {
524 Self {
525 sys: sys.clone(),
526 stop: Some(stop),
527 commands: sys.0.receiver.clone(),
528 watchdog: None,
529 }
530 }
531
532 fn stop_watchdog(&mut self) {
533 if let Some(stop) = self.watchdog.take() {
534 stop.store(true, Ordering::Relaxed);
535 }
536 }
537
538 async fn run(mut self) {
539 crate::metrics::start_latency_sampler(
540 &self.sys.0.arbiter.0.latency,
541 self.sys.0.config.latency_interval,
542 );
543 self.watchdog = crate::watchdog::start(&self.sys);
544 if self.sys.0.config.ping_interval != 0 {
545 crate::spawn_detached(ping_arbiters(self.sys.clone()));
546 }
547
548 loop {
549 match self.commands.recv().await {
550 Ok(SystemCommand::Exit(code)) => {
551 log::debug!("Stopping system with {code} code");
552 self.stop_watchdog();
553 self.sys.stop_arbiters();
554
555 crate::arbiter::run_shutdown_callbacks();
556
557 if let Some(stop) = self.stop.take() {
559 let _ = stop.send(code);
560 }
561 }
562 Err(_) => {
563 log::debug!("System stopped");
564 return;
565 }
566 }
567 }
568 }
569}
570
571#[derive(Copy, Clone, Debug)]
573pub struct PingRecord {
574 pub start: Instant,
576 pub rtt: Option<Duration>,
581}
582
583async fn ping_arbiters(sys: System) {
584 let interval = sys.0.config.ping_interval as u64;
585 let timer = crate::time::TimerHandle::new(0);
586
587 loop {
588 timer.reset(interval);
590 std::future::poll_fn(|cx| timer.poll_elapsed(cx)).await;
591
592 let start = Instant::now();
593 let arbiters = sys.0.arbiters.lock();
594
595 PINGS.with(|pings| {
597 pings
598 .borrow_mut()
599 .retain(|id, _| arbiters.all.contains_key(id));
600 });
601
602 for arb in &arbiters.list {
603 let id = arb.id();
604 let fut = arb.handle().spawn(async move {
605 yield_to().await;
606 });
607
608 PINGS.with(|pings| {
609 let mut p = pings.borrow_mut();
610 let recs = p.entry(id).or_default();
611 recs.push_front(PingRecord { start, rtt: None });
612 recs.truncate(10);
613 });
614
615 crate::spawn_detached(async move {
616 if fut.await.is_ok() {
617 PINGS.with(|pings| {
618 if let Some(recs) = pings.borrow_mut().get_mut(&id)
620 && let Some(rec) = recs.iter_mut().find(|r| r.start == start)
621 {
622 rec.rtt = Some(start.elapsed());
623 }
624 });
625 }
626 });
627 }
628 }
629}
630
631async fn yield_to() {
632 use std::task::{Context, Poll};
633
634 struct Yield {
635 completed: bool,
636 }
637
638 impl Future for Yield {
639 type Output = ();
640
641 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
642 if self.completed {
643 return Poll::Ready(());
644 }
645 self.completed = true;
646 cx.waker().wake_by_ref();
647 Poll::Pending
648 }
649 }
650
651 Yield { completed: false }.await;
652}
653
654#[cfg(test)]
655#[path = "../tests/unit/system.rs"]
656mod tests;