Module handlers

Module handlers 

Source
Expand description

§Programmable WebSocket Handlers

This module provides a flexible handler API for scripting WebSocket event flows. Unlike static replay, handlers allow you to write custom logic for responding to WebSocket events, manage rooms, and route messages dynamically.

§Features

  • Connection Lifecycle: on_connect and on_disconnect hooks
  • Pattern Matching: Route messages with regex or JSONPath patterns
  • Room Management: Broadcast messages to groups of connections
  • Passthrough: Selectively forward messages to upstream servers
  • Hot Reload: Automatically reload handlers when code changes (via MOCKFORGE_WS_HOTRELOAD)

§Quick Start

use mockforge_ws::handlers::{WsHandler, WsContext, WsMessage, HandlerResult};
use async_trait::async_trait;

struct EchoHandler;

#[async_trait]
impl WsHandler for EchoHandler {
    async fn on_connect(&self, ctx: &mut WsContext) -> HandlerResult<()> {
        ctx.send_text("Welcome to the echo server!").await?;
        Ok(())
    }

    async fn on_message(&self, ctx: &mut WsContext, msg: WsMessage) -> HandlerResult<()> {
        if let WsMessage::Text(text) = msg {
            ctx.send_text(&format!("echo: {}", text)).await?;
        }
        Ok(())
    }
}

§Message Pattern Matching

use mockforge_ws::handlers::{WsHandler, WsContext, WsMessage, HandlerResult, MessagePattern};
use async_trait::async_trait;

struct ChatHandler;

#[async_trait]
impl WsHandler for ChatHandler {
    async fn on_message(&self, ctx: &mut WsContext, msg: WsMessage) -> HandlerResult<()> {
        if let WsMessage::Text(text) = msg {
            // Use pattern matching to route messages
            if let Ok(pattern) = MessagePattern::regex(r"^/join (.+)$") {
                if pattern.matches(&text) {
                    // Extract room name and join
                    if let Some(room) = text.strip_prefix("/join ") {
                        ctx.join_room(room).await?;
                        ctx.send_text(&format!("Joined room: {}", room)).await?;
                    }
                }
            }
            // Handle JSON chat messages
            let jsonpath_pattern = MessagePattern::jsonpath("$.type");
            if jsonpath_pattern.matches(&text) {
                ctx.broadcast_to_room("general", &text).await?;
            }
        }
        Ok(())
    }
}

Structs§

HandlerRegistry
Handler registry for managing multiple handlers
MessageRouter
Pattern-based message router
PassthroughConfig
Passthrough handler configuration for forwarding messages to upstream servers
PassthroughHandler
Passthrough handler that forwards messages to an upstream server
RoomManager
Room manager for broadcasting messages to groups of connections
WsContext
Context provided to handlers for each connection

Enums§

HandlerError
Error type for handler operations
MessagePattern
Pattern for matching WebSocket messages
WsMessage
WebSocket message wrapper for different message types

Traits§

WsHandler
Trait for WebSocket message handlers

Type Aliases§

ConnectionId
Connection ID type
HandlerResult
Result type for handler operations