-
Notifications
You must be signed in to change notification settings - Fork 33
/
websocket.rs
187 lines (161 loc) · 5.64 KB
/
websocket.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use awc::{
error::{WsClientError, WsProtocolError},
http::StatusCode,
ws,
ws::Frame,
};
use bytes::Bytes;
use futures::{channel::mpsc::*, prelude::*};
use url::Url;
use libsignal_service::{
configuration::ServiceCredentials,
messagepipe::*,
push_service::{self, ServiceError},
};
pub struct AwcWebSocket {
socket_sink: Box<dyn Sink<ws::Message, Error = WsProtocolError> + Unpin>,
}
#[derive(thiserror::Error, Debug)]
pub enum AwcWebSocketError {
#[error("Could not connect to the Signal Server")]
ConnectionError(#[from] awc::error::WsClientError),
}
impl From<AwcWebSocketError> for ServiceError {
fn from(e: AwcWebSocketError) -> ServiceError {
match e {
AwcWebSocketError::ConnectionError(e) => match e {
WsClientError::InvalidResponseStatus(s) => match s {
StatusCode::FORBIDDEN => ServiceError::Unauthorized,
s => ServiceError::WsError {
reason: format!("HTTP status {}", s),
},
},
e => ServiceError::WsError {
reason: e.to_string(),
},
},
}
}
}
impl From<WsProtocolError> for AwcWebSocketError {
fn from(e: WsProtocolError) -> AwcWebSocketError {
todo!("error conversion {:?}", e)
// return Some(Err(ServiceError::WsError {
// reason: e.to_string(),
// }));
}
}
/// Process the WebSocket, until it times out.
async fn process<S: Stream>(
socket_stream: S,
mut incoming_sink: Sender<WebSocketStreamItem>,
) -> Result<(), AwcWebSocketError>
where
S: Unpin,
S: Stream<Item = Result<Frame, WsProtocolError>>,
{
let mut socket_stream = socket_stream.fuse();
let mut ka_interval = actix::clock::interval_at(
actix::clock::Instant::now(),
push_service::KEEPALIVE_TIMEOUT_SECONDS,
);
loop {
let tick = ka_interval.tick().fuse();
futures::pin_mut!(tick);
futures::select! {
_ = tick => {
log::trace!("Triggering keep-alive");
if let Err(e) = incoming_sink.send(WebSocketStreamItem::KeepAliveRequest).await {
log::info!("Websocket sink has closed: {:?}.", e);
break;
};
},
frame = socket_stream.next() => {
let frame = if let Some(frame) = frame {
frame
} else {
log::info!("process: Socket stream ended");
break;
};
let frame = match frame? {
Frame::Binary(s) => s,
Frame::Continuation(_c) => todo!(),
Frame::Ping(msg) => {
log::warn!("Received Ping({:?})", msg);
continue;
},
Frame::Pong(msg) => {
log::trace!("Received Pong({:?})", msg);
continue;
},
Frame::Text(frame) => {
log::warn!("Frame::Text {:?}", frame);
// this is a protocol violation, maybe break; is better?
continue;
},
Frame::Close(c) => {
log::warn!("Websocket closing: {:?}", c);
break;
},
};
// Match SendError
if let Err(e) = incoming_sink.send(WebSocketStreamItem::Message(frame)).await {
log::info!("Websocket sink has closed: {:?}.", e);
break;
}
},
}
}
Ok(())
}
impl AwcWebSocket {
pub(crate) async fn with_client(
client: &mut awc::Client,
base_url: impl std::borrow::Borrow<Url>,
path: &str,
credentials: Option<&ServiceCredentials>,
) -> Result<(Self, <Self as WebSocketService>::Stream), AwcWebSocketError>
{
let mut url = base_url.borrow().join(path).expect("valid url");
url.set_scheme("wss").expect("valid https base url");
if let Some(credentials) = credentials {
url.query_pairs_mut()
.append_pair("login", credentials.login().as_ref())
.append_pair(
"password",
credentials.password.as_ref().expect("a password"),
);
}
log::trace!("Will start websocket at {:?}", url);
let (response, framed) = client.ws(url.as_str()).connect().await?;
log::debug!("WebSocket connected: {:?}", response);
let (incoming_sink, incoming_stream) = channel(5);
let (socket_sink, socket_stream) = framed.split();
let processing_task = process(socket_stream, incoming_sink);
// When the processing_task stops, the consuming stream and sink also
// terminate.
actix_rt::spawn(processing_task.map(|v| match v {
Ok(()) => (),
Err(e) => {
log::warn!("Processing task terminated with error: {:?}", e)
},
}));
Ok((
Self {
socket_sink: Box::new(socket_sink),
},
incoming_stream,
))
}
}
#[async_trait::async_trait(?Send)]
impl WebSocketService for AwcWebSocket {
type Stream = Receiver<WebSocketStreamItem>;
async fn send_message(&mut self, msg: Bytes) -> Result<(), ServiceError> {
self.socket_sink
.send(ws::Message::Binary(msg))
.await
.map_err(AwcWebSocketError::from)?;
Ok(())
}
}