wsforge-core 0.1.1

Core library for WsForge WebSocket framework
Documentation
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Middleware system for request/response processing.
//!
//! This module provides a flexible middleware chain system that allows you to intercept
//! and process WebSocket messages before they reach handlers. Middleware can modify messages,
//! perform authentication, logging, rate limiting, and more.
//!
//! # Overview
//!
//! The middleware system is built around three core types:
//! - [`Middleware`] - Trait that all middleware must implement
//! - [`MiddlewareChain`] - Container that holds and executes middleware in order
//! - [`Next`] - Represents the next step in the middleware chain
//!
//! # Architecture
//!
//! ```
//! Message → Middleware 1 → Middleware 2 → ... → Handler → Response
//!              ↓              ↓                      ↓
//!           Next::run     Next::run            Handler::call
//! ```
//!
//! Each middleware can:
//! - Inspect the incoming message
//! - Modify the message before passing it forward
//! - Short-circuit the chain by not calling `next.run()`
//! - Modify the response after calling `next.run()`
//! - Handle errors and transform responses
//!
//! # Examples
//!
//! ## Using Built-in Logger Middleware
//!
//! ```
//! use wsforge::prelude::*;
//!
//! async fn echo(msg: Message) -> Result<Message> {
//!     Ok(msg)
//! }
//!
//! # async fn example() -> Result<()> {
//! let router = Router::new()
//!     .layer(LoggerMiddleware::new())
//!     .default_handler(handler(echo));
//!
//! router.listen("127.0.0.1:8080").await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Creating Custom Middleware
//!
//! ```
//! use wsforge::prelude::*;
//! use async_trait::async_trait;
//!
//! struct AuthMiddleware {
//!     secret: String,
//! }
//!
//! #[async_trait]
//! impl Middleware for AuthMiddleware {
//!     async fn handle(
//!         &self,
//!         message: Message,
//!         conn: Connection,
//!         state: AppState,
//!         extensions: Extensions,
//!         mut next: Next,
//!     ) -> Result<Option<Message>> {
//!         // Check for auth token in message
//!         if let Some(text) = message.as_text() {
//!             if !text.contains(&self.secret) {
//!                 return Err(Error::custom("Unauthorized"));
//!             }
//!         }
//!
//!         // Continue to next middleware/handler
//!         next.run(message, conn, state, extensions).await
//!     }
//! }
//! ```
//!
//! ## Function-based Middleware
//!
//! ```
//! use wsforge::prelude::*;
//!
//! # async fn example() {
//! let logging_middleware = from_fn(|msg, conn, state, ext, mut next| async move {
//!     println!("Before handler: {:?}", msg.as_text());
//!     let response = next.run(msg, conn, state, ext).await?;
//!     println!("After handler");
//!     Ok(response)
//! });
//!
//! // Use in router
//! // router.layer(logging_middleware);
//! # }
//! ```
//!
//! ## Chaining Multiple Middleware
//!
//! ```
//! use wsforge::prelude::*;
//!
//! # async fn example() -> Result<()> {
//! let router = Router::new()
//!     .layer(LoggerMiddleware::new())
//!     .layer(auth_middleware())
//!     .layer(rate_limit_middleware())
//!     .default_handler(handler(my_handler));
//! # Ok(())
//! # }
//! # async fn my_handler() -> Result<String> { Ok("".to_string()) }
//! # fn auth_middleware() -> Arc<dyn Middleware> { unimplemented!() }
//! # fn rate_limit_middleware() -> Arc<dyn Middleware> { unimplemented!() }
//! ```

pub mod logger;

pub use logger::LoggerMiddleware;

use crate::connection::Connection;
use crate::error::Result;
use crate::extractor::Extensions;
use crate::message::Message;
use crate::state::AppState;
use async_trait::async_trait;
use std::sync::Arc;

