wireframe 0.4.0-alpha1

Simplify building servers and clients for custom binary protocols.
Documentation
//! Metric helpers for `wireframe`.
//!
//! This module defines metric names and helper functions wrapping the
//! [`metrics`](https://docs.rs/metrics) crate. All functions become no-ops
//! if the optional `metrics` Cargo feature is disabled.
//!
//! # Prometheus Integration
//!
//! ```
//! use metrics_exporter_prometheus::PrometheusBuilder;
//!
//! let handle = PrometheusBuilder::new()
//!     .install_recorder()
//!     .expect("recorder install");
//! println!("{}", handle.render());
//! ```

use std::time::Duration;

#[cfg(feature = "metrics")]
use metrics::{counter, gauge, histogram};

mod app_response_sends;

mod client_pool;
#[cfg(all(feature = "pool", not(loom)))]
pub(crate) use client_pool::{
    PoolAcquisitionMode,
    PoolAcquisitionOutcome,
    PoolPermitRaceGuard,
    inc_pool_acquisition,
};
mod decode_rejections;

mod pool_scheduler;

mod preamble_rejections;

mod push_writes;

mod response_delivery;

#[cfg(not(loom))]
mod server_cancellation;
#[cfg(not(loom))]
pub(crate) use server_cancellation::ServerCancellationReason;

mod server_startup;

mod server_supervisor;

mod streaming_bodies;

pub use app_response_sends::APP_RESPONSE_SENDS;
pub(crate) use app_response_sends::{AppResponseSendOutcome, inc_app_response_send};
pub use client_pool::{
    POOL_ACQUISITIONS,
    POOL_CONNECTION_DISCARDS,
    POOL_PERMIT_RACE_DURATION,
    POOL_PERMIT_RACES,
    POOL_PERMIT_RACES_STARTED,
};
#[cfg(all(feature = "pool", not(loom)))]
pub(crate) use client_pool::{
    inc_pool_incomplete_operation_discard,
    inc_pool_pending_response_discard,
};
pub use decode_rejections::DECODE_REJECTIONS;
pub(crate) use decode_rejections::{
    DecodeRejectionPath,
    DecodeRejectionReason,
    inc_decode_rejection,
};
pub use pool_scheduler::POOL_SCHEDULER_FAILURES;
#[cfg(all(feature = "pool", not(loom)))]
pub(crate) use pool_scheduler::inc_pool_scheduler_failure;
pub use preamble_rejections::PREAMBLE_REJECTIONS;
pub(crate) use preamble_rejections::{PreambleRejectionReason, inc_preamble_rejection};
pub use push_writes::{PUSH_DROPS, PUSH_RATE_LIMITED, PUSH_WRITES_ABANDONED};
pub(crate) use push_writes::{PushDropOutcome, PushWriteAbandonReason, inc_push_rate_limited};
pub use response_delivery::RESPONSE_CANCELLATIONS;
pub(crate) use response_delivery::ResponseCancellationReason;
pub use server_startup::{SERVER_STARTUP_DURATION, SERVER_STARTUP_FAILURES};
#[cfg(not(loom))]
pub(crate) use server_startup::{
    ServerStartupFailureStage,
    ServerStartupOutcome,
    inc_server_startup_failure,
    record_server_startup_duration,
};
pub use server_supervisor::SERVER_SUPERVISOR_ABNORMAL_TERMINATIONS;
#[cfg(not(loom))]
pub(crate) use server_supervisor::inc_server_supervisor_abnormal_termination;
pub use streaming_bodies::{
    STREAMING_BODIES_PARKED,
    STREAMING_BODY_BYTES_QUEUED,
    STREAMING_BODY_OUTCOMES,
};
pub(crate) use streaming_bodies::{
    StreamingBodyOutcome,
    add_parked_body,
    add_queued_body_bytes,
    release_parked_bodies,
    release_queued_body_bytes,
};

/// Name of the gauge tracking active connections.
pub const CONNECTIONS_ACTIVE: &str = "wireframe_connections_active";

/// Name of the counter tracking processed frames.
pub const FRAMES_PROCESSED: &str = "wireframe_frames_processed_total";

/// Name of the counter tracking error occurrences.
pub const ERRORS_TOTAL: &str = "wireframe_errors_total";

/// Name of the counter tracking connection panics.
///
/// ```plaintext
/// # HELP wireframe_connection_panics_total Count of panicking connection tasks.
/// # TYPE wireframe_connection_panics_total counter
/// wireframe_connection_panics_total 1
/// ```
pub const CONNECTION_PANICS: &str = "wireframe_connection_panics_total";

