Migrated to global websocket state

This commit is contained in:
xeovalyte 2024-04-07 13:58:15 +02:00
parent 683233a4b5
commit 71c5bfd1f8
No known key found for this signature in database
4 changed files with 19 additions and 31 deletions

View File

@ -1,5 +1,3 @@
use application::util::websocket::{server::AppState, server::WebSocketState};
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
@ -8,9 +6,6 @@ async fn main() {
use axum::{routing::get, Router}; use axum::{routing::get, Router};
use leptos::*; use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes}; use leptos_axum::{generate_route_list, LeptosRoutes};
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::{broadcast, Mutex};
application::util::surrealdb::connect() application::util::surrealdb::connect()
.await .await
@ -26,23 +21,12 @@ async fn main() {
let addr = leptos_options.site_addr; let addr = leptos_options.site_addr;
let routes = generate_route_list(App); let routes = generate_route_list(App);
let client_set = Arc::new(Mutex::new(HashSet::<uuid::Uuid>::new()));
let (tx, _rx) = broadcast::channel(100);
let websocket_state = WebSocketState { client_set, tx };
let app_state = AppState {
websocket_state: websocket_state.into(),
routes: routes.clone(),
leptos_options,
};
// build our application with a route // build our application with a route
let app = Router::new() let app = Router::new()
.route("/ws", get(server::websocket_handler)) .route("/ws", get(server::websocket_handler))
.leptos_routes(&app_state, routes, App) .leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler) .fallback(file_and_error_handler)
.with_state(app_state); .with_state(leptos_options);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
logging::log!("listening on http://{}", &addr); logging::log!("listening on http://{}", &addr);

View File

@ -11,6 +11,10 @@ cfg_if::cfg_if! {
#[server(AddParticipant)] #[server(AddParticipant)]
async fn add_participant(name: String, group: String) -> Result<(), ServerFnError> { async fn add_participant(name: String, group: String) -> Result<(), ServerFnError> {
let websocket_sate = &server::WEBSOCKET_STATE;
websocket_sate.tx.send("BOE".to_string()).unwrap();
let created: Vec<schemas::ParticipantRecord> = DB let created: Vec<schemas::ParticipantRecord> = DB
.create("participant") .create("participant")
.content(schemas::NewParticipant { name, group }) .content(schemas::NewParticipant { name, group })

View File

@ -1,8 +1,6 @@
use leptos::*; use leptos::*;
use leptos_router::*; use leptos_router::*;
use crate::util::surrealdb::schemas;
/// Renders the home page of your application. /// Renders the home page of your application.
#[component] #[component]
pub fn HomePage() -> impl IntoView { pub fn HomePage() -> impl IntoView {

View File

@ -1,17 +1,22 @@
use axum::{ use axum::{
extract::{ extract::ws::{Message, WebSocket, WebSocketUpgrade},
ws::{Message, WebSocket, WebSocketUpgrade},
State,
},
response::IntoResponse, response::IntoResponse,
}; };
use futures::{sink::SinkExt, stream::StreamExt}; use futures::{sink::SinkExt, stream::StreamExt};
use leptos::LeptosOptions; use leptos::LeptosOptions;
use leptos_router::RouteListing; use leptos_router::RouteListing;
use once_cell::sync::Lazy;
use tokio::sync::{broadcast, Mutex}; use tokio::sync::{broadcast, Mutex};
use std::{collections::HashSet, sync::Arc}; use std::{collections::HashSet, sync::Arc};
pub static WEBSOCKET_STATE: Lazy<WebSocketState> = Lazy::new(|| {
let client_set = Arc::new(Mutex::new(HashSet::<uuid::Uuid>::new()));
let (tx, _rx) = broadcast::channel(100);
WebSocketState { client_set, tx }
});
#[derive(Clone)] #[derive(Clone)]
pub struct WebSocketState { pub struct WebSocketState {
pub client_set: Arc<Mutex<HashSet<uuid::Uuid>>>, pub client_set: Arc<Mutex<HashSet<uuid::Uuid>>>,
@ -25,15 +30,12 @@ pub struct AppState {
pub routes: Vec<RouteListing>, pub routes: Vec<RouteListing>,
} }
pub async fn websocket_handler( pub async fn websocket_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
ws: WebSocketUpgrade, ws.on_upgrade(|socket| websocket(socket))
State(state): State<AppState>,
) -> impl IntoResponse {
ws.on_upgrade(|socket| websocket(socket, Arc::new(state)))
} }
async fn websocket(stream: WebSocket, state: Arc<AppState>) { async fn websocket(stream: WebSocket) {
let state = &state.websocket_state; let state = &WEBSOCKET_STATE;
let (mut sender, mut receiver) = stream.split(); let (mut sender, mut receiver) = stream.split();