Async handler

This commit is contained in:
2026-02-19 04:15:31 +01:00
parent 0940731bd1
commit bad32bfc36
3 changed files with 24 additions and 9 deletions
+3 -1
View File
@@ -18,7 +18,9 @@ async fn main() -> session_rs::Result<()> {
session.request::<Data>(()).await?; session.request::<Data>(()).await?;
session.on::<Data>(|i, d| println!("Ok {i} {d:?}")).await; session
.on::<Data, _>(async |i, d| println!("Ok {i} {d:?}"))
.await;
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await; tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
+5 -1
View File
@@ -1,3 +1,5 @@
use std::pin::Pin;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub mod server; pub mod server;
@@ -5,10 +7,12 @@ pub mod session;
pub mod ws; pub mod ws;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
pub type BoxFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
pub type MethodHandler = Box<dyn Fn(u32, serde_json::Value) -> BoxFuture<'static> + Send + Sync>;
pub trait Method { pub trait Method {
const NAME: &'static str; const NAME: &'static str;
type Request: Serialize + for<'de> Deserialize<'de>; type Request: Serialize + for<'de> Deserialize<'de> + Send + Sync;
type Response: Serialize + for<'de> Deserialize<'de>; type Response: Serialize + for<'de> Deserialize<'de>;
} }
+14 -5
View File
@@ -3,7 +3,7 @@ use std::{collections::HashMap, sync::Arc};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use crate::{GenericMethod, Method, ws::WebSocket}; use crate::{GenericMethod, Method, MethodHandler, ws::WebSocket};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", tag = "type")] #[serde(rename_all = "lowercase", tag = "type")]
@@ -27,7 +27,7 @@ pub enum Message<M: Method> {
pub struct Session { pub struct Session {
pub ws: WebSocket, pub ws: WebSocket,
id: Arc<Mutex<u32>>, id: Arc<Mutex<u32>>,
methods: Arc<Mutex<HashMap<String, Box<dyn Fn(u32, serde_json::Value) + Send + Sync>>>>, methods: Arc<Mutex<HashMap<String, MethodHandler>>>,
} }
impl Session { impl Session {
@@ -68,7 +68,7 @@ impl Session {
match msg { match msg {
Message::Request { id, method, data } => { Message::Request { id, method, data } => {
if let Some(m) = s.methods.lock().await.get(&method) { if let Some(m) = s.methods.lock().await.get(&method) {
(m)(id, data) (m)(id, data).await
} }
} }
_ => {} _ => {}
@@ -81,13 +81,22 @@ impl Session {
}); });
} }
pub async fn on<M: Method>(&self, handler: impl Fn(u32, M::Request) + Send + Sync + 'static) { pub async fn on<M: Method, Fut: Future<Output = ()> + Send + 'static>(
&self,
handler: impl Fn(u32, M::Request) -> Fut + Send + Sync + 'static,
) {
let handler = Arc::new(handler);
self.methods.lock().await.insert( self.methods.lock().await.insert(
M::NAME.to_string(), M::NAME.to_string(),
Box::new(move |id, value| { Box::new(move |id, value| {
let handler = Arc::clone(&handler);
Box::pin(async move {
if let Ok(req) = serde_json::from_value(value) { if let Ok(req) = serde_json::from_value(value) {
(handler)(id, req) handler(id, req).await;
} }
})
}), }),
); );
} }