Skip to content

Commit

Permalink
Add builder for WebSocketRequestMessage
Browse files Browse the repository at this point in the history
I will stop with the bike-shedding now... =D
  • Loading branch information
gferon committed Oct 17, 2024
1 parent 23d1a1b commit c758d8f
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 41 deletions.
41 changes: 8 additions & 33 deletions src/websocket/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use futures::channel::{mpsc, oneshot};
use futures::future::BoxFuture;
use futures::prelude::*;
use futures::stream::FuturesUnordered;
use reqwest::Method;
use reqwest_websocket::WebSocket;
use serde::{Deserialize, Serialize};
use tokio::time::Instant;

use crate::proto::{
Expand All @@ -19,8 +19,10 @@ use crate::proto::{
};
use crate::push_service::{self, ServiceError, SignalServiceResponse};

mod request;
mod sender;
// pub(crate) mod tungstenite;

pub use request::WebSocketRequestMessageBuilder;

type RequestStreamItem = (
WebSocketRequestMessage,
Expand Down Expand Up @@ -202,12 +204,10 @@ impl SignalWebSocketProcess {
_ = ka_interval.tick().fuse() => {
use prost::Message;
tracing::debug!("sending keep-alive");
let request = WebSocketRequestMessage {
id: Some(self.next_request_id()),
path: Some(self.keep_alive_path.clone()),
verb: Some("GET".into()),
..Default::default()
};
let request = WebSocketRequestMessage::new(Method::GET)
.id(self.next_request_id())
.path(&self.keep_alive_path)
.build();
self.outgoing_keep_alive_set.insert(request.id.unwrap());
let msg = WebSocketMessage {
r#type: Some(web_socket_message::Type::Request.into()),
Expand Down Expand Up @@ -441,29 +441,4 @@ impl SignalWebSocket {
.await
.map_err(Into::into)
}

pub(crate) async fn put_json<'h, D, S>(
&mut self,
path: &str,
value: S,
mut extra_headers: Vec<String>,
) -> Result<D, ServiceError>
where
for<'de> D: Deserialize<'de>,
S: Serialize,
{
extra_headers.push("content-type:application/json".into());
let request = WebSocketRequestMessage {
path: Some(path.into()),
verb: Some("PUT".into()),
headers: extra_headers,
body: Some(serde_json::to_vec(&value).map_err(|e| {
ServiceError::SendError {
reason: format!("Serializing JSON {}", e),
}
})?),
..Default::default()
};
self.request_json(request).await
}
}
51 changes: 51 additions & 0 deletions src/websocket/request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use reqwest::Method;
use serde::Serialize;

use crate::proto::WebSocketRequestMessage;

#[derive(Debug)]
pub struct WebSocketRequestMessageBuilder {
request: WebSocketRequestMessage,
}

impl WebSocketRequestMessage {
pub fn new(method: Method) -> WebSocketRequestMessageBuilder {
WebSocketRequestMessageBuilder {
request: WebSocketRequestMessage {
verb: Some(method.to_string()),
..Default::default()
},
}
}

Check warning on line 19 in src/websocket/request.rs

View workflow job for this annotation

GitHub Actions / clippy

methods called `new` usually return `Self`

warning: methods called `new` usually return `Self` --> src/websocket/request.rs:12:5 | 12 | / pub fn new(method: Method) -> WebSocketRequestMessageBuilder { 13 | | WebSocketRequestMessageBuilder { 14 | | request: WebSocketRequestMessage { 15 | | verb: Some(method.to_string()), ... | 18 | | } 19 | | } | |_____^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#new_ret_no_self = note: `#[warn(clippy::new_ret_no_self)]` on by default
}

impl WebSocketRequestMessageBuilder {
pub fn id(mut self, id: u64) -> Self {
self.request.id = Some(id);
self
}

pub fn path(mut self, path: impl Into<String>) -> Self {
self.request.path = Some(path.into());
self
}

pub fn header(mut self, key: &str, value: impl AsRef<str>) -> Self {
self.request
.headers
.push(format!("{key}={}", value.as_ref()));
self
}

pub fn json<S: Serialize>(
mut self,
value: S,
) -> Result<WebSocketRequestMessage, serde_json::Error> {
self.request.body = Some(serde_json::to_vec(&value)?);
Ok(self.header("Content-Type", "application/json").request)
}

pub fn build(self) -> WebSocketRequestMessage {
self.request
}
}
20 changes: 12 additions & 8 deletions src/websocket/sender.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,24 @@ impl SignalWebSocket {
&mut self,
messages: OutgoingPushMessages,
) -> Result<SendMessageResponse, ServiceError> {
let path = format!("/v1/messages/{}", messages.destination);
self.put_json(&path, messages, vec![]).await
let request = WebSocketRequestMessage::new(Method::PUT)
.path(format!("/v1/messages/{}", messages.destination))
.json(&messages)?;
self.request_json(request).await
}

pub async fn send_messages_unidentified(
&mut self,
messages: OutgoingPushMessages,
access: &UnidentifiedAccess,
) -> Result<SendMessageResponse, ServiceError> {
let path = format!("/v1/messages/{}", messages.destination);
let header = format!(
"Unidentified-Access-Key:{}",
BASE64_RELAXED.encode(&access.key)
);
self.put_json(&path, messages, vec![header]).await
let request = WebSocketRequestMessage::new(Method::PUT)
.path(format!("/v1/messages/{}", messages.destination))
.header(
"Unidentified-Access-Key:{}",
BASE64_RELAXED.encode(&access.key),
)
.json(&messages)?;
self.request_json(request).await
}
}

0 comments on commit c758d8f

Please sign in to comment.