Expand description
WebSocket support for Reinhardt framework
This crate provides comprehensive WebSocket support for the Reinhardt framework, including connection management, room-based messaging, authentication, rate limiting, middleware integration, and distributed channel layers.
§Features
- Connection Management: Robust WebSocket connection handling with lifecycle hooks
- Room-Based Messaging: Group connections into rooms for targeted broadcasting
- Authentication & Authorization: Token-based auth and permission-based authorization
- Rate Limiting: Connection and message rate limiting to prevent abuse
- Middleware Integration: Pre-processing and post-processing of connections and messages
- WebSocket Routing: URL-based WebSocket endpoint registration
- Channel Layers: Distributed messaging for multi-instance deployments
- Consumer Classes: Django Channels-inspired message handling patterns
§Basic Usage
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;
use std::sync::Arc;
let (tx, mut rx) = mpsc::unbounded_channel();
let conn = Arc::new(WebSocketConnection::new("user_1".to_string(), tx));
conn.send_text("Hello, WebSocket!".to_string()).await.unwrap();
let msg = rx.recv().await.unwrap();
match msg {
Message::Text { data } => println!("Received: {}", data),
_ => {}
}§Advanced Features
§Message Compression
The compression feature enables gzip, deflate, and brotli compression for WebSocket messages:
[dependencies]
reinhardt-websockets = { version = "0.1", features = ["compression"] }§Automatic Reconnection
The reconnection module provides automatic reconnection with exponential backoff:
use reinhardt_websockets::reconnection::{ReconnectionConfig, ReconnectionStrategy};
use std::time::Duration;
let config = ReconnectionConfig::default()
.with_max_attempts(5)
.with_initial_delay(Duration::from_secs(1));
let mut strategy = ReconnectionStrategy::new(config);§Redis Channel Layer
The redis-channel feature enables distributed messaging via Redis:
[dependencies]
reinhardt-websockets = { version = "0.1", features = ["redis-channel"] }§Metrics and Monitoring
The metrics module provides comprehensive WebSocket metrics:
use reinhardt_websockets::metrics::{WebSocketMetrics, MetricsCollector};
let metrics = WebSocketMetrics::new();
metrics.record_connection();
metrics.record_message_sent();
let snapshot = metrics.snapshot();
println!("{}", snapshot.summary());§Integration with reinhardt-pages
The pages-integration feature enables seamless integration with reinhardt-pages,
allowing WebSocket connections to use the same Cookie/session-based authentication
as the HTTP layer:
[dependencies]
reinhardt-websockets = { version = "0.1", features = ["pages-integration"] }Server-side setup:
use reinhardt_websockets::{PagesAuthenticator, WebSocketRouter, WebSocketRoute};
use std::sync::Arc;
// Create authenticator that integrates with reinhardt-pages sessions
let authenticator = Arc::new(PagesAuthenticator::new());
// Register WebSocket routes
let mut router = WebSocketRouter::new();
router.register_route(WebSocketRoute::new(
"/ws/chat".to_string(),
Some("websocket:chat".to_string()),
)).await.unwrap();Client-side usage (WASM):
On the client side, use the use_websocket hook from reinhardt-pages:
use reinhardt_pages::reactive::hooks::{use_websocket, UseWebSocketOptions};
let ws = use_websocket("ws://localhost:8000/ws/chat", UseWebSocketOptions::default());
// Send message
ws.send_text("Hello, server!".to_string()).ok();
// Monitor connection state
use_effect({
let ws = ws.clone();
move || {
match ws.connection_state().get() {
ConnectionState::Open => log!("Connected"),
ConnectionState::Closed => log!("Disconnected"),
_ => {}
}
None::<fn()>
}
});The authentication cookies from the user’s HTTP session are automatically included in the WebSocket handshake, allowing the server to authenticate the connection.
Re-exports§
pub use auth::AuthError;pub use auth::AuthResult;pub use auth::AuthUser;pub use auth::AuthenticatedConnection;pub use auth::AuthorizationPolicy;pub use auth::PermissionBasedPolicy;pub use auth::SimpleAuthUser;pub use auth::TokenAuthenticator;pub use auth::WebSocketAuthenticator;pub use channels::ChannelError;pub use channels::ChannelLayer;pub use channels::ChannelLayerWrapper;pub use channels::ChannelMessage;pub use channels::ChannelResult;pub use channels::InMemoryChannelLayer;pub use connection::ConnectionConfig;pub use connection::ConnectionTimeoutMonitor;pub use connection::HeartbeatConfig;pub use connection::HeartbeatMonitor;pub use connection::Message;pub use connection::PingPongConfig;pub use connection::WebSocketConnection;pub use connection::WebSocketError;pub use connection::WebSocketResult;pub use consumers::BroadcastConsumer;pub use consumers::ConsumerChain;pub use consumers::ConsumerContext;pub use consumers::EchoConsumer;pub use consumers::JsonConsumer;pub use consumers::WebSocketConsumer;pub use handler::WebSocketHandler;pub use metrics::MetricsCollector;pub use metrics::MetricsSnapshot;pub use metrics::PeriodicReporter;pub use metrics::WebSocketMetrics;pub use middleware::ConnectionContext;pub use middleware::ConnectionMiddleware;pub use middleware::IpFilterMiddleware;pub use middleware::LoggingMiddleware;pub use middleware::MessageMiddleware;pub use middleware::MessageSizeLimitMiddleware;pub use middleware::MiddlewareChain;pub use middleware::MiddlewareError;pub use middleware::MiddlewareResult;pub use origin::OriginPolicy;pub use origin::OriginValidationConfig;pub use origin::OriginValidationMiddleware;pub use origin::validate_origin;pub use protocol::DEFAULT_MAX_FRAME_SIZE;pub use protocol::DEFAULT_MAX_MESSAGE_SIZE;pub use protocol::default_websocket_config;pub use protocol::websocket_config_with_limits;pub use reconnection::AutoReconnectHandler;pub use reconnection::ReconnectionConfig;pub use reconnection::ReconnectionState;pub use reconnection::ReconnectionStrategy;pub use room::BroadcastResult;pub use room::Room;pub use room::RoomError;pub use room::RoomManager;pub use room::RoomResult;pub use routing::RouteError;pub use routing::RouteResult;pub use routing::WebSocketRoute;pub use routing::WebSocketRouter;pub use routing::clear_websocket_router;pub use routing::get_websocket_router;pub use routing::register_websocket_router;pub use routing::reverse_websocket_url;pub use throttling::CombinedThrottler;pub use throttling::ConnectionRateLimiter;pub use throttling::ConnectionThrottler;pub use throttling::RateLimitConfig;pub use throttling::RateLimitMiddleware;pub use throttling::RateLimiter;pub use throttling::ThrottleError;pub use throttling::ThrottleResult;pub use throttling::WebSocketRateLimitConfig;
Modules§
- auth
- WebSocket authentication and authorization
- channels
- Channel layers for distributed WebSocket systems
- connection
- consumers
- WebSocket consumers for advanced message handling patterns
- handler
- WebSocket handler
- metrics
- WebSocket metrics and monitoring
- middleware
- WebSocket middleware integration
- origin
- Origin header validation for WebSocket handshake
- protocol
- Protocol-level WebSocket configuration
- reconnection
- WebSocket automatic reconnection support
- room
- WebSocket room management with advanced features
- routing
- WebSocket routing integration
- throttling
- WebSocket rate limiting and throttling