Skip to main content

micromegas_telemetry_sink/
lib.rs

1//! Telemetry HTTP sink library
2//!
3//! Provides logging, metrics, memory and performance profiling
4
5// crate-specific lint exceptions:
6#![allow(
7    unsafe_code,
8    missing_docs,
9    clippy::missing_errors_doc,
10    clippy::new_without_default
11)]
12
13// ---- Native-only modules ----
14#[cfg(not(target_arch = "wasm32"))]
15pub mod api_key_decorator;
16#[cfg(not(target_arch = "wasm32"))]
17pub mod composite_event_sink;
18#[cfg(not(target_arch = "wasm32"))]
19mod env_config;
20#[cfg(not(target_arch = "wasm32"))]
21pub mod http_event_sink;
22#[cfg(not(target_arch = "wasm32"))]
23pub mod local_event_sink;
24#[cfg(not(target_arch = "wasm32"))]
25pub mod log_interop;
26#[cfg(not(target_arch = "wasm32"))]
27pub mod oidc_client_credentials_decorator;
28#[cfg(not(target_arch = "wasm32"))]
29pub mod request_decorator;
30#[cfg(not(target_arch = "wasm32"))]
31pub mod stream_block;
32#[cfg(not(target_arch = "wasm32"))]
33pub mod stream_info;
34#[cfg(not(target_arch = "wasm32"))]
35pub mod system_monitor;
36#[cfg(not(target_arch = "wasm32"))]
37pub mod tracing_interop;
38
39// ---- Feature-gated, both targets ----
40// tikv-jemalloc-ctl is only a dependency for `cfg(all(not(wasm32), not(windows)))`
41// (see Cargo.toml), but the module itself needs no wasm32 gate: it declares no
42// dependency of its own, so it compiles to a no-op on wasm32 too.
43#[cfg(feature = "jemalloc")]
44pub mod jemalloc_conf;
45
46// ---- Wasm-only modules ----
47#[cfg(target_arch = "wasm32")]
48mod console_event_sink;
49#[cfg(target_arch = "wasm32")]
50pub use console_event_sink::*;
51
52// ---- Native implementation ----
53#[cfg(not(target_arch = "wasm32"))]
54mod native {
55    use std::any::TypeId;
56    use std::collections::HashMap;
57    use std::str::FromStr;
58    use std::sync::{Arc, Mutex, Weak};
59
60    use crate::env_config::{env_override, resolve};
61    use crate::log_interop::install_log_interop;
62    use crate::request_decorator::RequestDecorator;
63    use crate::tracing_interop::install_tracing_interop;
64    use micromegas_telemetry::property_names::RESERVED_PROPERTY_PREFIX;
65    use micromegas_tracing::event::BoxedEventSink;
66    use micromegas_tracing::info;
67    use micromegas_tracing::{
68        event::EventSink,
69        guards::{TracingSystemGuard, TracingThreadGuard},
70        prelude::*,
71    };
72
73    use crate::composite_event_sink::CompositeSink;
74    use crate::http_event_sink::{HttpEventSink, HttpSinkConfig};
75    use crate::local_event_sink::LocalEventSink;
76    use crate::system_monitor::spawn_system_monitor;
77
78    pub mod tokio_retry {
79        pub use tokio_retry2::*;
80    }
81
82    pub mod reqwest {
83        pub use reqwest::*;
84    }
85
86    /// Environment variable carrying deployment-supplied process properties as a
87    /// comma-separated `key=value` list, e.g. `cluster=prod,role=cache`. Read by
88    /// [`TelemetryGuardBuilder::build`], so every micromegas process honors it.
89    pub const PROCESS_PROPERTIES_ENV_VAR: &str = "MICROMEGAS_PROCESS_PROPERTIES";
90
91    /// Environment variable capping the local (stdout) sink's max level.
92    /// Read once by [`TelemetryGuardBuilder::build`]. Precedence is
93    /// *[`TelemetryGuardBuilder::with_local_sink_max_level`] (including the
94    /// `#[micromegas_main]` macro's `local_sink_max_level` attribute) > this
95    /// variable > the [`DEFAULT_LOCAL_SINK_MAX_LEVEL`] default*. Accepts `off`,
96    /// `fatal`, `error`, `warn`, `info`, `debug`, or `trace`, case-insensitively;
97    /// an unparseable value fails `build()`.
98    pub const LOCAL_SINK_MAX_LEVEL_ENV_VAR: &str = "MICROMEGAS_LOCAL_SINK_MAX_LEVEL";
99
100    /// Environment variable enabling CPU tracing (thread span streams) when set to
101    /// `true`. Read once by [`TelemetryGuardBuilder::build`]. Precedence is
102    /// *[`TelemetryGuardBuilder::with_cpu_tracing_enabled`] > this variable >
103    /// disabled*.
104    pub const ENABLE_CPU_TRACING_ENV_VAR: &str = "MICROMEGAS_ENABLE_CPU_TRACING";
105
106    /// Resolves whether CPU tracing is enabled: the explicit builder value,
107    /// else `env_value == "true"`, else `false`.
108    pub fn resolve_cpu_tracing_enabled(explicit: Option<bool>, env_value: Option<&str>) -> bool {
109        explicit.unwrap_or_else(|| env_value == Some("true"))
110    }
111
112    /// Environment variable capping the HTTP telemetry sink's max level.
113    /// Read once by [`TelemetryGuardBuilder::build`]. Precedence is
114    /// *[`TelemetryGuardBuilder::with_telemetry_sink_max_level`] > this
115    /// variable > the [`DEFAULT_TELEMETRY_SINK_MAX_LEVEL`] default*. Accepts
116    /// the same values as [`LOCAL_SINK_MAX_LEVEL_ENV_VAR`]; an unparseable
117    /// value fails `build()`, even if no telemetry URL ends up configured.
118    pub const TELEMETRY_SINK_MAX_LEVEL_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_SINK_MAX_LEVEL";
119
120    /// Default max level for the local (stdout) sink, applied when neither an
121    /// explicit builder call nor [`LOCAL_SINK_MAX_LEVEL_ENV_VAR`] sets one.
122    pub const DEFAULT_LOCAL_SINK_MAX_LEVEL: LevelFilter = LevelFilter::Info;
123
124    /// Default max level for the HTTP telemetry sink, applied when neither an
125    /// explicit builder call nor [`TELEMETRY_SINK_MAX_LEVEL_ENV_VAR`] sets one.
126    pub const DEFAULT_TELEMETRY_SINK_MAX_LEVEL: LevelFilter = LevelFilter::Debug;
127
128    const MAX_QUEUE_BYTES_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_MAX_QUEUE_BYTES";
129    const HARD_QUEUE_BYTES_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_HARD_QUEUE_BYTES";
130    const MAX_IN_FLIGHT_REQUESTS_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_MAX_IN_FLIGHT_REQUESTS";
131    const REQUEST_TIMEOUT_SECS_ENV_VAR: &str = "MICROMEGAS_TELEMETRY_REQUEST_TIMEOUT_SECS";
132
133    /// Merges a [`PROCESS_PROPERTIES_ENV_VAR`]-formatted list into `properties`,
134    /// leaving keys already present untouched. Precedence is therefore
135    /// *explicit [`TelemetryGuardBuilder::with_process_property`] calls > environment >
136    /// `populate_default_system_properties` defaults*: an operator
137    /// can add deployment tags but cannot spoof the `version` that `micromegas_main`
138    /// stamps nor the identity properties derived from the host, both of which
139    /// dashboards filter on. Within one list the first occurrence of a key wins,
140    /// consistent with that rule.
141    ///
142    /// The whole list is parsed before anything is merged, so a malformed entry
143    /// fails the call with `properties` untouched rather than applying half a
144    /// config. Blank entries are dropped and each entry is trimmed: a k8s manifest
145    /// rendering an unset optional var produces `""`, hand-written lists routinely
146    /// carry a trailing comma, and a space after a comma would otherwise create a
147    /// key no query could match.
148    ///
149    /// Keys in the server-reserved [`RESERVED_PROPERTY_PREFIX`] namespace are
150    /// rejected here, turning the ingestion service's silent strip into a startup
151    /// failure the operator can see.
152    pub fn merge_process_properties(
153        properties: &mut HashMap<String, String>,
154        raw: &str,
155    ) -> anyhow::Result<()> {
156        use anyhow::Context;
157
158        let mut parsed = Vec::new();
159        for entry in raw.split(',').map(str::trim).filter(|e| !e.is_empty()) {
160            let (key, value) = entry.split_once('=').with_context(|| {
161                format!("invalid {PROCESS_PROPERTIES_ENV_VAR} entry {entry:?}: expected key=value")
162            })?;
163            let (key, value) = (key.trim(), value.trim());
164            if key.is_empty() {
165                anyhow::bail!("invalid {PROCESS_PROPERTIES_ENV_VAR} entry {entry:?}: empty key");
166            }
167            if key.starts_with(RESERVED_PROPERTY_PREFIX) {
168                anyhow::bail!(
169                    "invalid {PROCESS_PROPERTIES_ENV_VAR} entry {entry:?}: the \
170                     {RESERVED_PROPERTY_PREFIX} namespace is server-written only and \
171                     would be stripped on ingestion"
172                );
173            }
174            parsed.push((key.to_string(), value.to_string()));
175        }
176        for (key, value) in parsed {
177            properties.entry(key).or_insert(value);
178        }
179        Ok(())
180    }
181
182    pub struct TelemetryGuardBuilder {
183        logs_buffer_size: usize,
184        metrics_buffer_size: usize,
185        threads_buffer_size: usize,
186        target_max_levels: HashMap<String, String>,
187        max_level_override: Option<LevelFilter>,
188        interop_max_level_override: Option<LevelFilter>,
189        install_log_capture: bool,
190        install_tracing_capture: bool,
191        local_sink_enabled: bool,
192        local_sink_max_level: Option<LevelFilter>,
193        cpu_tracing_enabled: Option<bool>,
194        telemetry_sink_url: Option<String>,
195        telemetry_sink_max_level: Option<LevelFilter>,
196        telemetry_max_queue_bytes: Option<usize>,
197        telemetry_hard_queue_bytes: Option<usize>,
198        telemetry_max_in_flight_requests: Option<usize>,
199        telemetry_request_timeout: Option<std::time::Duration>,
200        telemetry_retry_by_priority:
201            Option<[core::iter::Take<tokio_retry::strategy::ExponentialBackoff>; 4]>,
202        telemetry_make_request_decorator: Box<dyn FnOnce() -> Arc<dyn RequestDecorator> + Send>,
203        extra_sinks: HashMap<TypeId, (LevelFilter, BoxedEventSink)>,
204        system_metrics_enabled: bool,
205        default_system_properties_enabled: bool,
206        process_properties: HashMap<String, String>,
207    }
208
209    impl Default for TelemetryGuardBuilder {
210        fn default() -> Self {
211            Self {
212                logs_buffer_size: 10 * 1024 * 1024,
213                metrics_buffer_size: 1024 * 1024,
214                threads_buffer_size: 10 * 1024 * 1024,
215                local_sink_enabled: true,
216                local_sink_max_level: None,
217                cpu_tracing_enabled: None,
218                telemetry_sink_url: None,
219                telemetry_sink_max_level: None,
220                telemetry_max_queue_bytes: None,
221                telemetry_hard_queue_bytes: None,
222                telemetry_max_in_flight_requests: None,
223                telemetry_request_timeout: None,
224                telemetry_retry_by_priority: None,
225                telemetry_make_request_decorator: Box::new(|| {
226                    Arc::new(crate::request_decorator::TrivialRequestDecorator {})
227                }),
228                target_max_levels: HashMap::default(),
229                max_level_override: None,
230                interop_max_level_override: None,
231                install_log_capture: false,
232                install_tracing_capture: true,
233                extra_sinks: HashMap::default(),
234                system_metrics_enabled: true,
235                default_system_properties_enabled: true,
236                process_properties: HashMap::default(),
237            }
238        }
239    }
240
241    impl TelemetryGuardBuilder {
242        // Only one sink per type ?
243        #[must_use]
244        pub fn add_sink<Sink>(mut self, max_level: LevelFilter, sink: Sink) -> Self
245        where
246            Sink: EventSink + 'static,
247        {
248            let type_id = TypeId::of::<Sink>();
249
250            self.extra_sinks
251                .entry(type_id)
252                .or_insert_with(|| (max_level, Box::new(sink)));
253
254            self
255        }
256
257        /// Programmatic override
258        #[must_use]
259        pub fn with_max_level_override(mut self, level_filter: LevelFilter) -> Self {
260            self.max_level_override = Some(level_filter);
261            self
262        }
263
264        #[must_use]
265        pub fn with_local_sink_enabled(mut self, enabled: bool) -> Self {
266            self.local_sink_enabled = enabled;
267            self
268        }
269
270        #[must_use]
271        pub fn with_interop_max_level_override(mut self, level_filter: LevelFilter) -> Self {
272            self.interop_max_level_override = Some(level_filter);
273            self
274        }
275
276        #[must_use]
277        pub fn with_install_log_capture(mut self, enabled: bool) -> Self {
278            self.install_log_capture = enabled;
279            self
280        }
281
282        #[must_use]
283        pub fn with_install_tracing_capture(mut self, enabled: bool) -> Self {
284            self.install_tracing_capture = enabled;
285            self
286        }
287
288        /// Max level for the local (stdout) sink. Pins the value in code, so
289        /// [`LOCAL_SINK_MAX_LEVEL_ENV_VAR`] no longer applies. Falls back to
290        /// that variable, then [`DEFAULT_LOCAL_SINK_MAX_LEVEL`]; an
291        /// unparseable value for the variable fails `build()`.
292        #[must_use]
293        pub fn with_local_sink_max_level(mut self, level_filter: LevelFilter) -> Self {
294            self.local_sink_max_level = Some(level_filter);
295            self
296        }
297
298        /// Enables or disables CPU tracing (thread span streams, which async span
299        /// events also flow through). Pins the value in code, so
300        /// [`ENABLE_CPU_TRACING_ENV_VAR`] no longer applies. Falls back to that
301        /// variable, then disabled. `#[micromegas_main]` decides about tokio
302        /// runtime callbacks from the variable alone, so use this option with a
303        /// manually built guard.
304        #[must_use]
305        pub fn with_cpu_tracing_enabled(mut self, enabled: bool) -> Self {
306            self.cpu_tracing_enabled = Some(enabled);
307            self
308        }
309
310        /// Max level for the HTTP telemetry sink. Pins the value in code, so
311        /// [`TELEMETRY_SINK_MAX_LEVEL_ENV_VAR`] no longer applies. Falls back
312        /// to that variable, then [`DEFAULT_TELEMETRY_SINK_MAX_LEVEL`]; an
313        /// unparseable value for the variable fails `build()`.
314        #[must_use]
315        pub fn with_telemetry_sink_max_level(mut self, level_filter: LevelFilter) -> Self {
316            self.telemetry_sink_max_level = Some(level_filter);
317            self
318        }
319
320        #[must_use]
321        pub fn with_ctrlc_handling(self) -> Self {
322            ctrlc::set_handler(move || {
323                info!("Ctrl+C was hit!");
324                micromegas_tracing::guards::shutdown_telemetry();
325                std::process::exit(1);
326            })
327            .expect("Error setting Ctrl+C handler");
328            self
329        }
330
331        /// Soft byte cap for the telemetry upload queue: once reached, new
332        /// `Traces` items (thread and image blocks) are dropped first.
333        /// Falls back to `MICROMEGAS_TELEMETRY_MAX_QUEUE_BYTES`, then
334        /// [`HttpSinkConfig::DEFAULT_MAX_QUEUE_BYTES`]. An unparseable value
335        /// for that variable fails `build()`.
336        #[must_use]
337        pub fn with_max_queue_bytes(mut self, bytes: usize) -> Self {
338            self.telemetry_max_queue_bytes = Some(bytes);
339            self
340        }
341
342        /// Hard byte cap for the telemetry upload queue: once reached, `Logs`
343        /// and `Metrics` items are dropped too (`Metadata` is never
344        /// dropped). Falls back to `MICROMEGAS_TELEMETRY_HARD_QUEUE_BYTES`,
345        /// then [`HttpSinkConfig::DEFAULT_HARD_QUEUE_BYTES`]. An unparseable
346        /// value for that variable fails `build()`.
347        #[must_use]
348        pub fn with_hard_queue_bytes(mut self, bytes: usize) -> Self {
349            self.telemetry_hard_queue_bytes = Some(bytes);
350            self
351        }
352
353        /// Maximum number of `insert_*` HTTP requests in flight at once.
354        /// Falls back to `MICROMEGAS_TELEMETRY_MAX_IN_FLIGHT_REQUESTS`, then
355        /// [`HttpSinkConfig::DEFAULT_MAX_IN_FLIGHT_REQUESTS`]. An unparseable
356        /// value for that variable fails `build()`.
357        #[must_use]
358        pub fn with_max_in_flight_requests(mut self, max_in_flight_requests: usize) -> Self {
359            self.telemetry_max_in_flight_requests = Some(max_in_flight_requests);
360            self
361        }
362
363        /// Per-request timeout (covers connect + send + receive for one
364        /// attempt). Bounds how long a single retry attempt can hang against
365        /// an ingestion service that accepts connections but never responds,
366        /// which otherwise would make shutdown block indefinitely (`Drop for
367        /// HttpEventSink` joins the worker thread). Falls back to
368        /// `MICROMEGAS_TELEMETRY_REQUEST_TIMEOUT_SECS`, then
369        /// [`HttpSinkConfig::DEFAULT_REQUEST_TIMEOUT`]. An unparseable value
370        /// for that variable fails `build()`.
371        #[must_use]
372        pub fn with_request_timeout(mut self, timeout: std::time::Duration) -> Self {
373            self.telemetry_request_timeout = Some(timeout);
374            self
375        }
376
377        /// Retry strategy per upload priority (indexed by
378        /// `UploadPriority as usize`: Metadata, Logs, Metrics, Traces).
379        /// Defaults to [`HttpSinkConfig::default_retry_by_priority`].
380        #[must_use]
381        pub fn with_retry_by_priority(
382            mut self,
383            retry_by_priority: [core::iter::Take<tokio_retry::strategy::ExponentialBackoff>; 4],
384        ) -> Self {
385            self.telemetry_retry_by_priority = Some(retry_by_priority);
386            self
387        }
388
389        #[must_use]
390        pub fn with_request_decorator(
391            mut self,
392            make_decorator: Box<dyn FnOnce() -> Arc<dyn RequestDecorator> + Send>,
393        ) -> Self {
394            self.telemetry_make_request_decorator = make_decorator;
395            self
396        }
397
398        /// Automatically configure authentication from environment variables.
399        ///
400        /// Checks for authentication configuration in this order:
401        /// 1. API key authentication via `MICROMEGAS_INGESTION_API_KEY`
402        /// 2. OIDC client credentials via `MICROMEGAS_OIDC_TOKEN_ENDPOINT`,
403        ///    `MICROMEGAS_OIDC_CLIENT_ID`, and `MICROMEGAS_OIDC_CLIENT_SECRET`
404        /// 3. Falls back to no authentication (TrivialRequestDecorator)
405        ///
406        /// # Example
407        ///
408        /// ```rust,no_run
409        /// use micromegas_telemetry_sink::TelemetryGuardBuilder;
410        ///
411        /// // Set environment variable
412        /// unsafe {
413        ///     std::env::set_var("MICROMEGAS_INGESTION_API_KEY", "secret-key-123");
414        /// }
415        ///
416        /// // Builder automatically configures API key authentication
417        /// let _guard = TelemetryGuardBuilder::default()
418        ///     .with_auth_from_env()
419        ///     .build()
420        ///     .expect("Failed to build telemetry guard");
421        /// ```
422        #[must_use]
423        pub fn with_auth_from_env(mut self) -> Self {
424            use crate::api_key_decorator::ApiKeyRequestDecorator;
425            use crate::oidc_client_credentials_decorator::OidcClientCredentialsDecorator;
426
427            // Try API key authentication first
428            if let Ok(decorator) = ApiKeyRequestDecorator::from_env() {
429                info!("Configured telemetry sink with API key authentication");
430                self.telemetry_make_request_decorator = Box::new(move || Arc::new(decorator));
431                return self;
432            }
433
434            // Try OIDC client credentials authentication
435            if let Ok(decorator) = OidcClientCredentialsDecorator::from_env() {
436                info!("Configured telemetry sink with OIDC client credentials authentication");
437                self.telemetry_make_request_decorator = Box::new(move || Arc::new(decorator));
438                return self;
439            }
440
441            // No authentication configured - use trivial decorator (no-op)
442            info!(
443                "Telemetry sink authentication not configured - sending unauthenticated requests"
444            );
445            self
446        }
447
448        #[must_use]
449        pub fn with_system_metrics_enabled(mut self, enabled: bool) -> Self {
450            self.system_metrics_enabled = enabled;
451            self
452        }
453
454        #[must_use]
455        pub fn with_default_system_properties_enabled(mut self, enabled: bool) -> Self {
456            self.default_system_properties_enabled = enabled;
457            self
458        }
459
460        /// Set the URL of telemetry sink.
461        ///
462        /// If not explicitly set, the URL will be read from the `MICROMEGAS_TELEMETRY_URL` environment
463        /// variable.
464        #[must_use]
465        pub fn with_telemetry_sink_url(mut self, url: String) -> Self {
466            self.telemetry_sink_url = Some(url);
467            self
468        }
469
470        /// Add a single property to the process info.
471        ///
472        /// # Warning
473        ///
474        /// This will override any existing properties.
475        #[must_use]
476        pub fn with_process_property(mut self, key: String, value: String) -> Self {
477            self.process_properties.insert(key, value);
478            self
479        }
480
481        /// Add multiple properties to the process info.
482        ///
483        /// # Warning
484        ///
485        /// This will override any existing properties.
486        #[must_use]
487        pub fn with_process_properties(
488            mut self,
489            process_properties: HashMap<String, String>,
490        ) -> Self {
491            self.process_properties.extend(process_properties);
492            self
493        }
494
495        fn populate_default_system_properties(&mut self) {
496            let props = &mut self.process_properties;
497            // Process identity (duplicates ProcessInfo fields into properties)
498            type DefaultProperties = Vec<(&'static str, Box<dyn FnOnce() -> String>)>;
499            let defaults: DefaultProperties = vec![
500                (
501                    "exe",
502                    Box::new(|| {
503                        std::env::current_exe()
504                            .unwrap_or_default()
505                            .to_string_lossy()
506                            .into_owned()
507                    }),
508                ),
509                ("username", Box::new(whoami::username)),
510                ("realname", Box::new(whoami::realname)),
511                ("computer", Box::new(whoami::devicename)),
512                ("distro", Box::new(whoami::distro)),
513                (
514                    "cpu_brand",
515                    Box::new(micromegas_tracing::cpu_brand::get_cpu_brand),
516                ),
517                (
518                    "physical_core_count",
519                    Box::new(|| {
520                        sysinfo::System::physical_core_count()
521                            .map(|c: usize| c.to_string())
522                            .unwrap_or_default()
523                    }),
524                ),
525                (
526                    "logical_cpu_count",
527                    Box::new(|| {
528                        use sysinfo::{CpuRefreshKind, RefreshKind};
529                        let system = sysinfo::System::new_with_specifics(
530                            RefreshKind::nothing().with_cpu(CpuRefreshKind::nothing()),
531                        );
532                        system.cpus().len().to_string()
533                    }),
534                ),
535                (
536                    "total_memory",
537                    Box::new(|| {
538                        use sysinfo::{MemoryRefreshKind, RefreshKind};
539                        let system = sysinfo::System::new_with_specifics(
540                            RefreshKind::nothing()
541                                .with_memory(MemoryRefreshKind::nothing().with_ram()),
542                        );
543                        system.total_memory().to_string()
544                    }),
545                ),
546            ];
547            for (key, make_value) in defaults {
548                props.entry(key.to_string()).or_insert_with(make_value);
549            }
550        }
551
552        pub fn build(mut self) -> anyhow::Result<TelemetryGuard> {
553            // Merged before the defaults below, which use `or_insert_with`: that
554            // orders precedence as explicit builder calls > env > derived defaults.
555            // `var_os` rather than `var`: a set-but-non-UTF-8 value would otherwise be
556            // indistinguishable from an unset one and silently ignored, which is the
557            // one shape of bad input the parsing below is here to make loud.
558            if let Some(raw) = std::env::var_os(PROCESS_PROPERTIES_ENV_VAR) {
559                merge_process_properties(&mut self.process_properties, &raw.to_string_lossy())?;
560            }
561            if self.default_system_properties_enabled {
562                self.populate_default_system_properties();
563            }
564            // Resolved up front, before the global guard is created below, so a
565            // bad value fails `build()` even when the sink it feeds ends up
566            // unused (e.g. a telemetry knob set with no telemetry URL
567            // configured). A typo should not hide until the URL is set.
568            const LEVEL_EXPECTED: &str = "one of off, fatal, error, warn, info, debug, trace";
569            let local_sink_max_level = resolve(
570                self.local_sink_max_level,
571                LOCAL_SINK_MAX_LEVEL_ENV_VAR,
572                DEFAULT_LOCAL_SINK_MAX_LEVEL,
573                LEVEL_EXPECTED,
574            )?;
575            let telemetry_sink_max_level = resolve(
576                self.telemetry_sink_max_level,
577                TELEMETRY_SINK_MAX_LEVEL_ENV_VAR,
578                DEFAULT_TELEMETRY_SINK_MAX_LEVEL,
579                LEVEL_EXPECTED,
580            )?;
581            const NON_NEGATIVE_INTEGER: &str = "a non-negative integer";
582            let max_queue_bytes = resolve(
583                self.telemetry_max_queue_bytes,
584                MAX_QUEUE_BYTES_ENV_VAR,
585                HttpSinkConfig::DEFAULT_MAX_QUEUE_BYTES,
586                NON_NEGATIVE_INTEGER,
587            )?;
588            let hard_queue_bytes = resolve(
589                self.telemetry_hard_queue_bytes,
590                HARD_QUEUE_BYTES_ENV_VAR,
591                HttpSinkConfig::DEFAULT_HARD_QUEUE_BYTES,
592                NON_NEGATIVE_INTEGER,
593            )?;
594            let max_in_flight_requests = resolve(
595                self.telemetry_max_in_flight_requests,
596                MAX_IN_FLIGHT_REQUESTS_ENV_VAR,
597                HttpSinkConfig::DEFAULT_MAX_IN_FLIGHT_REQUESTS,
598                NON_NEGATIVE_INTEGER,
599            )?;
600            // `Duration` isn't `FromStr`, so this can't go through `resolve`.
601            let request_timeout = match self.telemetry_request_timeout {
602                Some(timeout) => timeout,
603                None => env_override::<u64>(REQUEST_TIMEOUT_SECS_ENV_VAR, NON_NEGATIVE_INTEGER)?
604                    .map(std::time::Duration::from_secs)
605                    .unwrap_or(HttpSinkConfig::DEFAULT_REQUEST_TIMEOUT),
606            };
607            let target_max_level: Vec<_> = self
608                .target_max_levels
609                .into_iter()
610                .filter(|(key, _val)| key != "MAX_LEVEL")
611                .map(|(key, val)| {
612                    (
613                        key,
614                        LevelFilter::from_str(val.as_str()).unwrap_or(LevelFilter::Off),
615                    )
616                })
617                .collect();
618
619            let guard = {
620                lazy_static::lazy_static! {
621                    static ref GLOBAL_WEAK_GUARD: Mutex<Weak<TracingSystemGuard>> = Mutex::new(Weak::new());
622                }
623                let mut weak_guard = GLOBAL_WEAK_GUARD.lock().unwrap();
624                let weak = &mut *weak_guard;
625
626                if let Some(arc) = weak.upgrade() {
627                    arc
628                } else {
629                    let mut sinks: Vec<(LevelFilter, BoxedEventSink)> = vec![];
630                    let telemetry_sink_url = self
631                        .telemetry_sink_url
632                        .or_else(|| std::env::var("MICROMEGAS_TELEMETRY_URL").ok())
633                        .filter(|url| !url.trim().is_empty());
634
635                    if let Some(url) = telemetry_sink_url {
636                        let retry_by_priority = self
637                            .telemetry_retry_by_priority
638                            .unwrap_or_else(HttpSinkConfig::default_retry_by_priority);
639                        let config = HttpSinkConfig {
640                            max_queue_bytes,
641                            hard_queue_bytes,
642                            max_in_flight_requests,
643                            request_timeout,
644                            retry_by_priority,
645                        };
646                        sinks.push((
647                            telemetry_sink_max_level,
648                            Box::new(HttpEventSink::new(
649                                &url,
650                                config,
651                                self.telemetry_make_request_decorator,
652                            )),
653                        ));
654                    }
655                    if self.local_sink_enabled {
656                        sinks.push((local_sink_max_level, Box::new(LocalEventSink::new())));
657                    }
658                    let mut extra_sinks = self.extra_sinks.into_values().collect();
659                    sinks.append(&mut extra_sinks);
660
661                    let sink: BoxedEventSink = Box::new(CompositeSink::new(
662                        sinks,
663                        target_max_level,
664                        self.max_level_override,
665                    ));
666
667                    // the composite sink inits micromegas_tracing::levels::set_max_level, which install_log_interop needs
668                    if self.install_log_capture {
669                        install_log_interop(self.interop_max_level_override);
670                    }
671                    if self.install_tracing_capture {
672                        install_tracing_interop(self.interop_max_level_override);
673                    }
674
675                    let arc = Arc::<TracingSystemGuard>::new(TracingSystemGuard::new(
676                        self.logs_buffer_size,
677                        self.metrics_buffer_size,
678                        self.threads_buffer_size,
679                        sink.into(),
680                        self.process_properties,
681                        resolve_cpu_tracing_enabled(
682                            self.cpu_tracing_enabled,
683                            std::env::var(ENABLE_CPU_TRACING_ENV_VAR).ok().as_deref(),
684                        ),
685                    )?);
686
687                    if self.system_metrics_enabled {
688                        spawn_system_monitor();
689                    }
690
691                    *weak = Arc::<TracingSystemGuard>::downgrade(&arc);
692                    arc
693                }
694            };
695            // order here is important
696            Ok(TelemetryGuard {
697                _guard: guard,
698                _thread_guard: TracingThreadGuard::new(),
699            })
700        }
701    }
702
703    pub struct TelemetryGuard {
704        // note we rely here on the drop order being the same as the declaration order
705        _thread_guard: TracingThreadGuard,
706        _guard: Arc<TracingSystemGuard>,
707    }
708
709    impl TelemetryGuard {
710        pub fn new() -> anyhow::Result<Self> {
711            TelemetryGuardBuilder::default().build()
712        }
713    }
714}
715
716#[cfg(not(target_arch = "wasm32"))]
717pub use native::*;
718
719// ---- Wasm implementation ----
720#[cfg(target_arch = "wasm32")]
721mod wasm {
722    use std::collections::HashMap;
723    use std::sync::Arc;
724
725    use micromegas_tracing::guards::TracingSystemGuard;
726
727    use crate::ConsoleEventSink;
728
729    pub struct TelemetryGuard {
730        _guard: Arc<TracingSystemGuard>,
731    }
732
733    pub fn init_telemetry() -> anyhow::Result<TelemetryGuard> {
734        let guard = Arc::new(TracingSystemGuard::new(
735            0,
736            0,
737            0,
738            Arc::new(ConsoleEventSink),
739            HashMap::new(),
740            false,
741        )?);
742        Ok(TelemetryGuard { _guard: guard })
743    }
744}
745
746#[cfg(target_arch = "wasm32")]
747pub use wasm::*;