forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

telemetry.rs641 lines, 25.2 KiBHistoryRawDownload
1//! Observability bootstrap: tracing subscriber, OTLP export and the process's
2//! metric instruments.
3//!
4//! **Privacy is the design constraint, not a caveat.** Legal analysis (KVKK)
5//! fixed the rule that telemetry leaving this process carries no user
6//! identity, no client address, no URL path (which holds record ids), no
7//! request or response bodies, and no headers or cookies. What may leave: the
8//! route *template* (`/notes/{id}`), the HTTP method, the status code, the
9//! school uuid, a random per-request id, and the id of a non-user resource
10//! (an exam room, a board) when an event is about that resource — never a
11//! user, session or attempt id, which name a person. Every attribute or event
12//! field added anywhere in this crate must fit that list — see the guard test
13//! in `tests/telemetry.rs`, which fails the build if a forbidden key ever
14//! shows up on a span or an exported log record.
15//!
16//! Export is off unless `OTEL_EXPORTER_OTLP_ENDPOINT` is set (the same
17//! "off unless configured" shape as `AI_QUIC_ADDR`). With it unset the process
18//! logs exactly as it always did and every instrument below is a noop.
19
20use std::sync::{Arc, OnceLock};
21
22use base64::Engine;
23use opentelemetry::metrics::{Counter, Gauge, Histogram, UpDownCounter};
24use opentelemetry::{KeyValue, global};
25use opentelemetry_sdk::Resource;
26use opentelemetry_sdk::logs::{LogProcessor, SdkLogRecord, SdkLoggerProvider};
27use opentelemetry_sdk::metrics::SdkMeterProvider;
28use opentelemetry_sdk::trace::SdkTracerProvider;
29use tracing_subscriber::layer::SubscriberExt;
30use tracing_subscriber::util::SubscriberInitExt;
31use tracing_subscriber::{EnvFilter, Layer};
32
33/// Instrumentation scope name — the OTLP `scope.name` on every metric below.
34const SCOPE: &str = "hezarfen_backend";
35
36/// The process's instruments, published by [`init`] (see [`Metrics::global`]).
37static GLOBAL: OnceLock<Metrics> = OnceLock::new();
38
39/// How stdout logs are rendered.
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
41pub enum LogFormat {
42 /// Human-readable lines, unchanged from before OpenTelemetry existed here.
43 #[default]
44 Pretty,
45 /// One JSON object per event, with the target, the span fields and (when
46 /// OTLP is on) the `trace_id`, so a collector can join logs to traces.
47 Json,
48}
49
50impl LogFormat {
51 /// `LOG_FORMAT`, rejecting anything that is not a spelling we render —
52 /// silently falling back would hand a log shipper a format it cannot parse
53 /// and nobody would notice until the logs were needed.
54 pub fn parse(value: Option<String>) -> Result<Self, TelemetryError> {
55 match value.as_deref().map(str::trim) {
56 None | Some("") => Ok(Self::Pretty),
57 Some(v) if v.eq_ignore_ascii_case("pretty") => Ok(Self::Pretty),
58 Some(v) if v.eq_ignore_ascii_case("json") => Ok(Self::Json),
59 Some(other) => Err(TelemetryError::LogFormat(other.to_string())),
60 }
61 }
62}
63
64/// What this process was told about telemetry (see [`crate::config::Config`]).
65/// Everything else — headers, protocol, sampler, service name — is read by the
66/// OpenTelemetry SDK straight from its own standard variables; re-parsing them
67/// here would only create a second, lying source of truth.
68#[derive(Clone, Debug)]
69pub struct TelemetryConfig {
70 /// `OTEL_EXPORTER_OTLP_ENDPOINT`. Presence alone turns export on; the SDK
71 /// re-reads the value itself, so it is never passed to an exporter here.
72 pub otlp_endpoint: Option<String>,
73 pub log_format: LogFormat,
74}
75
76#[derive(Debug, thiserror::Error)]
77pub enum TelemetryError {
78 #[error("LOG_FORMAT={0:?} is not one of: pretty, json")]
79 LogFormat(String),
80 #[error("OTEL_EXPORTER_OTLP_PROTOCOL={0:?} is not supported; use grpc or http/protobuf")]
81 Protocol(String),
82 #[error("could not build the OTLP {signal} exporter: {source}")]
83 Exporter {
84 signal: &'static str,
85 #[source]
86 source: opentelemetry_otlp::ExporterBuildError,
87 },
88}
89
90/// Keeps the export pipelines alive and drains them on the way out. Dropping it
91/// flushes whatever is still buffered — hold it in `main` until *after*
92/// graceful shutdown, or the last requests of a deployment go unreported.
93pub struct TelemetryGuard {
94 tracer: Option<SdkTracerProvider>,
95 meter: Option<SdkMeterProvider>,
96 logger: Option<SdkLoggerProvider>,
97}
98
99impl Drop for TelemetryGuard {
100 fn drop(&mut self) {
101 // Shutdown flushes; failures here are reported to stderr only, since
102 // the subscriber may already be on its way down.
103 if let Some(p) = self.tracer.take()
104 && let Err(err) = p.shutdown()
105 {
106 eprintln!("telemetry: tracer shutdown failed: {err}");
107 }
108 if let Some(p) = self.meter.take()
109 && let Err(err) = p.shutdown()
110 {
111 eprintln!("telemetry: meter shutdown failed: {err}");
112 }
113 if let Some(p) = self.logger.take()
114 && let Err(err) = p.shutdown()
115 {
116 eprintln!("telemetry: logger shutdown failed: {err}");
117 }
118 }
119}
120
121/// Explicit histogram buckets for `http.server.request.duration`, in seconds —
122/// the boundaries the HTTP semantic convention prescribes. Left to the SDK
123/// default they would be the generic 0–10000 ladder, which puts every web
124/// request this API serves into the first bucket.
125const HTTP_DURATION_BUCKETS: &[f64] = &[
126 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0,
127];
128
129/// Every instrument this process publishes, declared once at boot and cloned
130/// into whatever needs them. With no OTLP endpoint configured the global meter
131/// provider is the SDK's noop, so each instrument is a cheap empty shell and
132/// recording into one is a no-op — call sites never branch on "is telemetry on".
133#[derive(Clone)]
134pub struct Metrics {
135 /// Server-side request latency in seconds
136 /// (attrs: `http.request.method`, `http.route`,
137 /// `http.response.status_code`, `school`).
138 http_server_request_duration: Histogram<f64>,
139 /// Requests currently in flight (attrs: `http.request.method`).
140 http_server_active_requests: UpDownCounter<i64>,
141 /// Error responses, by kind (attrs: `error.type`, `http.response.status_code`).
142 pub errors_total: Counter<u64>,
143 /// Panics caught by the panic layer.
144 pub panics_total: Counter<u64>,
145 /// Requests refused by the rate limiter (attr: `tier`).
146 pub rate_limit_rejections_total: Counter<u64>,
147 /// AI services currently registered on the QUIC bridge.
148 pub ai_workers: Gauge<u64>,
149 /// AI requests dispatched and not yet answered.
150 pub ai_requests_inflight: UpDownCounter<i64>,
151 /// AI round-trip latency in seconds (attr: `capability`).
152 pub ai_request_duration: Histogram<f64>,
153 /// AI requests that hit their deadline.
154 pub ai_request_timeouts_total: Counter<u64>,
155 /// Rejected bridge handshakes (attr: `reason`).
156 pub ai_handshake_failures_total: Counter<u64>,
157 /// Open WebSockets (attr: `kind`, e.g. exam room or board).
158 pub ws_connections: UpDownCounter<i64>,
159 /// Schools currently held in the tenant connection cache.
160 pub tenant_cache_size: Gauge<u64>,
161}
162
163impl Metrics {
164 /// Declare every instrument against the global meter provider — the noop
165 /// one unless [`init`] installed an OTLP pipeline first.
166 pub fn new() -> Self {
167 Self::from_meter(global::meter(SCOPE))
168 }
169
170 /// The same instruments against a caller-supplied meter. Exists for tests
171 /// that want to read their own recordings back without claiming the
172 /// process-global meter provider, which the whole test binary shares.
173 pub fn from_meter(meter: opentelemetry::metrics::Meter) -> Self {
174 Self {
175 http_server_request_duration: meter
176 .f64_histogram("http.server.request.duration")
177 .with_unit("s")
178 .with_description("Duration of inbound HTTP requests")
179 .with_boundaries(HTTP_DURATION_BUCKETS.to_vec())
180 .build(),
181 http_server_active_requests: meter
182 .i64_up_down_counter("http.server.active_requests")
183 .with_description("Inbound HTTP requests currently in flight")
184 .build(),
185 errors_total: meter
186 .u64_counter("errors_total")
187 .with_description("Error responses served, by error type")
188 .build(),
189 panics_total: meter
190 .u64_counter("panics_total")
191 .with_description("Handler panics caught at the edge")
192 .build(),
193 rate_limit_rejections_total: meter
194 .u64_counter("rate_limit_rejections_total")
195 .with_description("Requests refused by a rate limit tier")
196 .build(),
197 ai_workers: meter
198 .u64_gauge("ai_workers")
199 .with_description("AI services registered on the QUIC bridge")
200 .build(),
201 ai_requests_inflight: meter
202 .i64_up_down_counter("ai_requests_inflight")
203 .with_description("AI requests awaiting an answer")
204 .build(),
205 ai_request_duration: meter
206 .f64_histogram("ai_request_duration")
207 .with_unit("s")
208 .with_description("AI request round trip, by capability")
209 .build(),
210 ai_request_timeouts_total: meter
211 .u64_counter("ai_request_timeouts_total")
212 .with_description("AI requests that hit their deadline")
213 .build(),
214 ai_handshake_failures_total: meter
215 .u64_counter("ai_handshake_failures_total")
216 .with_description("Rejected AI bridge handshakes, by reason")
217 .build(),
218 ws_connections: meter
219 .i64_up_down_counter("ws_connections")
220 .with_description("Open WebSockets, by kind")
221 .build(),
222 tenant_cache_size: meter
223 .u64_gauge("tenant_cache_size")
224 .with_description("Schools held in the tenant connection cache")
225 .build(),
226 }
227 }
228
229 /// Instruments bound to whatever meter provider is installed — the noop one
230 /// in tests, where nothing calls [`init`].
231 pub fn noop() -> Self {
232 Self::new()
233 }
234
235 /// The process's instruments, for the call sites that exist before (or
236 /// outside) [`crate::state::AppState`] — the rate limiter, built while the
237 /// state is still being assembled, the keepalive task and the tenant cache.
238 ///
239 /// [`init`] publishes the handle it built; before that (every test suite,
240 /// which never calls `init`) each call declares instruments against
241 /// whatever meter provider is installed, so a test that installs its own
242 /// provider first still sees what these call sites record. Reached on
243 /// error responses, panics, rate-limit rejections and tenant-cache changes
244 /// — never on the success path of a request.
245 pub fn global() -> Self {
246 GLOBAL.get().cloned().unwrap_or_else(Self::new)
247 }
248
249 /// Count one request in; the returned guard value must be handed back to
250 /// [`Metrics::request_finished`].
251 pub fn request_started(&self, method: &str) {
252 self.http_server_active_requests.add(
253 1,
254 &[KeyValue::new("http.request.method", method.to_string())],
255 );
256 }
257
258 /// Count the request out and record how long it took. `school` is the uuid
259 /// only — never a user, never a path.
260 pub fn request_finished(
261 &self,
262 method: &str,
263 route: &str,
264 status: u16,
265 school: Option<&str>,
266 elapsed: std::time::Duration,
267 ) {
268 self.http_server_active_requests.add(
269 -1,
270 &[KeyValue::new("http.request.method", method.to_string())],
271 );
272 let mut attrs = vec![
273 KeyValue::new("http.request.method", method.to_string()),
274 KeyValue::new("http.route", route.to_string()),
275 KeyValue::new("http.response.status_code", i64::from(status)),
276 ];
277 if let Some(school) = school {
278 attrs.push(KeyValue::new("school", school.to_string()));
279 }
280 self.http_server_request_duration
281 .record(elapsed.as_secs_f64(), &attrs);
282 }
283}
284
285impl Default for Metrics {
286 fn default() -> Self {
287 Self::new()
288 }
289}
290
291/// A slot on the request for the school it turned out to belong to.
292///
293/// The metrics middleware runs before anything knows which school a caller is
294/// in — the uuid only becomes known when
295/// [`crate::web::tenant_state::resolve_tenant`] reads the session cookie, deep
296/// inside the handler, where the request has already been moved. So the
297/// middleware puts an empty slot in the request's extensions on the way in and
298/// reads it on the way out; `resolve_tenant` fills it in between. The uuid is
299/// the only thing that ever goes in here.
300#[derive(Clone, Default)]
301pub struct SchoolSlot(Arc<OnceLock<String>>);
302
303impl SchoolSlot {
304 /// Name the school for this request. Later calls are ignored — a request
305 /// belongs to exactly one school.
306 pub fn set(&self, school: &str) {
307 let _ = self.0.set(school.to_string());
308 }
309
310 pub fn get(&self) -> Option<&str> {
311 self.0.get().map(String::as_str)
312 }
313}
314
315/// Install the subscriber and, when an OTLP endpoint is configured, the export
316/// pipelines. Call once, before anything logs.
317pub fn init(cfg: &TelemetryConfig) -> Result<(TelemetryGuard, Metrics), TelemetryError> {
318 install_panic_hook();
319 let filter = EnvFilter::try_from_default_env()
320 .unwrap_or_else(|_| EnvFilter::new("info,hezarfen_backend=debug"));
321 let fmt_layer = match cfg.log_format {
322 LogFormat::Pretty => tracing_subscriber::fmt::layer().boxed(),
323 LogFormat::Json => tracing_subscriber::fmt::layer()
324 .json()
325 .with_current_span(true)
326 .with_span_list(true)
327 .boxed(),
328 };
329
330 let Some(_endpoint) = cfg.otlp_endpoint.as_deref() else {
331 tracing_subscriber::registry()
332 .with(filter)
333 .with(fmt_layer)
334 .init();
335 return Ok((
336 TelemetryGuard {
337 tracer: None,
338 meter: None,
339 logger: None,
340 },
341 publish(Metrics::new()),
342 ));
343 };
344 // SDK reads OTEL_EXPORTER_OTLP_HEADERS itself. If the operator left it
345 // unset, mint HTTP Basic from the same ZO_ROOT_USER_* the OpenObserve
346 // container already has — no hand-rolled base64 in the env file.
347 fill_otlp_headers_from_zo();
348
349 let resource = resource();
350 let protocol = Protocol::from_env()?;
351
352 // Sampling is left to the SDK, which reads OTEL_TRACES_SAMPLER and
353 // OTEL_TRACES_SAMPLER_ARG itself and defaults to parent-based always-on.
354 let tracer_provider = SdkTracerProvider::builder()
355 .with_resource(resource.clone())
356 .with_batch_exporter(protocol.span_exporter()?)
357 .build();
358 let meter_provider = SdkMeterProvider::builder()
359 .with_resource(resource.clone())
360 .with_periodic_exporter(protocol.metric_exporter()?)
361 .build();
362 let logger_provider = SdkLoggerProvider::builder()
363 .with_resource(resource)
364 // Registered before the exporter: processors run in registration order,
365 // so the stamp lands before the batch processor clones the record.
366 .with_log_processor(StampTimestamp)
367 .with_batch_exporter(protocol.log_exporter()?)
368 .build();
369
370 let tracer = {
371 use opentelemetry::trace::TracerProvider as _;
372 tracer_provider.tracer(SCOPE)
373 };
374 global::set_tracer_provider(tracer_provider.clone());
375 global::set_meter_provider(meter_provider.clone());
376
377 tracing_subscriber::registry()
378 .with(filter)
379 .with(fmt_layer)
380 .with(tracing_opentelemetry::layer().with_tracer(tracer))
381 // Events become OTLP logs carrying the enclosing span's trace id, so a
382 // collector can pivot from a log line to its trace.
383 .with(
384 opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge::new(
385 &logger_provider,
386 ),
387 )
388 .init();
389
390 Ok((
391 TelemetryGuard {
392 tracer: Some(tracer_provider),
393 meter: Some(meter_provider),
394 logger: Some(logger_provider),
395 },
396 publish(Metrics::new()),
397 ))
398}
399
400/// Gives every log record the `timestamp` the appender never sets.
401///
402/// `opentelemetry-appender-tracing` 0.32 leaves `timestamp` empty and the SDK
403/// fills only `observed_timestamp`, so collectors render the event as
404/// 1970-01-01 and anything ordering on `timestamp` sorts it first forever. The
405/// two differ only by the queueing delay inside this process, so copying the
406/// observed time across is the honest value. No clock is read here — that would
407/// invent a time the record does not have (and `SystemTime::now` is banned; see
408/// clippy.toml).
409#[derive(Debug)]
410struct StampTimestamp;
411
412impl LogProcessor for StampTimestamp {
413 fn emit(&self, data: &mut SdkLogRecord, _scope: &opentelemetry::InstrumentationScope) {
414 use opentelemetry::logs::LogRecord as _;
415 if data.timestamp().is_none()
416 && let Some(observed) = data.observed_timestamp()
417 {
418 data.set_timestamp(observed);
419 }
420 }
421
422 fn force_flush(&self) -> opentelemetry_sdk::error::OTelSdkResult {
423 Ok(())
424 }
425
426 fn shutdown(&self) -> opentelemetry_sdk::error::OTelSdkResult {
427 Ok(())
428 }
429}
430
431/// Hand the instruments to [`Metrics::global`]. A second [`init`] (there is
432/// none in production) keeps the first set rather than swapping under callers.
433fn publish(metrics: Metrics) -> Metrics {
434 let _ = GLOBAL.set(metrics.clone());
435 metrics
436}
437
438/// Report a panic anywhere in the process — worker task, background job, or a
439/// request handler on its way to the `catch-panic` layer — as one `error!` with
440/// the standard `exception.*` fields, and count it.
441///
442/// Installed once; the previous hook still runs, so the default "thread
443/// panicked at ..." line stays in stdout logs.
444pub fn install_panic_hook() {
445 static ONCE: std::sync::Once = std::sync::Once::new();
446 ONCE.call_once(|| {
447 let previous = std::panic::take_hook();
448 std::panic::set_hook(Box::new(move |info| {
449 let payload = info.payload();
450 let message = payload
451 .downcast_ref::<&str>()
452 .map(|s| (*s).to_owned())
453 .or_else(|| payload.downcast_ref::<String>().cloned())
454 .unwrap_or_else(|| "panic".to_owned());
455 Metrics::global().panics_total.add(1, &[]);
456 tracing::error!(
457 exception.type = "panic",
458 exception.message = %message,
459 exception.stacktrace = %std::backtrace::Backtrace::force_capture(),
460 "a task panicked"
461 );
462 previous(info);
463 }));
464 });
465}
466
467/// Which OTLP wire transport to use, from the standard
468/// `OTEL_EXPORTER_OTLP_PROTOCOL`. Both are compiled in; the collector is
469/// expected on localhost or a private network, so neither carries TLS.
470enum Protocol {
471 Grpc,
472 HttpProtobuf,
473}
474
475impl Protocol {
476 fn from_env() -> Result<Self, TelemetryError> {
477 match std::env::var("OTEL_EXPORTER_OTLP_PROTOCOL")
478 .ok()
479 .as_deref()
480 .map(str::trim)
481 {
482 None | Some("") | Some("grpc") => Ok(Self::Grpc),
483 Some("http/protobuf") => Ok(Self::HttpProtobuf),
484 Some(other) => Err(TelemetryError::Protocol(other.to_string())),
485 }
486 }
487
488 fn span_exporter(&self) -> Result<opentelemetry_otlp::SpanExporter, TelemetryError> {
489 let builder = opentelemetry_otlp::SpanExporter::builder();
490 match self {
491 Self::Grpc => builder.with_tonic().build(),
492 Self::HttpProtobuf => builder.with_http().build(),
493 }
494 .map_err(|source| TelemetryError::Exporter {
495 signal: "trace",
496 source,
497 })
498 }
499
500 fn metric_exporter(&self) -> Result<opentelemetry_otlp::MetricExporter, TelemetryError> {
501 let builder = opentelemetry_otlp::MetricExporter::builder();
502 match self {
503 Self::Grpc => builder.with_tonic().build(),
504 Self::HttpProtobuf => builder.with_http().build(),
505 }
506 .map_err(|source| TelemetryError::Exporter {
507 signal: "metric",
508 source,
509 })
510 }
511
512 fn log_exporter(&self) -> Result<opentelemetry_otlp::LogExporter, TelemetryError> {
513 let builder = opentelemetry_otlp::LogExporter::builder();
514 match self {
515 Self::Grpc => builder.with_tonic().build(),
516 Self::HttpProtobuf => builder.with_http().build(),
517 }
518 .map_err(|source| TelemetryError::Exporter {
519 signal: "log",
520 source,
521 })
522 }
523}
524/// When `OTEL_EXPORTER_OTLP_HEADERS` is unset, mint OpenObserve's gRPC Basic
525/// header from `ZO_ROOT_USER_EMAIL` / `ZO_ROOT_USER_PASSWORD`. An explicit
526/// headers value always wins (a different collector, a hand-set token).
527fn fill_otlp_headers_from_zo() {
528 if env_present("OTEL_EXPORTER_OTLP_HEADERS") {
529 return;
530 }
531 let Some(email) = env_nonempty("ZO_ROOT_USER_EMAIL") else {
532 return;
533 };
534 let Some(password) = env_nonempty("ZO_ROOT_USER_PASSWORD") else {
535 return;
536 };
537 let headers = openobserve_otlp_headers(&email, &password);
538 // SAFETY: `init` runs once from `main` before any exporter is built.
539 // The SDK reads this key on the next lines; no other thread has.
540 unsafe {
541 std::env::set_var("OTEL_EXPORTER_OTLP_HEADERS", headers);
542 }
543}
544
545fn env_present(key: &str) -> bool {
546 env_nonempty(key).is_some()
547}
548
549fn env_nonempty(key: &str) -> Option<String> {
550 std::env::var(key).ok().filter(|v| !v.trim().is_empty())
551}
552
553fn openobserve_otlp_headers(email: &str, password: &str) -> String {
554 let token = base64::engine::general_purpose::STANDARD.encode(format!("{email}:{password}"));
555 format!("Authorization=Basic {token},organization=default,stream-name=default")
556}
557
558/// What every exported signal says it came from. `OTEL_SERVICE_NAME` wins when
559/// set (the SDK's own default detector reads it); `DEPLOY_ENV` names the
560/// deployment, e.g. `staging`.
561fn resource() -> Resource {
562 let mut builder = Resource::builder().with_attributes([KeyValue::new(
563 opentelemetry_semantic_conventions::resource::SERVICE_VERSION,
564 env!("CARGO_PKG_VERSION"),
565 )]);
566 if std::env::var_os("OTEL_SERVICE_NAME").is_none() {
567 builder = builder.with_service_name(SCOPE);
568 }
569 if let Some(env_name) = std::env::var("DEPLOY_ENV")
570 .ok()
571 .filter(|v| !v.trim().is_empty())
572 {
573 builder = builder.with_attribute(KeyValue::new(
574 opentelemetry_semantic_conventions::resource::DEPLOYMENT_ENVIRONMENT_NAME,
575 env_name,
576 ));
577 }
578 builder.build()
579}
580
581#[cfg(test)]
582mod tests {
583 use opentelemetry::logs::{LogRecord as _, Logger as _, LoggerProvider as _};
584 use opentelemetry_sdk::logs::{InMemoryLogExporter, SdkLoggerProvider};
585
586 use super::{LogFormat, StampTimestamp, TelemetryError, openobserve_otlp_headers};
587
588 #[tokio::test]
589 async fn log_format_parses_the_two_spellings_and_rejects_the_rest() {
590 assert_eq!(LogFormat::parse(None).unwrap(), LogFormat::Pretty);
591 assert_eq!(
592 LogFormat::parse(Some(" ".into())).unwrap(),
593 LogFormat::Pretty
594 );
595 assert_eq!(
596 LogFormat::parse(Some("pretty".into())).unwrap(),
597 LogFormat::Pretty
598 );
599 assert_eq!(
600 LogFormat::parse(Some(" JSON ".into())).unwrap(),
601 LogFormat::Json
602 );
603 // Rejected, not defaulted: a shipper configured for JSON that silently
604 // receives pretty lines fails at the far end, hours later.
605 let err = LogFormat::parse(Some("logfmt".into())).unwrap_err();
606 assert!(matches!(err, TelemetryError::LogFormat(v) if v == "logfmt"));
607 }
608
609 #[tokio::test]
610 async fn a_record_without_a_timestamp_is_stamped_with_its_observed_time() {
611 let exporter = InMemoryLogExporter::default();
612 let provider = SdkLoggerProvider::builder()
613 .with_log_processor(StampTimestamp)
614 .with_simple_exporter(exporter.clone())
615 .build();
616 let logger = provider.logger("test");
617
618 // What the tracing appender hands the SDK: no `timestamp` at all.
619 let mut record = logger.create_log_record();
620 record.set_body("hello".into());
621 logger.emit(record);
622 provider.force_flush().unwrap();
623
624 let logs = exporter.get_emitted_logs().unwrap();
625 assert_eq!(logs.len(), 1);
626 let exported = &logs[0].record;
627 // Not 1970, and not a freshly invented clock read either.
628 assert!(exported.timestamp().is_some());
629 assert_eq!(exported.timestamp(), exported.observed_timestamp());
630 }
631
632 #[test]
633 fn openobserve_headers_are_basic_auth_of_email_and_password() {
634 // The pair compose.yaml used as local-dev OpenObserve credentials;
635 // the encoded value is what a collector would have accepted then.
636 assert_eq!(
637 openobserve_otlp_headers("admin@hezarfen.local", "Hezarfen_dev1!"),
638 "Authorization=Basic YWRtaW5AaGV6YXJmZW4ubG9jYWw6SGV6YXJmZW5fZGV2MSE=,organization=default,stream-name=default"
639 );
640 }
641}