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
use std::borrow::Borrow;
use std::collections::HashMap;
use std::future::Future;
use std::hash::Hash;
use std::sync::{Arc, Weak};
use derive_builder::Builder;
use parking_lot::Mutex;
use crate::context::{TreeContext, CONTEXT};
use crate::Span;
#[derive(Debug, Clone, Builder)]
#[builder(default)]
pub struct Config {
verbose: bool,
}
#[allow(clippy::derivable_impls)]
impl Default for Config {
fn default() -> Self {
Self { verbose: false }
}
}
pub struct TreeRoot {
context: Arc<Mutex<TreeContext>>,
}
impl TreeRoot {
pub async fn instrument<F: Future>(self, future: F) -> F::Output {
CONTEXT.scope(self.context, future).await
}
}
#[derive(Debug)]
pub struct Registry<K> {
contexts: HashMap<K, Weak<Mutex<TreeContext>>>,
config: Config,
}
impl<K> Registry<K> {
pub fn new(config: Config) -> Self {
Self {
contexts: HashMap::new(),
config,
}
}
}
impl<K> Registry<K>
where
K: std::hash::Hash + Eq + std::fmt::Debug,
{
pub fn register(&mut self, key: K, root_span: impl Into<Span>) -> TreeRoot {
self.contexts.retain(|_, v| v.upgrade().is_some());
let context = Arc::new(Mutex::new(TreeContext::new(
root_span.into(),
self.config.verbose,
)));
let weak = Arc::downgrade(&context);
self.contexts.insert(key, weak);
TreeRoot { context }
}
pub fn iter(&self) -> impl Iterator<Item = (&K, TreeContext)> {
self.contexts
.iter()
.filter_map(|(k, v)| v.upgrade().map(|v| (k, v.lock().clone())))
}
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<TreeContext>
where
K: Borrow<Q>,
Q: Hash + Eq,
{
self.contexts
.get(k)
.and_then(|v| v.upgrade())
.map(|v| v.lock().clone())
}
pub fn clear(&mut self) {
self.contexts.clear();
}
}