Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extracts core WebSocket upgrade logic for integration into other libraries #45

Merged
merged 16 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions ratchet_core/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@

use crate::errors::Error;
use crate::ext::NoExtProvider;
use crate::handshake::{ProtocolRegistry, UpgradedServer};
use crate::handshake::{SubprotocolRegistry, UpgradedServer};
use crate::{subscribe_with, TryIntoRequest, UpgradedClient, WebSocketConfig, WebSocketStream};
use ratchet_ext::ExtensionProvider;
use std::borrow::Cow;

/// A builder to construct WebSocket clients.
///
Expand All @@ -28,15 +27,15 @@ use std::borrow::Cow;
pub struct WebSocketClientBuilder<E> {
config: Option<WebSocketConfig>,
extension: E,
subprotocols: ProtocolRegistry,
subprotocols: SubprotocolRegistry,
}

impl Default for WebSocketClientBuilder<NoExtProvider> {
fn default() -> Self {
WebSocketClientBuilder {
config: None,
extension: NoExtProvider,
subprotocols: ProtocolRegistry::default(),
subprotocols: SubprotocolRegistry::default(),
}
}
}
Expand Down Expand Up @@ -95,9 +94,9 @@ impl<E> WebSocketClientBuilder<E> {
pub fn subprotocols<I>(mut self, subprotocols: I) -> Result<Self, Error>
where
I: IntoIterator,
I::Item: Into<Cow<'static, str>>,
I::Item: Into<String>,
{
self.subprotocols = ProtocolRegistry::new(subprotocols)?;
self.subprotocols = SubprotocolRegistry::new(subprotocols)?;
Ok(self)
}
}
Expand All @@ -110,7 +109,7 @@ impl<E> WebSocketClientBuilder<E> {
#[derive(Debug)]
pub struct WebSocketServerBuilder<E> {
config: Option<WebSocketConfig>,
subprotocols: ProtocolRegistry,
subprotocols: SubprotocolRegistry,
extension: E,
}

Expand All @@ -119,7 +118,7 @@ impl Default for WebSocketServerBuilder<NoExtProvider> {
WebSocketServerBuilder {
config: None,
extension: NoExtProvider,
subprotocols: ProtocolRegistry::default(),
subprotocols: SubprotocolRegistry::default(),
}
}
}
Expand Down Expand Up @@ -168,9 +167,9 @@ impl<E> WebSocketServerBuilder<E> {
pub fn subprotocols<I>(mut self, subprotocols: I) -> Result<Self, Error>
where
I: IntoIterator,
I::Item: Into<Cow<'static, str>>,
I::Item: Into<String>,
{
self.subprotocols = ProtocolRegistry::new(subprotocols)?;
self.subprotocols = SubprotocolRegistry::new(subprotocols)?;
Ok(self)
}
}
13 changes: 6 additions & 7 deletions ratchet_core/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use crate::protocol::{CloseCodeParseErr, OpCodeParseErr};
use http::header::{HeaderName, InvalidHeaderValue};
use http::status::InvalidStatusCode;
use http::uri::InvalidUri;
use http::StatusCode;
use std::any::Any;
use std::error::Error as StdError;
use std::fmt::{Display, Formatter};
Expand Down Expand Up @@ -156,8 +155,8 @@ pub enum HttpError {
#[error("Redirected: `{0}`")]
Redirected(String),
/// The peer returned with a status code other than 101.
#[error("Status code: `{0}`")]
Status(StatusCode),
#[error("Status code: `{0:?}`")]
Status(Option<u16>),
/// An invalid HTTP version was received in a request.
#[error("Invalid HTTP version: `{0:?}`")]
HttpVersion(Option<u8>),
Expand Down Expand Up @@ -269,14 +268,11 @@ pub enum CloseCause {
}

/// WebSocket protocol errors.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Error)]
#[derive(Clone, Debug, Eq, PartialEq, Error)]
pub enum ProtocolError {
/// Invalid encoding was received.
#[error("Not valid UTF-8 encoding")]
Encoding,
/// A peer selected a protocol that was not sent.
#[error("Received an unknown subprotocol")]
UnknownProtocol,
/// An invalid OpCode was received.
#[error("Bad OpCode: `{0}`")]
OpCode(OpCodeParseErr),
Expand Down Expand Up @@ -310,6 +306,9 @@ pub enum ProtocolError {
/// An invalid control frame was received.
#[error("Received an invalid control frame")]
InvalidControlFrame,
/// Failed to build subprotocol header.
#[error("Invalid subprotocol header: `{0}`")]
InvalidSubprotocolHeader(String),
}

impl From<FromUtf8Error> for Error {
Expand Down
123 changes: 2 additions & 121 deletions ratchet_core/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use crate::Error;
use bytes::BytesMut;
use http::{HeaderMap, HeaderValue};
use httparse::Header;
use ratchet_ext::{
Extension, ExtensionDecoder, ExtensionEncoder, ExtensionProvider, FrameHeader,
ReunitableExtension, RsvBits, SplittableExtension,
Expand Down Expand Up @@ -61,14 +60,14 @@ impl ExtensionProvider for NoExtProvider {

fn negotiate_client(
&self,
_headers: &[Header],
_headers: &HeaderMap,
) -> Result<Option<Self::Extension>, Self::Error> {
Ok(None)
}

fn negotiate_server(
&self,
_headers: &[Header],
_headers: &HeaderMap,
) -> Result<Option<(Self::Extension, HeaderValue)>, Self::Error> {
Ok(None)
}
Expand Down Expand Up @@ -134,121 +133,3 @@ impl ExtensionDecoder for NoExtDecoder {
Ok(())
}
}

#[derive(Debug)]
#[allow(missing_docs)]
pub struct NegotiatedExtension<E>(Option<E>);

impl<E> NegotiatedExtension<E>
where
E: Extension,
{
#[allow(missing_docs)]
pub fn take(self) -> Option<E> {
self.0
}
}

impl<E> From<Option<E>> for NegotiatedExtension<E>
where
E: Extension,
{
fn from(ext: Option<E>) -> Self {
NegotiatedExtension(ext)
}
}

impl<E> From<E> for NegotiatedExtension<E>
where
E: Extension,
{
fn from(ext: E) -> Self {
NegotiatedExtension::from(Some(ext))
}
}

impl<E> ExtensionEncoder for NegotiatedExtension<E>
where
E: ExtensionEncoder,
{
type Error = E::Error;

fn encode(
&mut self,
payload: &mut BytesMut,
header: &mut FrameHeader,
) -> Result<(), Self::Error> {
match &mut self.0 {
Some(ext) => ext.encode(payload, header),
None => Ok(()),
}
}
}

impl<E> ExtensionDecoder for NegotiatedExtension<E>
where
E: ExtensionDecoder,
{
type Error = E::Error;

fn decode(
&mut self,
payload: &mut BytesMut,
header: &mut FrameHeader,
) -> Result<(), Self::Error> {
match &mut self.0 {
Some(ext) => ext.decode(payload, header),
None => Ok(()),
}
}
}

impl<E> Extension for NegotiatedExtension<E>
where
E: Extension,
{
fn bits(&self) -> RsvBits {
match &self.0 {
Some(ext) => ext.bits(),
None => RsvBits {
rsv1: false,
rsv2: false,
rsv3: false,
},
}
}
}

impl<E> SplittableExtension for NegotiatedExtension<E>
where
E: SplittableExtension,
{
type SplitEncoder = NegotiatedExtension<E::SplitEncoder>;
type SplitDecoder = NegotiatedExtension<E::SplitDecoder>;

fn split(self) -> (Self::SplitEncoder, Self::SplitDecoder) {
match self.0 {
Some(ext) => {
let (enc, dec) = ext.split();
(
NegotiatedExtension(Some(enc)),
NegotiatedExtension(Some(dec)),
)
}
None => (NegotiatedExtension(None), NegotiatedExtension(None)),
}
}
}

impl<E> ReunitableExtension for NegotiatedExtension<E>
where
E: ReunitableExtension,
{
fn reunite(encoder: Self::SplitEncoder, decoder: Self::SplitDecoder) -> Self {
match (encoder.0, decoder.0) {
(Some(enc), Some(dec)) => NegotiatedExtension(Some(E::reunite(enc, dec))),
(None, None) => NegotiatedExtension(None),
_ => panic!("Illegal state"),
}
}
}
8 changes: 3 additions & 5 deletions ratchet_core/src/handshake/client/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ use ratchet_ext::ExtensionProvider;

use crate::errors::{Error, ErrorKind, HttpError};
use crate::handshake::client::Nonce;
use crate::handshake::{
apply_to, ProtocolRegistry, UPGRADE_STR, WEBSOCKET_STR, WEBSOCKET_VERSION_STR,
};
use crate::handshake::{SubprotocolRegistry, UPGRADE_STR, WEBSOCKET_STR, WEBSOCKET_VERSION_STR};

use base64::engine::general_purpose::STANDARD;

Expand Down Expand Up @@ -125,7 +123,7 @@ pub struct ValidatedRequest {
pub fn build_request<E>(
request: Request<()>,
extension: &E,
subprotocols: &ProtocolRegistry,
subprotocols: &SubprotocolRegistry,
) -> Result<ValidatedRequest, Error>
where
E: ExtensionProvider,
Expand Down Expand Up @@ -197,7 +195,7 @@ where
));
}

apply_to(subprotocols, &mut headers);
subprotocols.apply_to(&mut headers);

let option = headers
.get(header::SEC_WEBSOCKET_KEY)
Expand Down
Loading
Loading