grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 โ€” do not edit; change sdk-kit and run "sdk-kit sync"
//! Log record model and its normalized JSON form (`spec/schemas/log-record.schema.json`).

use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::core::{Error, Result};

/// Attribute value: string, number, boolean, array or map (SPEC ยง4 `AttrValue`).
///
/// This is [`serde_json::Value`]; `null` is accepted but exporters may drop it.
pub type AttrValue = serde_json::Value;

/// Attribute map with deterministic (sorted) key order.
pub type Attributes = BTreeMap<String, AttrValue>;

/// Log severity with OpenTelemetry severity numbers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(u8)]
pub enum Severity {
    /// `TRACE` (1).
    Trace = 1,
    /// `DEBUG` (5).
    Debug = 5,
    /// `INFO` (9), the default.
    #[default]
    Info = 9,
    /// `WARN` (13).
    Warn = 13,
    /// `ERROR` (17).
    Error = 17,
    /// `FATAL` (21).
    Fatal = 21,
}

impl Severity {
    /// All severities, lowest first.
    pub const ALL: [Severity; 6] = [
        Severity::Trace,
        Severity::Debug,
        Severity::Info,
        Severity::Warn,
        Severity::Error,
        Severity::Fatal,
    ];

    /// OpenTelemetry severity number (1, 5, 9, 13, 17, 21).
    pub fn number(self) -> u8 {
        self as u8
    }

    /// Canonical text: `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`.
    pub fn text(self) -> &'static str {
        match self {
            Severity::Trace => "TRACE",
            Severity::Debug => "DEBUG",
            Severity::Info => "INFO",
            Severity::Warn => "WARN",
            Severity::Error => "ERROR",
            Severity::Fatal => "FATAL",
        }
    }

    /// Maps any OpenTelemetry severity number (1โ€“24) to its range; `0` (unspecified) โ†’ `Info`.
    pub fn from_number(n: u8) -> Severity {
        match n {
            1..=4 => Severity::Trace,
            5..=8 => Severity::Debug,
            13..=16 => Severity::Warn,
            17..=20 => Severity::Error,
            21..=u8::MAX => Severity::Fatal,
            _ => Severity::Info,
        }
    }
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.text())
    }
}

impl FromStr for Severity {
    type Err = Error;

    /// Parses `trace|debug|info|warn|warning|error|fatal|critical` (case-insensitive) or a
    /// severity number.
    fn from_str(s: &str) -> Result<Self> {
        let t = s.trim();
        if let Ok(n) = t.parse::<u8>() {
            return Ok(Severity::from_number(n));
        }
        match t.to_ascii_lowercase().as_str() {
            "trace" => Ok(Severity::Trace),
            "debug" => Ok(Severity::Debug),
            "info" | "information" | "notice" => Ok(Severity::Info),
            "warn" | "warning" => Ok(Severity::Warn),
            "error" | "err" => Ok(Severity::Error),
            "fatal" | "critical" | "crit" | "panic" | "emergency" | "alert" => Ok(Severity::Fatal),
            _ => Err(Error::validation(format!("unknown log severity {t:?}"))),
        }
    }
}

/// One log record (SPEC ยง4 `LogRecord`).
#[derive(Debug, Clone, PartialEq)]
pub struct LogRecord {
    /// When the event happened.
    pub timestamp: SystemTime,
    /// When the SDK observed the event.
    pub observed_timestamp: Option<SystemTime>,
    /// Severity.
    pub severity: Severity,
    /// Severity text (`TRACE`..`FATAL` or the vendor's word).
    pub severity_text: String,
    /// Message; structured bodies are JSON-encoded strings.
    pub body: String,
    /// Record attributes.
    pub attributes: Attributes,
    /// Resource attributes (`service.name`, `service.version`, `deployment.environment`, `host.name`).
    pub resource: Attributes,
    /// Trace id, 32 lower-case hex characters.
    pub trace_id: Option<String>,
    /// Span id, 16 lower-case hex characters.
    pub span_id: Option<String>,
    /// W3C trace flags.
    pub trace_flags: Option<u8>,
}

