use futures::{SinkExt, StreamExt};
use std::net::SocketAddr;
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use std::{collections::HashMap, env};
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
use tokio::sync::RwLock;
use tokio_stream::wrappers::UnboundedReceiverStream;
use warp::ws::Message;
use warp::Filter;
type Clients = Arc<RwLock<HashMap<usize, UnboundedSender<Message>>>>;
static NEXT_UID: AtomicUsize = AtomicUsize::new(0);
pub async fn run_reload_server(host: String, port: u16) {
let host = if host == "localhost" {
"127.0.0.1".to_string()
} else {
host
};
let addr: SocketAddr = format!("{}:{}", host, port).parse().unwrap();
let clients = Clients::default();
let clients = warp::any().map(move || clients.clone());
let command = warp::path("send")
.and(clients.clone())
.then(|clients: Clients| async move {
for (_id, tx) in clients.read().await.iter() {
let _ = tx.send(Message::text("reload"));
}
"sent".to_string()
});
let receive = warp::path("receive").and(warp::ws()).and(clients).map(
|ws: warp::ws::Ws, clients: Clients| {
ws.on_upgrade(|ws| async move {
let id = NEXT_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (mut ws_tx, mut ws_rx) = ws.split();
let (tx, rx) = unbounded_channel();
let mut rx = UnboundedReceiverStream::new(rx);
tokio::task::spawn(async move {
while let Some(message) = rx.next().await {
let _ = ws_tx.send(message).await;
}
});
clients.write().await.insert(id, tx);
while ws_rx.next().await.is_some() {
continue;
}
clients.write().await.remove(&id);
})
},
);
let routes = command.or(receive);
warp::serve(routes).run(addr).await
}
pub fn order_reload(host: String, port: u16) {
if env::var("PERSEUS_USE_RELOAD_SERVER").is_ok() {
tokio::task::spawn(async move {
let _ = reqwest::get(&format!("http://{}:{}/send", host, port)).await;
});
}
}