perseus_cli/
reload_server.rs

1use futures::{SinkExt, StreamExt};
2use std::net::SocketAddr;
3use std::sync::atomic::AtomicUsize;
4use std::sync::Arc;
5use std::{collections::HashMap, env};
6use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
7use tokio::sync::RwLock;
8use tokio_stream::wrappers::UnboundedReceiverStream;
9use warp::ws::Message;
10use warp::Filter;
11
12/// A representation of the clients to the server. These are only the clients
13/// that will be told about reloads, any user can command a reload over the HTTP
14/// endpoint (unauthenticated because this is a development server).
15type Clients = Arc<RwLock<HashMap<usize, UnboundedSender<Message>>>>;
16
17/// A simple counter that can be incremented from anywhere. This will be used as
18/// the source of the next user ID. This is an atomic `usize` for maximum
19/// platform portability (see the Rust docs on atomic primitives).
20static NEXT_UID: AtomicUsize = AtomicUsize::new(0);
21
22/// Runs the reload server, which is used to instruct the browser on when to
23/// reload for updates.
24pub async fn run_reload_server(host: String, port: u16) {
25    // Parse `localhost` into `127.0.0.1` (picky Rust `std`)
26    let host = if host == "localhost" {
27        "127.0.0.1".to_string()
28    } else {
29        host
30    };
31    // Parse the host and port into an address
32    let addr: SocketAddr = format!("{}:{}", host, port).parse().unwrap();
33
34    let clients = Clients::default();
35    let clients = warp::any().map(move || clients.clone());
36
37    // This will be used by the CLI to order reloads
38    let command = warp::path("send")
39        .and(clients.clone())
40        .then(|clients: Clients| async move {
41            // Iterate through all the clients and tell them all to reload
42            for (_id, tx) in clients.read().await.iter() {
43                // We don't care if this fails, that means the client has disconnected and the
44                // disconnection code will be running
45                let _ = tx.send(Message::text("reload"));
46            }
47
48            "sent".to_string()
49        });
50    // This will be used by the browser to listen for reload orders
51    let receive = warp::path("receive").and(warp::ws()).and(clients).map(
52        |ws: warp::ws::Ws, clients: Clients| {
53            // This code will run once the WS handshake completes
54            ws.on_upgrade(|ws| async move {
55                // Assign a new ID to this user
56                // This nifty operation just gets the current value and then increments
57                let id = NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
58                // Split out their sender/receiver
59                let (mut ws_tx, mut ws_rx) = ws.split();
60                // Use an unbounded channel as an intermediary to the WebSocket
61                let (tx, rx) = unbounded_channel();
62                let mut rx = UnboundedReceiverStream::new(rx);
63                tokio::task::spawn(async move {
64                    // Whenever a message come sin on that intermediary channel, we'll just relay it
65                    // to the client
66                    while let Some(message) = rx.next().await {
67                        let _ = ws_tx.send(message).await;
68                    }
69                });
70
71                // Save the sender and their intermediary channel
72                clients.write().await.insert(id, tx);
73
74                // Because we don't accept messages from listening clients, we'll just hold a
75                // loop until the client disconnects Then, this will become
76                // `None` and we'll move on
77                while ws_rx.next().await.is_some() {
78                    continue;
79                }
80
81                // Once we're here, the client has disconnected
82                clients.write().await.remove(&id);
83            })
84        },
85    );
86
87    let routes = command.or(receive);
88    warp::serve(routes).run(addr).await
89}
90
91/// Orders all connected browsers to reload themselves. This spawns a blocking
92/// task through Tokio under the hood. Note that this will only do anything if
93/// `PERSEUS_USE_RELOAD_SERVER` is set to `true`.
94pub fn order_reload(host: String, port: u16) {
95    // This environment variable is only for use by the CLI internally
96    if env::var("PERSEUS_USE_RELOAD_SERVER").is_ok() {
97        tokio::task::spawn(async move {
98            // We don't care if this fails because we have no guarantees that the server is
99            // actually up
100            let _ = reqwest::get(&format!("http://{}:{}/send", host, port)).await;
101        });
102    }
103}