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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Type-safe data extraction from WebSocket messages and context.
//!
//! This module provides a powerful type extraction system inspired by frameworks like Axum,
//! allowing handlers to declaratively specify what data they need. Extractors automatically
//! parse and validate data from messages, connection state, and application context.
//!
//! # Overview
//!
//! Extractors are types that implement the [`FromMessage`] trait. They can extract:
//! - **Message content**: JSON, binary data, text
//! - **Connection info**: Client address, connection ID, metadata
//! - **Application state**: Shared data like database pools, configuration
//! - **Route parameters**: Path and query parameters from routing
//! - **Custom extensions**: User-defined request-scoped data
//!
//! # Design Philosophy
//!
//! The extractor system follows these principles:
//! - **Type safety**: Extraction failures are caught at runtime with clear errors
//! - **Composability**: Multiple extractors can be used in a single handler
//! - **Zero cost**: Extraction happens only once per handler invocation
//! - **Flexibility**: Custom extractors can be easily implemented
//!
//! # Built-in Extractors
//!
//! | Extractor | Description | Example |
//! |-----------|-------------|---------|
//! | [`Json<T>`] | Deserialize JSON from message | `Json(user): Json<User>` |
//! | [`State<T>`] | Extract shared application state | `State(db): State<Arc<Database>>` |
//! | [`Connection`] | Get the active connection | `conn: Connection` |
//! | [`ConnectInfo`] | Get connection metadata | `ConnectInfo(info)` |
//! | [`Message`] | Get raw message | `msg: Message` |
//! | [`Data`] | Extract binary data | `Data(bytes)` |
//! | [`Path<T>`] | Extract path parameters | `Path(id): Path<UserId>` |
//! | [`Query<T>`] | Extract query parameters | `Query(params): Query<SearchParams>` |
//! | [`Extension<T>`] | Extract custom extensions | `Extension(auth): Extension<Auth>` |
//!
//! # Examples
//!
//! ## Simple JSON Extraction
//!
//! ```
//! use wsforge::prelude::*;
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct ChatMessage {
//! username: String,
//! text: String,
//! }
//!
//! async fn chat_handler(Json(msg): Json<ChatMessage>) -> Result<String> {
//! println!("{} says: {}", msg.username, msg.text);
//! Ok(format!("Message from {} received", msg.username))
//! }
//! ```
//!
//! ## Multiple Extractors
//!
//! ```
//! use wsforge::prelude::*;
//! use serde::Deserialize;
//! use std::sync::Arc;
//!
//! #[derive(Deserialize)]
//! struct GameMove {
//! player: String,
//! action: String,
//! }
//!
//! async fn game_handler(
//! Json(game_move): Json<GameMove>,
//! conn: Connection,
//! State(manager): State<Arc<ConnectionManager>>,
//! ) -> Result<()> {
//! println!("Player {} from connection {} made move: {}",
//! game_move.player, conn.id(), game_move.action);
//!
//! // Broadcast to other players
//! manager.broadcast_except(conn.id(),
//! Message::text(format!("{} moved", game_move.player)));
//!
//! Ok(())
//! }
//! ```
//!
//! ## Custom Extractors
//!
//! ```
//! use wsforge::prelude::*;
//! use async_trait::async_trait;
//!
//! // Custom extractor for authenticated users
//! struct AuthUser {
//! user_id: u64,
//! username: String,
//! }
//!
//! #[async_trait]
//! impl FromMessage for AuthUser {
//! async fn from_message(
//! message: &Message,
//! conn: &Connection,
//! state: &AppState,
//! extensions: &Extensions,
//! ) -> Result<Self> {
//! // Extract authentication token from message
//! let text = message.as_text()
//! .ok_or_else(|| Error::extractor("Message must be text"))?;
//!
//! // Validate and extract user info
//! // (In production, verify JWT, session token, etc.)
//! Ok(AuthUser {
//! user_id: 123,
//! username: "user".to_string(),
//! })
//! }
//! }
//!
//! async fn protected_handler(user: AuthUser) -> Result<String> {
//! Ok(format!("Hello, {}!", user.username))
//! }
//! ```
use crate;
use crate;
use crateMessage;
use crateAppState;
use async_trait;
use DashMap;
use Serialize;
use DeserializeOwned;
use Arc;
/// Trait for types that can be extracted from WebSocket messages and context.
///
/// This trait is the core of the extractor system. Types that implement `FromMessage`
/// can be used as handler parameters, and the framework will automatically extract
/// and validate the data before calling the handler.
///
/// # Implementation Guidelines
///
/// When implementing custom extractors:
/// 1. **Be specific**: Return clear error messages when extraction fails
/// 2. **Be efficient**: Avoid expensive operations if possible
/// 3. **Be safe**: Validate all extracted data
/// 4. **Document**: Explain what data is extracted and any requirements
///
/// # Examples
///
/// ## Simple Extractor
///
/// ```
/// use wsforge::prelude::*;
/// use async_trait::async_trait;
///
/// struct MessageLength(usize);
///
/// #[async_trait]
/// impl FromMessage for MessageLength {
/// async fn from_message(
/// message: &Message,
/// _conn: &Connection,
/// _state: &AppState,
/// _extensions: &Extensions,
/// ) -> Result<Self> {
/// let len = message.as_bytes().len();
/// Ok(MessageLength(len))
/// }
/// }
///
/// async fn handler(MessageLength(len): MessageLength) -> Result<String> {
/// Ok(format!("Message length: {}", len))
/// }
/// ```
///
/// ## Extractor with Validation
///
/// ```
/// use wsforge::prelude::*;
/// use async_trait::async_trait;
///
/// struct ValidatedText(String);
///
/// #[async_trait]
/// impl FromMessage for ValidatedText {
/// async fn from_message(
/// message: &Message,
/// _conn: &Connection,
/// _state: &AppState,
/// _extensions: &Extensions,
/// ) -> Result<Self> {
/// let text = message.as_text()
/// .ok_or_else(|| Error::extractor("Message must be text"))?;
///
/// if text.is_empty() {
/// return Err(Error::extractor("Text cannot be empty"));
/// }
///
/// if text.len() > 1000 {
/// return Err(Error::extractor("Text too long (max 1000 characters)"));
/// }
///
/// Ok(ValidatedText(text.to_string()))
/// }
/// }
/// ```
/// Container for request-scoped extension data.
///
/// Extensions provide a way to pass arbitrary data through the request pipeline.
/// This is useful for middleware to attach data (like authentication info, request IDs)
/// that handlers can later extract.
///
/// # Thread Safety
///
/// Extensions are thread-safe and can be safely shared across tasks.
///
/// # Examples
///
/// ## Adding and Retrieving Data
///
/// ```
/// use wsforge::prelude::*;
///
/// # fn example() {
/// let extensions = Extensions::new();
///
/// // Add data
/// extensions.insert("request_id", "req_123");
/// extensions.insert("user_id", 42_u64);
///
/// // Retrieve data
/// if let Some(request_id) = extensions.get::<&str>("request_id") {
/// println!("Request ID: {}", request_id);
/// }
///
/// if let Some(user_id) = extensions.get::<u64>("user_id") {
/// println!("User ID: {}", user_id);
/// }
/// # }
/// ```
///
/// ## Use in Middleware
///
/// ```
/// use wsforge::prelude::*;
///
/// async fn auth_middleware(
/// msg: Message,
/// conn: Connection,
/// extensions: &Extensions,
/// ) -> Result<()> {
/// // Extract and validate auth token
/// let token = extract_token(&msg)?;
/// let user_id = validate_token(&token)?;
///
/// // Store for handler to use
/// extensions.insert("user_id", user_id);
///
/// Ok(())
/// }
///
/// # fn extract_token(_: &Message) -> Result<String> { Ok("token".to_string()) }
/// # fn validate_token(_: &str) -> Result<u64> { Ok(123) }
/// ```
/// Extractor for shared application state.
///
/// Use this to access data that's shared across all connections, such as:
/// - Database connection pools
/// - Configuration
/// - Caches
/// - Connection managers
///
/// # Type Parameter
///
/// The generic parameter `T` should be wrapped in `Arc` since state is shared.
///
/// # Examples
///
/// ## Accessing Connection Manager
///
/// ```
/// use wsforge::prelude::*;
/// use std::sync::Arc;
///
/// async fn broadcast_handler(
/// msg: Message,
/// State(manager): State<Arc<ConnectionManager>>,
/// ) -> Result<()> {
/// manager.broadcast(msg);
/// Ok(())
/// }
/// ```
///
/// ## Custom State Type
///
/// ```
/// use wsforge::prelude::*;
/// use std::sync::Arc;
///
/// struct AppConfig {
/// max_message_size: usize,
/// rate_limit: u32,
/// }
///
/// async fn handler(State(config): State<Arc<AppConfig>>) -> Result<String> {
/// Ok(format!("Max message size: {}", config.max_message_size))
/// }
/// ```
;
/// Extractor for JSON data from messages.
///
/// Automatically deserializes the message content as JSON into the specified type.
/// The type must implement `serde::Deserialize`.
///
/// # Errors
///
/// Returns an error if:
/// - The message is not text
/// - The JSON is malformed
/// - Required fields are missing
/// - Type constraints are not satisfied
///
/// # Examples
///
/// ## Simple Struct
///
/// ```
/// use wsforge::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct LoginRequest {
/// username: String,
/// password: String,
/// }
///
/// async fn login_handler(Json(req): Json<LoginRequest>) -> Result<String> {
/// // Validate credentials
/// Ok(format!("Login attempt by {}", req.username))
/// }
/// ```
///
/// ## With Validation
///
/// ```
/// use wsforge::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct CreateUser {
/// #[serde(deserialize_with = "validate_username")]
/// username: String,
/// age: u8,
/// }
///
/// async fn create_user(Json(user): Json<CreateUser>) -> Result<String> {
/// Ok(format!("Creating user: {}", user.username))
/// }
///
/// # fn validate_username<'de, D>(_: D) -> std::result::Result<String, D::Error>
/// # where D: serde::Deserializer<'de> {
/// # Ok("valid".to_string())
/// # }
/// ```
///
/// ## Nested Structures
///
/// ```
/// use wsforge::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct GameState {
/// player: Player,
/// score: u32,
/// }
///
/// #[derive(Deserialize)]
/// struct Player {
/// id: u64,
/// name: String,
/// }
///
/// async fn update_game(Json(state): Json<GameState>) -> Result<()> {
/// println!("Player {} score: {}", state.player.name, state.score);
/// Ok(())
/// }
/// ```
;
/// Extractor for the active connection.
///
/// Provides access to the connection that sent the message, allowing you to:
/// - Get the connection ID
/// - Access connection metadata
/// - Send messages back to the specific client
///
/// # Examples
///
/// ## Sending Response
///
/// ```
/// use wsforge::prelude::*;
///
/// async fn handler(msg: Message, conn: Connection) -> Result<()> {
/// conn.send_text("Message received!")?;
/// Ok(())
/// }
/// ```
///
/// ## Using Connection Info
///
/// ```
/// use wsforge::prelude::*;
///
/// async fn handler(conn: Connection) -> Result<String> {
/// let info = conn.info();
/// Ok(format!("Client from {} connected at {}",
/// info.addr, info.connected_at))
/// }
/// ```
/// Extractor for connection metadata.
///
/// Provides detailed information about the connection, including:
/// - Connection ID
/// - Client socket address
/// - Connection timestamp
/// - Protocol information
///
/// # Examples
///
/// ## Logging Connection Info
///
/// ```
/// use wsforge::prelude::*;
///
/// async fn handler(ConnectInfo(info): ConnectInfo) -> Result<String> {
/// println!("Connection {} from {} at {}",
/// info.id, info.addr, info.connected_at);
/// Ok("Connected".to_string())
/// }
/// ```
;
/// Extractor for the raw message.
///
/// Use this when you need access to the complete message without
/// automatic deserialization.
///
/// # Examples
///
/// ## Raw Message Processing
///
/// ```
/// use wsforge::prelude::*;
///
/// async fn handler(msg: Message) -> Result<String> {
/// if msg.is_text() {
/// Ok(format!("Text: {}", msg.as_text().unwrap()))
/// } else if msg.is_binary() {
/// Ok(format!("Binary: {} bytes", msg.as_bytes().len()))
/// } else {
/// Ok("Unknown message type".to_string())
/// }
/// }
/// ```
/// Extractor for raw binary data.
///
/// Extracts the message payload as raw bytes. Works with both text and binary messages.
///
/// # Examples
///
/// ## Processing Binary Data
///
/// ```
/// use wsforge::prelude::*;
///
/// async fn handler(Data(bytes): Data) -> Result<String> {
/// println!("Received {} bytes", bytes.len());
/// Ok(format!("Processed {} bytes", bytes.len()))
/// }
/// ```
;
/// Extractor for path parameters.
///
/// Extracts typed parameters from the request path. The type must implement
/// `serde::Deserialize` and be stored in extensions by routing middleware.
///
/// # Examples
///
/// ## Single Parameter
///
/// ```
/// use wsforge::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct UserId(u64);
///
/// async fn get_user(Path(UserId(id)): Path<UserId>) -> Result<String> {
/// Ok(format!("Getting user {}", id))
/// }
/// ```
///
/// ## Multiple Parameters
///
/// ```
/// use wsforge::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct RoomParams {
/// room_id: String,
/// user_id: u64,
/// }
///
/// async fn join_room(Path(params): Path<RoomParams>) -> Result<String> {
/// Ok(format!("User {} joining room {}", params.user_id, params.room_id))
/// }
/// ```
;
/// Extractor for query parameters.
///
/// Extracts typed parameters from the query string. The type must implement
/// `serde::Deserialize` and be stored in extensions during connection establishment.
///
/// # Examples
///
/// ## Search Parameters
///
/// ```
/// use wsforge::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct SearchQuery {
/// q: String,
/// limit: Option<u32>,
/// }
///
/// async fn search(Query(params): Query<SearchQuery>) -> Result<String> {
/// let limit = params.limit.unwrap_or(10);
/// Ok(format!("Searching for '{}' (limit: {})", params.q, limit))
/// }
/// ```
;
/// Extractor for custom extension data.
///
/// Retrieves data that was previously stored in extensions by middleware or other handlers.
///
/// # Examples
///
/// ## Authentication Data
///
/// ```
/// use wsforge::prelude::*;
/// use std::sync::Arc;
///
/// #[derive(Clone)]
/// struct AuthData {
/// user_id: u64,
/// role: String,
/// }
///
/// async fn protected_handler(Extension(auth): Extension<AuthData>) -> Result<String> {
/// Ok(format!("User {} with role {}", auth.user_id, auth.role))
/// }
/// ```
;