1use std::{
38 cell::Cell,
39 collections::HashMap,
40 mem,
41 ops::AddAssign,
42 sync::{atomic::Ordering, Arc, Mutex, MutexGuard, PoisonError},
43 time::{Duration, Instant},
44};
45
46use metrics::{
47 atomics::AtomicU64, Counter, CounterFn, Gauge, GaugeFn, Histogram, HistogramFn, Key, KeyName,
48 Metadata, Recorder, SharedString, Unit,
49};
50use metrics_util::registry::{Registry, Storage};
51
52pub(crate) const FLUSH_INTERVAL: Duration = Duration::from_secs(60);
57
58pub(crate) const HISTOGRAM_CAP: usize = 20;
63
64pub(crate) const ENVELOPE_METRICS: usize = 100;
67
68pub(crate) const TRANSPORT_QUEUE_ENVELOPES: usize = 30;
71
72pub(crate) const FLUSH_BUDGET: usize = TRANSPORT_QUEUE_ENVELOPES / 2 * ENVELOPE_METRICS;
79
80pub(crate) const LABEL_SET_CAP: usize = 256;
85
86pub(crate) const GAUGE_REFRESH_FLUSHES: u64 = 5;
89
90const DROP_WARNING_INTERVAL: Duration = Duration::from_secs(60 * 60);
92
93pub(crate) const SENT_DIRECTLY: &[&str] = &["zcash.chain.tip.block_delay_seconds"];
96
97#[derive(Clone, Debug, PartialEq)]
99pub(crate) struct SentryMetric {
100 pub(crate) metric_type: MetricType,
102 pub(crate) name: String,
104 pub(crate) value: f64,
105 pub(crate) unit: Option<Unit>,
107 pub(crate) attributes: Vec<(String, AttributeValue)>,
109}
110
111#[derive(Clone, Copy, Debug, Eq, PartialEq)]
113pub(crate) enum MetricType {
114 Counter,
116 Gauge,
118 Distribution,
120}
121
122#[derive(Clone, Debug, Eq, Hash, PartialEq)]
124pub(crate) enum AttributeValue {
125 String(String),
126}
127
128pub(crate) struct SentryPolicy {
130 registry: Registry<Key, PolicyStorage>,
131
132 label_sets: Mutex<LabelSets>,
135
136 untracked: Arc<Untracked>,
138
139 units: Mutex<HashMap<String, Unit>>,
141
142 flushing: Mutex<FlushState>,
145}
146
147thread_local! {
148 static IN_FLUSH: Cell<bool> = const { Cell::new(false) };
151}
152
153impl Default for SentryPolicy {
154 fn default() -> Self {
155 Self {
156 registry: Registry::new(PolicyStorage),
157 label_sets: Mutex::default(),
158 untracked: Arc::default(),
159 units: Mutex::default(),
160 flushing: Mutex::default(),
161 }
162 }
163}
164
165impl SentryPolicy {
166 #[cfg(test)]
168 pub(crate) fn flush(&self, send: impl FnOnce(Vec<SentryMetric>)) {
169 self.flush_if(|| true, send);
170 }
171
172 pub(crate) fn flush_if(
180 &self,
181 transport_ready: impl FnOnce() -> bool,
182 send: impl FnOnce(Vec<SentryMetric>),
183 ) {
184 if IN_FLUSH.get() {
185 return;
186 }
187
188 let mut state = self.flushing.lock().unwrap_or_else(PoisonError::into_inner);
189 IN_FLUSH.set(true);
190
191 let mut dropped = Dropped {
192 label_set_cap: self.untracked.take(),
193 ..Dropped::default()
194 };
195 let batch = if transport_ready() {
196 let (batch, left_out) = self.take_batch(&mut state, FLUSH_BUDGET);
197 dropped.flush_budget = left_out;
198 batch
199 } else {
200 let (_, left_out) = self.take_batch(&mut state, 0);
201 dropped.transport_backlog = left_out;
202 Vec::new()
203 };
204 let capped = mem::take(&mut self.lock_label_sets().newly_capped);
205
206 dropped.record();
207 if let Some((dropped, capped)) = state.warning.add(dropped, capped, Instant::now()) {
208 tracing::warn!(
209 flush_budget = dropped.flush_budget,
210 transport_backlog = dropped.transport_backlog,
211 label_set_cap = dropped.label_set_cap,
212 capped_metrics = ?capped,
213 "some metric values weren't sent to Sentry; \
214 zebrad.sentry.metrics.dropped.total counts them by reason",
215 );
216 }
217
218 send(batch);
219 IN_FLUSH.set(false);
220 }
221
222 fn take_batch(&self, state: &mut FlushState, mut room: usize) -> (Vec<SentryMetric>, u64) {
225 state.flushes += 1;
226 let flush = state.flushes;
227
228 let mut counters = Vec::new();
229 self.registry.visit_counters(|key, counter| {
230 if counter.has_increase() {
231 counters.push((key.clone(), counter.clone()));
232 }
233 });
234
235 let mut changed_gauges = Vec::new();
236 let mut unchanged_gauges = Vec::new();
237 self.registry
238 .visit_gauges(|key, gauge| match gauge.due(flush) {
239 Some(GaugeDue::Changed) => changed_gauges.push((key.clone(), gauge.clone())),
240 Some(GaugeDue::Refresh) => unchanged_gauges.push((key.clone(), gauge.clone())),
241 None => {}
242 });
243
244 let mut histograms = Vec::new();
245 self.registry.visit_histograms(|key, distribution| {
246 let values = distribution.take_sample().values;
247 if !values.is_empty() {
248 histograms.push((key.clone(), values));
249 }
250 });
251
252 let units = self.units.lock().unwrap_or_else(PoisonError::into_inner);
253 let unit = |key: &Key| units.get(key.name()).copied();
254 let mut over_budget = 0;
255 let mut batch = Vec::new();
256 let [next_counter, next_changed_gauge, next_unchanged_gauge] = &mut state.next;
257
258 let (counters, left_out) = take_turns(counters, &mut room, next_counter);
259 over_budget += left_out;
260 for (key, counter) in counters {
261 let value = counter.take_increase() as f64;
263 batch.push(metric(MetricType::Counter, &key, value, unit(&key)));
264 }
265
266 for (gauges, next) in [
267 (changed_gauges, next_changed_gauge),
268 (unchanged_gauges, next_unchanged_gauge),
269 ] {
270 let (gauges, left_out) = take_turns(gauges, &mut room, next);
271 over_budget += left_out;
272 for (key, gauge) in gauges {
273 if let Some(value) = gauge.take_unsent(flush) {
274 batch.push(metric(MetricType::Gauge, &key, value, unit(&key)));
275 }
276 }
277 }
278
279 let recorded: usize = histograms.iter().map(|(_, values)| values.len()).sum();
280 let kept = recorded.min(room);
281 over_budget += recorded - kept;
282 let mut kept_indexes = (0..kept).map(|i| i * recorded / kept).peekable();
284 let values = histograms
285 .iter()
286 .flat_map(|(key, values)| values.iter().map(move |value| (key, value)));
287 for (index, (key, value)) in values.enumerate() {
288 if kept_indexes.next_if_eq(&index).is_some() {
289 batch.push(metric(MetricType::Distribution, key, *value, unit(key)));
290 }
291 }
292
293 (batch, u64::try_from(over_budget).unwrap_or(u64::MAX))
294 }
295
296 fn tracked<T>(
299 &self,
300 key: &Key,
301 get: impl Fn(&Key) -> Option<T>,
302 create: impl FnOnce(&Key) -> T,
303 ) -> Option<T> {
304 if let Some(value) = get(key) {
305 return Some(value);
306 }
307
308 let mut label_sets = self.lock_label_sets();
309 if let Some(value) = get(key) {
311 return Some(value);
312 }
313
314 label_sets.try_add(key.name()).then(|| create(key))
315 }
316
317 fn lock_label_sets(&self) -> MutexGuard<'_, LabelSets> {
318 self.label_sets
319 .lock()
320 .unwrap_or_else(PoisonError::into_inner)
321 }
322
323 fn describe(&self, key: KeyName, unit: Option<Unit>) {
324 if let Some(unit) = unit {
325 self.units
326 .lock()
327 .unwrap_or_else(PoisonError::into_inner)
328 .insert(key.as_str().to_owned(), unit);
329 }
330 }
331}
332
333fn take_turns<T>(mut due: Vec<T>, room: &mut usize, next: &mut usize) -> (Vec<T>, usize) {
337 let len = due.len();
338 let taken = len.min(*room);
339 *room -= taken;
340
341 if taken < len {
342 let start = *next % len;
343 due.rotate_left(start);
344 due.truncate(taken);
345 *next = start + taken;
346 }
347
348 (due, len - taken)
349}
350
351fn metric(metric_type: MetricType, key: &Key, value: f64, unit: Option<Unit>) -> SentryMetric {
353 let attributes = key
354 .labels()
355 .map(|label| {
356 (
357 label.key().to_owned(),
358 AttributeValue::String(label.value().to_owned()),
359 )
360 })
361 .collect();
362
363 SentryMetric {
364 metric_type,
365 name: key.name().to_owned(),
366 value,
367 unit,
368 attributes,
369 }
370}
371
372impl Recorder for SentryPolicy {
373 fn describe_counter(&self, key: KeyName, unit: Option<Unit>, _: SharedString) {
374 self.describe(key, unit);
375 }
376
377 fn describe_gauge(&self, key: KeyName, unit: Option<Unit>, _: SharedString) {
378 self.describe(key, unit);
379 }
380
381 fn describe_histogram(&self, key: KeyName, unit: Option<Unit>, _: SharedString) {
382 self.describe(key, unit);
383 }
384
385 fn register_counter(&self, key: &Key, _: &Metadata<'_>) -> Counter {
386 let counter = self.tracked(
387 key,
388 |key| self.registry.get_counter(key),
389 |key| self.registry.get_or_create_counter(key, Arc::clone),
390 );
391 match counter {
392 Some(counter) => Counter::from_arc(counter),
393 None => Counter::from_arc(self.untracked.clone()),
394 }
395 }
396
397 fn register_gauge(&self, key: &Key, _: &Metadata<'_>) -> Gauge {
398 let gauge = self.tracked(
399 key,
400 |key| self.registry.get_gauge(key),
401 |key| self.registry.get_or_create_gauge(key, Arc::clone),
402 );
403 match gauge {
404 Some(gauge) => Gauge::from_arc(gauge),
405 None => Gauge::from_arc(self.untracked.clone()),
406 }
407 }
408
409 fn register_histogram(&self, key: &Key, _: &Metadata<'_>) -> Histogram {
410 if SENT_DIRECTLY.contains(&key.name()) {
411 return Histogram::noop();
412 }
413
414 let distribution = self.tracked(
415 key,
416 |key| self.registry.get_histogram(key),
417 |key| self.registry.get_or_create_histogram(key, Arc::clone),
418 );
419 match distribution {
420 Some(distribution) => Histogram::from_arc(distribution),
421 None => Histogram::from_arc(self.untracked.clone()),
422 }
423 }
424}
425
426struct PolicyStorage;
428
429impl Storage<Key> for PolicyStorage {
430 type Counter = Arc<CounterValue>;
431 type Gauge = Arc<GaugeValue>;
432 type Histogram = Arc<Distribution>;
433
434 fn counter(&self, _: &Key) -> Self::Counter {
435 Arc::default()
436 }
437
438 fn gauge(&self, _: &Key) -> Self::Gauge {
439 Arc::default()
440 }
441
442 fn histogram(&self, _: &Key) -> Self::Histogram {
443 Arc::default()
444 }
445}
446
447#[derive(Default)]
449struct LabelSets {
450 by_name: HashMap<String, NameLabelSets>,
451 newly_capped: Vec<String>,
453}
454
455#[derive(Default)]
456struct NameLabelSets {
457 kept: usize,
458 capped: bool,
459}
460
461impl LabelSets {
462 fn try_add(&mut self, name: &str) -> bool {
464 let Some(label_sets) = self.by_name.get_mut(name) else {
465 self.by_name.insert(
466 name.to_owned(),
467 NameLabelSets {
468 kept: 1,
469 capped: false,
470 },
471 );
472 return true;
473 };
474
475 if label_sets.kept < LABEL_SET_CAP {
476 label_sets.kept += 1;
477 return true;
478 }
479
480 if !label_sets.capped {
481 label_sets.capped = true;
482 self.newly_capped.push(name.to_owned());
483 }
484 false
485 }
486}
487
488#[derive(Default)]
490struct FlushState {
491 flushes: u64,
493 next: [usize; 3],
496 warning: DropWarning,
497}
498
499#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
501struct Dropped {
502 flush_budget: u64,
504 transport_backlog: u64,
507 label_set_cap: u64,
509}
510
511impl Dropped {
512 fn record(&self) {
514 for (reason, values) in [
515 ("flush_budget", self.flush_budget),
516 ("transport_backlog", self.transport_backlog),
517 ("label_set_cap", self.label_set_cap),
518 ] {
519 if values > 0 {
520 metrics::counter!("zebrad.sentry.metrics.dropped.total", "reason" => reason)
521 .increment(values);
522 }
523 }
524 }
525}
526
527impl AddAssign for Dropped {
528 fn add_assign(&mut self, other: Self) {
529 self.flush_budget = self.flush_budget.saturating_add(other.flush_budget);
530 self.transport_backlog = self
531 .transport_backlog
532 .saturating_add(other.transport_backlog);
533 self.label_set_cap = self.label_set_cap.saturating_add(other.label_set_cap);
534 }
535}
536
537#[derive(Default)]
539struct DropWarning {
540 last: Option<Instant>,
542 dropped: Dropped,
544 capped: Vec<String>,
546}
547
548impl DropWarning {
549 fn add(
552 &mut self,
553 dropped: Dropped,
554 capped: Vec<String>,
555 now: Instant,
556 ) -> Option<(Dropped, Vec<String>)> {
557 self.dropped += dropped;
558 self.capped.extend(capped);
559
560 let nothing_dropped = self.dropped == Dropped::default() && self.capped.is_empty();
561 let warned_recently = self
562 .last
563 .is_some_and(|last| now.saturating_duration_since(last) < DROP_WARNING_INTERVAL);
564 if nothing_dropped || warned_recently {
565 return None;
566 }
567
568 self.last = Some(now);
569 Some((mem::take(&mut self.dropped), mem::take(&mut self.capped)))
570 }
571}
572
573#[derive(Default)]
575struct Untracked(AtomicU64);
576
577impl Untracked {
578 fn drop_value(&self) {
579 self.0.fetch_add(1, Ordering::Relaxed);
580 }
581
582 fn take(&self) -> u64 {
584 self.0.swap(0, Ordering::Relaxed)
585 }
586}
587
588impl CounterFn for Untracked {
589 fn increment(&self, _: u64) {
590 self.drop_value();
591 }
592
593 fn absolute(&self, _: u64) {
594 self.drop_value();
595 }
596}
597
598impl GaugeFn for Untracked {
599 fn increment(&self, _: f64) {
600 self.drop_value();
601 }
602
603 fn decrement(&self, _: f64) {
604 self.drop_value();
605 }
606
607 fn set(&self, _: f64) {
608 self.drop_value();
609 }
610}
611
612impl HistogramFn for Untracked {
613 fn record(&self, _: f64) {
614 self.drop_value();
615 }
616}
617
618#[derive(Default)]
623struct CounterValue {
624 total: AtomicU64,
625 flushed: AtomicU64,
626}
627
628impl CounterValue {
629 fn has_increase(&self) -> bool {
630 self.total.load(Ordering::Relaxed) > self.flushed.load(Ordering::Relaxed)
631 }
632
633 fn take_increase(&self) -> u64 {
635 let total = self.total.load(Ordering::Relaxed);
636 let flushed = self.flushed.swap(total, Ordering::Relaxed);
637 total.saturating_sub(flushed)
638 }
639}
640
641impl CounterFn for CounterValue {
642 fn increment(&self, value: u64) {
643 self.total.fetch_add(value, Ordering::Relaxed);
644 }
645
646 fn absolute(&self, value: u64) {
647 self.total.fetch_max(value, Ordering::Relaxed);
648 }
649}
650
651struct GaugeValue {
655 value: AtomicU64,
657 sent: AtomicU64,
659 sent_at: AtomicU64,
661}
662
663enum GaugeDue {
665 Changed,
666 Refresh,
667}
668
669impl Default for GaugeValue {
670 fn default() -> Self {
671 Self {
672 value: AtomicU64::new(f64::NAN.to_bits()),
673 sent: AtomicU64::new(f64::NAN.to_bits()),
674 sent_at: AtomicU64::new(0),
675 }
676 }
677}
678
679impl GaugeValue {
680 fn get(&self) -> Option<f64> {
683 Some(f64::from_bits(self.value.load(Ordering::Relaxed))).filter(|value| value.is_finite())
684 }
685
686 fn due(&self, flush: u64) -> Option<GaugeDue> {
688 let value = self.get()?;
689
690 if value.to_bits() != self.sent.load(Ordering::Relaxed) {
691 Some(GaugeDue::Changed)
692 } else if flush.saturating_sub(self.sent_at.load(Ordering::Relaxed))
693 >= GAUGE_REFRESH_FLUSHES
694 {
695 Some(GaugeDue::Refresh)
696 } else {
697 None
698 }
699 }
700
701 fn take_unsent(&self, flush: u64) -> Option<f64> {
703 let value = self.get()?;
704 self.sent.store(value.to_bits(), Ordering::Relaxed);
705 self.sent_at.store(flush, Ordering::Relaxed);
706 Some(value)
707 }
708
709 fn update(&self, change: impl Fn(f64) -> f64) {
710 let mut bits = self.value.load(Ordering::Relaxed);
711 loop {
712 let current = Some(f64::from_bits(bits))
714 .filter(|value| !value.is_nan())
715 .unwrap_or_default();
716 match self.value.compare_exchange_weak(
717 bits,
718 change(current).to_bits(),
719 Ordering::Relaxed,
720 Ordering::Relaxed,
721 ) {
722 Ok(_) => return,
723 Err(actual) => bits = actual,
724 }
725 }
726 }
727}
728
729impl GaugeFn for GaugeValue {
730 fn increment(&self, value: f64) {
731 self.update(|current| current + value);
732 }
733
734 fn decrement(&self, value: f64) {
735 self.update(|current| current - value);
736 }
737
738 fn set(&self, value: f64) {
739 self.value.store(value.to_bits(), Ordering::Relaxed);
740 }
741}
742
743#[derive(Default)]
749struct Distribution {
750 sample: Mutex<Sample>,
751}
752
753impl Distribution {
754 fn add(&self, value: f64) {
756 if !value.is_finite() {
757 return;
758 }
759
760 self.sample
761 .lock()
762 .unwrap_or_else(PoisonError::into_inner)
763 .record(value);
764 }
765
766 fn take_sample(&self) -> Sample {
768 mem::take(&mut *self.sample.lock().unwrap_or_else(PoisonError::into_inner))
769 }
770}
771
772impl HistogramFn for Distribution {
773 fn record(&self, value: f64) {
774 self.add(value);
775 }
776}
777
778#[derive(Default)]
783struct Sample {
784 recorded: u64,
786 values: Vec<f64>,
787}
788
789impl Sample {
790 fn record(&mut self, value: f64) {
791 let index = self.recorded;
792 self.recorded = self.recorded.saturating_add(1);
793 match sample_slot(index) {
794 Some(slot) if slot < self.values.len() => self.values[slot] = value,
795 Some(_) => self.values.push(value),
796 None => {}
797 }
798 }
799}
800
801fn sample_slot(index: u64) -> Option<usize> {
805 if let Some(index) = usize::try_from(index)
806 .ok()
807 .filter(|index| *index < HISTOGRAM_CAP)
808 {
809 return Some(index);
810 }
811
812 usize::try_from(rand::random_range(0..=index))
813 .ok()
814 .filter(|slot| *slot < HISTOGRAM_CAP)
815}
816
817#[cfg(test)]
818mod tests {
819 use std::{sync::mpsc, thread};
820
821 use metrics::with_local_recorder;
822
823 use super::*;
824
825 fn flush(policy: &SentryPolicy) -> Vec<SentryMetric> {
827 let mut sent = Vec::new();
828 policy.flush(|batch| sent = batch);
829 sent
830 }
831
832 fn string(value: &str) -> AttributeValue {
833 AttributeValue::String(value.to_owned())
834 }
835
836 #[test]
837 fn counters_send_their_increase_once_per_flush() {
838 let policy = SentryPolicy::default();
839
840 with_local_recorder(&policy, || {
841 metrics::describe_counter!("a.count", Unit::Count, "A count.");
842 for _ in 0..3 {
843 metrics::counter!("a.count", "kind" => "not_found").increment(1);
844 }
845 });
846
847 assert_eq!(
848 flush(&policy),
849 [SentryMetric {
850 metric_type: MetricType::Counter,
851 name: "a.count".to_owned(),
852 value: 3.0,
853 unit: Some(Unit::Count),
854 attributes: vec![("kind".to_owned(), string("not_found"))],
855 }],
856 );
857 assert!(flush(&policy).is_empty(), "nothing new was counted");
858
859 with_local_recorder(&policy, || {
860 metrics::counter!("a.count", "kind" => "not_found").increment(2)
861 });
862 assert_eq!(
863 flush(&policy)
864 .iter()
865 .map(|metric| metric.value)
866 .collect::<Vec<_>>(),
867 [2.0],
868 );
869 }
870
871 #[test]
872 fn absolute_counters_send_their_increase() {
873 let policy = SentryPolicy::default();
874 let cpu_seconds = |total| {
875 with_local_recorder(&policy, || {
876 metrics::counter!("process_cpu_seconds_total").absolute(total)
877 })
878 };
879 let values =
880 |batch: Vec<SentryMetric>| batch.iter().map(|metric| metric.value).collect::<Vec<_>>();
881
882 cpu_seconds(100);
883 assert_eq!(values(flush(&policy)), [100.0]);
884
885 cpu_seconds(130);
886 cpu_seconds(145);
887 assert_eq!(values(flush(&policy)), [45.0]);
888
889 cpu_seconds(145);
890 assert!(flush(&policy).is_empty(), "the total didn't increase");
891 }
892
893 #[test]
894 fn gauges_send_their_latest_value_once_set() {
895 let policy = SentryPolicy::default();
896
897 with_local_recorder(&policy, || {
898 metrics::describe_gauge!("a.bytes", Unit::Bytes, "Some bytes.");
899 metrics::gauge!("a.bytes").set(30.0);
900 metrics::gauge!("a.bytes").set(90.0);
901 let _ = metrics::gauge!("a.unset");
903 metrics::gauge!("a.connections").increment(2.0);
905 metrics::gauge!("a.connections").decrement(1.0);
906 });
907
908 let mut sent: Vec<_> = flush(&policy)
909 .into_iter()
910 .map(|metric| (metric.metric_type, metric.name, metric.value, metric.unit))
911 .collect();
912 sent.sort_by(|a, b| a.1.cmp(&b.1));
913
914 let gauge = |name: &str, value, unit| (MetricType::Gauge, name.to_owned(), value, unit);
915 assert_eq!(
916 sent,
917 [
918 gauge("a.bytes", 90.0, Some(Unit::Bytes)),
919 gauge("a.connections", 1.0, None),
920 ],
921 );
922 assert!(
923 flush(&policy).is_empty(),
924 "unchanged gauges wait for their refresh",
925 );
926 }
927
928 #[test]
929 fn unchanged_gauges_are_sent_again_only_at_each_refresh() {
930 let policy = SentryPolicy::default();
931 let set = |value| with_local_recorder(&policy, || metrics::gauge!("a.peers").set(value));
932 let values =
933 |batch: Vec<SentryMetric>| batch.iter().map(|metric| metric.value).collect::<Vec<_>>();
934
935 set(8.0);
936 assert_eq!(values(flush(&policy)), [8.0], "a new gauge is sent");
937
938 for _ in 1..GAUGE_REFRESH_FLUSHES {
939 set(8.0);
940 assert!(
941 flush(&policy).is_empty(),
942 "an unchanged gauge waits for its refresh",
943 );
944 }
945 assert_eq!(
946 values(flush(&policy)),
947 [8.0],
948 "an unchanged gauge is sent at its refresh",
949 );
950
951 set(9.0);
952 assert_eq!(
953 values(flush(&policy)),
954 [9.0],
955 "a changed gauge is sent at the next flush",
956 );
957 assert!(flush(&policy).is_empty());
958 }
959
960 fn count(values: usize) -> f64 {
961 f64::from(u32::try_from(values).expect("test counts are small"))
962 }
963
964 fn dropped(batch: &[SentryMetric], reason: &str) -> f64 {
966 batch
967 .iter()
968 .filter(|metric| {
969 metric.name == "zebrad.sentry.metrics.dropped.total"
970 && metric.attributes == [("reason".to_owned(), string(reason))]
971 })
972 .map(|metric| metric.value)
973 .sum()
974 }
975
976 fn record_label_sets<T>(
979 policy: &SentryPolicy,
980 prefix: &str,
981 label_sets: usize,
982 register: impl Fn(String, String) -> T,
983 record: impl Fn(T),
984 ) {
985 with_local_recorder(policy, || {
986 for label_set in 0..label_sets {
987 let name = format!("{prefix}{}", label_set / LABEL_SET_CAP);
988 record(register(name, label_set.to_string()));
989 }
990 });
991 }
992
993 #[test]
994 fn a_full_flush_sends_counters_then_changed_gauges_then_histogram_values() {
995 let policy = SentryPolicy::default();
996 let (counters, gauges, histograms) = (600, 600, 400);
997 let records_per_histogram = 2 * HISTOGRAM_CAP;
998
999 record_label_sets(
1000 &policy,
1001 "c",
1002 counters,
1003 |name, label| metrics::counter!(name, "i" => label),
1004 |counter| counter.increment(1),
1005 );
1006 record_label_sets(
1007 &policy,
1008 "g",
1009 gauges,
1010 |name, label| metrics::gauge!(name, "i" => label),
1011 |gauge| gauge.set(1.0),
1012 );
1013 record_label_sets(
1014 &policy,
1015 "h",
1016 histograms,
1017 |name, label| metrics::histogram!(name, "i" => label),
1018 |histogram| {
1019 for _ in 0..records_per_histogram {
1020 histogram.record(1.0);
1021 }
1022 },
1023 );
1024
1025 let sent = with_local_recorder(&policy, || flush(&policy));
1026 let types: Vec<MetricType> = sent.iter().map(|metric| metric.metric_type).collect();
1027 let histogram_room = FLUSH_BUDGET - counters - gauges;
1028
1029 assert_eq!(sent.len(), FLUSH_BUDGET, "a full flush sends its budget");
1030 assert!(
1031 types[..counters].iter().all(|t| *t == MetricType::Counter)
1032 && types[counters..counters + gauges]
1033 .iter()
1034 .all(|t| *t == MetricType::Gauge)
1035 && types[counters + gauges..]
1036 .iter()
1037 .all(|t| *t == MetricType::Distribution),
1038 "counters, then gauges, then histogram values",
1039 );
1040
1041 let mut sampled_label_sets: Vec<_> = sent[counters + gauges..]
1042 .iter()
1043 .map(|metric| (&metric.name, &metric.attributes))
1044 .collect();
1045 sampled_label_sets.dedup();
1046 assert_eq!(
1047 sampled_label_sets.len(),
1048 histogram_room.min(histograms),
1049 "histogram values are spread across label sets",
1050 );
1051
1052 let next = flush(&policy);
1053 assert_eq!(
1054 dropped(&next, "flush_budget"),
1055 count(histograms * HISTOGRAM_CAP - histogram_room),
1056 "every histogram value left out is counted",
1057 );
1058 assert_eq!(dropped(&next, "label_set_cap"), 0.0);
1059 }
1060
1061 #[test]
1062 fn counters_left_out_of_a_full_flush_take_turns_and_keep_their_increase() {
1063 let policy = SentryPolicy::default();
1064 let label_sets = FLUSH_BUDGET + FLUSH_BUDGET / 3;
1065 let increment = |policy: &SentryPolicy| {
1066 record_label_sets(
1067 policy,
1068 "c",
1069 label_sets,
1070 |name, label| metrics::counter!(name, "i" => label),
1071 |counter| counter.increment(1),
1072 )
1073 };
1074
1075 let mut sent = Vec::new();
1076 increment(&policy);
1077 let first = flush(&policy);
1078 assert_eq!(first.len(), FLUSH_BUDGET);
1079 sent.extend(first);
1080
1081 increment(&policy);
1082 for _ in 0..3 {
1083 sent.extend(flush(&policy));
1084 }
1085
1086 let mut totals: HashMap<_, f64> = HashMap::new();
1087 for metric in &sent {
1088 *totals
1089 .entry((metric.name.clone(), format!("{:?}", metric.attributes)))
1090 .or_default() += metric.value;
1091 }
1092 assert_eq!(totals.len(), label_sets, "every label set gets its turn");
1093 assert!(
1094 totals.values().all(|total| *total == 2.0),
1095 "counters left out keep their increase for a later flush",
1096 );
1097 }
1098
1099 #[test]
1100 fn a_flush_the_transport_isnt_ready_for_sends_nothing_and_counts_what_was_due() {
1101 let policy = SentryPolicy::default();
1102 let histogram_values = 3;
1103
1104 with_local_recorder(&policy, || {
1105 metrics::counter!("a.count").increment(2);
1106 metrics::gauge!("a.peers").set(8.0);
1107 let histogram = metrics::histogram!("a.duration_seconds");
1108 for _ in 0..histogram_values {
1109 histogram.record(1.0);
1110 }
1111 });
1112
1113 let mut sent = vec![];
1114 with_local_recorder(&policy, || {
1115 policy.flush_if(|| false, |batch| sent = batch);
1116 });
1117 assert!(
1118 sent.is_empty(),
1119 "nothing is sent while the transport is behind"
1120 );
1121
1122 let next = flush(&policy);
1123 let value = |name: &str| {
1124 next.iter()
1125 .find(|metric| metric.name == name)
1126 .map(|metric| metric.value)
1127 };
1128 assert_eq!(value("a.count"), Some(2.0), "counters keep their increase");
1129 assert_eq!(value("a.peers"), Some(8.0), "changed gauges stay due");
1130 assert_eq!(
1131 value("a.duration_seconds"),
1132 None,
1133 "histogram values are dropped"
1134 );
1135 assert_eq!(
1136 dropped(&next, "transport_backlog"),
1137 count(1 + 1 + histogram_values),
1138 "every due value is counted",
1139 );
1140 assert_eq!(dropped(&next, "flush_budget"), 0.0);
1141 }
1142
1143 #[test]
1144 fn label_sets_over_the_cap_are_neither_kept_nor_sent() {
1145 let policy = SentryPolicy::default();
1146 let over = 10;
1147
1148 with_local_recorder(&policy, || {
1149 for label_set in 0..LABEL_SET_CAP + over {
1150 metrics::counter!("a.count", "i" => label_set.to_string()).increment(1);
1151 }
1152 let kept_handle = metrics::counter!("a.count", "i" => "kept_handle");
1153 for _ in 0..5 {
1154 kept_handle.increment(1);
1155 }
1156 for label_set in 0..=LABEL_SET_CAP {
1157 metrics::gauge!("a.gauge", "i" => label_set.to_string()).set(1.0);
1158 metrics::histogram!("a.delay_seconds", "i" => label_set.to_string()).record(1.0);
1159 }
1160 metrics::counter!("a.count", "i" => "0").increment(1);
1162 metrics::counter!("b.count", "i" => "0").increment(1);
1163 });
1164
1165 let mut a_label_sets = 0;
1166 policy.registry.visit_counters(|key, _| {
1167 if key.name() == "a.count" {
1168 a_label_sets += 1;
1169 }
1170 });
1171 assert_eq!(a_label_sets, LABEL_SET_CAP);
1172
1173 let sent = with_local_recorder(&policy, || flush(&policy));
1174 let total = |name: &str| -> (usize, f64) {
1175 let values: Vec<f64> = sent
1176 .iter()
1177 .filter(|metric| metric.name == name)
1178 .map(|metric| metric.value)
1179 .collect();
1180 (values.len(), values.iter().sum())
1181 };
1182 assert_eq!(total("a.count"), (LABEL_SET_CAP, count(LABEL_SET_CAP + 1)));
1183 assert_eq!(total("a.gauge").0, LABEL_SET_CAP);
1184 assert_eq!(total("a.delay_seconds").0, LABEL_SET_CAP);
1185 assert_eq!(total("b.count"), (1, 1.0), "the cap is for each name");
1186
1187 let next = flush(&policy);
1188 assert_eq!(
1189 dropped(&next, "label_set_cap"),
1190 count(over + 5 + 1 + 1),
1191 "every value recorded for a label set over the cap is counted",
1192 );
1193 }
1194
1195 #[test]
1196 fn drop_warnings_start_with_the_first_drop_and_repeat_at_most_hourly() {
1197 let mut warning = DropWarning::default();
1198 let start = Instant::now();
1199 let over_budget = |values| Dropped {
1200 flush_budget: values,
1201 ..Dropped::default()
1202 };
1203 let capped = || vec!["a.count".to_owned()];
1204
1205 assert_eq!(warning.add(Dropped::default(), Vec::new(), start), None);
1206 assert_eq!(
1207 warning.add(over_budget(3), Vec::new(), start),
1208 Some((over_budget(3), Vec::new())),
1209 "drops that start are logged at once",
1210 );
1211 assert_eq!(
1212 warning.add(over_budget(4), capped(), start + FLUSH_INTERVAL),
1213 None,
1214 );
1215
1216 let an_hour_later = start + DROP_WARNING_INTERVAL;
1217 assert_eq!(
1218 warning.add(over_budget(5), Vec::new(), an_hour_later),
1219 Some((over_budget(9), capped())),
1220 "the next warning has everything dropped since the last one",
1221 );
1222
1223 let later = an_hour_later + 2 * DROP_WARNING_INTERVAL;
1224 assert_eq!(warning.add(Dropped::default(), Vec::new(), later), None);
1225 assert_eq!(
1226 warning.add(over_budget(1), Vec::new(), later),
1227 Some((over_budget(1), Vec::new())),
1228 "drops that start again are logged at once",
1229 );
1230 }
1231
1232 #[test]
1233 fn histograms_send_at_most_the_cap_sampled_from_the_interval() {
1234 let policy = SentryPolicy::default();
1235 let cap = u32::try_from(HISTOGRAM_CAP).expect("the cap is small");
1236 let recorded = 10 * cap;
1237
1238 with_local_recorder(&policy, || {
1239 metrics::describe_histogram!("a.duration_seconds", Unit::Seconds, "A duration.");
1240 let histogram = metrics::histogram!("a.duration_seconds", "result" => "success");
1241 for value in 0..recorded {
1242 histogram.record(f64::from(value));
1243 }
1244 metrics::histogram!("a.duration_seconds", "result" => "failure").record(f64::NAN);
1245 metrics::histogram!("b.duration_seconds").record(1.5);
1246 });
1247
1248 let sent = flush(&policy);
1249 let values = |name: &str| -> Vec<f64> {
1250 sent.iter()
1251 .filter(|metric| metric.name == name)
1252 .map(|metric| metric.value)
1253 .collect()
1254 };
1255
1256 let mut capped = values("a.duration_seconds");
1257 capped.sort_by(f64::total_cmp);
1258 capped.dedup();
1259 assert_eq!(capped.len(), HISTOGRAM_CAP, "distinct values up to the cap");
1260 assert!(
1261 capped.iter().all(|value| *value < f64::from(recorded)),
1262 "only recorded values are sent: {capped:?}",
1263 );
1264 assert!(sent
1265 .iter()
1266 .filter(|metric| metric.name == "a.duration_seconds")
1267 .all(|metric| metric.metric_type == MetricType::Distribution
1268 && metric.unit == Some(Unit::Seconds)
1269 && metric.attributes == [("result".to_owned(), string("success"))]));
1270 assert_eq!(values("b.duration_seconds"), [1.5]);
1271 assert!(flush(&policy).is_empty(), "histograms only send new values");
1272 }
1273
1274 #[test]
1275 fn histogram_samples_stay_bounded_without_a_flush() {
1276 let policy = SentryPolicy::default();
1277 let recorded = 100_000_u32;
1278
1279 with_local_recorder(&policy, || {
1280 let histogram = metrics::histogram!("a.duration_seconds");
1281 for value in 0..recorded {
1282 histogram.record(f64::from(value));
1283 }
1284 });
1285
1286 let distribution = policy
1287 .registry
1288 .get_histogram(&Key::from_name("a.duration_seconds"))
1289 .expect("the label set was recorded");
1290 let sample = distribution
1291 .sample
1292 .lock()
1293 .unwrap_or_else(PoisonError::into_inner);
1294 assert_eq!(sample.recorded, u64::from(recorded));
1295 assert_eq!(
1296 sample.values.len(),
1297 HISTOGRAM_CAP,
1298 "the sample keeps only the cap"
1299 );
1300 drop(sample);
1301
1302 assert_eq!(flush(&policy).len(), HISTOGRAM_CAP);
1303 assert!(flush(&policy).is_empty(), "a flush starts a new interval");
1304 }
1305
1306 #[test]
1307 fn values_recorded_during_a_flush_stay_in_one_interval() {
1308 let distribution = Arc::new(Distribution::default());
1309 let recorded = 200_000_u32;
1310
1311 let recorder = {
1312 let distribution = distribution.clone();
1313 thread::spawn(move || {
1314 for value in 0..recorded {
1315 distribution.add(f64::from(value));
1316 }
1317 })
1318 };
1319
1320 let mut counted = 0;
1321 let check = |sample: Sample| {
1322 let expected = usize::try_from(sample.recorded)
1323 .expect("an interval's count fits in usize")
1324 .min(HISTOGRAM_CAP);
1325 assert_eq!(
1326 sample.values.len(),
1327 expected,
1328 "a flush sends every value it counted, up to the cap",
1329 );
1330 sample.recorded
1331 };
1332 while !recorder.is_finished() {
1333 counted += check(distribution.take_sample());
1334 }
1335 recorder.join().expect("the recording thread doesn't panic");
1336 counted += check(distribution.take_sample());
1337
1338 assert_eq!(counted, u64::from(recorded), "each value is counted once");
1339 }
1340
1341 #[test]
1342 fn histogram_samples_are_uniform_over_the_interval() {
1343 let policy = SentryPolicy::default();
1344 let (intervals, recorded) = (200, 1_000_u32);
1345
1346 let mut sampled = Vec::new();
1347 for _ in 0..intervals {
1348 with_local_recorder(&policy, || {
1349 let histogram = metrics::histogram!("a.duration_seconds");
1350 for value in 0..recorded {
1351 histogram.record(f64::from(value));
1352 }
1353 });
1354 sampled.extend(flush(&policy).into_iter().map(|metric| metric.value));
1355 }
1356
1357 assert_eq!(sampled.len(), intervals * HISTOGRAM_CAP);
1361 let mut tenths = [0_usize; 10];
1362 for value in &sampled {
1363 tenths[(*value / f64::from(recorded / 10)) as usize] += 1;
1365 }
1366 assert!(
1367 tenths.iter().all(|values| (280..=520).contains(values)),
1368 "each tenth of the interval is sampled about as often: {tenths:?}",
1369 );
1370 let mean = sampled.iter().sum::<f64>() / count(sampled.len());
1371 assert!((470.0..=530.0).contains(&mean), "mean: {mean}");
1372 }
1373
1374 #[test]
1375 fn flush_waits_for_a_flush_in_progress() {
1376 let policy = Arc::new(SentryPolicy::default());
1377 let (locked_tx, locked_rx) = mpsc::channel();
1378 let (release_tx, release_rx) = mpsc::channel();
1379
1380 let in_progress = thread::spawn({
1382 let policy = policy.clone();
1383 move || {
1384 let _flushing = policy
1385 .flushing
1386 .lock()
1387 .unwrap_or_else(PoisonError::into_inner);
1388 locked_tx.send(()).expect("the test thread is waiting");
1389 release_rx
1390 .recv()
1391 .expect("the test thread releases the flush");
1392 }
1393 });
1394 locked_rx
1395 .recv()
1396 .expect("the other thread holds the flush lock");
1397
1398 let (flushed_tx, flushed_rx) = mpsc::channel();
1399 let flushing = thread::spawn({
1400 let policy = policy.clone();
1401 move || {
1402 policy.flush(drop);
1403 flushed_tx.send(()).expect("the test thread is waiting");
1404 }
1405 });
1406
1407 assert!(
1408 flushed_rx.recv_timeout(Duration::from_millis(100)).is_err(),
1409 "a flush finished while another one was in progress"
1410 );
1411 release_tx.send(()).expect("the other thread is waiting");
1412 flushed_rx
1413 .recv()
1414 .expect("the flush finishes once the other one does");
1415
1416 in_progress.join().expect("the other thread doesn't panic");
1417 flushing.join().expect("the flushing thread doesn't panic");
1418 }
1419
1420 #[test]
1421 fn flush_returns_when_reentered_from_a_flush_on_the_same_thread() {
1422 let policy = SentryPolicy::default();
1423
1424 let _flushing = policy
1426 .flushing
1427 .lock()
1428 .unwrap_or_else(PoisonError::into_inner);
1429 IN_FLUSH.set(true);
1430
1431 policy.flush(|_| panic!("a reentered flush doesn't send"));
1432
1433 IN_FLUSH.set(false);
1434 }
1435}