krab_core 0.6.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
Documentation
//! Structured-logging setup: JSON `tracing` output and the canonical
//! `service_started` event.
//!
//! Call [`init_tracing_with_version`] once at startup. The per-request types
//! further down (`RequestTelemetry`, `RedMetrics`, `EndpointMetrics`) are
//! deprecated and unused; request metrics live on the HTTP runtime state.

use tracing_subscriber::EnvFilter;

/// Standard fields emitted on every service startup log event.
/// Keeps the shape consistent across all services so log aggregators
/// and dashboards can rely on stable field names.
#[derive(Debug, Clone)]
pub struct TelemetryConfig {
    /// Service name: `KRAB_SERVICE_NAME`, else the name the caller passes.
    pub service: String,
    /// The service's version, as passed by the caller.
    pub version: String,
    /// `KRAB_ENVIRONMENT`, verbatim (default `dev`).
    pub environment: String,
    /// Stable per-process identifier (hostname + PID by default).
    pub instance_id: String,
}

impl TelemetryConfig {
    /// Build from environment, using `service_name` and the crate version
    /// of the *calling* binary (passed as `version`).
    pub fn from_env(service_name: &str, version: &str) -> Self {
        let environment = std::env::var("KRAB_ENVIRONMENT").unwrap_or_else(|_| "dev".to_string());
        let hostname = std::env::var("HOSTNAME")
            .or_else(|_| std::env::var("COMPUTERNAME"))
            .unwrap_or_else(|_| "unknown".to_string());
        let pid = std::process::id();
        Self {
            service: std::env::var("KRAB_SERVICE_NAME")
                .unwrap_or_else(|_| service_name.to_string()),
            version: version.to_string(),
            environment,
            instance_id: format!("{}.{}", hostname, pid),
        }
    }
}

/// Initialise JSON structured tracing and emit a canonical `service_started`
/// event with the standardised field set.
///
/// All services **must** call this (or [`init_tracing_with_version`]) before
/// emitting any other log events so that the `service`, `version`,
/// `environment`, and `instance_id` fields appear in every structured log line.
///
/// **Reports the wrong version.** `version` here is `krab_core`'s own crate
/// version: `env!("CARGO_PKG_VERSION")` is expanded inside this crate, not the
/// caller's, so every service logged the framework's version as its own.
#[deprecated(
    since = "0.6.0",
    note = "logs krab_core's version as the service version; call \
            `init_tracing_with_version(name, env!(\"CARGO_PKG_VERSION\"))` so the \
            version is expanded in your crate"
)]
pub fn init_tracing(service_name: &str) {
    init_tracing_with_version(service_name, env!("CARGO_PKG_VERSION"));
}

/// Initialise JSON structured tracing for a service at `version`.
///
/// Pass `env!("CARGO_PKG_VERSION")` from the service's own crate — the macro
/// must expand there to name the service's version rather than the
/// framework's. The framework version is logged separately as `krab.version`.
pub fn init_tracing_with_version(service_name: &str, version: &str) {
    let cfg = TelemetryConfig::from_env(service_name, version);
    init_tracing_with_config(&cfg);
}

/// Variant for callers that have already resolved [`TelemetryConfig`].
pub fn init_tracing_with_config(cfg: &TelemetryConfig) {
    let filter = std::env::var("RUST_LOG")
        .ok()
        .and_then(|s| EnvFilter::try_new(s).ok())
        .unwrap_or_else(|| EnvFilter::new("info"));

    // `try_init`, not `init`: a second initialisation (embedding scenario,
    // test harness, a service that also sets its own subscriber) must not
    // panic the startup path — the first subscriber simply stays in place.
    if let Err(error) = tracing_subscriber::fmt()
        .json()
        .flatten_event(true)
        .with_env_filter(filter)
        .with_current_span(false)
        .with_target(true)
        .try_init()
    {
        tracing::warn!(error = %error, "tracing_subscriber_already_initialised");
    }

    tracing::info!(
        service = %cfg.service,
        version = %cfg.version,
        environment = %cfg.environment,
        instance_id = %cfg.instance_id,
        krab.version = env!("CARGO_PKG_VERSION"),
        "service_started"
    );
}

// ---------------------------------------------------------------------------
// Unified telemetry model
// ---------------------------------------------------------------------------

/// Standard per-request telemetry fields propagated through the system.
///
/// Every log line, span, and metric emitted for a given request should include
/// these fields so that log aggregation, distributed tracing, and RED dashboards
/// share a single correlation model.
#[derive(Debug, Clone)]
#[deprecated(
    since = "0.6.0",
    note = "nothing in Krab populates or reads this per-request telemetry struct; request ids and route labels are attached by the HTTP layers, and metrics live on RuntimeState and /metrics/prometheus. Removed in 0.7.0"
)]
pub struct RequestTelemetry {
    /// W3C `traceparent` trace-id (128-bit hex).
    pub trace_id: String,
    /// Per-request unique id generated by the gateway / first-hop service.
    pub request_id: String,
    /// Logical service name (e.g. `service_users`).
    pub service: String,
    /// HTTP route pattern that matched (e.g. `/api/v1/users/:id`).
    pub route: String,
    /// Tenant identifier (optional, for multi-tenant deployments).
    pub tenant: Option<String>,
    /// Redacted user identifier. The redaction policy is:
    /// - `None` if no authenticated user.
    /// - Short prefix hash in non-dev environments.
    pub user_id: Option<String>,
}

