bunqueue_client/
telemetry.rs1use std::panic::{AssertUnwindSafe, catch_unwind};
2use std::sync::Arc;
3use std::time::Duration;
4
5use crate::Error;
6
7#[derive(Clone, Debug, PartialEq)]
9#[non_exhaustive]
10pub enum TelemetryEvent {
11 Connecting {
12 host: String,
13 port: u16,
14 },
15 Reconnecting {
16 previous_generation: i64,
17 },
18 Connected {
19 generation: i64,
20 },
21 Authenticated {
22 generation: i64,
23 },
24 CommandStarted {
25 command: String,
26 request_id: String,
27 },
28 CommandFinished {
29 command: String,
30 request_id: String,
31 duration: Duration,
32 ok: bool,
33 },
34 Timeout {
35 operation: String,
36 duration: Duration,
37 },
38 Error {
39 operation: String,
40 message: String,
41 },
42 WorkerRetry {
43 queue: String,
44 message: String,
45 retry_in: Duration,
46 },
47 Closed,
48}
49
50pub type TelemetryCallback = Arc<dyn Fn(TelemetryEvent) + Send + Sync + 'static>;
51
52pub(crate) fn emit(callback: Option<&TelemetryCallback>, event: TelemetryEvent) {
53 if let Some(callback) = callback {
54 let _ = catch_unwind(AssertUnwindSafe(|| callback(event)));
55 }
56}
57
58pub(crate) fn emit_all(
59 callback: Option<&TelemetryCallback>,
60 events: impl IntoIterator<Item = TelemetryEvent>,
61) {
62 for event in events {
63 emit(callback, event);
64 }
65}
66
67pub(crate) fn record_failure(
68 events: &mut Vec<TelemetryEvent>,
69 operation: impl Into<String>,
70 duration: Duration,
71 error: &Error,
72) {
73 let operation = operation.into();
74 if matches!(error, Error::Timeout(_)) {
75 events.push(TelemetryEvent::Timeout {
76 operation: operation.clone(),
77 duration,
78 });
79 }
80 events.push(TelemetryEvent::Error {
81 operation,
82 message: error.to_string(),
83 });
84}