-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'websockets-backend' into feature/wasm32-unknown
- Loading branch information
Showing
11 changed files
with
738 additions
and
678 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
use futures_util::{ | ||
stream::{SplitSink, SplitStream}, | ||
StreamExt, | ||
}; | ||
use tokio::net::TcpStream; | ||
use tokio_tungstenite::{ | ||
connect_async_tls_with_config, tungstenite, Connector, MaybeTlsStream, WebSocketStream, | ||
}; | ||
|
||
use super::GatewayMessage; | ||
use crate::errors::GatewayError; | ||
|
||
#[derive(Debug, Clone)] | ||
pub struct WebSocketBackend; | ||
|
||
// These could be made into inherent associated types when that's stabilized | ||
pub type WsSink = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, tungstenite::Message>; | ||
pub type WsStream = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>; | ||
|
||
impl WebSocketBackend { | ||
pub async fn connect( | ||
websocket_url: &str, | ||
) -> Result<(WsSink, WsStream), crate::errors::GatewayError> { | ||
let mut roots = rustls::RootCertStore::empty(); | ||
for cert in rustls_native_certs::load_native_certs().expect("could not load platform certs") | ||
{ | ||
roots.add(&rustls::Certificate(cert.0)).unwrap(); | ||
} | ||
let (websocket_stream, _) = match connect_async_tls_with_config( | ||
websocket_url, | ||
None, | ||
false, | ||
Some(Connector::Rustls( | ||
rustls::ClientConfig::builder() | ||
.with_safe_defaults() | ||
.with_root_certificates(roots) | ||
.with_no_client_auth() | ||
.into(), | ||
)), | ||
) | ||
.await | ||
{ | ||
Ok(websocket_stream) => websocket_stream, | ||
Err(e) => { | ||
return Err(GatewayError::CannotConnect { | ||
error: e.to_string(), | ||
}) | ||
} | ||
}; | ||
|
||
Ok(websocket_stream.split()) | ||
} | ||
} | ||
|
||
impl From<GatewayMessage> for tungstenite::Message { | ||
fn from(message: GatewayMessage) -> Self { | ||
Self::Text(message.0) | ||
} | ||
} | ||
|
||
impl From<tungstenite::Message> for GatewayMessage { | ||
fn from(value: tungstenite::Message) -> Self { | ||
Self(value.to_string()) | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.