/// Name of the counter tracking recovered client pool bookkeeping lock poison.
///
/// ```plaintext
/// # HELP wireframe_pool_bookkeeping_poison_recoveries_total Count of recovered client pool bookkeeping locks.
/// # TYPE wireframe_pool_bookkeeping_poison_recoveries_total counter
/// wireframe_pool_bookkeeping_poison_recoveries_total 1
/// ```
pub const POOL_BOOKKEEPING_POISON_RECOVERIES: &str =
    "wireframe_pool_bookkeeping_poison_recoveries_total";

/// Name of the counter tracking codec errors by type and recovery policy.
///
/// ```plaintext
/// # HELP wireframe_codec_errors_total Count of codec errors by type and recovery policy.
/// # TYPE wireframe_codec_errors_total counter
/// wireframe_codec_errors_total{error_type="framing",recovery_policy="drop"} 5
/// wireframe_codec_errors_total{error_type="eof",recovery_policy="disconnect"} 2
/// ```
pub const CODEC_ERRORS: &str = "wireframe_codec_errors_total";

/// Name of the counter tracking application preparation outcomes.
///
/// The bounded `outcome` label is either `"success"` or `"failure"`.
pub const APPLICATION_PREPARATIONS: &str = "wireframe_application_preparations_total";

/// Name of the counter tracking connections handled by prepared applications.
pub const PREPARED_CONNECTION_USES: &str = "wireframe_prepared_connection_uses_total";

/// Name of the histogram recording application preparation duration in seconds.
pub const APPLICATION_PREPARATION_DURATION: &str =
    "wireframe_application_preparation_duration_seconds";

/// Name of the counter tracking server-supervisor cancellation requests.
///
/// The `reason` label is always either `"graceful"`, when the supplied
/// shutdown future resolved, or `"dropped"`, when the supervisor future was
/// dropped before graceful shutdown completed. The latter includes task abort.
///
/// ```plaintext
/// # HELP wireframe_server_supervisor_cancellations_total Count of server-supervisor cancellation requests.
/// # TYPE wireframe_server_supervisor_cancellations_total counter
/// wireframe_server_supervisor_cancellations_total{reason="graceful"} 1
/// ```
pub const SERVER_SUPERVISOR_CANCELLATIONS: &str = "wireframe_server_supervisor_cancellations_total";

/// Name of the counter tracking accept loops that observed cancellation.
///
/// The `reason` label has the same bounded vocabulary as
/// [`SERVER_SUPERVISOR_CANCELLATIONS`].
///
/// ```plaintext
/// # HELP wireframe_server_accept_loops_exited_total Count of accept loops that exited after cancellation.
/// # TYPE wireframe_server_accept_loops_exited_total counter
/// wireframe_server_accept_loops_exited_total{reason="dropped"} 2
/// ```
pub const SERVER_ACCEPT_LOOPS_EXITED: &str = "wireframe_server_accept_loops_exited_total";

/// Bounded outcomes for application preparation metrics.
#[derive(Clone, Copy)]
pub(crate) enum PreparationOutcome {
    /// Preparation completed and produced an immutable application template.
    Success,
    /// Preparation failed before exposing an application template.
    Failure,
}

#[cfg(feature = "metrics")]
impl PreparationOutcome {
    /// Return the stable metric label value for this preparation outcome.
    pub(crate) const fn as_str(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::Failure => "failure",
        }
    }
}

/// Direction of frame processing.
#[derive(Clone, Copy)]
pub enum Direction {
    /// Inbound frames received from a client.
    Inbound,
    /// Outbound frames sent to a client.
    Outbound,
}

#[cfg(feature = "metrics")]
impl Direction {
    /// Supplies the bounded metric label value, avoiding call-site strings
    /// that could make inbound and outbound observations incomparable.
    const fn as_str(self) -> &'static str {
        match self {
            Self::Inbound => "inbound",
            Self::Outbound => "outbound",
        }
    }
}

/// Increment the active connections gauge.
#[cfg(feature = "metrics")]
pub fn inc_connections() { gauge!(CONNECTIONS_ACTIVE).increment(1.0); }

/// Increment the active connections gauge.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn inc_connections() {}

/// Decrement the active connections gauge.
#[cfg(feature = "metrics")]
pub fn dec_connections() { gauge!(CONNECTIONS_ACTIVE).decrement(1.0); }

/// Decrement the active connections gauge.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn dec_connections() {}

/// Record a processed frame for the given direction.
#[cfg(feature = "metrics")]
pub fn inc_frames(direction: Direction) {
    counter!(FRAMES_PROCESSED, "direction" => direction.as_str()).increment(1);
}

/// Record a processed frame for the given direction.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn inc_frames(_direction: Direction) {}

/// Record a deserialization error.
#[cfg(feature = "metrics")]
pub fn inc_deser_errors() { counter!(ERRORS_TOTAL, "kind" => "deserialization").increment(1); }

