Skip to main content

Module hooks

Module hooks 

Source
Expand description

Connection hooks for customizing connection establishment.

Connection hooks are attached when establishing connections and allow custom authentication, handshakes, or protocol negotiations. The ConnectionHook trait is called during connection setup, before the connection is used for messaging.

§Built-in Hooks

The token module provides ready-to-use token-based authentication hooks:

§Custom Hooks

Implement ConnectionHook for custom authentication or protocol negotiation:

use msg_socket::hooks::{ConnectionHook, Error, HookResult};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};

struct MyAuth;

#[derive(Debug, thiserror::Error)]
enum MyAuthError {
    #[error("invalid token")]
    InvalidToken,
}

impl<Io> ConnectionHook<Io> for MyAuth
where
    Io: AsyncRead + AsyncWrite + Send + Unpin + 'static,
{
    type Error = MyAuthError;

    async fn on_connection(&self, mut io: Io) -> HookResult<Io, Self::Error> {
        let mut buf = [0u8; 32];
        io.read_exact(&mut buf).await?;
        if &buf == b"expected_token_value_32_bytes!!!" {
            io.write_all(b"OK").await?;
            Ok(io)
        } else {
            Err(Error::hook(MyAuthError::InvalidToken))
        }
    }
}

§Future Extensions

TODO: Additional hooks may be added for different parts of the connection lifecycle (e.g., disconnection, reconnection, periodic health checks).

Modules§

token
Token-based authentication connection hooks.

Enums§

Error
Error type for connection hooks.

Traits§

ConnectionHook
Connection hook executed during connection establishment.

Type Aliases§

HookResult
Result type for connection hooks.