1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
//! # WebSocket Support Module
//!
//! This module provides comprehensive WebSocket functionality for the Ignitia web framework,
//! including connection management, message handling, and protocol upgrades. The WebSocket
//! implementation follows RFC 6455 standards and provides both low-level and high-level
//! APIs for real-time bidirectional communication.
//!
//! ## Features
//!
//! - **Protocol Compliance**: Full RFC 6455 WebSocket protocol implementation
//! - **Connection Management**: Automatic connection lifecycle handling
//! - **Message Types**: Support for text, binary, ping, pong, and close messages
//! - **Handler Patterns**: Multiple handler patterns for different use cases
//! - **Performance Optimized**: Efficient message processing with batching support
//! - **Error Handling**: Comprehensive error handling and recovery
//! - **Graceful Shutdown**: Proper connection cleanup and resource management
//!
//! ## Architecture
//!
//! The WebSocket module is organized into several key components:
//!
//! - **Connection**: Low-level WebSocket connection management
//! - **Handler**: High-level message and event handling
//! - **Message**: Message types and serialization
//! - **Upgrade**: HTTP to WebSocket protocol upgrade handling
//!
//! ## Usage Examples
//!
//! ### Basic WebSocket Server
//!
//! ```
//! use ignitia::{Router, Server, websocket::*};
//! use std::net::SocketAddr;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let router = Router::new()
//! .websocket("/ws", websocket_handler(|ws: WebSocketConnection| async move {
//! while let Some(message) = ws.recv().await {
//! match message {
//! Message::Text(text) => {
//! println!("Received: {}", text);
//! ws.send_text(format!("Echo: {}", text)).await?;
//! }
//! Message::Binary(data) => {
//! println!("Received {} bytes", data.len());
//! ws.send_bytes(data).await?;
//! }
//! Message::Close(_) => break,
//! _ => {}
//! }
//! }
//! Ok(())
//! }));
//!
//! let addr: SocketAddr = "127.0.0.1:3000".parse()?;
//! let server = Server::new(router, addr);
//! server.ignitia().await
//! }
//! ```
//!
//! ### JSON Message Handling
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use ignitia::{Router, websocket::*};
//!
//! #[derive(Serialize, Deserialize)]
//! struct ChatMessage {
//! user: String,
//! message: String,
//! timestamp: u64,
//! }
//!
//! let router = Router::new()
//! .websocket("/chat", websocket_handler(|ws: WebSocketConnection| async move {
//! while let Some(message) = ws.recv().await {
//! if let Message::Text(text) = message {
//! if let Ok(chat_msg) = serde_json::from_str::<ChatMessage>(&text) {
//! println!("Chat from {}: {}", chat_msg.user, chat_msg.message);
//!
//! // Broadcast to other clients (in real app, you'd maintain client list)
//! let response = ChatMessage {
//! user: "Server".to_string(),
//! message: format!("Received: {}", chat_msg.message),
//! timestamp: std::time::SystemTime::now()
//! .duration_since(std::time::UNIX_EPOCH)
//! .unwrap()
//! .as_secs(),
//! };
//!
//! ws.send_json(&response).await?;
//! }
//! }
//! }
//! Ok(())
//! }));
//! ```
//!
//! ### Batch Message Processing
//!
//! ```
//! use ignitia::{Router, websocket::*};
//!
//! let router = Router::new()
//! .websocket("/batch", websocket_batch_handler(
//! |ws: WebSocketConnection, messages: Vec<Message>| async move {
//! println!("Processing batch of {} messages", messages.len());
//!
//! let mut responses = Vec::new();
//! for msg in messages {
//! if let Message::Text(text) = msg {
//! responses.push(Message::text(format!("Processed: {}", text)));
//! }
//! }
//!
//! ws.send_batch(responses).await?;
//! Ok(())
//! },
//! 10, // batch size
//! 100, // timeout in milliseconds
//! ));
//! ```
//!
//! ## Handler Types
//!
//! The module provides several handler types for different use cases:
//!
//! - **Simple Handler**: `websocket_handler` - Basic message-by-message processing
//! - **Message Handler**: `websocket_message_handler` - Optimized single message processing
//! - **Batch Handler**: `websocket_batch_handler` - Efficient batch processing
//!
//! ## Message Types
//!
//! WebSocket messages support various formats:
//!
//! - **Text**: UTF-8 encoded string messages
//! - **Binary**: Raw byte data
//! - **Ping/Pong**: Connection keepalive frames
//! - **Close**: Connection termination with optional reason
//!
//! ## Performance Considerations
//!
//! - Use batch processing for high-throughput scenarios
//! - Implement connection pooling for multiple clients
//! - Consider message size limits to prevent memory exhaustion
//! - Use binary messages for non-text data to avoid encoding overhead
//!
//! ## Security Notes
//!
//! - Validate all incoming messages
//! - Implement rate limiting to prevent abuse
//! - Use secure WebSocket (WSS) in production
//! - Sanitize data before broadcasting to other clients
// Export all WebSocket functionality when the feature is enabled
pub use WebSocketConnection;
pub use ;
pub use ;
pub use ;
// Stub implementations when WebSocket feature is not enabled
// These provide helpful error messages at runtime
;
;
;
;
/// Creates a WebSocket handler when the feature is disabled.
///
/// # Panics
///
/// This function will panic with an informative message when called
/// without the `websocket` feature enabled.
/// Checks if a request is a WebSocket upgrade request when the feature is disabled.
///
/// # Returns
///
/// Always returns `false` when the WebSocket feature is not enabled.
/// Attempts to upgrade a connection to WebSocket when the feature is disabled.
///
/// # Returns
///
/// Always returns an error indicating WebSocket support is not available.