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