impl LogRecord {
    /// A record with `timestamp = now`, the given severity and body, and no attributes.
    pub fn new(severity: Severity, body: impl Into<String>) -> Self {
        LogRecord {
            timestamp: SystemTime::now(),
            observed_timestamp: None,
            severity,
            severity_text: severity.text().to_string(),
            body: body.into(),
            attributes: Attributes::new(),
            resource: Attributes::new(),
            trace_id: None,
            span_id: None,
            trace_flags: None,
        }
    }

    /// Adds one attribute.
    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<AttrValue>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Sets the trace and span ids.
    pub fn with_trace(mut self, trace_id: impl Into<String>, span_id: impl Into<String>) -> Self {
        self.trace_id = Some(trace_id.into());
        self.span_id = Some(span_id.into());
        self
    }

    /// Normalized JSON value (camelCase, RFC 3339 UTC timestamps).
    pub fn to_json_value(&self) -> serde_json::Value {
        // Serialising plain data into a Value cannot fail.
        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
    }

    /// Normalized JSON text.
    pub fn to_json(&self) -> String {
        self.to_json_value().to_string()
    }

    /// Parses the normalized JSON form. Non-string bodies are JSON-encoded.
    pub fn from_json(text: &str) -> Result<Self> {
        serde_json::from_str(text)
            .map_err(|e| Error::validation(format!("invalid log record JSON: {e}")))
    }

    /// Size of the normalized JSON form in bytes (used for `maxBatchBytes`).
    pub fn json_size(&self) -> usize {
        serde_json::to_vec(self).map(|v| v.len()).unwrap_or(0)
    }

    /// Returns `true` when `needle` occurs in the body or any string attribute value.
    pub fn contains_text(&self, needle: &str) -> bool {
        fn walk(v: &AttrValue, needle: &str) -> bool {
            match v {
                AttrValue::String(s) => s.contains(needle),
                AttrValue::Array(a) => a.iter().any(|x| walk(x, needle)),
                AttrValue::Object(m) => m.values().any(|x| walk(x, needle)),
                _ => false,
            }
        }
        self.body.contains(needle) || self.attributes.values().any(|v| walk(v, needle))
    }
}

/// Input for [`LogClient::send`](super::LogClient::send) โ€” the client fills in defaults.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LogInput {
    /// Message (record body).
    pub message: String,
    /// Severity, default [`Severity::Info`].
    pub severity: Option<Severity>,
    /// Attributes.
    pub attributes: Attributes,
    /// Timestamp, default now.
    pub timestamp: Option<SystemTime>,
    /// Trace id; when missing the active OpenTelemetry span is used.
    pub trace_id: Option<String>,
    /// Span id.
    pub span_id: Option<String>,
}

impl LogInput {
    /// Input with a message and default severity.
    pub fn new(message: impl Into<String>) -> Self {
        LogInput {
            message: message.into(),
            ..Default::default()
        }
    }

    /// Sets the severity.
    pub fn severity(mut self, severity: Severity) -> Self {
        self.severity = Some(severity);
        self
    }

    /// Adds one attribute.
    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<AttrValue>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Replaces the attributes.
    pub fn attributes(mut self, attributes: Attributes) -> Self {
        self.attributes = attributes;
        self
    }

    /// Sets the timestamp.
    pub fn timestamp(mut self, timestamp: SystemTime) -> Self {
        self.timestamp = Some(timestamp);
        self
    }

    /// Sets trace and span ids.
    pub fn trace(mut self, trace_id: impl Into<String>, span_id: impl Into<String>) -> Self {
        self.trace_id = Some(trace_id.into());
        self.span_id = Some(span_id.into());
        self
    }
}

impl From<&str> for LogInput {
    fn from(message: &str) -> Self {
        LogInput::new(message)
    }
}

impl From<String> for LogInput {
    fn from(message: String) -> Self {
        LogInput::new(message)
    }
}

/// Formats a timestamp as RFC 3339 UTC with nanoseconds (`โ€ฆZ`).
pub fn format_timestamp(t: SystemTime) -> String {
    // Times before the epoch cannot be represented in the wire form; clamp them.
    let t = if t < UNIX_EPOCH { UNIX_EPOCH } else { t };
    humantime::format_rfc3339_nanos(t).to_string()
}