/// Record a deserialization error.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn inc_deser_errors() {}

/// Record a handler error.
#[cfg(feature = "metrics")]
pub fn inc_handler_errors() { counter!(ERRORS_TOTAL, "kind" => "handler").increment(1); }

/// Record a handler error.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn inc_handler_errors() {}

/// Record a panicking connection task.
///
/// # Examples
///
/// ```no_run
/// use std::panic::catch_unwind;
///
/// use wireframe::metrics;
///
/// let res = catch_unwind(|| {
///     panic!("boom");
/// });
/// if res.is_err() {
///     metrics::inc_connection_panics();
/// }
/// ```
#[cfg(feature = "metrics")]
pub fn inc_connection_panics() { counter!(CONNECTION_PANICS).increment(1); }

/// Record a panicking connection task.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn inc_connection_panics() {}

/// Record a recovered client pool bookkeeping lock poison event.
#[cfg(feature = "metrics")]
pub fn inc_pool_bookkeeping_poison_recoveries() {
    counter!(POOL_BOOKKEEPING_POISON_RECOVERIES).increment(1);
}

/// Record a recovered client pool bookkeeping lock poison event.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn inc_pool_bookkeeping_poison_recoveries() {}

/// Record a codec error with its type and recovery policy.
///
/// # Arguments
///
/// * `error_type` - The category of error: `"framing"`, `"protocol"`, `"io"`, or `"eof"`.
/// * `recovery_policy` - The recovery action taken: `"drop"`, `"quarantine"`, or `"disconnect"`.
///
/// The connection runtime calls this helper exactly once for every decoder
/// failure it observes on a live connection. `recovery_policy` is the policy
/// the loop applied, which can differ from the policy a
/// [`RecoveryPolicyHook`](crate::codec::RecoveryPolicyHook) selected after a
/// fallback escalates the failure to a disconnect.
///
/// # Examples
///
/// ```no_run
/// use wireframe::metrics;
///
/// // Record an oversized frame that was dropped
/// metrics::inc_codec_error("framing", "drop");
///
/// // Record a premature EOF that caused disconnect
/// metrics::inc_codec_error("eof", "disconnect");
/// ```
#[cfg(feature = "metrics")]
pub fn inc_codec_error(error_type: &'static str, recovery_policy: &'static str) {
    counter!(
        CODEC_ERRORS,
        "error_type" => error_type,
        "recovery_policy" => recovery_policy
    )
    .increment(1);
}

/// Record a codec error with its type and recovery policy.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub fn inc_codec_error(_error_type: &'static str, _recovery_policy: &'static str) {}

/// Record an application preparation outcome and its elapsed duration.
#[cfg(feature = "metrics")]
pub(crate) fn record_application_preparation(outcome: PreparationOutcome, elapsed: Duration) {
    counter!(APPLICATION_PREPARATIONS, "outcome" => outcome.as_str()).increment(1);
    histogram!(APPLICATION_PREPARATION_DURATION, "outcome" => outcome.as_str())
        .record(elapsed.as_secs_f64());
}

/// Record an application preparation outcome and its elapsed duration.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub(crate) fn record_application_preparation(_outcome: PreparationOutcome, _elapsed: Duration) {}

/// Record a connection handled by an immutable prepared application.
#[cfg(feature = "metrics")]
pub(crate) fn inc_prepared_connection_uses() { counter!(PREPARED_CONNECTION_USES).increment(1); }

/// Record a connection handled by an immutable prepared application.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(not(feature = "metrics"))]
pub(crate) fn inc_prepared_connection_uses() {}

/// Record a server-supervisor cancellation request with a bounded reason.
#[cfg(all(feature = "metrics", not(loom)))]
pub(crate) fn inc_server_supervisor_cancellation(reason: ServerCancellationReason) {
    counter!(SERVER_SUPERVISOR_CANCELLATIONS, "reason" => reason.as_str()).increment(1);
}

/// Record a server-supervisor cancellation request with a bounded reason.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(all(not(feature = "metrics"), not(loom)))]
pub(crate) fn inc_server_supervisor_cancellation(_reason: ServerCancellationReason) {}

/// Record an accept loop that exited after supervisor cancellation.
#[cfg(all(feature = "metrics", not(loom)))]
pub(crate) fn inc_server_accept_loop_exit(reason: ServerCancellationReason) {
    counter!(SERVER_ACCEPT_LOOPS_EXITED, "reason" => reason.as_str()).increment(1);
}

/// Record an accept loop that exited after supervisor cancellation.
///
/// This function is a no-op when the `metrics` feature is disabled.
#[cfg(all(not(feature = "metrics"), not(loom)))]
pub(crate) fn inc_server_accept_loop_exit(_reason: ServerCancellationReason) {}