elif_http/websocket/
handler.rs1use super::connection::WebSocketConnection;
4use super::registry::ConnectionRegistry;
5use super::types::{ConnectionId, WebSocketConfig, WebSocketResult};
6use axum::extract::ws::WebSocketUpgrade as AxumWebSocketUpgrade;
7use std::sync::Arc;
8
9pub struct WebSocketUpgrade {
12 _config: WebSocketConfig,
14 _registry: Arc<ConnectionRegistry>,
16}
17
18impl WebSocketUpgrade {
19 pub fn new(registry: Arc<ConnectionRegistry>) -> Self {
21 Self {
22 _config: WebSocketConfig::default(),
23 _registry: registry,
24 }
25 }
26
27 pub fn with_config(registry: Arc<ConnectionRegistry>, config: WebSocketConfig) -> Self {
29 Self {
30 _config: config,
31 _registry: registry,
32 }
33 }
34
35 pub async fn upgrade<H, F>(
38 self,
39 ws: AxumWebSocketUpgrade,
40 _handler: H,
41 ) -> axum::response::Response
42 where
43 H: FnOnce(ConnectionId, Arc<WebSocketConnection>) -> F + Send + 'static,
44 F: std::future::Future<Output = ()> + Send + 'static,
45 {
46 ws.on_upgrade(|_socket| async move {
47 tracing::info!("WebSocket connection upgraded (foundation mode)");
48 })
50 }
51}
52
53pub trait WebSocketHandler: Send + Sync + 'static {
55 fn handle_connection(
57 &self,
58 id: ConnectionId,
59 connection: Arc<WebSocketConnection>,
60 ) -> impl std::future::Future<Output = ()> + Send;
61}
62
63pub fn extract_websocket_upgrade(
66 ws: AxumWebSocketUpgrade,
67) -> WebSocketResult<AxumWebSocketUpgrade> {
68 Ok(ws)
69}
70
71#[derive(Clone)]
73pub struct SimpleWebSocketHandler<F> {
74 handler: F,
75}
76
77impl<F, Fut> SimpleWebSocketHandler<F>
78where
79 F: Fn(ConnectionId, Arc<WebSocketConnection>) -> Fut + Send + Sync + 'static,
80 Fut: std::future::Future<Output = ()> + Send,
81{
82 pub fn new(handler: F) -> Self {
83 Self { handler }
84 }
85}
86
87impl<F, Fut> WebSocketHandler for SimpleWebSocketHandler<F>
88where
89 F: Fn(ConnectionId, Arc<WebSocketConnection>) -> Fut + Send + Sync + 'static,
90 Fut: std::future::Future<Output = ()> + Send,
91{
92 async fn handle_connection(&self, id: ConnectionId, connection: Arc<WebSocketConnection>) {
93 (self.handler)(id, connection).await;
94 }
95}
96
97#[macro_export]
100macro_rules! websocket_handler {
101 (|$id:ident: ConnectionId, $conn:ident: Arc<WebSocketConnection>| $body:expr) => {
102 SimpleWebSocketHandler::new(
103 |$id: ConnectionId, $conn: Arc<WebSocketConnection>| async move { $body },
104 )
105 };
106}