hashiverse_client_wasm/
wasm_transport.rs1use crate::wasm_bootstrap_provider::WasmBootstrapProvider;
2use anyhow::anyhow;
3use bytes::Bytes;
4use gloo_net::http::Request;
5use hashiverse_lib::transport::bootstrap_provider::bootstrap_provider::BootstrapProvider;
6use hashiverse_lib::transport::ddos::ddos::DdosProtection;
7use hashiverse_lib::transport::ddos::noop_ddos::NoopDdosProtection;
8use hashiverse_lib::transport::transport::{IncomingRequest, TransportFactory, TransportServer};
9use send_wrapper::SendWrapper;
10use std::sync::Arc;
11use tokio_util::sync::CancellationToken;
12
13#[derive(Clone)]
14pub struct WasmTransportFactory {
15 bootstrap_provider: Arc<dyn BootstrapProvider>,
16}
17
18impl WasmTransportFactory {
19 pub fn new(_ddos_protection: Arc<dyn DdosProtection>, bootstrap_provider: Arc<dyn BootstrapProvider>) -> Self {
20 WasmTransportFactory { bootstrap_provider }
21 }
22}
23
24impl Default for WasmTransportFactory {
25 fn default() -> Self {
26 Self::new(NoopDdosProtection::default(), Arc::new(WasmBootstrapProvider::new()))
27 }
28}
29
30pub struct WasmTransportServer {}
31
32#[async_trait::async_trait]
33impl TransportServer for WasmTransportServer {
34 fn get_address(&self) -> &String {
35 panic!("not implemented");
36 }
37
38 async fn listen(&self, _: CancellationToken, _: tokio::sync::mpsc::Sender<IncomingRequest>) -> anyhow::Result<()> {
39 panic!("not implemented");
40 }
41}
42
43#[async_trait::async_trait]
44impl TransportFactory for WasmTransportFactory {
45 async fn get_bootstrap_addresses(&self) -> Vec<String> {
46 self.bootstrap_provider.get_bootstrap_addresses().await
47 }
48
49 async fn create_server(&self, _: &str, _: u16, _: bool) -> anyhow::Result<Arc<dyn TransportServer>> {
50 panic!("not implemented");
51 }
52
53 async fn rpc(&self, address: &str, bytes: Bytes) -> anyhow::Result<Bytes> {
54 let address = format!("https://{}/", address);
55
56 let response_bytes = async {
57 let bytes_uint8array = js_sys::Uint8Array::from(bytes.as_ref());
58 let request = Request::post(&address).header("Accept", "application/octet-stream").body(bytes_uint8array)?;
59
60 let response = request.send().await.map_err(|e| anyhow!("Fetch error: {}", e))?;
61
62 let response_bytes = response.binary().await.map_err(|e| anyhow!("Failed to read response: {}", e))?;
63
64 Ok::<Vec<u8>, anyhow::Error>(response_bytes)
65 };
66
67 let response_bytes = SendWrapper::new(response_bytes).await?;
68
69 Ok(Bytes::from(response_bytes))
70 }
71}