Skip to main content

zero_client/
tokio_transport.rs

1//! A scheduler and a WebSocket transport on tokio, behind the
2//! `tokio-transport` feature, for apps that don't bring their own.
3//!
4//! The client is single-threaded, so both run on a tokio
5//! [`LocalSet`](tokio::task::LocalSet): make the client, and call it, from
6//! inside one.
7//!
8//! ```no_run
9//! # use std::{rc::Rc, sync::Arc};
10//! # use zero_client::{client::{Zero, ZeroOptions}, schema::Schema};
11//! # use zero_client::tokio_transport::{TokioScheduler, TokioSocketFactory};
12//! # async fn run(schema: Arc<Schema>) -> Result<(), zero_client::client::Error> {
13//! let local = tokio::task::LocalSet::new();
14//! local
15//!     .run_until(async {
16//!         let zero = Zero::new(
17//!             schema,
18//!             (),
19//!             Vec::new(),
20//!             ZeroOptions {
21//!                 cache_url: Some("https://zero.example.com".to_owned()),
22//!                 ..ZeroOptions::default()
23//!             },
24//!             Rc::new(TokioScheduler::new()),
25//!             Some(Rc::new(TokioSocketFactory::new())),
26//!         )?;
27//!         // Materialize views, mutate, and keep the LocalSet running.
28//!         # drop(zero);
29//!         Ok(())
30//!     })
31//!     .await
32//! # }
33//! ```
34//!
35//! `wss://` needs the `tls` feature too: rustls on the `ring` crypto
36//! provider, with the Mozilla root certificates (`webpki-roots`). Without
37//! it, a `wss://` connection fails as a close with code 1006, as a browser
38//! reports a socket it couldn't open.
39//!
40//! A frame or message from the server may be up to 64 MB, as in zero-swift's
41//! transports; a larger one closes the socket with 1006. A browser has no
42//! limit, but tungstenite's default of 16 MB a frame would close the socket
43//! on a large poke that zero-cache sends as one frame.
44
45use 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
60/// The clock and timers of the client on tokio: timers are local tasks, and
61/// follow-ups to API calls run as a local task spawned when the call is
62/// done, so they run after the caller's synchronous code, as JS microtasks
63/// do.
64///
65/// Its methods must be called from inside a
66/// [`LocalSet`](tokio::task::LocalSet); they panic otherwise.
67pub struct TokioScheduler {
68    start: Instant,
69}
70
71impl TokioScheduler {
72    /// A scheduler on the current tokio `LocalSet`.
73    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    /// Follows tokio's clock, so a test that pauses tokio's time moves it.
106    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        // tokio's interval needs a period; browsers clamp one too.
121        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/// Opens the client's sync socket with `tokio-tungstenite`, on a local task
139/// per socket. Like [`TokioScheduler`], it must be used from inside a
140/// [`LocalSet`](tokio::task::LocalSet).
141#[derive(Default)]
142pub struct TokioSocketFactory {
143    _private: (),
144}
145
146impl TokioSocketFactory {
147    /// A factory of WebSockets on the current tokio `LocalSet`.
148    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        // The task is gone once the socket closed, and the engine ignores
165        // what it sends after that.
166        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
189/// The browser's code for a socket that closed without a close frame.
190const ABNORMAL_CLOSURE: u16 = 1006;
191
192/// The largest frame and message the socket takes, as in zero-swift.
193const 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                // Closed (or dropped) before it opened: no events.
218                _ = 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                    // A failed write shows up as an error on the next read.
236                    let _ = ws.send(Message::text(text)).await;
237                }
238                // The engine closed the socket, or dropped it.
239                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                // tungstenite answers pings itself.
263                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}