/// Represents the next middleware or handler in the chain.
///
/// `Next` is used to pass control to the next step in the middleware pipeline.
/// When a middleware calls `next.run()`, it invokes the next middleware or,
/// if there are no more middleware, the final handler.
///
/// # Examples
///
/// ```
/// use wsforge::prelude::*;
/// use async_trait::async_trait;
///
/// struct MyMiddleware;
///
/// #[async_trait]
/// impl Middleware for MyMiddleware {
///     async fn handle(
///         &self,
///         message: Message,
///         conn: Connection,
///         state: AppState,
///         extensions: Extensions,
///         mut next: Next,
///     ) -> Result<Option<Message>> {
///         println!("Before next");
///
///         // Call the next middleware/handler
///         let response = next.run(message, conn, state, extensions).await?;
///
///         println!("After next");
///         Ok(response)
///     }
/// }
/// ```
pub struct Next {
    chain: Arc<MiddlewareChain>,
    index: usize,
}

impl Next {
    /// Creates a new `Next` instance.
    ///
    /// # Arguments
    ///
    /// * `chain` - The middleware chain to execute
    /// * `index` - Current position in the chain
    pub fn new(chain: Arc<MiddlewareChain>, index: usize) -> Self {
        Self { chain, index }
    }

    /// Call the next middleware in the chain.
    ///
    /// This method executes the next middleware in the sequence. If all middleware
    /// have been executed, it calls the final handler.
    ///
    /// # Arguments
    ///
    /// * `message` - The WebSocket message being processed
    /// * `conn` - The connection that sent the message
    /// * `state` - Application state
    /// * `extensions` - Request-scoped extension data
    ///
    /// # Returns
    ///
    /// Returns the response from the next middleware or handler, or `None` if
    /// no response should be sent.
    ///
    /// # Examples
    ///
    /// ```
    /// use wsforge::prelude::*;
    /// use async_trait::async_trait;
    ///
    /// struct TimingMiddleware;
    ///
    /// #[async_trait]
    /// impl Middleware for TimingMiddleware {
    ///     async fn handle(
    ///         &self,
    ///         message: Message,
    ///         conn: Connection,
    ///         state: AppState,
    ///         extensions: Extensions,
    ///         mut next: Next,
    ///     ) -> Result<Option<Message>> {
    ///         let start = std::time::Instant::now();
    ///
    ///         let response = next.run(message, conn, state, extensions).await?;
    ///
    ///         let duration = start.elapsed();
    ///         println!("Request took: {:?}", duration);
    ///
    ///         Ok(response)
    ///     }
    /// }
    /// ```
    pub async fn run(
        mut self,
        message: Message,
        conn: Connection,
        state: AppState,
        extensions: Extensions,
    ) -> Result<Option<Message>> {
        if self.index < self.chain.middlewares.len() {
            let middleware = self.chain.middlewares[self.index].clone();
            self.index += 1;
            middleware
                .handle(message, conn, state, extensions, self)
                .await
        } else if let Some(ref handler) = self.chain.handler {
            handler.call(message, conn, state, extensions).await
        } else {
            Ok(None)
        }
    }
}

