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
use crate::attributes::{Attributes, MetricId, OnFlush, Prefixed, WithAttributes};
use crate::input::{InputKind, InputMetric, InputScope};
use crate::name::{MetricName, NameParts};
use crate::output::void::VOID_INPUT;
use crate::Flush;
use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Weak};
use std::{fmt, io};
#[cfg(not(feature = "parking_lot"))]
use std::sync::RwLock;
#[cfg(feature = "parking_lot")]
use parking_lot::RwLock;
use atomic_refcell::*;
lazy_static! {
static ref ROOT_PROXY: Proxy = Proxy::new();
}
#[derive(Debug)]
struct ProxyMetric {
name: NameParts,
kind: InputKind,
target: AtomicRefCell<(InputMetric, usize)>,
proxy: Arc<RwLock<InnerProxy>>,
}
impl Drop for ProxyMetric {
fn drop(&mut self) {
write_lock!(self.proxy).drop_metric(&self.name)
}
}
#[derive(Clone, Debug)]
pub struct Proxy {
attributes: Attributes,
inner: Arc<RwLock<InnerProxy>>,
}
impl Default for Proxy {
fn default() -> Self {
ROOT_PROXY.clone()
}
}
struct InnerProxy {
targets: HashMap<NameParts, Arc<dyn InputScope + Send + Sync>>,
metrics: BTreeMap<NameParts, Weak<ProxyMetric>>,
}
impl fmt::Debug for InnerProxy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "metrics: {:?}", self.metrics.keys())?;
write!(f, "targets: {:?}", self.targets.keys())
}
}
impl InnerProxy {
fn new() -> Self {
Self {
targets: HashMap::new(),
metrics: BTreeMap::new(),
}
}
fn set_target(
&mut self,
namespace: &NameParts,
target_scope: Arc<dyn InputScope + Send + Sync>,
) {
self.targets.insert(namespace.clone(), target_scope.clone());
for (metric_name, metric) in self.metrics.range_mut(namespace.clone()..) {
if let Some(metric) = metric.upgrade() {
if !metric_name.is_within(namespace) {
break;
}
if metric.target.borrow().1 > namespace.len() {
continue;
}
let target_metric = target_scope.new_metric(metric.name.short(), metric.kind);
*metric.target.borrow_mut() = (target_metric, namespace.len());
}
}
}
fn get_effective_target(
&self,
namespace: &NameParts,
) -> Option<(Arc<dyn InputScope + Send + Sync>, usize)> {
if let Some(target) = self.targets.get(namespace) {
return Some((target.clone(), namespace.len()));
}
let mut name = namespace.clone();
while let Some(_popped) = name.pop_back() {
if let Some(target) = self.targets.get(&name) {
return Some((target.clone(), name.len()));
}
}
None
}
fn unset_target(&mut self, namespace: &NameParts) {
if self.targets.remove(namespace).is_none() {
return;
}
let (up_target, up_nslen) = self
.get_effective_target(namespace)
.unwrap_or_else(|| (VOID_INPUT.input_dyn(), 0));
for (name, metric) in self.metrics.range_mut(namespace.clone()..) {
if !name.is_within(namespace) {
break;
}
if let Some(metric) = metric.upgrade() {
if metric.target.borrow().1 > namespace.len() {
continue;
}
let new_metric = up_target.new_metric(name.short(), metric.kind);
*metric.target.borrow_mut() = (new_metric, up_nslen);
}
}
}
fn drop_metric(&mut self, name: &NameParts) {
if self.metrics.remove(name).is_none() {
panic!("Could not remove DelegatingMetric weak ref from delegation point")
}
}
fn flush(&self, namespace: &NameParts) -> io::Result<()> {
if let Some((target, _nslen)) = self.get_effective_target(namespace) {
target.flush()
} else {
Ok(())
}
}
}
impl Proxy {
pub fn new() -> Self {
Proxy {
attributes: Attributes::default(),
inner: Arc::new(RwLock::new(InnerProxy::new())),
}
}
#[deprecated(since = "0.7.2", note = "Use target()")]
pub fn set_target<T: InputScope + Send + Sync + 'static>(&self, target: T) {
self.target(target)
}
pub fn target<T: InputScope + Send + Sync + 'static>(&self, target: T) {
write_lock!(self.inner).set_target(self.get_prefixes(), Arc::new(target))
}
pub fn unset_target(&self) {
write_lock!(self.inner).unset_target(self.get_prefixes())
}
#[deprecated(since = "0.7.2", note = "Use default_target()")]
pub fn set_default_target<T: InputScope + Send + Sync + 'static>(target: T) {
Self::default_target(target)
}
pub fn default_target<T: InputScope + Send + Sync + 'static>(target: T) {
ROOT_PROXY.target(target)
}
pub fn unset_default_target(&self) {
ROOT_PROXY.unset_target()
}
}
impl<S: AsRef<str>> From<S> for Proxy {
fn from(name: S) -> Proxy {
Proxy::new().named(name.as_ref())
}
}
impl InputScope for Proxy {
fn new_metric(&self, name: MetricName, kind: InputKind) -> InputMetric {
let name: MetricName = self.prefix_append(name);
let mut inner = write_lock!(self.inner);
let proxy = inner
.metrics
.get(&name)
.and_then(|proxy_ref| Weak::upgrade(proxy_ref))
.unwrap_or_else(|| {
let namespace = &*name;
{
let (target, target_namespace_length) = inner
.get_effective_target(namespace)
.unwrap_or_else(|| (VOID_INPUT.input_dyn(), 0));
let metric_object = target.new_metric(namespace.short(), kind);
let proxy = Arc::new(ProxyMetric {
name: namespace.clone(),
kind,
target: AtomicRefCell::new((metric_object, target_namespace_length)),
proxy: self.inner.clone(),
});
inner
.metrics
.insert(namespace.clone(), Arc::downgrade(&proxy));
proxy
}
});
InputMetric::new(MetricId::forge("proxy", name), move |value, labels| {
proxy.target.borrow().0.write(value, labels)
})
}
}
impl Flush for Proxy {
fn flush(&self) -> io::Result<()> {
self.notify_flush_listeners();
write_lock!(self.inner).flush(self.get_prefixes())
}
}
impl WithAttributes for Proxy {
fn get_attributes(&self) -> &Attributes {
&self.attributes
}
fn mut_attributes(&mut self) -> &mut Attributes {
&mut self.attributes
}
}
#[cfg(feature = "bench")]
mod bench {
use super::*;
use crate::AtomicBucket;
#[bench]
fn proxy_marker_to_aggregate(b: &mut test::Bencher) {
ROOT_PROXY.target(AtomicBucket::new());
let metric = ROOT_PROXY.marker("event_a");
b.iter(|| test::black_box(metric.mark()));
}
#[bench]
fn proxy_marker_to_void(b: &mut test::Bencher) {
let metric = ROOT_PROXY.marker("event_a");
b.iter(|| test::black_box(metric.mark()));
}
}