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")]
#[tokio::main]
async fn main() {
@ -8,9 +6,6 @@ async fn main() {
use axum::{routing::get, Router};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::{broadcast, Mutex};
application::util::surrealdb::connect()
.await
@ -26,23 +21,12 @@ async fn main() {
let addr = leptos_options.site_addr;
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
let app = Router::new()
.route("/ws", get(server::websocket_handler))
.leptos_routes(&app_state, routes, App)
.leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler)
.with_state(app_state);
.with_state(leptos_options);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
logging::log!("listening on http://{}", &addr);

View File

@ -11,6 +11,10 @@ cfg_if::cfg_if! {
#[server(AddParticipant)]
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
.create("participant")
.content(schemas::NewParticipant { name, group })

View File

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

View File

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