/// Middleware trait that all middleware must implement.
///
/// Middleware can intercept messages before they reach handlers, perform
/// transformations, add metadata to extensions, or short-circuit the request.
///
/// # Implementation Guidelines
///
/// - **Always call `next.run()`** unless you want to short-circuit
/// - **Use extensions** to pass data to handlers or other middleware
/// - **Handle errors gracefully** and provide clear error messages
/// - **Be mindful of performance** - middleware runs on every message
///
/// # Examples
///
/// ## Authentication Middleware
///
/// ```
/// use wsforge::prelude::*;
/// use async_trait::async_trait;
///
/// struct AuthMiddleware {
///     required_token: String,
/// }
///
/// #[async_trait]
/// impl Middleware for AuthMiddleware {
///     async fn handle(
///         &self,
///         message: Message,
///         conn: Connection,
///         state: AppState,
///         extensions: Extensions,
///         mut next: Next,
///     ) -> Result<Option<Message>> {
///         if let Some(text) = message.as_text() {
///             if let Some(token) = text.strip_prefix("TOKEN:") {
///                 if token == self.required_token {
///                     extensions.insert("authenticated", true);
///                     return next.run(message, conn, state, extensions).await;
///                 }
///             }
///         }
///
///         Err(Error::custom("Unauthorized"))
///     }
/// }
/// ```
///
/// ## Rate Limiting Middleware
///
/// ```
/// use wsforge::prelude::*;
/// use async_trait::async_trait;
/// use std::sync::Arc;
/// use tokio::sync::RwLock;
/// use std::collections::HashMap;
///
/// struct RateLimitMiddleware {
///     limits: Arc<RwLock<HashMap<String, u32>>>,
///     max_requests: u32,
/// }
///
/// #[async_trait]
/// impl Middleware for RateLimitMiddleware {
///     async fn handle(
///         &self,
///         message: Message,
///         conn: Connection,
///         state: AppState,
///         extensions: Extensions,
///         mut next: Next,
///     ) -> Result<Option<Message>> {
///         let conn_id = conn.id();
///         let mut limits = self.limits.write().await;
///         let count = limits.entry(conn_id.clone()).or_insert(0);
///
///         if *count >= self.max_requests {
///             return Err(Error::custom("Rate limit exceeded"));
///         }
///
///         *count += 1;
///         drop(limits);
///
///         next.run(message, conn, state, extensions).await
///     }
/// }
/// ```
///
/// ## Request ID Middleware
///
/// ```
/// use wsforge::prelude::*;
/// use async_trait::async_trait;
///
/// struct RequestIdMiddleware;
///
/// #[async_trait]
/// impl Middleware for RequestIdMiddleware {
///     async fn handle(
///         &self,
///         message: Message,
///         conn: Connection,
///         state: AppState,
///         extensions: Extensions,
///         mut next: Next,
///     ) -> Result<Option<Message>> {
///         use std::sync::atomic::{AtomicU64, Ordering};
///         static COUNTER: AtomicU64 = AtomicU64::new(0);
///
///         let request_id = COUNTER.fetch_add(1, Ordering::SeqCst);
///         extensions.insert("request_id", request_id);
///
///         next.run(message, conn, state, extensions).await
///     }
/// }
/// ```
#[async_trait]
pub trait Middleware: Send + Sync + 'static {
    /// Handle a message and optionally pass it to the next middleware.
    ///
    /// # Arguments
    ///
    /// * `message` - The incoming WebSocket message
    /// * `conn` - The connection that sent the message
    /// * `state` - Application state
    /// * `extensions` - Request-scoped extension data
    /// * `next` - The next step in the middleware chain
    ///
    /// # Returns
    ///
    /// Returns an optional message to send back to the client, or an error.
    async fn handle(
        &self,
        message: Message,
        conn: Connection,
        state: AppState,
        extensions: Extensions,
        next: Next,
    ) -> Result<Option<Message>>;
}

/// Middleware chain holds all middlewares and the final handler.
///
/// The chain executes middleware in the order they were added, and finally
/// calls the handler if all middleware pass control forward.
///
/// # Examples
///
/// ```
/// use wsforge::prelude::*;
///
/// # fn example() {
/// let mut chain = MiddlewareChain::new();
///
/// // Add middleware
/// chain.layer(LoggerMiddleware::new());
///
/// // Set final handler
/// chain.handler(handler(my_handler));
/// # }
/// # async fn my_handler() -> Result<String> { Ok("".to_string()) }
/// ```
#[derive(Clone)]
pub struct MiddlewareChain {
    /// All middleware in the chain, executed in order
    pub middlewares: Vec<Arc<dyn Middleware>>,
    /// The final handler to call after all middleware
    pub handler: Option<Arc<dyn crate::handler::Handler>>,
}

impl MiddlewareChain {
    /// Creates a new empty middleware chain.
    ///
    /// # Examples
    ///
    /// ```
    /// use wsforge::prelude::*;
    ///
    /// let chain = MiddlewareChain::new();
    /// ```
    pub fn new() -> Self {
        Self {
            middlewares: Vec::new(),
            handler: None,
        }
    }

    /// Add a middleware to the chain.
    ///
    /// Middleware are executed in the order they are added.
    ///
    /// # Arguments
    ///
    /// * `middleware` - The middleware to add
    ///
    /// # Examples
    ///
    /// ```
    /// use wsforge::prelude::*;
    ///
    /// # fn example() {
    /// let mut chain = MiddlewareChain::new();
    ///
    /// chain.layer(LoggerMiddleware::new());
    /// # }
    /// ```
    pub fn layer(mut self, middleware: Arc<dyn Middleware>) -> Self {
        self.middlewares.push(middleware);
        self
    }

