1use std::{
4 io,
5 sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, Weak},
6 thread,
7 time::{Duration, Instant},
8};
9
10use sentry::{
11 protocol::{LogAttribute, Unit},
12 transports::DefaultTransportFactory,
13 Transport, TransportFactory, TransportOptions,
14};
15
16use crate::components::metrics::sentry_policy::{
17 AttributeValue, MetricType, SentryMetric, SentryPolicy, ENVELOPE_METRICS, FLUSH_INTERVAL,
18};
19
20static POLICY: OnceLock<SentryPolicy> = OnceLock::new();
22
23const ENVELOPE_INTERVAL: Duration = Duration::from_secs(1);
30
31static PACE: Pace = Pace::new(ENVELOPE_INTERVAL);
33
34const TRANSPORT_WAIT: Duration = Duration::from_secs(2);
40
41static TRANSPORT: TransportCheck = TransportCheck::new();
43
44pub(super) fn start() -> Option<&'static SentryPolicy> {
50 start_with(&POLICY, || {
51 thread::Builder::new()
52 .name("sentry transport check".to_owned())
53 .spawn(|| TRANSPORT.run())?;
54
55 thread::Builder::new()
56 .name("sentry metrics flush".to_owned())
57 .spawn(|| {
58 let mut sending = Duration::ZERO;
59 loop {
60 thread::sleep(FLUSH_INTERVAL.saturating_sub(sending));
61 let started = Instant::now();
62 if let Some(policy) = POLICY.get() {
63 flush_paced(policy, &PACE, transport_ready, send);
64 }
65 sending = started.elapsed();
66 }
67 })
68 })
69}
70
71fn start_with<T>(
76 policy: &OnceLock<SentryPolicy>,
77 spawn_flush: impl FnOnce() -> io::Result<T>,
78) -> Option<&SentryPolicy> {
79 if let Some(policy) = policy.get() {
80 return Some(policy);
81 }
82
83 match spawn_flush() {
84 Ok(_) => Some(policy.get_or_init(SentryPolicy::default)),
85 Err(error) => {
86 error!(
87 ?error,
88 "unable to start the Sentry metrics threads: Zebra won't send metrics to Sentry",
89 );
90 None
91 }
92 }
93}
94
95pub(super) fn flush_at_exit() {
99 PACE.stop();
100
101 if let Some(policy) = POLICY.get() {
102 flush_paced(policy, &PACE, transport_ready, send);
103 }
104}
105
106fn transport_ready() -> bool {
109 TRANSPORT.sent_everything(TRANSPORT_WAIT)
110}
111
112fn flush_paced(
114 policy: &SentryPolicy,
115 pace: &Pace,
116 transport_ready: impl FnOnce() -> bool,
117 send: impl FnMut(Vec<SentryMetric>),
118) {
119 policy.flush_if(transport_ready, |batch| send_paced(batch, pace, send));
120}
121
122fn send_paced(batch: Vec<SentryMetric>, pace: &Pace, mut send: impl FnMut(Vec<SentryMetric>)) {
124 let mut metrics = batch.into_iter();
125 let mut envelope: Vec<_> = metrics.by_ref().take(ENVELOPE_METRICS).collect();
126
127 while !envelope.is_empty() {
128 send(envelope);
129 envelope = metrics.by_ref().take(ENVELOPE_METRICS).collect();
130 if !envelope.is_empty() {
131 pace.wait();
132 }
133 }
134}
135
136struct Pace {
138 interval: Duration,
139 stopped: Mutex<bool>,
140 stop: Condvar,
141}
142
143impl Pace {
144 const fn new(interval: Duration) -> Self {
145 Self {
146 interval,
147 stopped: Mutex::new(false),
148 stop: Condvar::new(),
149 }
150 }
151
152 fn wait(&self) {
154 let _ = self
155 .stop
156 .wait_timeout_while(lock(&self.stopped), self.interval, |stopped| !*stopped);
157 }
158
159 fn stop(&self) {
161 *lock(&self.stopped) = true;
162 self.stop.notify_all();
163 }
164}
165
166pub(super) fn transport_factory() -> impl TransportFactory {
169 CheckedTransport(&TRANSPORT)
170}
171
172struct CheckedTransport(&'static TransportCheck);
174
175impl TransportFactory for CheckedTransport {
176 fn create_transport_with_options(&self, options: TransportOptions) -> Arc<dyn Transport> {
177 let transport = DefaultTransportFactory.create_transport_with_options(options);
178 self.0.watch(&transport);
179 transport
180 }
181}
182
183struct TransportCheck {
192 transport: Mutex<Option<Weak<dyn Transport>>>,
193 pending: Mutex<bool>,
195 changed: Condvar,
196}
197
198impl TransportCheck {
199 const fn new() -> Self {
200 Self {
201 transport: Mutex::new(None),
202 pending: Mutex::new(false),
203 changed: Condvar::new(),
204 }
205 }
206
207 fn watch(&self, transport: &Arc<dyn Transport>) {
209 *lock(&self.transport) = Some(Arc::downgrade(transport));
210 }
211
212 fn sent_everything(&self, wait: Duration) -> bool {
215 let mut pending = lock(&self.pending);
216 if !*pending {
217 *pending = true;
218 self.changed.notify_all();
219 }
220
221 let (pending, _) = self
222 .changed
223 .wait_timeout_while(pending, wait, |pending| *pending)
224 .unwrap_or_else(PoisonError::into_inner);
225 !*pending
226 }
227
228 fn run(&self) {
230 let mut pending = lock(&self.pending);
231 loop {
232 pending = self
233 .changed
234 .wait_while(pending, |pending| !*pending)
235 .unwrap_or_else(PoisonError::into_inner);
236 drop(pending);
237
238 let transport = lock(&self.transport).as_ref().and_then(Weak::upgrade);
239 if let Some(transport) = transport {
240 transport.flush(Duration::MAX);
241 }
242
243 pending = lock(&self.pending);
244 *pending = false;
245 self.changed.notify_all();
246 }
247 }
248}
249
250fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
251 mutex.lock().unwrap_or_else(PoisonError::into_inner)
252}
253
254pub(super) fn send(batch: Vec<SentryMetric>) {
256 for metric in batch {
257 let attributes = metric
258 .attributes
259 .into_iter()
260 .map(|(key, value)| (key, log_attribute(value)));
261 let unit = UNIT_OVERRIDES
262 .iter()
263 .find(|(name, _)| *name == metric.name)
264 .map(|(_, unit)| unit.clone())
265 .or_else(|| metric.unit.and_then(sentry_unit));
266
267 match metric.metric_type {
268 MetricType::Counter => attributes
269 .fold(
270 sentry::metrics::counter(metric.name, metric.value),
271 |counter, (key, value)| counter.attribute(key, value),
272 )
273 .capture(),
274 MetricType::Gauge => {
275 let gauge = sentry::metrics::gauge(metric.name, metric.value);
276 let gauge = match unit {
277 Some(unit) => gauge.unit(unit),
278 None => gauge,
279 };
280 attributes
281 .fold(gauge, |gauge, (key, value)| gauge.attribute(key, value))
282 .capture()
283 }
284 MetricType::Distribution => {
285 let distribution = sentry::metrics::distribution(metric.name, metric.value);
286 let distribution = match unit {
287 Some(unit) => distribution.unit(unit),
288 None => distribution,
289 };
290 attributes
291 .fold(distribution, |distribution, (key, value)| {
292 distribution.attribute(key, value)
293 })
294 .capture()
295 }
296 }
297 }
298}
299
300fn log_attribute(value: AttributeValue) -> LogAttribute {
301 match value {
302 AttributeValue::String(value) => value.into(),
303 }
304}
305
306const UNIT_OVERRIDES: &[(&str, Unit)] = &[("process.memory.rss_fraction", Unit::Ratio)];
308
309fn sentry_unit(unit: metrics::Unit) -> Option<Unit> {
311 use metrics::Unit as M;
312
313 Some(match unit {
314 M::Seconds => Unit::Second,
315 M::Milliseconds => Unit::Millisecond,
316 M::Microseconds => Unit::Microsecond,
317 M::Nanoseconds => Unit::Nanosecond,
318 M::Bytes => Unit::Byte,
319 M::Kibibytes => Unit::Kibibyte,
320 M::Mebibytes => Unit::Mebibyte,
321 M::Gibibytes => Unit::Gibibyte,
322 M::Tebibytes => Unit::Tebibyte,
323 M::Percent => Unit::Percent,
324 _ => return None,
325 })
326}
327
328#[cfg(test)]
329mod tests {
330 use std::{
331 io,
332 net::TcpListener,
333 sync::{
334 atomic::{AtomicUsize, Ordering},
335 mpsc, Arc, Condvar, Mutex, OnceLock,
336 },
337 thread,
338 time::Duration,
339 };
340
341 use metrics::with_local_recorder;
342 use sentry::{
343 protocol::{Envelope, EnvelopeItem, Event, ItemContainer},
344 test::with_captured_envelopes_options,
345 ClientOptions, Transport, TransportFactory, TransportOptions,
346 };
347
348 use crate::components::metrics::sentry_policy::{
349 MetricType, SentryMetric, SentryPolicy, ENVELOPE_METRICS, FLUSH_BUDGET,
350 TRANSPORT_QUEUE_ENVELOPES,
351 };
352
353 use super::{
354 flush_paced, lock, send, send_paced, start_with, CheckedTransport, Pace, TransportCheck,
355 };
356
357 fn metrics(count: usize) -> Vec<SentryMetric> {
358 (0..count)
359 .map(|i| SentryMetric {
360 metric_type: MetricType::Counter,
361 name: format!("a{i}.count"),
362 value: 1.0,
363 unit: None,
364 attributes: Vec::new(),
365 })
366 .collect()
367 }
368
369 #[test]
370 fn policy_is_created_only_with_a_flush_thread() {
371 let _init_guard = zebra_test::init();
372
373 let policy = OnceLock::new();
374 let started = start_with(&policy, || {
375 Err::<(), _>(io::Error::other("no threads left"))
376 });
377 assert!(
378 started.is_none() && policy.get().is_none(),
379 "without a flush thread, the policy would keep every histogram value",
380 );
381
382 assert!(start_with(&policy, || Ok(())).is_some());
383
384 let mut spawned_again = false;
385 let started_again = start_with(&policy, || {
386 spawned_again = true;
387 Ok(())
388 });
389 assert!(started_again.is_some());
390 assert!(!spawned_again, "one flush thread flushes the policy");
391 }
392
393 #[test]
395 fn a_full_flush_is_sent_in_sdk_envelopes() {
396 let pace = Pace::new(Duration::ZERO);
397
398 let envelopes = with_captured_envelopes_options(
399 || send_paced(metrics(FLUSH_BUDGET), &pace, send),
400 ClientOptions::default(),
401 );
402 let metrics_per_envelope: Vec<usize> = envelopes
403 .iter()
404 .flat_map(|envelope| envelope.items())
405 .filter_map(|item| match item {
406 EnvelopeItem::ItemContainer(ItemContainer::Metrics(metrics)) => Some(metrics.len()),
407 _ => None,
408 })
409 .collect();
410
411 assert_eq!(
412 metrics_per_envelope,
413 vec![ENVELOPE_METRICS; FLUSH_BUDGET / ENVELOPE_METRICS],
414 );
415 }
416
417 #[test]
418 fn paced_flushes_wait_between_envelopes_until_stopped() {
419 let pace = Arc::new(Pace::new(Duration::from_secs(60 * 60)));
420 let (parts_tx, parts_rx) = mpsc::channel();
421
422 let sending = thread::spawn({
423 let pace = pace.clone();
424 move || {
425 send_paced(metrics(2 * ENVELOPE_METRICS + 1), &pace, |part| {
426 parts_tx
427 .send(part.len())
428 .expect("the test thread is waiting");
429 })
430 }
431 });
432
433 assert_eq!(parts_rx.recv(), Ok(ENVELOPE_METRICS));
434 assert!(
435 parts_rx.recv_timeout(Duration::from_millis(100)).is_err(),
436 "the next part waits",
437 );
438
439 pace.stop();
440 assert_eq!(parts_rx.recv(), Ok(ENVELOPE_METRICS));
441 assert_eq!(parts_rx.recv(), Ok(1), "a stopped pace doesn't wait");
442 sending.join().expect("the sending thread doesn't panic");
443 }
444
445 #[derive(Default)]
447 struct StallingTransport {
448 stalled: Mutex<bool>,
449 resumed: Condvar,
450 flushes: AtomicUsize,
451 }
452
453 impl StallingTransport {
454 fn stall(&self, stalled: bool) {
455 *lock(&self.stalled) = stalled;
456 self.resumed.notify_all();
457 }
458 }
459
460 impl Transport for StallingTransport {
461 fn send_envelope(&self, _: Envelope) {}
462
463 fn flush(&self, _: Duration) -> bool {
464 self.flushes.fetch_add(1, Ordering::Relaxed);
465 let _resumed = self
466 .resumed
467 .wait_while(lock(&self.stalled), |stalled| *stalled);
468 true
469 }
470 }
471
472 fn running_check() -> &'static TransportCheck {
474 let check: &'static TransportCheck = Box::leak(Box::new(TransportCheck::new()));
475 thread::spawn(|| check.run());
476 check
477 }
478
479 fn count_and_flush(
482 policy: &SentryPolicy,
483 check: &TransportCheck,
484 wait: Duration,
485 ) -> Vec<SentryMetric> {
486 with_local_recorder(policy, || metrics::counter!("a.count").increment(1));
487
488 let mut sent = Vec::new();
489 flush_paced(
490 policy,
491 &Pace::new(Duration::ZERO),
492 || check.sent_everything(wait),
493 |part| sent.extend(part),
494 );
495 sent
496 }
497
498 #[test]
501 fn flushes_send_nothing_until_the_transport_sends_what_was_queued() {
502 let transport = Arc::new(StallingTransport::default());
503 let check = running_check();
504 check.watch(&(transport.clone() as Arc<dyn Transport>));
505 let policy = SentryPolicy::default();
506
507 transport.stall(true);
508 for _ in 0..3 {
509 assert!(
510 count_and_flush(&policy, check, Duration::from_millis(50)).is_empty(),
511 "the transport is still sending",
512 );
513 }
514 assert_eq!(
515 transport.flushes.load(Ordering::Relaxed),
516 1,
517 "one check at a time waits in the transport queue",
518 );
519
520 transport.stall(false);
521 let sent = count_and_flush(&policy, check, Duration::from_secs(60));
522 let sent: Vec<_> = sent
523 .iter()
524 .map(|metric| (metric.name.as_str(), metric.value))
525 .collect();
526 assert_eq!(
527 sent,
528 [("a.count", 4.0)],
529 "the counter keeps the increase of the flushes that sent nothing",
530 );
531 }
532
533 #[test]
537 fn a_flush_at_exit_waits_for_the_transport_to_send_the_flush_in_progress() {
538 let transport = Arc::new(StallingTransport::default());
539 let check = running_check();
540 check.watch(&(transport.clone() as Arc<dyn Transport>));
541 let policy = Arc::new(SentryPolicy::default());
542 let pace = Arc::new(Pace::new(Duration::from_secs(60 * 60)));
543 with_local_recorder(&*policy, || {
544 for i in 0..2 * FLUSH_BUDGET {
545 metrics::counter!(format!("a{i}.count")).increment(1);
546 }
547 });
548
549 let (parts_tx, parts_rx) = mpsc::channel();
550 let send_to_test = |parts_tx: mpsc::Sender<usize>| {
551 move |part: Vec<SentryMetric>| {
552 parts_tx
553 .send(part.len())
554 .expect("the test thread is waiting");
555 }
556 };
557
558 let periodic = thread::spawn({
559 let (policy, pace, send) =
560 (policy.clone(), pace.clone(), send_to_test(parts_tx.clone()));
561 move || {
562 flush_paced(
563 &policy,
564 &pace,
565 || check.sent_everything(Duration::from_secs(60)),
566 send,
567 )
568 }
569 });
570 assert_eq!(
571 parts_rx.recv(),
572 Ok(ENVELOPE_METRICS),
573 "the periodic flush sends its first envelope, then waits",
574 );
575
576 transport.stall(true);
577 pace.stop();
578 flush_paced(
579 &policy,
580 &pace,
581 || check.sent_everything(Duration::from_millis(50)),
582 send_to_test(parts_tx),
583 );
584 periodic.join().expect("the periodic flush doesn't panic");
585 transport.stall(false);
586
587 let sent_after_the_first_envelope: usize = parts_rx.iter().sum();
588 assert_eq!(
589 ENVELOPE_METRICS + sent_after_the_first_envelope,
590 FLUSH_BUDGET,
591 "the periodic flush sends its budget, and the flush at exit sends nothing while the \
592 transport hasn't sent it",
593 );
594 }
595
596 #[test]
600 fn a_sentry_server_that_never_responds_stops_metrics_flushes() {
601 let listener = TcpListener::bind("127.0.0.1:0").expect("the test can listen on localhost");
602 let address = listener.local_addr().expect("the listener has an address");
603 let mut options =
604 ClientOptions::new().transport_channel_capacity(TRANSPORT_QUEUE_ENVELOPES);
605 options.dsn = Some(
606 format!("http://public@{address}/1")
607 .parse()
608 .expect("the DSN is valid"),
609 );
610 let options =
611 TransportOptions::try_from_client_options(&options).expect("the options have a DSN");
612
613 let check = running_check();
614 let transport = CheckedTransport(check).create_transport_with_options(options);
615 let policy = SentryPolicy::default();
616
617 let mut envelope = Envelope::new();
618 envelope.add_item(Event::default());
619 transport.send_envelope(envelope);
620 let (connection, _) = listener
621 .accept()
622 .expect("the transport connects to send the envelope");
623
624 assert!(
625 count_and_flush(&policy, check, Duration::from_millis(200)).is_empty(),
626 "the transport is waiting for the server's response",
627 );
628
629 drop((connection, listener));
630 assert_eq!(
631 count_and_flush(&policy, check, Duration::from_secs(60)).len(),
632 1,
633 "once the connection fails, the transport sends the rest of its queue, and flushes \
634 send again",
635 );
636 }
637}