Session types

This commit is contained in:
2026-02-19 02:26:32 +01:00
parent f7f1e97671
commit 0253f15931
2 changed files with 76 additions and 22 deletions
+22 -22
View File
@@ -1,32 +1,32 @@
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use session_rs::session::Session;
use session_rs::ws::{Frame, WebSocket};
#[derive(Debug, Serialize, Deserialize)]
struct Data {}
type Communication = Session<Data, Data, Data, Data, Data>;
#[tokio::main(flavor = "current_thread")]
async fn main() -> session_rs::Result<()> {
let session = Arc::new(WebSocket::connect("127.0.0.1:8080", "/").await?);
let session = Communication::connect("127.0.0.1:8080", "/").await?;
// Spawn read loop
let read_session = Arc::clone(&session);
tokio::spawn(async move {
loop {
match read_session.read().await {
Ok(Frame::Text(text)) => {
println!("Server says: {}", text);
}
Ok(_) => {}
Err(_) => break,
}
}
});
// tokio::spawn({
// let session = session.clone();
// async move {
// loop {
// match session.read().await {
// Ok(Frame::Text(text)) => {
// println!("Server says: {}", text);
// }
// Ok(_) => {}
// Err(_) => break,
// }
// }
// }
// });
// Send a few messages
for i in 0..5 {
println!("sending");
let msg = serde_json::json!({ "hello": i });
session.send(&msg.to_string()).await?;
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
session.request(&Data {}).await?;
session.close().await?;
Ok(())
+54
View File
@@ -37,6 +37,56 @@ pub struct Session<
id: Arc<Mutex<u32>>,
}
impl<
Req: Serialize + for<'a> Deserialize<'a>,
Res: Serialize + for<'a> Deserialize<'a>,
PeerReq: Serialize + for<'a> Deserialize<'a>,
PeerRes: Serialize + for<'a> Deserialize<'a>,
Notification: Serialize + for<'a> Deserialize<'a>,
> Session<Req, Res, PeerReq, PeerRes, Notification>
{
pub fn clone(&self) -> Self {
Self {
_pd: (
PhantomData,
PhantomData,
PhantomData,
PhantomData,
PhantomData,
),
ws: self.ws.clone(),
id: self.id.clone(),
}
}
}
impl<
Req: Serialize + for<'a> Deserialize<'a>,
Res: Serialize + for<'a> Deserialize<'a>,
PeerReq: Serialize + for<'a> Deserialize<'a>,
PeerRes: Serialize + for<'a> Deserialize<'a>,
Notification: Serialize + for<'a> Deserialize<'a>,
> Session<Req, Res, PeerReq, PeerRes, Notification>
{
pub fn from_ws(ws: WebSocket) -> Self {
Self {
_pd: (
PhantomData,
PhantomData,
PhantomData,
PhantomData,
PhantomData,
),
ws,
id: Arc::new(Mutex::new(0)),
}
}
pub async fn connect(addr: &str, path: &str) -> crate::Result<Self> {
Ok(Self::from_ws(WebSocket::connect(addr, path).await?))
}
}
impl<
Req: Serialize + for<'a> Deserialize<'a>,
Res: Serialize + for<'a> Deserialize<'a>,
@@ -87,4 +137,8 @@ impl<
pub async fn notify(&self, data: &Res) -> crate::Result<()> {
self.send(SessionMessageKind::Notification, data).await
}
pub async fn close(&self) -> crate::Result<()> {
Ok(self.ws.close().await?)
}
}