monocle_agent/config.rs
1//! Resolved telemetry configuration for the Monocle OTLP exporter.
2
3use opentelemetry::KeyValue;
4
5/// Default OTLP ingestion endpoint for Monocle cloud.
6const DEFAULT_ENDPOINT: &str = "https://ingest.monocle.sh";
7/// Default deployment environment reported to Monocle when `MONOCLE_ENV` is unset.
8const DEFAULT_ENV: &str = "production";
9/// Fallback tracing filter used when `RUST_LOG` is not set.
10const DEFAULT_LOG_FILTER: &str = "info";
11
12/// Configuration for the Monocle telemetry exporter.
13///
14/// Build it from the environment with [`MonocleConfig::from_env`] (the usual
15/// path) and tweak it with the `with_*` builder methods. Export stays **off**
16/// until an API key is present ([`MonocleConfig::is_enabled`]).
17///
18/// ```
19/// let cfg = monocle_agent::MonocleConfig::from_env(
20/// env!("CARGO_PKG_NAME"),
21/// env!("CARGO_PKG_VERSION"),
22/// )
23/// .with_environment("staging");
24/// ```
25#[derive(Clone, Debug)]
26pub struct MonocleConfig {
27 /// Monocle API key. `None` disables all OTLP export (stdout logging only).
28 pub api_key: Option<String>,
29 /// OTLP/HTTP base endpoint. Per-signal paths (`/v1/traces`, …) are appended internally.
30 pub endpoint: String,
31 /// Deployment environment (`development` | `staging` | `production`).
32 pub environment: String,
33 /// `service.name` resource attribute.
34 pub service_name: String,
35 /// `service.version` resource attribute.
36 pub service_version: String,
37 /// Fallback tracing filter used when `RUST_LOG` is unset (e.g. `"my_svc=debug,info"`).
38 pub log_filter: String,
39 /// Extra OpenTelemetry resource attributes, merged on top of the defaults.
40 pub extra_resource_attributes: Vec<KeyValue>,
41}
42
43impl MonocleConfig {
44 /// Resolve configuration from environment variables.
45 ///
46 /// `service_name` / `service_version` are the fallbacks used when the
47 /// matching env vars are unset — pass `env!("CARGO_PKG_NAME")` and
48 /// `env!("CARGO_PKG_VERSION")` so they resolve to *your* crate (the `env!`
49 /// macro must expand in the calling crate, not in this library).
50 ///
51 /// | Env var | Field | Default |
52 /// |---------|-------|---------|
53 /// | `MONOCLE_API_KEY` | `api_key` | `None` (export disabled) |
54 /// | `MONOCLE_ENDPOINT` | `endpoint` | `https://ingest.monocle.sh` |
55 /// | `MONOCLE_ENV` | `environment` | `production` |
56 /// | `OTEL_SERVICE_NAME` | `service_name` | `service_name` arg |
57 /// | `MONOCLE_SERVICE_VERSION` | `service_version` | `service_version` arg |
58 pub fn from_env(service_name: impl Into<String>, service_version: impl Into<String>) -> Self {
59 Self {
60 // Treat an empty value the same as unset everywhere.
61 api_key: env_nonempty("MONOCLE_API_KEY"),
62 endpoint: env_nonempty("MONOCLE_ENDPOINT")
63 .unwrap_or_else(|| DEFAULT_ENDPOINT.to_string()),
64 environment: env_nonempty("MONOCLE_ENV").unwrap_or_else(|| DEFAULT_ENV.to_string()),
65 service_name: env_nonempty("OTEL_SERVICE_NAME").unwrap_or_else(|| service_name.into()),
66 service_version: env_nonempty("MONOCLE_SERVICE_VERSION")
67 .unwrap_or_else(|| service_version.into()),
68 log_filter: DEFAULT_LOG_FILTER.to_string(),
69 extra_resource_attributes: Vec::new(),
70 }
71 }
72
73 /// Override the API key (and thereby enable export).
74 #[must_use]
75 pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
76 let key = key.into();
77 self.api_key = if key.trim().is_empty() {
78 None
79 } else {
80 Some(key)
81 };
82 self
83 }
84
85 /// Override the OTLP/HTTP base endpoint.
86 #[must_use]
87 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
88 self.endpoint = endpoint.into();
89 self
90 }
91
92 /// Override the deployment environment.
93 #[must_use]
94 pub fn with_environment(mut self, environment: impl Into<String>) -> Self {
95 self.environment = environment.into();
96 self
97 }
98
99 /// Override the fallback tracing filter (used only when `RUST_LOG` is unset).
100 #[must_use]
101 pub fn with_log_filter(mut self, filter: impl Into<String>) -> Self {
102 self.log_filter = filter.into();
103 self
104 }
105
106 /// Append an extra OpenTelemetry resource attribute.
107 #[must_use]
108 pub fn with_resource_attribute(
109 mut self,
110 key: impl Into<opentelemetry::Key>,
111 value: impl Into<opentelemetry::Value>,
112 ) -> Self {
113 self.extra_resource_attributes
114 .push(KeyValue::new(key.into(), value.into()));
115 self
116 }
117
118 /// Whether OTLP export is enabled (i.e. an API key is present).
119 pub fn is_enabled(&self) -> bool {
120 self.api_key.is_some()
121 }
122}
123
124/// Read an env var, treating an empty/whitespace value the same as unset.
125fn env_nonempty(key: &str) -> Option<String> {
126 std::env::var(key).ok().filter(|v| !v.trim().is_empty())
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 #[test]
134 fn with_api_key_enables_export() {
135 let cfg = MonocleConfig::from_env("svc", "1.0").with_api_key("secret");
136 assert!(cfg.is_enabled());
137 assert_eq!(cfg.api_key.as_deref(), Some("secret"));
138 }
139
140 #[test]
141 fn blank_api_key_stays_disabled() {
142 let cfg = MonocleConfig::from_env("svc", "1.0").with_api_key(" ");
143 assert!(!cfg.is_enabled());
144 }
145
146 #[test]
147 fn builder_overrides_apply() {
148 let cfg = MonocleConfig::from_env("svc", "1.0")
149 .with_endpoint("http://localhost:4318")
150 .with_environment("staging")
151 .with_resource_attribute("team", "platform");
152 assert_eq!(cfg.endpoint, "http://localhost:4318");
153 assert_eq!(cfg.environment, "staging");
154 assert_eq!(cfg.extra_resource_attributes.len(), 1);
155 }
156}