    /// Set the final handler for the chain.
    ///
    /// The handler is called after all middleware have been executed.
    ///
    /// # Arguments
    ///
    /// * `handler` - The handler to call
    ///
    /// # Examples
    ///
    /// ```
    /// use wsforge::prelude::*;
    ///
    /// async fn my_handler(msg: Message) -> Result<String> {
    ///     Ok("response".to_string())
    /// }
    ///
    /// # fn example() {
    /// let mut chain = MiddlewareChain::new();
    /// chain.handler(handler(my_handler));
    /// # }
    /// ```
    pub fn handler(mut self, handler: Arc<dyn crate::handler::Handler>) -> Self {
        self.handler = Some(handler);
        self
    }

    /// Execute the middleware chain.
    ///
    /// This runs all middleware in order, then calls the handler if present.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to process
    /// * `conn` - The connection
    /// * `state` - Application state
    /// * `extensions` - Extension data
    ///
    /// # Examples
    ///
    /// ```
    /// use wsforge::prelude::*;
    ///
    /// # async fn example(chain: MiddlewareChain, msg: Message, conn: Connection) -> Result<()> {
    /// let state = AppState::new();
    /// let extensions = Extensions::new();
    ///
    /// let response = chain.execute(msg, conn, state, extensions).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute(
        &self,
        message: Message,
        conn: Connection,
        state: AppState,
        extensions: Extensions,
    ) -> Result<Option<Message>> {
        let next = Next::new(Arc::new(self.clone()), 0);
        next.run(message, conn, state, extensions).await
    }
}

impl Default for MiddlewareChain {
    fn default() -> Self {
        Self::new()
    }
}

/// Function-based Middleware
///
/// Helper to create middleware from async functions without implementing
/// the full `Middleware` trait.
pub struct FnMiddleware<F> {
    func: F,
}

impl<F> FnMiddleware<F> {
    /// Creates a new function-based middleware.
    ///
    /// # Examples
    ///
    /// ```
    /// use wsforge::prelude::*;
    ///
    /// # fn example() {
    /// let middleware = FnMiddleware::new(|msg, conn, state, ext, mut next| async move {
    ///     println!("Before handler");
    ///     let response = next.run(msg, conn, state, ext).await?;
    ///     println!("After handler");
    ///     Ok(response)
    /// });
    /// # }
    /// ```
    pub fn new(func: F) -> Arc<Self> {
        Arc::new(Self { func })
    }
}

#[async_trait]
impl<F, Fut> Middleware for FnMiddleware<F>
where
    F: Fn(Message, Connection, AppState, Extensions, Next) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<Option<Message>>> + Send + 'static,
{
    async fn handle(
        &self,
        message: Message,
        conn: Connection,
        state: AppState,
        extensions: Extensions,
        next: Next,
    ) -> Result<Option<Message>> {
        (self.func)(message, conn, state, extensions, next).await
    }
}

/// Helper function to create middleware from async functions.
///
/// This is a convenience function that wraps an async function in a middleware.
///
/// # Arguments
///
/// * `f` - Async function with signature matching middleware requirements
///
/// # Examples
///
/// ## Simple Logging
///
/// ```
/// use wsforge::prelude::*;
///
/// # fn example() {
/// let logging = from_fn(|msg, conn, state, ext, mut next| async move {
///     println!("Processing message from {}", conn.id());
///     next.run(msg, conn, state, ext).await
/// });
/// # }
/// ```
///
/// ## With State Access
///
/// ```
/// use wsforge::prelude::*;
/// use std::sync::Arc;
///
/// # fn example() {
/// let counter = from_fn(|msg, conn, state, ext, mut next| async move {
///     // Access state
///     if let Some(counter) = state.get::<Arc<std::sync::atomic::AtomicU64>>() {
///         counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
///     }
///     next.run(msg, conn, state, ext).await
/// });
/// # }
/// ```
pub fn from_fn<F, Fut>(f: F) -> Arc<FnMiddleware<F>>
where
    F: Fn(Message, Connection, AppState, Extensions, Next) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<Option<Message>>> + Send + 'static,
{
    FnMiddleware::new(f)
}