minor changes

This commit is contained in:
Toshit Chawda 2024-01-14 21:44:27 -08:00
parent 1b7181d78f
commit f035e51256
No known key found for this signature in database
GPG key ID: 91480ED99E2B3D9D
3 changed files with 140 additions and 97 deletions

View file

@ -2,12 +2,13 @@
#[macro_use] #[macro_use]
mod utils; mod utils;
mod tokioio; mod tokioio;
mod wrappers;
mod websocket; mod websocket;
mod wrappers;
use tokioio::TokioIo; use tokioio::TokioIo;
use utils::{ReplaceErr, UriExt}; use utils::{ReplaceErr, UriExt};
use wrappers::{IncomingBody, WsStreamWrapper}; use wrappers::{IncomingBody, WsStreamWrapper};
use websocket::EpxWebSocket;
use std::sync::Arc; use std::sync::Arc;
@ -15,12 +16,8 @@ use async_compression::tokio::bufread as async_comp;
use bytes::Bytes; use bytes::Bytes;
use futures_util::StreamExt; use futures_util::StreamExt;
use http::{uri, HeaderName, HeaderValue, Request, Response}; use http::{uri, HeaderName, HeaderValue, Request, Response};
use hyper::{ use hyper::{body::Incoming, client::conn::http1::Builder, Uri};
body::Incoming, use js_sys::{Function, Array, Object, Reflect, Uint8Array};
client::conn::http1::Builder,
Uri,
};
use js_sys::{Array, Object, Reflect, Uint8Array};
use penguin_mux_wasm::{Multiplexor, MuxStream}; use penguin_mux_wasm::{Multiplexor, MuxStream};
use tokio_rustls::{client::TlsStream, rustls, rustls::RootCertStore, TlsConnector}; use tokio_rustls::{client::TlsStream, rustls, rustls::RootCertStore, TlsConnector};
use tokio_util::{ use tokio_util::{
@ -163,10 +160,6 @@ impl EpoxyClient {
redirect_limit, redirect_limit,
}) })
} }
#[wasm_bindgen]
pub fn ptr(&mut self) -> *mut EpoxyClient {
self as *mut Self
}
async fn get_http_io(&self, url: &Uri) -> Result<EpxStream, JsError> { async fn get_http_io(&self, url: &Uri) -> Result<EpxStream, JsError> {
let url_host = url.host().replace_err("URL must have a host")?; let url_host = url.host().replace_err("URL must have a host")?;
@ -221,6 +214,21 @@ impl EpoxyClient {
} }
} }
// shut up
#[allow(clippy::too_many_arguments)]
pub async fn connect_ws(
&self,
onopen: Function,
onclose: Function,
onerror: Function,
onmessage: Function,
url: String,
protocols: Vec<String>,
origin: String,
) -> Result<EpxWebSocket, JsError> {
EpxWebSocket::connect(self, onopen, onclose, onerror, onmessage, url, protocols, origin).await
}
pub async fn fetch(&self, url: String, options: Object) -> Result<web_sys::Response, JsError> { pub async fn fetch(&self, url: String, options: Object) -> Result<web_sys::Response, JsError> {
let uri = url.parse::<uri::Uri>().replace_err("Failed to parse URL")?; let uri = url.parse::<uri::Uri>().replace_err("Failed to parse URL")?;
let uri_scheme = uri.scheme().replace_err("URL must have a scheme")?; let uri_scheme = uri.scheme().replace_err("URL must have a scheme")?;

View file

@ -12,7 +12,7 @@
const tconn0 = performance.now(); const tconn0 = performance.now();
// args: websocket url, user agent, redirect limit // args: websocket url, user agent, redirect limit
let wstcp = await new wasm_bindgen.WsTcp("wss://localhost:4000", navigator.userAgent, 10); let epoxy = await new wasm_bindgen.EpoxyClient("wss://localhost:4000", navigator.userAgent, 10);
const tconn1 = performance.now(); const tconn1 = performance.now();
console.warn(`conn establish took ${tconn1 - tconn0} ms or ${(tconn1 - tconn0) / 1000} s`); console.warn(`conn establish took ${tconn1 - tconn0} ms or ${(tconn1 - tconn0) / 1000} s`);
@ -25,14 +25,14 @@
["https://httpbin.org/redirect/11", {}], ["https://httpbin.org/redirect/11", {}],
["https://httpbin.org/redirect/1", { redirect: "manual" }] ["https://httpbin.org/redirect/1", { redirect: "manual" }]
]) { ]) {
let resp = await wstcp.fetch(url[0], url[1]); let resp = await epoxy.fetch(url[0], url[1]);
console.warn(url, resp, Object.fromEntries(resp.headers)); console.warn(url, resp, Object.fromEntries(resp.headers));
console.warn(await resp.text()); console.warn(await resp.text());
} }
} else if (should_perf_test) { } else if (should_perf_test) {
const test_mux = async (url) => { const test_mux = async (url) => {
const t0 = performance.now(); const t0 = performance.now();
await wstcp.fetch(url); await epoxy.fetch(url);
const t1 = performance.now(); const t1 = performance.now();
return t1 - t0; return t1 - t0;
}; };
@ -62,10 +62,18 @@
console.warn(`avg native (10) took ${total_native} ms or ${total_native / 1000} s`); console.warn(`avg native (10) took ${total_native} ms or ${total_native / 1000} s`);
console.warn(`mux - native: ${total_mux - total_native} ms or ${(total_mux - total_native) / 1000} s`); console.warn(`mux - native: ${total_mux - total_native} ms or ${(total_mux - total_native) / 1000} s`);
} else if (should_ws_test) { } else if (should_ws_test) {
let ws = await new wasm_bindgen.WsWebSocket(() => console.log("opened"), () => console.log("closed"), msg => console.log(msg), wstcp, "ws://localhost:9000", [], "localhost"); let ws = await epoxy.connect_ws(
() => console.log("opened"),
() => console.log("closed"),
err => console.error(err),
msg => console.log(msg),
"ws://localhost:9000",
[],
"localhost"
);
await ws.send("data"); await ws.send("data");
} else { } else {
let resp = await wstcp.fetch("https://httpbin.org/get"); let resp = await epoxy.fetch("https://httpbin.org/get");
console.warn(resp, Object.fromEntries(resp.headers)); console.warn(resp, Object.fromEntries(resp.headers));
console.warn(await resp.text()); console.warn(await resp.text());
} }

