Skip to main content

rustapi_ws/
lib.rs

1//! # rustapi-ws
2//!
3//! WebSocket support for the RustAPI framework.
4//!
5//! This crate provides WebSocket upgrade handling, message types, and utilities
6//! for building real-time bidirectional communication in your RustAPI applications.
7//!
8//! ## Features
9//!
10//! - **WebSocket Upgrade**: Seamless HTTP to WebSocket upgrade via the `WebSocket` extractor
11//! - **Message Types**: Support for Text, Binary, Ping/Pong messages
12//! - **Type-Safe JSON**: Serialize/deserialize JSON messages with serde
13//! - **Connection Management**: Clean connection lifecycle with proper close handling
14//! - **Broadcast Support**: Send messages to multiple connected clients
15//!
16//! ## Quick Start
17//!
18//! ```rust,ignore
19//! use rustapi_rs::prelude::*;
20//! use rustapi_ws::{WebSocket, Message};
21//!
22//! async fn ws_handler(ws: WebSocket) -> impl IntoResponse {
23//!     ws.on_upgrade(|socket| async move {
24//!         let (mut sender, mut receiver) = socket.split();
25//!         
26//!         while let Some(msg) = receiver.next().await {
27//!             match msg {
28//!                 Ok(Message::Text(text)) => {
29//!                     let _ = sender.send(Message::Text(format!("Echo: {}", text))).await;
30//!                 }
31
32// Allow large error types in Results - WebSocket errors include tungstenite errors which are large
33#![allow(clippy::result_large_err)]
34//!                 Ok(Message::Close(_)) => break,
35//!                 _ => {}
36//!             }
37//!         }
38//!     })
39//! }
40//!
41//! #[tokio::main]
42//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
43//!     RustApi::new()
44//!         .route("/ws", get(ws_handler))
45//!         .run("127.0.0.1:8080")
46//!         .await
47//! }
48//! ```
49
50#![warn(missing_docs)]
51#![warn(rustdoc::missing_crate_level_docs)]
52
53mod broadcast;
54mod compression;
55mod error;
56mod extractor;
57mod heartbeat;
58mod message;
59mod socket;
60mod upgrade;
61
62/// Authentication support for WebSocket connections
63pub mod auth;
64
65pub use broadcast::Broadcast;
66pub use compression::WsCompressionConfig;
67pub use error::WebSocketError;
68pub use extractor::WebSocket;
69pub use heartbeat::WsHeartbeatConfig;
70pub use message::{CloseCode, CloseFrame, Message};
71pub use socket::{WebSocketReceiver, WebSocketSender, WebSocketStream};
72pub use upgrade::WebSocketUpgrade;
73
74/// Prelude module for convenient imports
75pub mod prelude {
76    pub use crate::auth::{AuthError, Claims, TokenExtractor, TokenValidator, WsAuthConfig};
77    pub use crate::{
78        Broadcast, CloseCode, CloseFrame, Message, WebSocket, WebSocketError, WebSocketReceiver,
79        WebSocketSender, WebSocketStream, WebSocketUpgrade, WsCompressionConfig,
80    };
81}