aimdb-core 3.0.0

Type-safe async data pipelines — one Rust codebase from MCU to cloud
Documentation
//! Internal operational events. Payloads are borrowed only for synchronous reporting.
//! Logging policy lives here; metrics and public observation remain separate decisions.

use super::{AuthError, CodecError, FrameFault, TransportError};

/// `tracing`/`log` targets: the module that raises each event, as before
/// logging moved here, so per-module target filters keep matching.
/// `tests/log_targets.rs` in aimdb-core checks each names a real module.
#[allow(dead_code)] // some arms are feature-gated
mod target {
    pub(super) const CLIENT: &str = "aimdb_core::session::client";
    pub(super) const DISPATCH: &str = "aimdb_core::session::aimx::dispatch";
    pub(super) const IO: &str = "aimdb_core::session::io";
    pub(super) const SERVER: &str = "aimdb_core::session::server";
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub(crate) enum SessionEvent<'a> {
    AuthenticationRejected {
        error: &'a AuthError,
    },
    HandshakeReset {
        ended_subscriptions: usize,
    },
    SubscribeRefused {
        id: &'a str,
    },
    SubscriptionEnded {
        id: &'a str,
    },
    SnapshotEncodeFailed {
        id: &'a str,
        topic: &'a str,
        error: &'a CodecError,
    },
    AcceptFailed {
        error: TransportError,
    },
    AcceptStillFailing {
        attempts: u64,
        error: TransportError,
    },
    AcceptRecovered {
        after: u64,
    },
    ConnectionLimitReached {
        limit: usize,
    },
    ListenerClosed {
        open_connections: usize,
    },
    DialFailed {
        error: &'a TransportError,
    },
    ReconnectExhausted {
        attempts: usize,
    },
    MirrorGap {
        topic: &'a str,
        skipped: u64,
    },
    ReceiveFramingFailed,
    SendFrameRejected {
        bytes: usize,
        fault: FrameFault,
    },
    #[cfg(feature = "remote")]
    WildcardSubscribeFailed {
        pattern: &'a str,
        record: &'a str,
        error: &'a crate::DbError,
    },
    #[cfg(feature = "remote")]
    HandshakeVersionRejected {
        client_version: &'a str,
        server_version: &'a str,
    },
}

pub(crate) fn report(event: SessionEvent<'_>) {
    #[cfg(all(test, feature = "std"))]
    capture::record(&event);
    match event {
        SessionEvent::AuthenticationRejected { error } => {
            log_warn!(target: target::SERVER, "session authenticate rejected: {:?}", error)
        }
        SessionEvent::HandshakeReset {
            ended_subscriptions,
        } => log_info!(
            target: target::SERVER,
            "new handshake on a live connection: ending {} subscription(s) of the previous client",
            ended_subscriptions
        ),
        SessionEvent::SubscribeRefused { id } => {
            log_warn!(target: target::SERVER, "subscribe refused: id {} is still live", id)
        }
        SessionEvent::SubscriptionEnded { id } => {
            log_warn!(target: target::SERVER, "subscription {} ended: its source closed", id)
        }
        SessionEvent::SnapshotEncodeFailed { id, topic, error } => {
            log_warn!(
                target: target::SERVER,
                "snapshot encode failed, skipping: sub={} topic={} err={:?}",
                id,
                topic,
                error
            )
        }
        SessionEvent::AcceptFailed { error } => log_error!(
            target: target::SERVER,
            "accept failed: {:?}; retrying, further failures are summarized",
            error
        ),
        SessionEvent::AcceptStillFailing { attempts, error } => log_warn!(
            target: target::SERVER,
            "accept still failing: {} attempts in a row, last: {:?}",
            attempts,
            error
        ),
        SessionEvent::AcceptRecovered { after } => {
            log_info!(target: target::SERVER, "accept recovered after {} failed attempt(s)", after)
        }
        SessionEvent::ConnectionLimitReached { limit } => {
            log_warn!(target: target::SERVER, "max_connections={} reached, refusing client", limit)
        }
        SessionEvent::ListenerClosed { open_connections } => log_info!(
            target: target::SERVER,
            "listener closed; serving {} open connection(s) to their end",
            open_connections
        ),
        SessionEvent::DialFailed { error } => {
            log_warn!(target: target::CLIENT, "client dial failed: {:?}", error)
        }
        SessionEvent::ReconnectExhausted { attempts } => {
            log_warn!(
                target: target::CLIENT,
                "client giving up after {} reconnect attempts",
                attempts
            )
        }
        SessionEvent::MirrorGap { topic, skipped } => log_warn!(
            target: target::CLIENT,
            "mirror gap on '{}': {} update(s) lost (latest-state, no resync)",
            topic,
            skipped
        ),
        SessionEvent::ReceiveFramingFailed => {
            log_warn!(
                target: target::IO,
                "framed recv: unrecoverable framing error, closing connection"
            )
        }
        SessionEvent::SendFrameRejected { bytes, fault } => log_warn!(
            target: target::IO,
            "framed send: framer rejected a {}-byte frame ({:?}), closing connection",
            bytes,
            fault
        ),
        #[cfg(feature = "remote")]
        SessionEvent::WildcardSubscribeFailed {
            pattern,
            record,
            error,
        } => log_warn!(
            target: target::DISPATCH,
            "wildcard subscribe '{}': skipping '{}': {:?}",
            pattern,
            record,
            error
        ),
        #[cfg(feature = "remote")]
        SessionEvent::HandshakeVersionRejected {
            client_version,
            server_version,
        } => log_warn!(
            target: target::DISPATCH,
            "refusing handshake: client protocol version {:?} incompatible with server {}",
            client_version,
            server_version
        ),
    }
}

// Poll-scoped capture: no thread-local state survives an await. Wrap spawned
// futures individually; unrelated tasks and parallel tests do not inherit it.
#[cfg(all(test, feature = "std"))]
crate::__event_capture!(super::SessionEvent<'_>);

#[cfg(all(test, feature = "std"))]
mod tests;