/// Parses an RFC 3339 timestamp (`Z` or numeric offset) or integer nanoseconds since the epoch.
pub fn parse_timestamp(s: &str) -> Result<SystemTime> {
    let s = s.trim();
    if let Ok(ns) = s.parse::<u64>() {
        return Ok(UNIX_EPOCH + Duration::from_nanos(ns));
    }
    let bad = || Error::validation(format!("invalid timestamp {s:?}"));
    // Split a numeric offset (+hh:mm / -hh:mm) after the time part.
    let (base, offset_secs) = match s.char_indices().rev().find(|(_, c)| *c == '+' || *c == '-') {
        Some((i, sign)) if i > 10 && s[i..].len() == 6 && &s[i + 3..i + 4] == ":" => {
            let h: i64 = s[i + 1..i + 3].parse().map_err(|_| bad())?;
            let m: i64 = s[i + 4..].parse().map_err(|_| bad())?;
            let secs = h * 3600 + m * 60;
            (
                format!("{}Z", &s[..i]),
                if sign == '+' { secs } else { -secs },
            )
        }
        _ => (s.to_string(), 0),
    };
    let t = humantime::parse_rfc3339_weak(base.trim_end_matches('Z')).map_err(|_| bad())?;
    let shifted = if offset_secs >= 0 {
        t.checked_sub(Duration::from_secs(offset_secs as u64))
    } else {
        t.checked_add(Duration::from_secs(offset_secs.unsigned_abs()))
    };
    shifted.ok_or_else(bad)
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WireRecord {
    timestamp: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    observed_timestamp: Option<String>,
    severity: u8,
    severity_text: String,
    body: serde_json::Value,
    #[serde(default)]
    attributes: Attributes,
    #[serde(default)]
    resource: Attributes,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    trace_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    span_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    trace_flags: Option<u8>,
}

impl Serialize for LogRecord {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        WireRecord {
            timestamp: format_timestamp(self.timestamp),
            observed_timestamp: self.observed_timestamp.map(format_timestamp),
            severity: self.severity.number(),
            severity_text: self.severity_text.clone(),
            body: serde_json::Value::String(self.body.clone()),
            attributes: self.attributes.clone(),
            resource: self.resource.clone(),
            trace_id: self.trace_id.clone(),
            span_id: self.span_id.clone(),
            trace_flags: self.trace_flags,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for LogRecord {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
        let w = WireRecord::deserialize(deserializer)?;
        let timestamp = parse_timestamp(&w.timestamp).map_err(serde::de::Error::custom)?;
        let observed_timestamp = match &w.observed_timestamp {
            Some(t) => Some(parse_timestamp(t).map_err(serde::de::Error::custom)?),
            None => None,
        };
        let body = match w.body {
            serde_json::Value::String(s) => s,
            other => other.to_string(),
        };
        Ok(LogRecord {
            timestamp,
            observed_timestamp,
            severity: Severity::from_number(w.severity),
            severity_text: w.severity_text,
            body,
            attributes: w.attributes,
            resource: w.resource,
            trace_id: w.trace_id,
            span_id: w.span_id,
            trace_flags: w.trace_flags,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn timestamp_offsets_and_nanos() {
        let z = parse_timestamp("2026-01-02T03:04:05.5Z").unwrap();
        assert_eq!(parse_timestamp("2026-01-02T05:04:05.5+02:00").unwrap(), z);
        assert_eq!(parse_timestamp("2026-01-02T01:04:05.5-02:00").unwrap(), z);
        assert_eq!(
            parse_timestamp("1000000000").unwrap(),
            UNIX_EPOCH + Duration::from_secs(1)
        );
        assert!(parse_timestamp("yesterday").is_err());
        assert!(parse_timestamp("2026-01-02T05:04:05+xx:00").is_err());
        assert!(parse_timestamp("2026-01-02T05:04:05+02:yy").is_err());
        assert_eq!(
            format_timestamp(UNIX_EPOCH - Duration::from_secs(5)),
            "1970-01-01T00:00:00.000000000Z"
        );
    }
}