#[allow(deprecated)]
impl RequestTelemetry {
    /// Create a new telemetry context for a request.
    pub fn new(
        trace_id: impl Into<String>,
        request_id: impl Into<String>,
        service: impl Into<String>,
        route: impl Into<String>,
    ) -> Self {
        Self {
            trace_id: trace_id.into(),
            request_id: request_id.into(),
            service: service.into(),
            route: route.into(),
            tenant: None,
            user_id: None,
        }
    }
}

/// RED (Rate, Errors, Duration) metrics snapshot for a single endpoint.
///
/// These are the three golden signals for request-driven services:
/// - **Rate**: requests per second.
/// - **Errors**: failed request count.
/// - **Duration**: latency distribution.
#[derive(Debug, Clone, Default)]
#[deprecated(
    since = "0.6.0",
    note = "nothing in Krab populates or reads this RED metrics snapshot; request ids and route labels are attached by the HTTP layers, and metrics live on RuntimeState and /metrics/prometheus. Removed in 0.7.0"
)]
pub struct RedMetrics {
    /// Total request count observed.
    pub total_requests: u64,
    /// Total error count (HTTP 5xx or application-level errors).
    pub total_errors: u64,
    /// Sum of request durations in milliseconds (for computing mean).
    pub duration_sum_ms: u64,
    /// Maximum observed latency in milliseconds.
    pub duration_max_ms: u64,
}

/// Associates a route pattern with its RED metrics for per-endpoint tracking.
#[derive(Debug, Clone)]
#[deprecated(
    since = "0.6.0",
    note = "nothing in Krab populates or reads this per-endpoint RED tracker; request ids and route labels are attached by the HTTP layers, and metrics live on RuntimeState and /metrics/prometheus. Removed in 0.7.0"
)]
#[allow(deprecated)]
pub struct EndpointMetrics {
    /// Route pattern (e.g. `GET /api/v1/users/:id`).
    pub route_pattern: String,
    /// The endpoint's accumulated counters.
    pub red: RedMetrics,
}

#[allow(deprecated)]
impl EndpointMetrics {
    /// A tracker for `route_pattern` with zeroed counters.
    pub fn new(route_pattern: impl Into<String>) -> Self {
        Self {
            route_pattern: route_pattern.into(),
            red: RedMetrics::default(),
        }
    }

    /// Record a completed request.
    pub fn record(&mut self, duration_ms: u64, is_error: bool) {
        self.red.total_requests += 1;
        self.red.duration_sum_ms += duration_ms;
        if duration_ms > self.red.duration_max_ms {
            self.red.duration_max_ms = duration_ms;
        }
        if is_error {
            self.red.total_errors += 1;
        }
    }
}

#[cfg(test)]
#[allow(deprecated)]
mod tests {
    use super::*;
    use serial_test::serial;

    // Serialized: mutates process-global env vars (`KRAB_ENVIRONMENT`) that
    // the auth/config test suites also read under their own `#[serial]` lock.
    // Running this concurrently with them produced rare flakes.
    #[test]
    #[serial]
    fn telemetry_config_from_env_uses_overrides() {
        std::env::set_var("KRAB_SERVICE_NAME", "service_override");
        std::env::set_var("KRAB_ENVIRONMENT", "staging");

        let cfg = TelemetryConfig::from_env("service_default", "1.2.3");
        assert_eq!(cfg.service, "service_override");
        assert_eq!(cfg.environment, "staging");
        assert_eq!(cfg.version, "1.2.3");
        assert!(!cfg.instance_id.is_empty());

        std::env::remove_var("KRAB_SERVICE_NAME");
        std::env::remove_var("KRAB_ENVIRONMENT");
    }

    #[test]
    fn request_telemetry_new_sets_expected_defaults() {
        let telemetry = RequestTelemetry::new("trace-1", "req-1", "svc", "/health");
        assert_eq!(telemetry.trace_id, "trace-1");
        assert_eq!(telemetry.request_id, "req-1");
        assert_eq!(telemetry.service, "svc");
        assert_eq!(telemetry.route, "/health");
        assert!(telemetry.tenant.is_none());
        assert!(telemetry.user_id.is_none());
    }

    #[test]
    fn endpoint_metrics_record_updates_red_counters() {
        let mut endpoint = EndpointMetrics::new("GET /api/v1/ping");
        endpoint.record(10, false);
        endpoint.record(30, true);

        assert_eq!(endpoint.red.total_requests, 2);
        assert_eq!(endpoint.red.total_errors, 1);
        assert_eq!(endpoint.red.duration_sum_ms, 40);
        assert_eq!(endpoint.red.duration_max_ms, 30);
    }
}