-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathmod.rs
More file actions
1250 lines (1131 loc) · 39.4 KB
/
mod.rs
File metadata and controls
1250 lines (1131 loc) · 39.4 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Utility functions for metrics
pub mod histogram;
mod registration;
pub mod status;
pub(crate) mod task;
/// Prefix for runtime metrics.
pub(crate) const METRICS_PREFIX: &str = "runtime";
pub use commonware_runtime_macros::{EncodeLabelSet, EncodeLabelValue, EncodeStruct};
pub use prometheus_client::{
collector, encoding,
encoding::{
CounterValueEncoder, DescriptorEncoder, EncodeCounterValue, EncodeExemplarTime,
EncodeExemplarValue, EncodeGaugeValue, EncodeLabel, EncodeLabelKey,
EncodeLabelSet as EncodeLabelSetTrait, EncodeLabelValue as EncodeLabelValueTrait,
EncodeMetric, ExemplarValueEncoder, GaugeValueEncoder, LabelEncoder, LabelKeyEncoder,
LabelSetEncoder, LabelValueEncoder, MetricEncoder, NoLabelSet,
},
metrics::{MetricType, TypedMetric},
registry,
registry::Metric,
};
/// Underlying Prometheus metric types. Used when constructing a metric
/// to pass to [`crate::Metrics::register`].
pub mod raw {
pub use prometheus_client::metrics::{
counter::Counter,
family::{self, Family},
gauge::Gauge,
histogram::Histogram,
};
}
use commonware_utils::sync::Mutex;
use prometheus_client::encoding::text::{encode_descriptor, encode_eof, encode_metric};
pub use registration::Registration;
use std::{
any::Any,
borrow::Cow,
collections::{BTreeMap, HashMap},
ops::Deref,
sync::{atomic::Ordering, Arc, Weak},
};
/// Native integer width used by [`raw::Gauge`] on this target.
///
/// `i64` on platforms with 64-bit atomics, `i32` otherwise. Matches
/// `prometheus_client::metrics::gauge::Gauge`'s backing type.
#[cfg(target_has_atomic = "64")]
pub type GaugeValue = i64;
#[cfg(not(target_has_atomic = "64"))]
pub type GaugeValue = i32;
/// A registered counter metric.
pub type Counter = Registered<raw::Counter>;
/// A registered gauge metric.
pub type Gauge = Registered<raw::Gauge>;
/// A registered histogram metric.
pub type Histogram = Registered<raw::Histogram>;
/// A registered family of counters keyed by `L`.
pub type CounterFamily<L> = Registered<raw::Family<L, raw::Counter>>;
/// A registered family of gauges keyed by `L`.
pub type GaugeFamily<L> = Registered<raw::Family<L, raw::Gauge>>;
/// Convenience methods for Prometheus gauges.
pub trait GaugeExt {
/// Set a gauge from a lossless integer conversion.
fn try_set<T: TryInto<GaugeValue>>(&self, value: T) -> Result<GaugeValue, T::Error>;
/// Atomically raise a gauge to at least the provided value.
fn try_set_max<T: TryInto<GaugeValue> + Copy>(&self, value: T) -> Result<GaugeValue, T::Error>;
}
impl GaugeExt for raw::Gauge {
fn try_set<T: TryInto<GaugeValue>>(&self, value: T) -> Result<GaugeValue, T::Error> {
let value = value.try_into()?;
Ok(self.set(value))
}
fn try_set_max<T: TryInto<GaugeValue> + Copy>(&self, value: T) -> Result<GaugeValue, T::Error> {
let value = value.try_into()?;
Ok(self.inner().fetch_max(value, Ordering::Relaxed))
}
}
pub use histogram::HistogramExt;
/// One-line constructors for the common metric types.
pub trait MetricsExt: crate::Metrics {
/// Register a counter with the runtime.
fn counter<N: Into<String>, H: Into<String>>(&self, name: N, help: H) -> Counter {
self.register(name, help, raw::Counter::default())
}
/// Register a gauge with the runtime.
fn gauge<N: Into<String>, H: Into<String>>(&self, name: N, help: H) -> Gauge {
self.register(name, help, raw::Gauge::default())
}
/// Register a histogram with the runtime.
fn histogram<N: Into<String>, H: Into<String>, I>(
&self,
name: N,
help: H,
buckets: I,
) -> Histogram
where
I: IntoIterator<Item = f64>,
{
self.register(name, help, raw::Histogram::new(buckets))
}
/// Register a metric family with the runtime.
fn family<N, H, S, M>(&self, name: N, help: H) -> Registered<raw::Family<S, M>>
where
N: Into<String>,
H: Into<String>,
S: Clone + std::hash::Hash + Eq,
M: Default,
raw::Family<S, M>: Metric,
{
self.register(name, help, raw::Family::<S, M>::default())
}
}
impl<T: crate::Metrics> MetricsExt for T {}
/// Validates that a label matches Prometheus metric name format: `[a-zA-Z][a-zA-Z0-9_]*`.
///
/// # Panics
///
/// Panics if the label is empty, starts with a non-alphabetic character,
/// or contains characters other than `[a-zA-Z0-9_]`.
pub fn validate_label(label: &str) {
let mut chars = label.chars();
assert!(
chars.next().is_some_and(|c| c.is_ascii_alphabetic()),
"label must start with [a-zA-Z]: {label}"
);
assert!(
chars.all(|c| c.is_ascii_alphanumeric() || c == '_'),
"label must only contain [a-zA-Z0-9_]: {label}"
);
}
/// Add an attribute to a sorted attribute list, maintaining sorted order via binary search.
///
/// Returns `true` if the key was new, `false` if it was a duplicate (value overwritten).
pub fn add_attribute(
attributes: &mut Vec<(String, String)>,
key: &str,
value: impl std::fmt::Display,
) -> bool {
let key_string = key.to_string();
let value_string = value.to_string();
match attributes.binary_search_by(|(k, _)| k.cmp(&key_string)) {
Ok(pos) => {
attributes[pos].1 = value_string;
false
}
Err(pos) => {
attributes.insert(pos, (key_string, value_string));
true
}
}
}
/// Count the number of running tasks whose name starts with the given prefix.
///
/// This function encodes metrics and counts tasks that are currently running
/// (have a value of 1) and whose name starts with the specified prefix.
///
/// This is useful for verifying that all child tasks under a given label hierarchy
/// have been properly shut down.
///
/// # Example
///
/// ```rust
/// use commonware_runtime::{
/// deterministic, telemetry::metrics::count_running_tasks, Clock, Metrics, Runner, Spawner,
/// };
/// use std::time::Duration;
///
/// let executor = deterministic::Runner::default();
/// executor.start(|context| async move {
/// // Spawn a task under a labeled context
/// let handle = context.with_label("worker").spawn(|ctx| async move {
/// ctx.sleep(Duration::from_secs(100)).await;
/// });
///
/// // Allow the task to start
/// context.sleep(Duration::from_millis(10)).await;
///
/// // Count running tasks with "worker" prefix
/// let count = count_running_tasks(&context, "worker");
/// assert!(count > 0, "worker task should be running");
///
/// // Abort the task
/// handle.abort();
/// let _ = handle.await;
/// context.sleep(Duration::from_millis(10)).await;
///
/// // Verify task is stopped
/// let count = count_running_tasks(&context, "worker");
/// assert_eq!(count, 0, "worker task should be stopped");
/// });
/// ```
#[cfg(any(test, feature = "test-utils"))]
pub fn count_running_tasks(metrics: &impl crate::Metrics, prefix: &str) -> usize {
let encoded = metrics.encode();
encoded
.lines()
.filter_map(|line| {
if !line.starts_with("runtime_tasks_running{") || !line.contains("kind=\"Task\"") {
return None;
}
let name = line.split("name=\"").nth(1)?.split('"').next()?;
if !name.starts_with(prefix) {
return None;
}
line.trim_end().rsplit(' ').next()?.parse::<usize>().ok()
})
.sum()
}
/// Join a metric or label prefix with a child name using Prometheus' `_` separator.
pub(crate) fn prefixed_name(prefix: &str, name: &str) -> String {
if prefix.is_empty() {
name.to_string()
} else {
format!("{prefix}_{name}")
}
}
/// Build a child context label by appending `label` to `prefix`, asserting that
/// `label` is valid and does not shadow the reserved runtime metric prefix.
pub(crate) fn child_label(prefix: &str, label: &str) -> String {
validate_label(label);
let name = prefixed_name(prefix, label);
assert!(
!name.starts_with(METRICS_PREFIX),
"using runtime label is not allowed"
);
name
}
struct RegistryGuard {
id: usize,
registry: Weak<Mutex<RegistryInner>>,
}
impl Drop for RegistryGuard {
fn drop(&mut self) {
let Some(registry) = self.registry.upgrade() else {
return;
};
registry.lock().release_registration(self.id);
}
}
/// A metric handle whose lifetime controls registry exposure and attached cleanup.
#[must_use = "registered metrics are removed when the returned handle is dropped"]
pub struct Registered<M> {
metric: Arc<M>,
registration: Registration,
}
impl<M> Clone for Registered<M> {
fn clone(&self) -> Self {
Self {
metric: self.metric.clone(),
registration: self.registration.clone(),
}
}
}
impl<M> Registered<M> {
/// Create a metric handle with an explicit lifecycle registration.
///
/// The provided [`Registration`] controls what happens when the last clone
/// of this handle is dropped. Use [`Registration::from`] with `()` for a
/// raw handle that is not exposed by a runtime registry.
pub fn with_registration(metric: M, registration: Registration) -> Self {
Self {
metric: Arc::new(metric),
registration,
}
}
pub fn metric(&self) -> &M {
self.metric.as_ref()
}
}
impl<S, M, C> Registered<raw::Family<S, M, C>>
where
S: Clone + std::hash::Hash + Eq,
C: raw::family::MetricConstructor<M>,
{
pub fn get_by<Q>(&self, label_set: &Q) -> Option<impl Deref<Target = M> + '_>
where
for<'a> S: From<&'a Q>,
{
let label_set = S::from(label_set);
self.get(&label_set)
}
pub fn get_or_create_by<Q>(&self, label_set: &Q) -> impl Deref<Target = M> + '_
where
for<'a> S: From<&'a Q>,
{
let label_set = S::from(label_set);
self.get_or_create(&label_set)
}
pub fn remove_by<Q>(&self, label_set: &Q) -> bool
where
for<'a> S: From<&'a Q>,
{
let label_set = S::from(label_set);
self.remove(&label_set)
}
}
impl<M> Deref for Registered<M> {
type Target = M;
fn deref(&self) -> &Self::Target {
self.metric()
}
}
impl<M: std::fmt::Debug> std::fmt::Debug for Registered<M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Registered")
.field("metric", self.metric())
.finish_non_exhaustive()
}
}
type MetricAttributes = Vec<(Cow<'static, str>, Cow<'static, str>)>;
type MetricKey = (String, MetricAttributes);
struct PendingMetricEntry {
family_name: String,
attributes: MetricAttributes,
metric: Arc<dyn Metric>,
metric_any: Arc<dyn Any + Send + Sync>,
}
fn owned_attributes(attributes: Vec<(String, String)>) -> MetricAttributes {
attributes
.into_iter()
.map(|(k, v)| (Cow::Owned(k), Cow::Owned(v)))
.collect()
}
// Match upstream prometheus-client's `Descriptor::new` normalization.
//
// Source:
// https://github.com/prometheus/client_rust/blob/4a6d40a55443d5b18f5be311d246c03e56f417d6/src/registry.rs#L340-L348
fn normalize_help(help: String) -> String {
help + "."
}
struct MetricEntry {
family_name: String,
attributes: MetricAttributes,
metric: Arc<dyn Metric>,
metric_any: Arc<dyn Any + Send + Sync>,
claims: usize,
family_index: usize,
}
#[derive(Debug)]
struct MetricFamily {
help: String,
metric_type: MetricType,
descriptor: String,
metric_ids: Vec<usize>,
}
/// Manages metrics with explicit lifetimes.
#[derive(Clone)]
pub struct Registry {
inner: Arc<Mutex<RegistryInner>>,
}
struct RegistryInner {
/// Dense metric storage indexed by stable metric id.
metrics: Vec<Option<MetricEntry>>,
/// Metric ids that can be reused after a metric is fully unregistered.
free_metric_ids: Vec<usize>,
/// Metric families keyed by family name, kept sorted for deterministic encoding.
families: BTreeMap<String, MetricFamily>,
/// Exact metric keys for duplicate registration detection.
keys: HashMap<MetricKey, usize>,
/// Monotonic id source used when there is no reusable metric slot.
next_metric_id: usize,
}
impl Default for Registry {
fn default() -> Self {
Self::new()
}
}
impl Registry {
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(RegistryInner::new())),
}
}
pub(crate) fn register<M>(
&self,
name: String,
help: String,
attributes: Vec<(String, String)>,
metric: Arc<M>,
) -> Registered<M>
where
M: Metric,
{
let mut inner = self.inner.lock();
inner.register(Arc::downgrade(&self.inner), name, help, attributes, metric)
}
pub fn encode(&self) -> String {
self.inner.lock().encode()
}
}
impl RegistryInner {
fn new() -> Self {
Self {
metrics: Vec::new(),
free_metric_ids: Vec::new(),
families: BTreeMap::new(),
keys: HashMap::new(),
next_metric_id: 0,
}
}
fn register<M>(
&mut self,
registry: Weak<Mutex<Self>>,
name: String,
help: String,
attributes: Vec<(String, String)>,
metric: Arc<M>,
) -> Registered<M>
where
M: Metric,
{
let attributes = owned_attributes(attributes);
let help = normalize_help(help);
let metric_type = metric.metric_type();
let key = (name.clone(), attributes.clone());
if let Some(existing_id) = self.keys.get(&key).copied() {
let entry = self.metric_ref(existing_id);
if let Some(family) = self.families.get(&name) {
assert_eq!(
family.help, help,
"metric family `{}` registered with inconsistent help text",
name
);
}
let existing_metric = Arc::clone(&entry.metric_any)
.downcast::<M>()
.unwrap_or_else(|_| {
panic!(
"duplicate metric `{}` with attributes {:?} registered with different type",
key.0, key.1
)
});
self.claim_registration(existing_id);
return Registered {
metric: existing_metric,
registration: Registration::from(RegistryGuard {
id: existing_id,
registry,
}),
};
}
self.assert_family_matches(&name, &help, metric_type);
let id = self.allocate_metric_id();
let registration = Registration::from(RegistryGuard { id, registry });
let metric_any: Arc<dyn Any + Send + Sync> = metric.clone();
let metric_erased: Arc<dyn Metric> = metric.clone();
self.insert_metric_entry(
id,
help,
metric_type,
PendingMetricEntry {
family_name: name,
attributes,
metric: metric_erased,
metric_any,
},
);
Registered {
metric,
registration,
}
}
fn metric_slot_mut(&mut self, id: usize) -> &mut Option<MetricEntry> {
if id == self.metrics.len() {
self.metrics.push(None);
}
&mut self.metrics[id]
}
fn metric_ref(&self, id: usize) -> &MetricEntry {
self.metrics
.get(id)
.and_then(Option::as_ref)
.expect("metric id missing from registry")
}
fn metric_mut(&mut self, id: usize) -> &mut MetricEntry {
self.metrics
.get_mut(id)
.and_then(Option::as_mut)
.expect("metric id missing from registry")
}
fn allocate_metric_id(&mut self) -> usize {
if let Some(id) = self.free_metric_ids.pop() {
return id;
}
let id = self.next_metric_id;
self.next_metric_id = self
.next_metric_id
.checked_add(1)
.expect("metric id overflow");
id
}
fn assert_family_matches(&self, name: &str, help: &str, metric_type: MetricType) {
if let Some(family) = self.families.get(name) {
assert_eq!(
family.help, help,
"metric family `{}` registered with inconsistent help text",
name
);
assert_eq!(
family.metric_type.as_str(),
metric_type.as_str(),
"metric family `{}` registered with inconsistent metric type",
name
);
}
}
fn insert_metric_entry(
&mut self,
id: usize,
help: String,
metric_type: MetricType,
entry: PendingMetricEntry,
) {
let PendingMetricEntry {
family_name,
attributes,
metric,
metric_any,
} = entry;
self.keys
.insert((family_name.clone(), attributes.clone()), id);
let family = match self.families.entry(family_name.clone()) {
std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::btree_map::Entry::Vacant(entry) => {
let mut descriptor = String::new();
encode_descriptor(&mut descriptor, &family_name, &help, None, metric_type)
.expect("encoding cached descriptor failed");
entry.insert(MetricFamily {
help,
metric_type,
descriptor,
metric_ids: Vec::new(),
})
}
};
let family_index = family.metric_ids.len();
family.metric_ids.push(id);
self.metric_slot_mut(id).replace(MetricEntry {
family_name,
attributes,
metric,
metric_any,
claims: 1,
family_index,
});
}
fn claim_registration(&mut self, id: usize) {
let entry = self.metric_mut(id);
entry.claims = entry
.claims
.checked_add(1)
.expect("registration claims overflow");
}
fn release_registration(&mut self, id: usize) {
let entry = self.metric_mut(id);
entry.claims = entry
.claims
.checked_sub(1)
.expect("registration claim count underflow");
if entry.claims > 0 {
return;
}
self.drop_metric_entry(id);
}
fn drop_metric_entry(&mut self, id: usize) {
let metric = self
.metrics
.get_mut(id)
.and_then(Option::take)
.expect("metric id missing from registry");
let MetricEntry {
family_name,
attributes,
family_index,
..
} = metric;
let key = (family_name, attributes);
if self.keys.get(&key).copied() == Some(id) {
self.keys.remove(&key);
}
let (family_name, _) = key;
let (swapped_metric_id, remove_family) = {
let family = self
.families
.get_mut(&family_name)
.expect("family missing during unregister");
let removed = family.metric_ids.swap_remove(family_index);
assert_eq!(removed, id, "family index mismatch during unregister");
let swapped = family.metric_ids.get(family_index).copied();
(swapped, family.metric_ids.is_empty())
};
if let Some(swapped_metric_id) = swapped_metric_id {
self.metric_mut(swapped_metric_id).family_index = family_index;
}
if remove_family {
self.families.remove(&family_name);
}
self.free_metric_ids.push(id);
}
pub fn encode(&self) -> String {
let mut output = String::new();
for family in self.families.values() {
let mut encoded_descriptor = false;
for metric_id in &family.metric_ids {
let metric = self.metric_ref(*metric_id);
// Suppress the HELP/TYPE descriptor when the family would
// produce no samples (e.g. a `Family<S, M>` with no child
// entries). Matches upstream prometheus-client's empty-metric
// filtering.
if metric.metric.is_empty() {
continue;
}
if !encoded_descriptor {
output.push_str(&family.descriptor);
encoded_descriptor = true;
}
encode_metric(
&mut output,
&metric.family_name,
None,
&metric.attributes,
metric.metric.as_ref(),
)
.expect("encoding live metric samples failed");
}
}
encode_eof(&mut output).expect("encoding EOF failed");
output
}
}
pub(crate) struct Scope {
registry: Registry,
prefix: String,
}
pub(crate) trait Register {
/// Register a metric under this scope's prefix.
fn register<M: Metric>(&mut self, name: &str, help: &str, metric: M) -> Registered<M>;
/// Create a child scope by appending `prefix` to the current prefix.
fn sub_registry(&mut self, prefix: &str) -> Scope;
}
impl Register for Registry {
fn register<M: Metric>(&mut self, name: &str, help: &str, metric: M) -> Registered<M> {
validate_label(name);
Self::register(
self,
name.to_string(),
help.to_string(),
Vec::new(),
Arc::new(metric),
)
}
fn sub_registry(&mut self, prefix: &str) -> Scope {
validate_label(prefix);
Scope {
registry: self.clone(),
prefix: prefix.to_string(),
}
}
}
impl Register for Scope {
fn register<M: Metric>(&mut self, name: &str, help: &str, metric: M) -> Registered<M> {
validate_label(name);
let name = prefixed_name(&self.prefix, name);
let help = help.to_string();
let metric = Arc::new(metric);
Registry::register(&self.registry, name, help, Vec::new(), metric)
}
fn sub_registry(&mut self, prefix: &str) -> Scope {
validate_label(prefix);
Self {
registry: self.registry.clone(),
prefix: prefixed_name(&self.prefix, prefix),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{deterministic, Metrics, Runner, Spawner};
use commonware_macros::test_traced;
use futures::future;
use prometheus_client::encoding::text::encode;
use std::sync::mpsc::{self, TryRecvError};
#[test_traced]
fn test_count_running_tasks() {
let executor = deterministic::Runner::default();
executor.start(|context| async move {
// Initially no tasks with "worker" prefix
assert_eq!(
count_running_tasks(&context, "worker"),
0,
"no worker tasks initially"
);
// Spawn a task under a labeled context that stays running
let worker_ctx = context.with_label("worker");
let handle1 = worker_ctx.clone().spawn(|_| async move {
future::pending::<()>().await;
});
// Count running tasks with "worker" prefix
let count = count_running_tasks(&context, "worker");
assert_eq!(count, 1, "worker task should be running");
// Non-matching prefix should return 0
assert_eq!(
count_running_tasks(&context, "other"),
0,
"no tasks with 'other' prefix"
);
// Spawn a nested task (worker_child)
let handle2 = worker_ctx.with_label("child").spawn(|_| async move {
future::pending::<()>().await;
});
// Count should include both parent and nested tasks
let count = count_running_tasks(&context, "worker");
assert_eq!(count, 2, "both worker and worker_child should be counted");
// Abort parent task
handle1.abort();
let _ = handle1.await;
// Only nested task remains
let count = count_running_tasks(&context, "worker");
assert_eq!(count, 1, "only worker_child should remain");
// Abort nested task
handle2.abort();
let _ = handle2.await;
// All tasks stopped
assert_eq!(
count_running_tasks(&context, "worker"),
0,
"all worker tasks should be stopped"
);
});
}
#[test_traced]
fn test_no_duplicate_metrics() {
let executor = deterministic::Runner::default();
executor.start(|context| async move {
// Register metrics under different labels (no duplicates)
let c1 = raw::Counter::<u64>::default();
let _metric_a = context.with_label("a").register("test", "help", c1);
let c2 = raw::Counter::<u64>::default();
let _metric_b = context.with_label("b").register("test", "help", c2);
});
// Test passes if runtime doesn't panic on shutdown
}
#[test_traced]
fn test_duplicate_metrics_reuse_existing_handle() {
let executor = deterministic::Runner::default();
executor.start(|context| async move {
let c1 = raw::Counter::<u64>::default();
let metric_a = context.with_label("a").register("test", "help", c1);
let c2 = raw::Counter::<u64>::default();
let metric_b = context.with_label("a").register("test", "help", c2);
assert!(std::ptr::eq(metric_a.metric(), metric_b.metric()));
metric_a.inc();
metric_b.inc_by(2);
let encoded = context.encode();
assert!(encoded.contains("a_test_total 3"));
});
}
#[test]
fn test_claims_track_register_calls_not_handle_clones() {
let registry = Registry::new();
let key: MetricKey = ("votes".to_string(), Vec::new());
let first = registry.register(
key.0.clone(),
"vote count".to_string(),
Vec::new(),
Arc::new(raw::Counter::<u64>::default()),
);
let first_clone = first.clone();
let id = {
let registry = registry.inner.lock();
let id = *registry.keys.get(&key).expect("metric key missing");
assert_eq!(registry.metric_ref(id).claims, 1);
id
};
let second = registry.register(
key.0,
"vote count".to_string(),
Vec::new(),
Arc::new(raw::Counter::<u64>::default()),
);
let second_clone = second.clone();
{
let registry = registry.inner.lock();
assert_eq!(registry.metric_ref(id).claims, 2);
}
drop(first);
drop(second);
{
let registry = registry.inner.lock();
assert_eq!(registry.metric_ref(id).claims, 2);
}
drop(second_clone);
{
let registry = registry.inner.lock();
assert_eq!(registry.metric_ref(id).claims, 1);
}
drop(first_clone);
let registry = registry.inner.lock();
assert!(
registry.keys.is_empty(),
"keys left behind: {:?}",
registry.keys
);
assert!(
registry.families.is_empty(),
"families left behind: {:?}",
registry.families
);
}
#[test]
#[should_panic(expected = "registered with different type")]
fn test_duplicate_metrics_different_type_panics() {
let executor = deterministic::Runner::default();
executor.start(|context| async move {
let counter = raw::Counter::<u64>::default();
let _metric_a = context.with_label("a").register("test", "help", counter);
let gauge = raw::Gauge::<i64>::default();
let _metric_b = context.with_label("a").register("test", "help", gauge);
});
}
#[test]
fn test_duplicate_register_acquires_during_last_drop_window() {
let registry = Registry::new();
let key: MetricKey = ("votes".to_string(), Vec::new());
let original = registry.register(
key.0.clone(),
"vote count".to_string(),
Vec::new(),
Arc::new(raw::Counter::<u64>::default()),
);
let original_metric = Arc::clone(&original.metric);
let _original = std::mem::ManuallyDrop::new(original);
let original_id = {
let registry = registry.inner.lock();
*registry.keys.get(&key).expect("metric key missing")
};
// Simulate the final drop after it has decided to clean up but before
// it obtains the registry lock. The dropped claim is still counted in
// this window.
let duplicate = registry.register(
key.0,
"vote count".to_string(),
Vec::new(),
Arc::new(raw::Counter::<u64>::default()),
);
assert!(Arc::ptr_eq(&original_metric, &duplicate.metric));
registry.inner.lock().release_registration(original_id);
duplicate.inc_by(7);
let encoded = registry.encode();
assert!(
encoded.contains("votes_total 7"),
"last drop removed duplicate registration: {encoded}"
);
drop(duplicate);
let registry = registry.inner.lock();
assert!(
registry.keys.is_empty(),
"keys left behind: {:?}",
registry.keys
);
assert!(
registry.families.is_empty(),
"families left behind: {:?}",
registry.families
);
}
#[test]
fn test_registered_with_registration_notifies_on_last_drop() {
struct NotifyOnDrop(mpsc::Sender<&'static str>);
impl Drop for NotifyOnDrop {
fn drop(&mut self) {
let _ = self.0.send("dropped");
}
}
let (tx, rx) = mpsc::channel();
let registered = Registered::with_registration(
raw::Counter::<u64>::default(),
Registration::from(NotifyOnDrop(tx)),
);
let clone = registered.clone();
drop(registered);
assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
drop(clone);
assert_eq!(rx.recv().unwrap(), "dropped");
assert!(matches!(rx.try_recv(), Err(TryRecvError::Disconnected)));
}
fn register_counter(registry: &Registry, name: &str, help: &str, value: u64) -> Counter {
let counter = raw::Counter::<u64>::default();
counter.inc_by(value);
registry.register(
name.to_string(),
help.to_string(),
Vec::new(),
Arc::new(counter),
)
}
#[test]