pakem/core/echo/
handler.rs1use crate::core::application::AppState;
2use crate::core::echo::broadcaster::ChannelAuthRequest;
3use crate::core::echo::manager::EchoMessage;
4use axum::{
5 extract::{
6 ws::{Message, WebSocket, WebSocketUpgrade},
7 Query, State,
8 },
9 http::StatusCode,
10 response::IntoResponse,
11 Json,
12};
13use futures::{sink::SinkExt, stream::StreamExt};
14use serde::Deserialize;
15use uuid::Uuid;
16
17#[derive(Debug, Deserialize, Default)]
18pub struct WsQueryParams {
19 pub token: Option<String>,
20}
21
22#[derive(Debug, Deserialize)]
23#[allow(dead_code)]
24struct ClientMessage {
25 event: String,
26 channel: Option<String>,
27 token: Option<String>,
28 data: Option<serde_json::Value>,
29}
30
31pub async fn echo_handler(
32 ws: WebSocketUpgrade,
33 Query(params): Query<WsQueryParams>,
34 State(state): State<AppState>,
35) -> impl IntoResponse {
36 ws.on_upgrade(move |socket| handle_socket(socket, state, params.token))
37}
38
39pub async fn echo_auth_handler(
41 State(state): State<AppState>,
42 headers: axum::http::HeaderMap,
43 Json(mut payload): Json<ChannelAuthRequest>,
44) -> impl IntoResponse {
45 if payload.token.is_none() {
46 if let Some(auth_header) = headers.get(axum::http::header::AUTHORIZATION) {
47 if let Ok(auth_str) = auth_header.to_str() {
48 if auth_str.starts_with("Bearer ") {
49 payload.token = Some(auth_str["Bearer ".len()..].to_string());
50 }
51 }
52 }
53 }
54 let res = state.echo.authenticate_channel(&payload);
55 if res.authorized {
56 (StatusCode::OK, Json(res)).into_response()
57 } else {
58 (StatusCode::FORBIDDEN, Json(res)).into_response()
59 }
60}
61
62async fn handle_socket(socket: WebSocket, state: AppState, connection_token: Option<String>) {
63 let (mut sender, mut receiver) = socket.split();
64 let id = Uuid::new_v4();
65 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<EchoMessage>();
66
67 state.echo.add_connection(id, tx);
69
70 let mut send_task = tokio::spawn(async move {
72 while let Some(msg) = rx.recv().await {
73 let json = serde_json::to_string(&msg).unwrap();
74 if sender.send(Message::Text(json)).await.is_err() {
75 break;
76 }
77 }
78 });
79
80 let echo_manager = state.echo.clone();
82 let conn_id_str = id.to_string();
83 let mut recv_task = tokio::spawn(async move {
84 while let Some(Ok(msg)) = receiver.next().await {
85 if let Message::Text(text) = msg {
86 if let Ok(client_msg) = serde_json::from_str::<ClientMessage>(&text) {
87 match client_msg.event.as_str() {
88 "subscribe" => {
89 if let Some(channel) = client_msg.channel {
90 let auth_token = client_msg
91 .token
92 .as_deref()
93 .or(connection_token.as_deref())
94 .or(Some(&conn_id_str));
95 if echo_manager.is_authorized(&channel, auth_token) {
96 echo_manager.subscribe(id, &channel);
97 }
98 }
99 }
100 "unsubscribe" => {
101 if let Some(channel) = client_msg.channel {
102 echo_manager.unsubscribe(&id, &channel);
103 }
104 }
105 "ping" => {
106 }
108 _ => {}
109 }
110 }
111 }
112 }
113 });
114
115 tokio::select! {
117 _ = (&mut send_task) => recv_task.abort(),
118 _ = (&mut recv_task) => send_task.abort(),
119 };
120
121 state.echo.remove_connection(&id);
123}