View file

@ -20,20 +20,31 @@ enum EpxMsg {
#[wasm_bindgen] #[wasm_bindgen]
pub struct EpxWebSocket { pub struct EpxWebSocket {
msg_sender: mpsc::Sender<EpxMsg>, msg_sender: mpsc::Sender<EpxMsg>,
onerror: Function,
} }
#[wasm_bindgen] #[wasm_bindgen]
impl EpxWebSocket { impl EpxWebSocket {
#[wasm_bindgen(constructor)] #[wasm_bindgen(constructor)]
pub fn new() -> Result<EpxWebSocket, JsError> {
Err(jerr!("Use EpoxyClient.connect_ws() instead."))
}
// shut up
#[allow(clippy::too_many_arguments)]
pub async fn connect( pub async fn connect(
tcp: &EpoxyClient,
onopen: Function, onopen: Function,
onclose: Function, onclose: Function,
onerror: Function,
onmessage: Function, onmessage: Function,
tcp: &EpoxyClient,
url: String, url: String,
protocols: Vec<String>, protocols: Vec<String>,
origin: String, origin: String,
) -> Result<EpxWebSocket, JsError> { ) -> Result<EpxWebSocket, JsError> {
let onerr = onerror.clone();
let ret: Result<EpxWebSocket, JsError> = async move {
let url = Uri::try_from(url).replace_err("Failed to parse URL")?; let url = Uri::try_from(url).replace_err("Failed to parse URL")?;
let host = url.host().replace_err("URL must have a host")?; let host = url.host().replace_err("URL must have a host")?;
@ -83,7 +94,6 @@ impl EpxWebSocket {
tokio::select! { tokio::select! {
frame = ws.read_frame() => { frame = ws.read_frame() => {
if let Ok(frame) = frame { if let Ok(frame) = frame {
error!("hiii");
match frame.opcode { match frame.opcode {
OpCode::Text => { OpCode::Text => {
if let Ok(str) = from_utf8(&frame.payload) { if let Ok(str) = from_utf8(&frame.payload) {
@ -121,7 +131,8 @@ impl EpxWebSocket {
} }
} }
} }
let _ = ws.write_frame(Frame::close(CloseCode::Normal.into(), b"")) let _ = ws
.write_frame(Frame::close(CloseCode::Normal.into(), b""))
.await; .await;
}); });
@ -129,14 +140,30 @@ impl EpxWebSocket {
.call0(&Object::default()) .call0(&Object::default())
.replace_err("Failed to call onopen")?; .replace_err("Failed to call onopen")?;
Ok(Self { msg_sender }) Ok(Self { msg_sender, onerror })
}.await;
if let Err(ret) = ret {
let _ = onerr.call1(&JsValue::null(), &jval!(ret.clone()));
Err(ret)
} else {
ret
}
} }
#[wasm_bindgen] #[wasm_bindgen]
pub async fn send(&mut self, payload: String) -> Result<(), JsError> { pub async fn send(&mut self, payload: String) -> Result<(), JsError> {
let onerr = self.onerror.clone();
let ret: Result<(), JsError> = async move {
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
self.msg_sender.send(EpxMsg::SendText(payload, tx)).await?; self.msg_sender.send(EpxMsg::SendText(payload, tx)).await?;
Ok(rx.await??) Ok(rx.await??)
}.await;
if let Err(ret) = ret {
let _ = onerr.call1(&JsValue::null(), &jval!(ret.clone()));
Err(ret)
} else {
ret
}
} }
#[wasm_bindgen] #[wasm_bindgen]