1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use std::sync::Arc;
use crate::CloseFrame;
use crate::Error;
use crate::Message;
use crate::Socket;
use async_trait::async_trait;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::sync::Mutex;
#[async_trait]
pub trait SessionExt: Send {
type ID: Send + Sync + Clone + std::fmt::Debug + std::fmt::Display;
type Args: std::fmt::Debug + Send;
type Params: std::fmt::Debug + Send;
fn id(&self) -> &Self::ID;
async fn text(&mut self, text: String) -> Result<(), Error>;
async fn binary(&mut self, bytes: Vec<u8>) -> Result<(), Error>;
async fn call(&mut self, params: Self::Params) -> Result<(), Error>;
}
type CloseReceiver = oneshot::Receiver<Result<Option<CloseFrame>, Error>>;
#[derive(Debug)]
pub struct Session<I: std::fmt::Display + Clone, P: std::fmt::Debug> {
pub id: I,
socket: mpsc::UnboundedSender<Message>,
calls: mpsc::UnboundedSender<P>,
closed: Arc<Mutex<Option<CloseReceiver>>>,
}
impl<I: std::fmt::Display + Clone, P: std::fmt::Debug> std::clone::Clone for Session<I, P> {
fn clone(&self) -> Self {
Self {
id: self.id.clone(),
socket: self.socket.clone(),
calls: self.calls.clone(),
closed: self.closed.clone(),
}
}
}
impl<I: std::fmt::Display + Clone + Send, P: std::fmt::Debug + Send> Session<I, P> {
pub fn create<S: SessionExt<ID = I, Params = P> + 'static>(
session_fn: impl FnOnce(Session<I, P>) -> S,
session_id: I,
socket: Socket,
) -> Self {
let (socket_sender, socket_receiver) = mpsc::unbounded_channel();
let (call_sender, call_receiver) = mpsc::unbounded_channel();
let (closed_sender, closed_receiver) = oneshot::channel();
let handle = Self {
id: session_id.clone(),
socket: socket_sender,
calls: call_sender,
closed: Arc::new(Mutex::new(Some(closed_receiver))),
};
let session = session_fn(handle.clone());
let mut actor =
SessionActor::new(session, session_id, socket_receiver, call_receiver, socket);
tokio::spawn(async move {
let result = actor.run().await;
closed_sender.send(result).unwrap();
});
handle
}
}
impl<I: std::fmt::Display + Clone, P: std::fmt::Debug> Session<I, P> {
#[doc(hidden)]
pub(super) async fn closed(&self) -> Result<Option<CloseFrame>, Error> {
let mut closed = self.closed.lock().await;
let closed = closed
.take()
.expect("someone already called .closed() before");
closed.await.unwrap()
}
pub async fn text(&self, text: String) {
self.socket.send(Message::Text(text)).unwrap();
}
pub async fn binary(&self, bytes: Vec<u8>) {
self.socket.send(Message::Binary(bytes)).unwrap();
}
pub async fn call(&self, params: P) {
self.calls.send(params).unwrap();
}
pub async fn call_with<R: std::fmt::Debug>(
&self,
f: impl FnOnce(oneshot::Sender<R>) -> P,
) -> R {
let (sender, receiver) = oneshot::channel();
let params = f(sender);
self.calls.send(params).unwrap();
let response = receiver.await.unwrap();
response
}
}
pub(crate) struct SessionActor<E: SessionExt> {
pub extension: E,
id: E::ID,
socket_receiver: mpsc::UnboundedReceiver<Message>,
call_receiver: mpsc::UnboundedReceiver<E::Params>,
socket: Socket,
}
impl<E: SessionExt> SessionActor<E> {
pub(crate) fn new(
extension: E,
id: E::ID,
socket_receiver: mpsc::UnboundedReceiver<Message>,
call_receiver: mpsc::UnboundedReceiver<E::Params>,
socket: Socket,
) -> Self {
Self {
id,
extension,
socket_receiver,
call_receiver,
socket,
}
}
pub(crate) async fn run(&mut self) -> Result<Option<CloseFrame>, Error> {
loop {
tokio::select! {
Some(message) = self.socket_receiver.recv() => {
self.socket.send(message.clone()).await;
if let Message::Close(frame) = message {
return Ok(frame)
}
}
Some(params) = self.call_receiver.recv() => {
self.extension.call(params).await?;
}
message = self.socket.recv() => {
match message {
Some(Ok(message)) => match message {
Message::Text(text) => self.extension.text(text).await?,
Message::Binary(bytes) => self.extension.binary(bytes).await?,
Message::Close(frame) => {
return Ok(frame.map(CloseFrame::from))
},
}
Some(Err(error)) => {
tracing::error!(id = %self.id, "connection error: {error}");
}
None => break
};
}
else => break,
}
}
Ok(None)
}
}