use std::sync::atomic::{AtomicU8, Ordering};
pub const CAPTURE_CONTENT_ENV: &str = "OTEL_INSTRUMENTATION_GENAI_CAPTURE_CONTENT";
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CaptureContent {
#[default]
NoContent,
SpanOnly,
EventOnly,
SpanAndEvent,
}
impl CaptureContent {
pub fn parse(value: &str) -> Self {
match value.trim().to_ascii_uppercase().as_str() {
"SPAN_ONLY" => Self::SpanOnly,
"EVENT_ONLY" => Self::EventOnly,
"SPAN_AND_EVENT" => Self::SpanAndEvent,
_ => Self::NoContent,
}
}
pub fn on_spans(self) -> bool {
matches!(self, Self::SpanOnly | Self::SpanAndEvent)
}
pub fn on_events(self) -> bool {
matches!(self, Self::EventOnly | Self::SpanAndEvent)
}
fn code(self) -> u8 {
match self {
Self::NoContent => 1,
Self::SpanOnly => 2,
Self::EventOnly => 3,
Self::SpanAndEvent => 4,
}
}
}
const UNSET: u8 = 0;
static CAPTURE: AtomicU8 = AtomicU8::new(UNSET);
pub fn set_capture_content(mode: CaptureContent) {
CAPTURE.store(mode.code(), Ordering::Relaxed);
}
pub fn capture_content() -> CaptureContent {
match CAPTURE.load(Ordering::Relaxed) {
1 => CaptureContent::NoContent,
2 => CaptureContent::SpanOnly,
3 => CaptureContent::EventOnly,
4 => CaptureContent::SpanAndEvent,
_ => std::env::var(CAPTURE_CONTENT_ENV)
.map(|value| CaptureContent::parse(&value))
.unwrap_or_default(),
}
}
#[derive(Debug, Clone, Default)]
pub struct SemconvConfig {
pub capture_content: CaptureContent,
}
impl SemconvConfig {
pub fn from_process() -> Self {
Self { capture_content: capture_content() }
}
pub fn install(&self) {
set_capture_content(self.capture_content);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config_disables_content_capture() {
assert_eq!(SemconvConfig::default().capture_content, CaptureContent::NoContent);
}
#[test]
fn modes_parse_as_the_conventions_spell_them() {
for (value, mode) in [
("NO_CONTENT", CaptureContent::NoContent),
("span_only", CaptureContent::SpanOnly),
("Event_Only", CaptureContent::EventOnly),
(" SPAN_AND_EVENT ", CaptureContent::SpanAndEvent),
("true", CaptureContent::NoContent),
("", CaptureContent::NoContent),
] {
assert_eq!(CaptureContent::parse(value), mode, "{value}");
}
}
}