add autoreconnect, wisp_mux 1.2.0

This commit is contained in:
Toshit Chawda 2024-03-08 22:40:15 -08:00
parent 5b4fb1392a
commit a8709255b2
20 changed files with 404 additions and 333 deletions

View file

@ -1,9 +1,10 @@
use crate::*;
use wasm_bindgen::prelude::*;
use hyper::rt::Executor;
use hyper::{header::HeaderValue, Uri};
use js_sys::{Array, Object};
use std::future::Future;
use wisp_mux::{CloseReason, WispError};
#[wasm_bindgen]
extern "C" {
@ -186,3 +187,39 @@ pub fn get_url_port(url: &Uri) -> Result<u16, JsError> {
Ok(80)
}
}
pub async fn make_mux(url: &str) -> Result<(ClientMux<WebSocketWrapper>, impl Future<Output = Result<(), WispError>>), WispError> {
let (wtx, wrx) = WebSocketWrapper::connect(url, vec![])
.await
.map_err(|_| WispError::WsImplSocketClosed)?;
wtx.wait_for_open().await;
let mux = ClientMux::new(wrx, wtx).await?;
Ok(mux)
}
pub fn spawn_mux_fut(mux: Arc<RwLock<ClientMux<WebSocketWrapper>>>, fut: impl Future<Output = Result<(), WispError>> + 'static, url: String) {
wasm_bindgen_futures::spawn_local(async move {
if let Err(e) = fut.await {
error!("epoxy: error in mux future, restarting: {:?}", e);
while let Err(e) = replace_mux(mux.clone(), &url).await {
error!("epoxy: failed to restart mux future: {:?}", e);
wasmtimer::tokio::sleep(std::time::Duration::from_millis(500)).await;
}
}
debug!("epoxy: mux future exited");
});
}
pub async fn replace_mux(
mux: Arc<RwLock<ClientMux<WebSocketWrapper>>>,
url: &str,
) -> Result<(), WispError> {
let (mux_replace, fut) = make_mux(url).await?;
let mut mux_write = mux.write().await;
mux_write.close(CloseReason::Unknown).await;
*mux_write = mux_replace;
drop(mux_write);
spawn_mux_fut(mux, fut, url.into());
Ok(())
}