zero_client/
tokio_transport.rs1use crate::client::{
46 Scheduler, SocketConnection, SocketEvents, SocketFactory, SocketMessage, Timer, timer_delay,
47};
48use futures_util::{SinkExt, StreamExt};
49use std::rc::Rc;
50use std::time::{Duration, SystemTime, UNIX_EPOCH};
51use tokio::sync::mpsc;
52use tokio::task::{AbortHandle, spawn_local};
53use tokio::time::{Instant, MissedTickBehavior};
54use tokio_tungstenite::tungstenite::client::IntoClientRequest;
55use tokio_tungstenite::tungstenite::http::HeaderValue;
56use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
57use tokio_tungstenite::tungstenite::protocol::{CloseFrame, WebSocketConfig};
58use tokio_tungstenite::tungstenite::{self, Message};
59
60pub struct TokioScheduler {
68 start: Instant,
69}
70
71impl TokioScheduler {
72 pub fn new() -> Self {
74 TokioScheduler {
75 start: Instant::now(),
76 }
77 }
78}
79
80impl Default for TokioScheduler {
81 fn default() -> Self {
82 Self::new()
83 }
84}
85
86fn delay(ms: f64) -> Duration {
87 Duration::from_secs_f64(timer_delay(ms) / 1000.0)
88}
89
90struct TokioTimer(AbortHandle);
91
92impl Timer for TokioTimer {
93 fn cancel(&self) {
94 self.0.abort();
95 }
96}
97
98impl Scheduler for TokioScheduler {
99 fn now(&self) -> f64 {
100 SystemTime::now()
101 .duration_since(UNIX_EPOCH)
102 .map_or(0.0, |d| d.as_millis() as f64)
103 }
104
105 fn monotonic_now(&self) -> f64 {
107 self.start.elapsed().as_secs_f64() * 1000.0
108 }
109
110 fn schedule(&self, ms: f64, action: Box<dyn FnOnce()>) -> Box<dyn Timer> {
111 let d = delay(ms);
112 let task = spawn_local(async move {
113 tokio::time::sleep(d).await;
114 action();
115 });
116 Box::new(TokioTimer(task.abort_handle()))
117 }
118
119 fn schedule_repeating(&self, ms: f64, mut action: Box<dyn FnMut()>) -> Box<dyn Timer> {
120 let period = delay(ms).max(Duration::from_millis(1));
122 let task = spawn_local(async move {
123 let mut interval = tokio::time::interval_at(Instant::now() + period, period);
124 interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
125 loop {
126 interval.tick().await;
127 action();
128 }
129 });
130 Box::new(TokioTimer(task.abort_handle()))
131 }
132
133 fn checkpoint(&self, action: Box<dyn FnOnce()>) {
134 spawn_local(async move { action() });
135 }
136}
137
138#[derive(Default)]
142pub struct TokioSocketFactory {
143 _private: (),
144}
145
146impl TokioSocketFactory {
147 pub fn new() -> Self {
149 Self::default()
150 }
151}
152
153enum Command {
154 Send(String),
155 Close(Option<u16>),
156}
157
158struct TokioSocket {
159 commands: mpsc::UnboundedSender<Command>,
160}
161
162impl SocketConnection for TokioSocket {
163 fn send(&self, text: &str) {
164 let _ = self.commands.send(Command::Send(text.to_owned()));
167 }
168
169 fn close(&self, code: Option<u16>) {
170 let _ = self.commands.send(Command::Close(code));
171 }
172}
173
174impl SocketFactory for TokioSocketFactory {
175 fn open(
176 &self,
177 url: &str,
178 sec_protocol: Option<&str>,
179 events: Rc<dyn SocketEvents>,
180 ) -> Box<dyn SocketConnection> {
181 let (commands, receiver) = mpsc::unbounded_channel();
182 let url = url.to_owned();
183 let sec_protocol = sec_protocol.map(str::to_owned);
184 spawn_local(run_socket(url, sec_protocol, events, receiver));
185 Box::new(TokioSocket { commands })
186 }
187}
188
189const ABNORMAL_CLOSURE: u16 = 1006;
191
192const MAX_MESSAGE_SIZE: usize = 64 << 20;
194
195async fn run_socket(
196 url: String,
197 sec_protocol: Option<String>,
198 events: Rc<dyn SocketEvents>,
199 mut commands: mpsc::UnboundedReceiver<Command>,
200) {
201 let request = (|| -> Result<_, tungstenite::Error> {
202 let mut request = url.as_str().into_client_request()?;
203 if let Some(p) = &sec_protocol {
204 let value = HeaderValue::from_str(p).map_err(tungstenite::http::Error::from)?;
205 request
206 .headers_mut()
207 .insert("Sec-WebSocket-Protocol", value);
208 }
209 Ok(request)
210 })();
211 let connected = match request {
212 Ok(request) => {
213 tokio::select! {
214 r = tokio_tungstenite::connect_async_with_config(request, Some(config()), false) => {
215 r.map(|(ws, _)| ws)
216 }
217 _ = commands.recv() => return,
219 }
220 }
221 Err(e) => Err(e),
222 };
223 let mut ws = match connected {
224 Ok(ws) => ws,
225 Err(e) => {
226 events.did_close(ABNORMAL_CLOSURE, &e.to_string(), false);
227 return;
228 }
229 };
230 events.did_open();
231 loop {
232 tokio::select! {
233 command = commands.recv() => match command {
234 Some(Command::Send(text)) => {
235 let _ = ws.send(Message::text(text)).await;
237 }
238 Some(Command::Close(code)) => {
240 let _ = ws.close(close_frame(code)).await;
241 return;
242 }
243 None => {
244 let _ = ws.close(None).await;
245 return;
246 }
247 },
248 message = ws.next() => match message {
249 Some(Ok(Message::Text(text))) => {
250 events.did_receive(SocketMessage::Text(text.as_str().to_owned()));
251 }
252 Some(Ok(Message::Binary(bytes))) => {
253 events.did_receive(SocketMessage::Binary(bytes.to_vec()));
254 }
255 Some(Ok(Message::Close(frame))) => {
256 let (code, reason) = frame.map_or((1005, String::new()), |f| {
257 (u16::from(f.code), f.reason.as_str().to_owned())
258 });
259 events.did_close(code, &reason, true);
260 return;
261 }
262 Some(Ok(_)) => {}
264 Some(Err(e)) => {
265 events.did_close(ABNORMAL_CLOSURE, &e.to_string(), false);
266 return;
267 }
268 None => {
269 events.did_close(ABNORMAL_CLOSURE, "", false);
270 return;
271 }
272 },
273 }
274 }
275}
276
277fn config() -> WebSocketConfig {
278 WebSocketConfig::default()
279 .max_frame_size(Some(MAX_MESSAGE_SIZE))
280 .max_message_size(Some(MAX_MESSAGE_SIZE))
281}
282
283fn close_frame(code: Option<u16>) -> Option<CloseFrame> {
284 code.map(|c| CloseFrame {
285 code: CloseCode::from(c),
286 reason: "".into(),
287 })
288}