waddling-errors 0.7.3

Structured, secure-by-default diagnostic codes for distributed systems with no_std and role-based documentation
Documentation
//! Cache Component
//!
//! Redis caching layer - cache operations, TTL management, invalidation strategies.

use crate::primaries::Primary;
use waddling_errors::ComponentIdDocumented;
use waddling_errors::prelude::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Cache;

impl ComponentId for Cache {
    fn as_str(&self) -> &'static str {
        "Cache"
    }
}

impl ComponentIdDocumented for Cache {
    fn description(&self) -> Option<&'static str> {
        Some(
            "Redis caching layer. Handles cache operations, TTL management, and cache \
              invalidation strategies.",
        )
    }

    fn examples(&self) -> &'static [&'static str] {
        &[
            "E.Cache.Connection.027: Redis server unavailable",
            "W.Cache.Data.018: Cache entry stale, refreshing from DB",
            "I.Cache.Data.999: Cache warmed successfully",
        ]
    }

    fn tags(&self) -> &'static [&'static str] {
        &["performance", "redis", "memory"]
    }
}

// ============================================================================
// Error Code Definitions
// ============================================================================

/// Redis cache server unavailable (.027 = UNAVAILABLE)
pub const ERR_CONNECTION_UNAVAILABLE: Code<Cache, Primary> =
    Code::error(Cache, Primary::Connection, 27);

/// Cache entry stale - refreshing from database (.018 = STALE)
pub const WARN_DATA_STALE: Code<Cache, Primary> = Code::warning(Cache, Primary::Data, 18);

/// Cache miss - fetching from primary source (.001 = MISSING)
pub const INFO_DATA_MISS: Code<Cache, Primary> = Code::info(Cache, Primary::Data, 1);

/// Cache successfully warmed with fresh data (.999 = COMPLETE)
pub const SUCCESS_WARMED: Code<Cache, Primary> = Code::success(Cache, Primary::Data, 999);

// ============================================================================
// Component Registration
// ============================================================================

#[cfg(feature = "doc-gen")]
pub fn register_component(generator: &mut waddling_errors::doc_generator::DocRegistry) {
    use waddling_errors::Role;

    generator.register_component(
        "Cache",
        Some("Redis caching layer. Handles cache operations, TTL management, and cache invalidation strategies. Supports distributed caching, cache warming, and automatic fallback to primary data sources."),
        &[
            "Key-value caching with TTL",
            "Cache-aside pattern implementation",
            "Cache warming on startup",
            "Distributed cache invalidation",
            "Cache hit/miss ratio tracking",
            "Automatic fallback on miss",
        ],
        &["Cache", "redis", "performance", "memory", "distributed", "ttl"]);

    // Register component locations with role-based visibility

    // PUBLIC: Examples safe for external users
    generator.register_component_location_with_role(
        "Cache",
        "examples/complete_system/components/cache.rs",
        Some(Role::Public),
    );
    generator.register_component_location_with_role(
        "Cache",
        "examples/cache_usage.rs",
        Some(Role::Public),
    );

    // DEVELOPER: Performance monitoring and debugging
    generator.register_component_location_with_role(
        "Cache",
        "src/cache/debug_stats.rs",
        Some(Role::Developer),
    );
    generator.register_component_location_with_role(
        "Cache",
        "src/cache/cache_profiler.rs",
        Some(Role::Developer),
    );

    // INTERNAL: Production implementation
    generator.register_component_location_with_role(
        "Cache",
        "src/cache/redis_client.rs",
        Some(Role::Internal),
    );
    generator.register_component_location_with_role(
        "Cache",
        "src/cache/cache_manager.rs",
        Some(Role::Internal),
    );
    generator.register_component_location_with_role(
        "Cache",
        "src/cache/connection_pool.rs",
        Some(Role::Internal),
    );
}

#[cfg(feature = "doc-gen")]
pub fn register_errors(generator: &mut waddling_errors::doc_generator::DocRegistry) {
    use waddling_errors::Role;

    let errors = vec![
        (
            "E.Cache.Connection.027",
            "Redis cache server unavailable",
            &[
                "Check Redis status",
                "Verify connection string",
                "Enable fallback",
            ][..],
            &["Cache", "redis", "connectivity"][..],
            Role::Internal,
        ),
        (
            "W.Cache.Data.018",
            "Cache entry stale - refreshing from database",
            &["Normal operation", "Adjust TTL if frequent"],
            &["Cache", "performance"],
            Role::Internal,
        ),
        (
            "I.Cache.Data.001",
            "Cache miss - fetching from primary source",
            &["Normal operation", "Consider cache warming"],
            &["Cache", "performance"],
            Role::Internal,
        ),
        (
            "S.Cache.Data.999",
            "Cache successfully warmed with fresh data",
            &["Cache optimization complete"],
            &["Cache", "success"],
            Role::Internal,
        ),
    ];

    for (code, desc, hints, tags, role) in &errors {
        let _ = generator.register(*code, *desc, hints, tags);

        let snippet = match role {
            Role::Internal => format!(
                "// Internal debugging\nlog::error!(\"[{}] {}\");",
                code, desc
            ),
            Role::Developer => format!(
                "// Developer API usage\nif let Err(e) = operation() {{\n    eprintln!(\"Error: {}\");\n}}",
                code
            ),
            Role::Public => format!(
                "// Public error handling\nmatch result {{\n    Err(_) => println!(\"Operation failed: {}\"),\n    Ok(_) => println!(\"Success\"),\n}}",
                desc
            ),
        };

        generator.add_snippet_for_role(
            format!("{:?} - Usage Example", role),
            "rust",
            snippet,
            *role,
        );
    }
}

// ============================================================================
// Demo Functions
// ============================================================================

pub fn demo() {
    println!("⚡ CACHE Component Errors:\n");
    println!(
        "  {} - Connection unavailable",
        ERR_CONNECTION_UNAVAILABLE.code()
    );
    println!("  {} - Data stale", WARN_DATA_STALE.code());
    println!("  {} - Cache miss", INFO_DATA_MISS.code());
    println!("  {} - Cache warmed", SUCCESS_WARMED.code());
}