stream-tungstenite 0.6.1

A streaming implementation of the Tungstenite WebSocket protocol
Documentation
//! Extension trait for extending WebSocket client functionality.

use async_trait::async_trait;
use tungstenite::Message;

use crate::context::ConnectionContext;
use crate::error::ExtensionError;

/// Unified extension trait with default lifecycle and message handlers.
///
/// Implementers can override the helper methods to declare whether they
/// participate in lifecycle events and/or message processing.
#[async_trait]
pub trait Extension: Send + Sync {
    /// Extension name for identification
    fn name(&self) -> &'static str;

    /// Extension version
    fn version(&self) -> &'static str {
        "1.0.0"
    }

    /// Extension description
    fn description(&self) -> &'static str {
        ""
    }

    /// Whether this extension handles lifecycle events
    fn handles_lifecycle(&self) -> bool {
        true
    }

    /// Whether this extension handles messages
    fn handles_messages(&self) -> bool {
        false
    }

    /// Called when the extension is initialized
    async fn on_init(&self, _ctx: &ConnectionContext) -> Result<(), ExtensionError> {
        Ok(())
    }

    /// Called when a connection is established
    async fn on_connect(&self, _ctx: &ConnectionContext) -> Result<(), ExtensionError> {
        Ok(())
    }

    /// Called when a connection is lost
    async fn on_disconnect(&self, _ctx: &ConnectionContext) -> Result<(), ExtensionError> {
        Ok(())
    }

    /// Called when the extension is being shut down
    async fn on_shutdown(&self, _ctx: &ConnectionContext) -> Result<(), ExtensionError> {
        Ok(())
    }

    /// Process an incoming message
    ///
    /// Receives a reference to the message for zero-copy efficiency.
    /// Return:
    /// - `Ok(Some(msg))` to broadcast the (optionally modified) message
    /// - `Ok(None)` to filter out the message
    /// - `Err(_)` to signal a processing error
    async fn on_message(
        &self,
        message: &Message,
        _ctx: &ConnectionContext,
    ) -> Result<Option<Message>, ExtensionError> {
        Ok(Some(message.clone()))
    }
}

/// Box wrapper for the extension trait
pub type BoxExtension = Box<dyn Extension>;

/// Create a boxed extension
pub fn boxed<E: Extension + 'static>(ext: E) -> BoxExtension {
    Box::new(ext)
}