Diffinery

homeflare/celldpublic

celld/crates/celld/telemetry.rs
1214 lines · 43.1 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3// Telemetry is observational and does not affect Actor decisions.
4#![allow(clippy::disallowed_methods)]
5
6//! Telemetry: wide events out of the shell, Parquet into the bucket.
7//!
8//! This is v1's substrate. Off by default, and off is structural: `init`
9//! never runs, `start_trace` finds no globals and answers `None`, and no
10//! event is ever built.
11//! Sampling is decided at trace creation for the same reason — an
12//! unsampled request builds nothing.
13//!
14//! The hot path never blocks. `record` is a `try_send`; a full channel
15//! increments a drop counter. Under saturation celld sheds telemetry,
16//! counted, never requests. The pipeline is ordinary tasks on the shared
17//! runtime — no dedicated thread (the Deno pattern needs one because its
18//! main loop is a current-thread runtime; celld's is not) — and encoding
19//! runs on `spawn_blocking`, the `prune_local_cache` treatment.
20
21use crate::bucket::Bucket;
22use anyhow::anyhow;
23use anyhow::bail;
24use std::sync::atomic::AtomicU64;
25use std::sync::atomic::Ordering;
26use std::sync::OnceLock;
27use std::time::Duration;
28use std::time::SystemTime;
29use std::time::UNIX_EPOCH;
30
31/// Where telemetry objects live, under the sink bucket.
32pub const TRACES_PREFIX: &str = "telemetry/traces";
33pub const LOGS_PREFIX: &str = "telemetry/logs";
34
35/// A `console.log` body larger than this is truncated: log records are
36/// telemetry, not blob storage, and one runaway line must not dominate a
37/// batch.
38#[doc(hidden)]
39pub const LOG_BODY_CAP: usize = 8 * 1024;
40
41/// The schema is not frozen. Stamped on every object so a reader knows
42/// what contract the columns follow; the DuckDB page documents it.
43const SCHEMA_VERSION: &str = "v0-unstable";
44
45/// Queue between the hot path and the pump; a full queue sheds, counted.
46/// The pump drains continuously and the size trigger bounds its batch, so
47/// this only needs to cover a scheduling hiccup, not a flush interval.
48const CHANNEL_CAPACITY: usize = 8_192;
49
50/// One batch remains exporter-owned while it retries. The channel stays
51/// bounded behind it, so an outage can consume this batch and at most
52/// `CHANNEL_CAPACITY` newer events. Five attempts cover a short collector
53/// restart without turning telemetry into an unbounded delivery queue.
54const OTLP_MAX_ATTEMPTS: u32 = 5;
55const OTLP_BACKOFF_INITIAL: Duration = Duration::from_secs(1);
56const OTLP_BACKOFF_MAX: Duration = Duration::from_secs(30);
57
58/// The provider page and the S3 bulk-delete limit are both 1,000. Keeping
59/// them equal lets a sweep delete one page without retaining a second key
60/// collection or splitting one provider page across storage requests.
61const SWEEP_PAGE_SIZE: usize = 1_000;
62
63#[derive(Clone, Copy, PartialEq, Debug)]
64pub enum Retention {
65 Days(u32),
66 /// "Never delete, my lifecycle rules own this."
67 None,
68}
69
70impl Retention {
71 fn label(self) -> String {
72 match self {
73 Retention::Days(days) => format!("{days}d"),
74 Retention::None => "none".to_string(),
75 }
76 }
77}
78
79#[derive(Debug, Clone, PartialEq)]
80pub enum SinkChoice {
81 /// Parquet into the operator's bucket: zero configuration beyond the flag.
82 /// DuckDB reads the result as described in `docs/telemetry.md`.
83 Bucket,
84 /// OTLP/http-protobuf to a collector — the ClickHouse-class path.
85 Otlp { endpoint: String },
86}
87
88#[derive(Debug)]
89pub struct Config {
90 pub sink: SinkChoice,
91 /// `CELLD_OTEL_BUCKET`, same endpoint/region/credentials as the
92 /// fleet bucket. `None` means the fleet bucket itself.
93 pub bucket_override: Option<String>,
94 pub otlp_headers: Vec<(String, String)>,
95 pub otlp_timeout: Duration,
96 pub service: String,
97 pub sample_ratio: f64,
98 /// `parentbased_*`: a caller's sampled flag decides for its children;
99 /// the ratio applies to roots only.
100 pub parent_based: bool,
101 pub retention: Retention,
102 pub flush: Duration,
103 /// Estimated buffered bytes that trigger an early flush. This controls
104 /// batching independently of the export delay. One event can exceed it.
105 pub flush_bytes: usize,
106}
107
108impl Config {
109 /// `None` when `CELLD_OTEL` is unset or `0` — the default, and the
110 /// only zero-cost state.
111 pub fn from_env() -> anyhow::Result<Option<Config>> {
112 Self::from_lookup(crate::env_vars::value)
113 }
114
115 #[doc(hidden)]
116 pub fn from_lookup(
117 get: impl Fn(&str) -> anyhow::Result<Option<String>>,
118 ) -> anyhow::Result<Option<Config>> {
119 let sink = match get("CELLD_OTEL")?.as_deref() {
120 None | Some("0") => None,
121 Some("1") => Some(SinkChoice::Bucket),
122 Some(value) => {
123 let endpoint = reqwest::Url::parse(value)
124 .ok()
125 .filter(|url| {
126 matches!(url.scheme(), "http" | "https")
127 && url.host_str().is_some()
128 && url.query().is_none()
129 && url.fragment().is_none()
130 })
131 .ok_or_else(|| anyhow!("CELLD_OTEL must be 0, 1, or an HTTP(S) collector base URL, not {value:?}"))?;
132 Some(SinkChoice::Otlp {
133 endpoint: endpoint.as_str().trim_end_matches('/').to_string(),
134 })
135 }
136 };
137 let mut otlp_headers = Vec::new();
138 if let Some(list) = get("OTEL_EXPORTER_OTLP_HEADERS")? {
139 for pair in list.split(',').filter(|pair| !pair.trim().is_empty()) {
140 let (name, value) = pair
141 .split_once('=')
142 .ok_or_else(|| anyhow!("OTEL_EXPORTER_OTLP_HEADERS: {pair:?}"))?;
143 otlp_headers.push((name.trim().to_string(), value.trim().to_string()));
144 }
145 }
146 let otlp_timeout = crate::env_vars::parse_positive::<u64>(
147 "OTEL_EXPORTER_OTLP_TIMEOUT",
148 get("OTEL_EXPORTER_OTLP_TIMEOUT")?,
149 )?
150 .map(Duration::from_millis)
151 .unwrap_or(Duration::from_secs(10));
152 let service = get("OTEL_SERVICE_NAME")?.unwrap_or_else(|| "celld".to_string());
153 // Per the otel spec: a `parentbased_*` sampler defers to the
154 // caller's sampled flag and decides itself only for roots. That
155 // is an explicit statement of upstream trust — appropriate here,
156 // because celld's ingress sits behind the operator's own edge.
157 let sampler = get("OTEL_TRACES_SAMPLER")?;
158 let sampler = sampler.as_deref().unwrap_or("parentbased_always_on");
159 let parent_based = sampler.starts_with("parentbased_");
160 let sample_ratio = match sampler {
161 "parentbased_always_on" | "always_on" => 1.0,
162 "parentbased_always_off" | "always_off" => 0.0,
163 "traceidratio" | "parentbased_traceidratio" => {
164 let arg = get("OTEL_TRACES_SAMPLER_ARG")?
165 .ok_or_else(|| anyhow!("OTEL_TRACES_SAMPLER_ARG is required"))?;
166 let ratio: f64 = arg
167 .parse()
168 .map_err(|_| anyhow!("OTEL_TRACES_SAMPLER_ARG: {arg:?}"))?;
169 if !(0.0..=1.0).contains(&ratio) {
170 bail!("OTEL_TRACES_SAMPLER_ARG must be in [0, 1]: {arg}");
171 }
172 ratio
173 }
174 other => bail!("unsupported OTEL_TRACES_SAMPLER {other:?}"),
175 };
176 let retention = match get("CELLD_OTEL_RETENTION")?.as_deref() {
177 None => Retention::Days(30),
178 Some("none") => Retention::None,
179 Some(value) => {
180 let days = value
181 .strip_suffix('d')
182 .and_then(|days| days.parse::<u32>().ok())
183 .filter(|days| *days > 0)
184 .ok_or_else(|| {
185 anyhow!("CELLD_OTEL_RETENTION must be <n>d or none: {value:?}")
186 })?;
187 Retention::Days(days)
188 }
189 };
190 let flush = crate::env_vars::parse_positive::<u64>(
191 "CELLD_OTEL_FLUSH_MS",
192 get("CELLD_OTEL_FLUSH_MS")?,
193 )?
194 .map(Duration::from_millis)
195 .unwrap_or(Duration::from_secs(300));
196 let flush_bytes = crate::env_vars::parse_positive::<usize>(
197 "CELLD_OTEL_FLUSH_BYTES",
198 get("CELLD_OTEL_FLUSH_BYTES")?,
199 )?
200 .unwrap_or(5 * 1024 * 1024);
201 let bucket_override = get("CELLD_OTEL_BUCKET")?;
202 Ok(sink.map(|sink| Config {
203 sink,
204 bucket_override,
205 otlp_headers,
206 otlp_timeout,
207 service,
208 sample_ratio,
209 parent_based,
210 retention,
211 flush,
212 flush_bytes,
213 }))
214 }
215}
216
217/// Span kinds, numbered as the OTLP proto numbers them so the later OTLP
218/// sink is a transcription, not a mapping.
219pub const KIND_INTERNAL: u8 = 1;
220pub const KIND_SERVER: u8 = 2;
221pub const KIND_CLIENT: u8 = 3;
222pub const KIND_CONSUMER: u8 = 4;
223
224/// A recorded span's identity.
225#[derive(Clone, Copy, Debug)]
226pub struct TraceIds {
227 pub trace_id: [u8; 16],
228 pub span_id: [u8; 8],
229}
230
231/// The W3C context that crosses request boundaries. This keeps the recording
232/// decision with the ids, so an unsampled context can propagate without any
233/// caller mistaking its existence for permission to record an event.
234#[derive(Clone, Copy, Debug)]
235pub struct TraceContext {
236 pub trace_id: [u8; 16],
237 pub span_id: [u8; 8],
238 pub sampled: bool,
239}
240
241impl TraceContext {
242 pub fn recording_ids(self) -> Option<TraceIds> {
243 self.sampled.then_some(TraceIds {
244 trace_id: self.trace_id,
245 span_id: self.span_id,
246 })
247 }
248}
249
250/// A caller's trace context, extracted from a W3C `traceparent` header.
251/// celld does not terminate TLS; whoever can reach its ingress is the
252/// operator's own edge, so honoring this trusts the same infrastructure.
253#[derive(Clone, Copy, Debug, PartialEq)]
254pub struct ParentContext {
255 pub trace_id: [u8; 16],
256 pub span_id: [u8; 8],
257 pub sampled: bool,
258}
259
260/// Parse a W3C `traceparent` value. Anything malformed is `None`, and the
261/// request becomes an ordinary root, exactly as if the header were absent.
262pub fn parse_traceparent(value: &str) -> Option<ParentContext> {
263 let value = value.trim().as_bytes();
264 if value.len() < 55 || value[2] != b'-' || value[35] != b'-' || value[52] != b'-' {
265 return None;
266 }
267
268 let version = unhex::<1>(&value[..2])?[0];
269 if version == 0xff
270 || (version == 0 && value.len() != 55)
271 || (version != 0 && value.len() > 55 && value[55] != b'-')
272 {
273 return None;
274 }
275
276 let trace_id = unhex(&value[3..35])?;
277 let span_id = unhex(&value[36..52])?;
278 let flags = unhex::<1>(&value[53..55])?[0];
279 if trace_id == [0; 16] || span_id == [0; 8] {
280 return None;
281 }
282 Some(ParentContext {
283 trace_id,
284 span_id,
285 sampled: flags & 1 == 1,
286 })
287}
288
289/// The header for an outbound request made inside a propagated context.
290pub fn traceparent(context: &TraceContext) -> String {
291 let flags = if context.sampled { "01" } else { "00" };
292 format!(
293 "00-{}-{}-{flags}",
294 hex(&context.trace_id),
295 hex(&context.span_id)
296 )
297}
298
299fn unhex<const N: usize>(text: &[u8]) -> Option<[u8; N]> {
300 if text.len() != N * 2 {
301 return None;
302 }
303 let mut out = [0u8; N];
304 for (index, byte) in out.iter_mut().enumerate() {
305 let high = hex_nibble(text[index * 2])?;
306 let low = hex_nibble(text[index * 2 + 1])?;
307 *byte = high << 4 | low;
308 }
309 Some(out)
310}
311
312fn hex_nibble(byte: u8) -> Option<u8> {
313 match byte {
314 b'0'..=b'9' => Some(byte - b'0'),
315 b'a'..=b'f' => Some(byte - b'a' + 10),
316 _ => None,
317 }
318}
319
320/// One wide event. Flat on purpose: every field is a Parquet column, and the
321/// column names are the schema contract.
322pub struct Span {
323 pub ids: TraceIds,
324 pub parent_span_id: Option<[u8; 8]>,
325 pub name: &'static str,
326 pub kind: u8,
327 pub start_unix_us: i64,
328 pub duration_us: i64,
329 pub ok: bool,
330 pub error: Option<String>,
331 pub request_id: Option<String>,
332 pub cell: Option<String>,
333 pub epoch: Option<u64>,
334 pub isolate: Option<u64>,
335 pub queue_wait_us: Option<i64>,
336 pub url: Option<String>,
337 pub http_status: Option<u16>,
338 /// `Some(true)` for a parent extracted from a caller's traceparent,
339 /// `Some(false)` for an in-process parent, `None` for a root.
340 pub parent_remote: Option<bool>,
341}
342
343/// One captured console line, correlated to the trace whose turn (or
344/// whose promise continuation — that is what CPED buys) produced it.
345pub struct Log {
346 pub trace_id: Option<[u8; 16]>,
347 pub span_id: Option<[u8; 8]>,
348 pub time_unix_us: i64,
349 pub body: String,
350}
351
352impl Span {
353 pub fn new(ids: TraceIds, name: &'static str, kind: u8) -> Span {
354 Span {
355 ids,
356 parent_span_id: None,
357 name,
358 kind,
359 start_unix_us: 0,
360 duration_us: 0,
361 ok: true,
362 error: None,
363 request_id: None,
364 cell: None,
365 epoch: None,
366 isolate: None,
367 queue_wait_us: None,
368 url: None,
369 http_status: None,
370 parent_remote: None,
371 }
372 }
373}
374
375enum Event {
376 Span(Span),
377 Log(Log),
378}
379
380impl Event {
381 /// A cheap pre-encode size estimate for the flush trigger: fixed
382 /// columns plus the owned strings. Compression shrinks the object
383 /// afterwards, the same way Firehose's buffer counts raw bytes.
384 fn approx_bytes(&self) -> usize {
385 const LEN: fn(&Option<String>) -> usize = |s| s.as_deref().map_or(0, str::len);
386 match self {
387 Event::Span(span) => {
388 96 + span.name.len()
389 + LEN(&span.error)
390 + LEN(&span.request_id)
391 + LEN(&span.cell)
392 + LEN(&span.url)
393 }
394 Event::Log(log) => 40 + log.body.len(),
395 }
396 }
397}
398
399struct Telemetry {
400 tx: tokio::sync::mpsc::Sender<Event>,
401 dropped: AtomicU64,
402 sampler: Sampler,
403 parent_based: bool,
404}
405
406#[derive(Clone, Copy)]
407enum Sampler {
408 AlwaysOff,
409 /// The number of `u64` decision values that record, starting at zero.
410 TraceIdRatio(u64),
411 AlwaysOn,
412}
413
414impl Sampler {
415 fn from_ratio(ratio: f64) -> Sampler {
416 if ratio == 0.0 {
417 return Sampler::AlwaysOff;
418 }
419 if ratio == 1.0 {
420 return Sampler::AlwaysOn;
421 }
422 // A u64 has 2^64 possible values, which cannot fit in a u64. Keep
423 // the full-range endpoint as a distinct policy and store a count for
424 // every intermediate ratio. An inclusive maximum would add one
425 // sampled value and would make the zero endpoint nonempty again.
426 Sampler::TraceIdRatio((ratio * (u64::MAX as f64 + 1.0)) as u64)
427 }
428
429 fn samples(self, decision: u64) -> bool {
430 match self {
431 Sampler::AlwaysOff => false,
432 Sampler::TraceIdRatio(upper_bound) => decision < upper_bound,
433 Sampler::AlwaysOn => true,
434 }
435 }
436}
437
438static TELEMETRY: OnceLock<Telemetry> = OnceLock::new();
439
440pub fn active() -> bool {
441 TELEMETRY.get().is_some()
442}
443
444/// Decide a new root trace at its creation. `None` means off or unsampled,
445/// and the caller builds nothing at all.
446pub fn start_trace() -> Option<TraceContext> {
447 start_trace_with_parent(None)
448}
449
450/// Decide a trace at its creation, under a foreign parent when the
451/// caller sent one. A rejected foreign parent remains present for W3C
452/// propagation, but a rejected root remains absent to preserve the cheap path.
453pub fn start_trace_with_parent(parent: Option<&ParentContext>) -> Option<TraceContext> {
454 let telemetry = TELEMETRY.get()?;
455 let (trace_id, sampled) = decide_with_sampler(
456 telemetry.parent_based,
457 telemetry.sampler,
458 parent,
459 rand::random(),
460 );
461 if !sampled && parent.is_none() {
462 return None;
463 }
464 Some(TraceContext {
465 trace_id,
466 span_id: rand::random(),
467 sampled,
468 })
469}
470
471/// The sampling decision, pure so the semantics are testable: adopt the
472/// parent's trace id either way; `parent_based` defers to its sampled
473/// flag, everything else applies the sampler to the trace id itself.
474fn decide_with_sampler(
475 parent_based: bool,
476 sampler: Sampler,
477 parent: Option<&ParentContext>,
478 fresh: [u8; 16],
479) -> ([u8; 16], bool) {
480 let (trace_id, parent_sampled) = match parent {
481 Some(parent) => (parent.trace_id, Some(parent.sampled)),
482 None => (fresh, None),
483 };
484 let sampled = match (parent_sampled, parent_based) {
485 (Some(sampled), true) => sampled,
486 _ => {
487 let head = u64::from_be_bytes(trace_id[..8].try_into().unwrap());
488 sampler.samples(head)
489 }
490 };
491 (trace_id, sampled)
492}
493
494/// The sampler is private, so the private suite reaches the decision
495/// through the ratio the configuration carries.
496#[cfg(celld_internal_tests)]
497#[doc(hidden)]
498pub fn decide(
499 parent_based: bool,
500 sample_ratio: f64,
501 parent: Option<&ParentContext>,
502 fresh: [u8; 16],
503) -> ([u8; 16], bool) {
504 decide_with_sampler(
505 parent_based,
506 Sampler::from_ratio(sample_ratio),
507 parent,
508 fresh,
509 )
510}
511
512/// Join an in-process parent: same trace and decision, with a fresh span id.
513pub fn child_of(parent: &TraceContext) -> Option<TraceContext> {
514 TELEMETRY.get()?;
515 Some(TraceContext {
516 trace_id: parent.trace_id,
517 span_id: rand::random(),
518 sampled: parent.sampled,
519 })
520}
521
522/// A child context: same trace and decision, with a fresh span id.
523pub fn child_context(parent: &TraceContext) -> TraceContext {
524 TraceContext {
525 trace_id: parent.trace_id,
526 span_id: rand::random(),
527 sampled: parent.sampled,
528 }
529}
530
531/// Queue a finished span. Never blocks: a full channel counts a drop —
532/// telemetry sheds, requests do not.
533pub fn record(span: Span) {
534 send(Event::Span(span));
535}
536
537/// Queue a captured console line, truncated to the cap.
538pub fn record_log(mut log: Log) {
539 cap_body(&mut log.body);
540 send(Event::Log(log));
541}
542
543/// Bound a captured error the way a log body is bound, so one runaway
544/// exception message cannot dominate a batch or a span row.
545pub(crate) fn cap_error(mut error: String) -> String {
546 cap_body(&mut error);
547 error
548}
549
550#[doc(hidden)]
551pub fn cap_body(body: &mut String) {
552 if body.len() <= LOG_BODY_CAP {
553 return;
554 }
555 let mut end = LOG_BODY_CAP;
556 while !body.is_char_boundary(end) {
557 end -= 1;
558 }
559 body.truncate(end);
560}
561
562fn send(event: Event) {
563 let Some(telemetry) = TELEMETRY.get() else {
564 return;
565 };
566 if telemetry.tx.try_send(event).is_err() {
567 telemetry.dropped.fetch_add(1, Ordering::Relaxed);
568 }
569}
570
571pub fn now_unix_us() -> i64 {
572 SystemTime::now()
573 .duration_since(UNIX_EPOCH)
574 .unwrap_or_default()
575 .as_micros() as i64
576}
577
578/// Start the pipeline. Called at most once, from startup, only when the
579/// operator selects a bucket or a collector.
580pub fn init(
581 config: &Config,
582 bucket: Option<Bucket>,
583 node: String,
584 region: String,
585) -> anyhow::Result<()> {
586 let sink = match &config.sink {
587 SinkChoice::Bucket => {
588 let bucket = bucket.expect("the bucket sink needs a bucket");
589 tracing::info!(
590 retention = %config.retention.label(),
591 sample_ratio = config.sample_ratio,
592 bucket = %bucket.name,
593 "telemetry on; Parquet to the bucket"
594 );
595 if let Retention::Days(days) = config.retention {
596 tokio::spawn(sweep_loop(bucket.clone(), days));
597 }
598 SinkRuntime::Bucket {
599 bucket,
600 retention: config.retention.label(),
601 }
602 }
603 SinkChoice::Otlp { endpoint } => {
604 tracing::info!(
605 endpoint = %endpoint,
606 sample_ratio = config.sample_ratio,
607 "telemetry on; OTLP to the collector"
608 );
609 SinkRuntime::Otlp {
610 client: reqwest::Client::builder()
611 .timeout(config.otlp_timeout)
612 .build()
613 .map_err(|error| anyhow!("otlp client: {error}"))?,
614 traces_url: format!("{endpoint}/v1/traces"),
615 logs_url: format!("{endpoint}/v1/logs"),
616 headers: config.otlp_headers.clone(),
617 }
618 }
619 };
620 let (tx, rx) = tokio::sync::mpsc::channel(CHANNEL_CAPACITY);
621 let telemetry = Telemetry {
622 tx,
623 dropped: AtomicU64::new(0),
624 sampler: Sampler::from_ratio(config.sample_ratio),
625 parent_based: config.parent_based,
626 };
627 if TELEMETRY.set(telemetry).is_err() {
628 panic!("telemetry initialized twice");
629 }
630 tokio::spawn(pump(
631 rx,
632 sink,
633 node,
634 region,
635 config.service.clone(),
636 config.flush,
637 config.flush_bytes,
638 ));
639 Ok(())
640}
641
642enum SinkRuntime {
643 Bucket {
644 bucket: Bucket,
645 retention: String,
646 },
647 Otlp {
648 client: reqwest::Client,
649 traces_url: String,
650 logs_url: String,
651 headers: Vec<(String, String)>,
652 },
653}
654
655impl SinkRuntime {
656 /// Ship one flush interval's events. Encoding runs on the blocking
657 /// pool either way. For OTLP, the return value counts records discarded
658 /// after a permanent refusal or retry exhaustion.
659 async fn flush(
660 &self,
661 spans: Vec<Span>,
662 logs: Vec<Log>,
663 node: &str,
664 region: &str,
665 service: &str,
666 ) -> u64 {
667 let span_count = spans.len() as u64;
668 let log_count = logs.len() as u64;
669 match self {
670 SinkRuntime::Bucket { bucket, retention } => {
671 let node_ = node.to_string();
672 let region_ = region.to_string();
673 let encoded = tokio::task::spawn_blocking(move || {
674 let spans = (!spans.is_empty())
675 .then(|| encode_spans(&spans, &node_, &region_))
676 .transpose()?;
677 let logs = (!logs.is_empty())
678 .then(|| encode_logs(&logs, &node_, &region_))
679 .transpose()?;
680 anyhow::Ok((spans, logs))
681 })
682 .await;
683 let (span_bytes, log_bytes) = match flatten(encoded) {
684 Ok(bytes) => bytes,
685 Err(error) => {
686 tracing::warn!(%error, "telemetry batch lost: encode failed");
687 return 0;
688 }
689 };
690 let meta = [
691 ("celld-retention", retention.as_str()),
692 ("celld-schema", SCHEMA_VERSION),
693 ];
694 for (prefix, bytes) in [(TRACES_PREFIX, span_bytes), (LOGS_PREFIX, log_bytes)] {
695 let Some(bytes) = bytes else { continue };
696 let key = object_key(prefix, node, now_unix_us());
697 if let Err(error) = bucket.put_with_meta(&key, bytes, &meta).await {
698 tracing::warn!(%error, key, "telemetry batch lost: put failed");
699 }
700 }
701 0
702 }
703 SinkRuntime::Otlp {
704 client,
705 traces_url,
706 logs_url,
707 headers,
708 } => {
709 let node_ = node.to_string();
710 let region_ = region.to_string();
711 let service_ = service.to_string();
712 let encoded = tokio::task::spawn_blocking(move || {
713 let spans = (!spans.is_empty())
714 .then(|| crate::otlp::traces_request(&spans, &node_, &region_, &service_));
715 let logs = (!logs.is_empty())
716 .then(|| crate::otlp::logs_request(&logs, &node_, &region_, &service_));
717 anyhow::Ok((spans, logs))
718 })
719 .await;
720 let (span_bytes, log_bytes) = match flatten(encoded) {
721 Ok(bytes) => bytes,
722 Err(error) => {
723 tracing::warn!(%error, "telemetry batch lost: encode failed");
724 return span_count + log_count;
725 }
726 };
727 let mut dropped = 0;
728 for (url, bytes, count) in [
729 (traces_url, span_bytes, span_count),
730 (logs_url, log_bytes, log_count),
731 ] {
732 let Some(bytes) = bytes else { continue };
733 if !post_otlp(client, url, headers, bytes.into()).await {
734 dropped += count;
735 }
736 }
737 dropped
738 }
739 }
740 }
741}
742
743/// Send the same encoded request until the collector accepts it, refuses it
744/// permanently, or the retry budget expires. This future owns only one batch.
745/// While it sleeps, request handling continues and the bounded channel sheds
746/// excess telemetry instead of turning an outage into application backpressure.
747async fn post_otlp(
748 client: &reqwest::Client,
749 url: &str,
750 headers: &[(String, String)],
751 bytes: bytes::Bytes,
752) -> bool {
753 for attempt in 1..=OTLP_MAX_ATTEMPTS {
754 let mut request = client
755 .post(url)
756 .header("content-type", "application/x-protobuf")
757 .body(bytes.clone());
758 for (name, value) in headers {
759 request = request.header(name.as_str(), value.as_str());
760 }
761 let (error, delay) = match request.send().await {
762 Ok(response) if response.status().is_success() => return true,
763 Ok(response) if retryable_otlp_status(response.status()) => {
764 let status = response.status();
765 let delay =
766 otlp_response_delay(status, retry_after(&response), otlp_backoff(attempt))
767 .expect("the retryable status guard supplies a retry delay");
768 (format!("collector returned {status}"), delay)
769 }
770 Ok(response) => {
771 tracing::warn!(
772 status = %response.status(),
773 url,
774 "telemetry batch lost: collector refused permanently"
775 );
776 return false;
777 }
778 Err(error) => (error.to_string(), otlp_backoff(attempt)),
779 };
780 if attempt == OTLP_MAX_ATTEMPTS {
781 tracing::warn!(
782 %error,
783 url,
784 attempts = OTLP_MAX_ATTEMPTS,
785 "telemetry batch lost: OTLP retry budget exhausted"
786 );
787 return false;
788 }
789 tracing::warn!(
790 %error,
791 url,
792 attempt,
793 delay_ms = delay.as_millis(),
794 "telemetry export failed transiently; retrying"
795 );
796 tokio::time::sleep(delay).await;
797 }
798 unreachable!("the nonzero OTLP attempt range always returns")
799}
800
801fn retryable_otlp_status(status: reqwest::StatusCode) -> bool {
802 matches!(status.as_u16(), 408 | 429 | 502 | 503 | 504)
803}
804
805fn otlp_response_delay(
806 status: reqwest::StatusCode,
807 retry_after: Option<Duration>,
808 fallback: Duration,
809) -> Option<Duration> {
810 retryable_otlp_status(status).then(|| retry_after.unwrap_or(fallback).min(OTLP_BACKOFF_MAX))
811}
812
813fn retry_after(response: &reqwest::Response) -> Option<Duration> {
814 if !matches!(response.status().as_u16(), 429 | 503) {
815 return None;
816 }
817 let value = response
818 .headers()
819 .get(reqwest::header::RETRY_AFTER)?
820 .to_str()
821 .ok()?
822 .trim();
823 if let Ok(seconds) = value.parse::<u64>() {
824 return Some(Duration::from_secs(seconds));
825 }
826 let retry_at = httpdate::parse_http_date(value).ok()?;
827 Some(
828 retry_at
829 .duration_since(SystemTime::now())
830 .unwrap_or_default(),
831 )
832}
833
834fn otlp_backoff(attempt: u32) -> Duration {
835 let exponent = attempt.saturating_sub(1).min(31);
836 let ceiling = OTLP_BACKOFF_INITIAL
837 .saturating_mul(1_u32 << exponent)
838 .min(OTLP_BACKOFF_MAX);
839 let ceiling_ms = ceiling.as_millis() as u64;
840 Duration::from_millis(rand::random::<u64>() % (ceiling_ms + 1))
841}
842
843#[cfg(all(test, celld_internal_tests))]
844mod telemetry_contract {
845 use super::*;
846
847 include!(env!("CELLD_INTERNAL_TELEMETRY_TESTS"));
848}
849
850/// A `spawn_blocking` result unwrapped honestly: the panic and the
851/// encode error both lose the batch with a reason.
852fn flatten<T>(joined: Result<anyhow::Result<T>, tokio::task::JoinError>) -> anyhow::Result<T> {
853 match joined {
854 Ok(Ok(value)) => Ok(value),
855 Ok(Err(error)) => Err(error),
856 Err(error) => Err(anyhow!("encoder panicked: {error}")),
857 }
858}
859
860/// Drain the channel into Parquet objects — one per signal per flush
861/// interval with traffic. Encode on the blocking pool; PUT as ordinary
862/// async I/O.
863async fn pump(
864 mut rx: tokio::sync::mpsc::Receiver<Event>,
865 sink: SinkRuntime,
866 node: String,
867 region: String,
868 service: String,
869 flush: Duration,
870 flush_bytes: usize,
871) {
872 let mut batch: Vec<Event> = Vec::new();
873 loop {
874 let deadline = tokio::time::Instant::now() + flush;
875 let mut bytes = 0usize;
876 loop {
877 match tokio::time::timeout_at(deadline, rx.recv()).await {
878 Ok(Some(event)) => {
879 bytes += event.approx_bytes();
880 batch.push(event);
881 // Firehose semantics: the size trigger cuts a batch
882 // early so a busy node ships few, fat objects.
883 if bytes >= flush_bytes {
884 break;
885 }
886 }
887 Ok(None) => return, // sender is static; process is ending
888 Err(_) => break, // interval elapsed
889 }
890 }
891 if batch.is_empty() {
892 continue;
893 }
894 let mut spans = Vec::new();
895 let mut logs = Vec::new();
896 for event in batch.drain(..) {
897 match event {
898 Event::Span(span) => spans.push(span),
899 Event::Log(log) => logs.push(log),
900 }
901 }
902 let sink_dropped = sink.flush(spans, logs, &node, &region, &service).await;
903 let dropped = sink_dropped.saturating_add(
904 TELEMETRY
905 .get()
906 .map(|telemetry| telemetry.dropped.swap(0, Ordering::Relaxed))
907 .unwrap_or(0),
908 );
909 if dropped > 0 {
910 tracing::warn!(dropped, "telemetry shed");
911 }
912 }
913}
914
915/// `<prefix>/<node>/<yyyy/mm/dd/hh>/<flush_us>-<rand>.parquet`.
916/// Partitioned by arrival at the flush, which is what retention prunes
917/// by; event timestamps stay exact inside the file.
918#[doc(hidden)]
919pub fn object_key(prefix: &str, node: &str, unix_us: i64) -> String {
920 let seconds = unix_us / 1_000_000;
921 let (y, m, d) = civil_from_days(seconds.div_euclid(86_400));
922 let hour = seconds.rem_euclid(86_400) / 3_600;
923 let tag: u32 = rand::random();
924 format!("{prefix}/{node}/{y:04}/{m:02}/{d:02}/{hour:02}/{unix_us}-{tag:08x}.parquet")
925}
926
927/// The retention sweep: celld deletes its own old telemetry, because
928/// an S3 lifecycle rule needs bucket-level permissions the deliberately
929/// object-scoped credentials must not require. Prefix
930/// deletes over the day-partitioned layout, idempotent and safe to
931/// race between nodes — every node sweeps the whole telemetry prefix,
932/// so a dead node's data expires too. The sweep enforces the *current*
933/// configuration; the per-object retention stamp is forensic.
934async fn sweep_loop(bucket: Bucket, retention_days: u32) {
935 loop {
936 let cutoff = cutoff_date(now_unix_us(), retention_days);
937 let deleted = sweep_once(&bucket, cutoff).await;
938 if deleted > 0 {
939 tracing::info!(deleted, retention_days, "telemetry swept");
940 }
941 tokio::time::sleep(Duration::from_secs(6 * 3600)).await;
942 }
943}
944
945/// One complete retention pass. A page failure ends only that signal's pass,
946/// while deletions completed from its earlier pages remain effective.
947#[doc(hidden)]
948pub async fn sweep_once(bucket: &Bucket, cutoff: (i64, u32, u32)) -> u64 {
949 let mut deleted = 0u64;
950 for prefix in [TRACES_PREFIX, LOGS_PREFIX] {
951 let mut page_token = None;
952 loop {
953 let page = match bucket
954 .objects_page(prefix, page_token, SWEEP_PAGE_SIZE)
955 .await
956 {
957 Ok(page) => page,
958 Err(error) => {
959 tracing::warn!(%error, prefix, "telemetry sweep could not list");
960 break;
961 }
962 };
963 let next_page = page.page_token;
964 // Retain only the keys this page proves are expired. Fresh and
965 // unparseable descriptions are released before deletion starts.
966 let expired_keys: Vec<String> = page
967 .objects
968 .into_iter()
969 .filter_map(|object| {
970 let key = object.location.as_ref();
971 expired(key, prefix, cutoff).then(|| key.to_string())
972 })
973 .collect();
974 if !expired_keys.is_empty() {
975 deleted += bucket.delete_many(&expired_keys).await.len() as u64;
976 }
977 match next_page {
978 Some(token) => page_token = Some(token),
979 None => break,
980 }
981 }
982 }
983 deleted
984}
985
986/// The newest civil date old enough to delete: strictly before
987/// `retention_days` whole days ago.
988#[doc(hidden)]
989pub fn cutoff_date(now_unix_us: i64, retention_days: u32) -> (i64, u32, u32) {
990 let today = (now_unix_us / 1_000_000).div_euclid(86_400);
991 civil_from_days(today - retention_days as i64)
992}
993
994/// Whether a telemetry object key's day partition is older than the
995/// cutoff. Keys that do not parse as
996/// `<prefix>/<node>/<yyyy>/<mm>/<dd>/...` are never touched: the sweep
997/// deletes only what the layout proves is telemetry with a date.
998#[doc(hidden)]
999pub fn expired(key: &str, prefix: &str, cutoff: (i64, u32, u32)) -> bool {
1000 let Some(rest) = key
1001 .strip_prefix(prefix)
1002 .and_then(|rest| rest.strip_prefix('/'))
1003 else {
1004 return false;
1005 };
1006 let mut parts = rest.split('/');
1007 let _node = parts.next();
1008 let (Some(y), Some(m), Some(d)) = (parts.next(), parts.next(), parts.next()) else {
1009 return false;
1010 };
1011 let (Ok(y), Ok(m), Ok(d)) = (y.parse::<i64>(), m.parse::<u32>(), d.parse::<u32>()) else {
1012 return false;
1013 };
1014 if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
1015 return false;
1016 }
1017 (y, m, d) < cutoff
1018}
1019
1020/// Days since the Unix epoch to a civil date (Howard Hinnant's
1021/// `civil_from_days`, public domain construction).
1022#[doc(hidden)]
1023pub fn civil_from_days(days: i64) -> (i64, u32, u32) {
1024 let z = days + 719_468;
1025 let era = z.div_euclid(146_097);
1026 let doe = z.rem_euclid(146_097);
1027 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
1028 let y = yoe + era * 400;
1029 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1030 let mp = (5 * doy + 2) / 153;
1031 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
1032 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1033 (if m <= 2 { y + 1 } else { y }, m, d)
1034}
1035
1036fn hex(bytes: &[u8]) -> String {
1037 let mut out = String::with_capacity(bytes.len() * 2);
1038 for byte in bytes {
1039 out.push_str(&format!("{byte:02x}"));
1040 }
1041 out
1042}
1043
1044/// The Parquet schema, in message-type form because the text is the
1045/// documentation. These column names are the contract in `docs/telemetry.md`,
1046/// so a schema change requires a documentation change.
1047const MESSAGE_TYPE: &str = "
1048message celld_span {
1049 required binary node (STRING);
1050 required binary region (STRING);
1051 required binary trace_id (STRING);
1052 required binary span_id (STRING);
1053 optional binary parent_span_id (STRING);
1054 required binary name (STRING);
1055 required int32 kind (INTEGER(8,false));
1056 required int64 start_unix_us;
1057 required int64 duration_us;
1058 required boolean ok;
1059 optional binary error (STRING);
1060 optional binary request_id (STRING);
1061 optional binary cell (STRING);
1062 optional int64 epoch;
1063 optional int64 isolate;
1064 optional int64 queue_wait_us;
1065 optional binary url (STRING);
1066 optional int32 http_status (INTEGER(16,false));
1067 optional boolean parent_remote;
1068}";
1069
1070/// The logs signal: one row per captured console line, joined to traces
1071/// on `trace_id`.
1072const LOG_MESSAGE_TYPE: &str = "
1073message celld_log {
1074 required binary node (STRING);
1075 required binary region (STRING);
1076 optional binary trace_id (STRING);
1077 optional binary span_id (STRING);
1078 required int64 time_unix_us;
1079 required binary body (STRING);
1080}";
1081
1082/// The native column-writer API rather than the arrow one: the schema is
1083/// flat primitives, and skipping the `arrow` feature keeps the whole
1084/// arrow crate stack out of the binary.
1085#[doc(hidden)]
1086pub fn encode_spans(spans: &[Span], node: &str, region: &str) -> anyhow::Result<Vec<u8>> {
1087 use parquet::basic::Compression;
1088 use parquet::basic::ZstdLevel;
1089 use parquet::data_type::BoolType;
1090 use parquet::data_type::ByteArray;
1091 use parquet::data_type::ByteArrayType;
1092 use parquet::data_type::Int32Type;
1093 use parquet::data_type::Int64Type;
1094 use parquet::file::properties::WriterProperties;
1095 use parquet::file::writer::SerializedFileWriter;
1096 use parquet::schema::parser::parse_message_type;
1097 use parquet::schema::types::ColumnPath;
1098 use std::sync::Arc;
1099
1100 let schema = Arc::new(parse_message_type(MESSAGE_TYPE)?);
1101 let properties = Arc::new(
1102 WriterProperties::builder()
1103 .set_compression(Compression::ZSTD(ZstdLevel::default()))
1104 // Point lookups by trace id are the one query a
1105 // time-partitioned scan is bad at; the bloom filter is what
1106 // makes them cheap.
1107 .set_column_bloom_filter_enabled(ColumnPath::from("trace_id"), true)
1108 .build(),
1109 );
1110 let mut writer = SerializedFileWriter::new(Vec::new(), schema, properties)?;
1111 let mut group = writer.next_row_group()?;
1112
1113 // Columns are written in schema order; each macro arm consumes the
1114 // next one. Optionals carry definition levels (1 present, 0 null)
1115 // and pack only the present values, as the format requires.
1116 macro_rules! column {
1117 ($type:ty, req $values:expr) => {{
1118 let mut column = group.next_column()?.expect("schema column");
1119 let values = $values;
1120 column.typed::<$type>().write_batch(&values, None, None)?;
1121 column.close()?;
1122 }};
1123 ($type:ty, opt $values:expr) => {{
1124 let mut column = group.next_column()?.expect("schema column");
1125 let options = $values;
1126 let levels: Vec<i16> = options.iter().map(|value| value.is_some() as i16).collect();
1127 let values: Vec<_> = options.into_iter().flatten().collect();
1128 column
1129 .typed::<$type>()
1130 .write_batch(&values, Some(&levels), None)?;
1131 column.close()?;
1132 }};
1133 }
1134 let text = |value: &str| ByteArray::from(value.as_bytes().to_vec());
1135 let each = spans.iter();
1136
1137 column!(ByteArrayType, req each.clone().map(|_| text(node)).collect::<Vec<_>>());
1138 column!(ByteArrayType, req each.clone().map(|_| text(region)).collect::<Vec<_>>());
1139 column!(ByteArrayType, req each.clone().map(|s| text(&hex(&s.ids.trace_id))).collect::<Vec<_>>());
1140 column!(ByteArrayType, req each.clone().map(|s| text(&hex(&s.ids.span_id))).collect::<Vec<_>>());
1141 column!(ByteArrayType, opt each.clone().map(|s| s.parent_span_id.map(|id| text(&hex(&id)))).collect::<Vec<_>>());
1142 column!(ByteArrayType, req each.clone().map(|s| text(s.name)).collect::<Vec<_>>());
1143 column!(Int32Type, req each.clone().map(|s| s.kind as i32).collect::<Vec<_>>());
1144 column!(Int64Type, req each.clone().map(|s| s.start_unix_us).collect::<Vec<_>>());
1145 column!(Int64Type, req each.clone().map(|s| s.duration_us).collect::<Vec<_>>());
1146 column!(BoolType, req each.clone().map(|s| s.ok).collect::<Vec<_>>());
1147 column!(ByteArrayType, opt each.clone().map(|s| s.error.as_deref().map(text)).collect::<Vec<_>>());
1148 column!(ByteArrayType, opt each.clone().map(|s| s.request_id.as_deref().map(text)).collect::<Vec<_>>());
1149 column!(ByteArrayType, opt each.clone().map(|s| s.cell.as_deref().map(text)).collect::<Vec<_>>());
1150 column!(Int64Type, opt each.clone().map(|s| s.epoch.map(|v| v as i64)).collect::<Vec<_>>());
1151 column!(Int64Type, opt each.clone().map(|s| s.isolate.map(|v| v as i64)).collect::<Vec<_>>());
1152 column!(Int64Type, opt each.clone().map(|s| s.queue_wait_us).collect::<Vec<_>>());
1153 column!(ByteArrayType, opt each.clone().map(|s| s.url.as_deref().map(text)).collect::<Vec<_>>());
1154 column!(Int32Type, opt each.clone().map(|s| s.http_status.map(|v| v as i32)).collect::<Vec<_>>());
1155 column!(BoolType, opt each.clone().map(|s| s.parent_remote).collect::<Vec<_>>());
1156
1157 group.close()?;
1158 Ok(writer.into_inner()?)
1159}
1160
1161#[doc(hidden)]
1162pub fn encode_logs(logs: &[Log], node: &str, region: &str) -> anyhow::Result<Vec<u8>> {
1163 use parquet::basic::Compression;
1164 use parquet::basic::ZstdLevel;
1165 use parquet::data_type::ByteArray;
1166 use parquet::data_type::ByteArrayType;
1167 use parquet::data_type::Int64Type;
1168 use parquet::file::properties::WriterProperties;
1169 use parquet::file::writer::SerializedFileWriter;
1170 use parquet::schema::parser::parse_message_type;
1171 use parquet::schema::types::ColumnPath;
1172 use std::sync::Arc;
1173
1174 let schema = Arc::new(parse_message_type(LOG_MESSAGE_TYPE)?);
1175 let properties = Arc::new(
1176 WriterProperties::builder()
1177 .set_compression(Compression::ZSTD(ZstdLevel::default()))
1178 .set_column_bloom_filter_enabled(ColumnPath::from("trace_id"), true)
1179 .build(),
1180 );
1181 let mut writer = SerializedFileWriter::new(Vec::new(), schema, properties)?;
1182 let mut group = writer.next_row_group()?;
1183
1184 macro_rules! column {
1185 ($type:ty, req $values:expr) => {{
1186 let mut column = group.next_column()?.expect("schema column");
1187 let values = $values;
1188 column.typed::<$type>().write_batch(&values, None, None)?;
1189 column.close()?;
1190 }};
1191 ($type:ty, opt $values:expr) => {{
1192 let mut column = group.next_column()?.expect("schema column");
1193 let options = $values;
1194 let levels: Vec<i16> = options.iter().map(|value| value.is_some() as i16).collect();
1195 let values: Vec<_> = options.into_iter().flatten().collect();
1196 column
1197 .typed::<$type>()
1198 .write_batch(&values, Some(&levels), None)?;
1199 column.close()?;
1200 }};
1201 }
1202 let text = |value: &str| ByteArray::from(value.as_bytes().to_vec());
1203 let each = logs.iter();
1204
1205 column!(ByteArrayType, req each.clone().map(|_| text(node)).collect::<Vec<_>>());
1206 column!(ByteArrayType, req each.clone().map(|_| text(region)).collect::<Vec<_>>());
1207 column!(ByteArrayType, opt each.clone().map(|l| l.trace_id.map(|id| text(&hex(&id)))).collect::<Vec<_>>());
1208 column!(ByteArrayType, opt each.clone().map(|l| l.span_id.map(|id| text(&hex(&id)))).collect::<Vec<_>>());
1209 column!(Int64Type, req each.clone().map(|l| l.time_unix_us).collect::<Vec<_>>());
1210 column!(ByteArrayType, req each.clone().map(|l| text(&l.body)).collect::<Vec<_>>());
1211
1212 group.close()?;
1213 Ok(writer.into_inner()?)
1214}