-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathwebsocket.rs
345 lines (287 loc) · 9.77 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use {
self::connection::{connection_event_loop, ConnectionControl},
crate::{
error::{ClientError, Error},
ConnectionOptions,
},
relay_rpc::{
domain::{MessageId, SubscriptionId, Topic},
rpc::{
BatchFetchMessages,
BatchReceiveMessages,
BatchSubscribe,
BatchSubscribeBlocking,
BatchUnsubscribe,
FetchMessages,
Publish,
Receipt,
Subscribe,
SubscribeBlocking,
Subscription,
SubscriptionError,
Unsubscribe,
},
},
std::{future::Future, sync::Arc, time::Duration},
tokio::sync::{
mpsc::{self, UnboundedSender},
oneshot,
},
};
pub use {
fetch::*,
inbound::*,
outbound::*,
stream::*,
tokio_tungstenite::tungstenite::protocol::CloseFrame,
};
pub type TransportError = tokio_tungstenite::tungstenite::Error;
#[derive(Debug, thiserror::Error)]
pub enum WebsocketClientError {
#[error("Failed to connect: {0}")]
ConnectionFailed(TransportError),
#[error("Connection closed: {0}")]
ConnectionClosed(CloseReason),
#[error("Failed to close connection: {0}")]
ClosingFailed(TransportError),
#[error("Websocket transport error: {0}")]
Transport(TransportError),
#[error("Not connected")]
NotConnected,
}
/// Wrapper around the websocket [`CloseFrame`] providing info about the
/// connection closing reason.
#[derive(Debug, Clone)]
pub struct CloseReason(pub Option<CloseFrame<'static>>);
impl std::fmt::Display for CloseReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(frame) = &self.0 {
frame.fmt(f)
} else {
f.write_str("<close frame unavailable>")
}
}
}
mod connection;
mod fetch;
mod inbound;
mod outbound;
mod stream;
/// The message received from a subscription.
#[derive(Debug, Clone)]
pub struct PublishedMessage {
pub message_id: MessageId,
pub subscription_id: SubscriptionId,
pub topic: Topic,
pub message: Arc<str>,
pub tag: u32,
pub published_at: chrono::DateTime<chrono::Utc>,
pub received_at: chrono::DateTime<chrono::Utc>,
}
impl PublishedMessage {
fn from_request(request: &InboundRequest<Subscription>) -> Self {
let Subscription { id, data } = request.data();
let now = chrono::Utc::now();
Self {
message_id: request.id(),
subscription_id: id.clone(),
topic: data.topic.clone(),
message: data.message.clone(),
tag: data.tag,
// TODO: Set proper value once implemented.
published_at: now,
received_at: now,
}
}
}
/// Handlers for the RPC stream events.
pub trait ConnectionHandler: Send + 'static {
/// Called when a connection to the Relay is established.
fn connected(&mut self) {}
/// Called when the Relay connection is closed.
fn disconnected(&mut self, _frame: Option<CloseFrame<'static>>) {}
/// Called when a message is received from the Relay.
fn message_received(&mut self, message: PublishedMessage);
/// Called when an inbound error occurs, such as data deserialization
/// failure, or an unknown response message ID.
fn inbound_error(&mut self, _error: ClientError) {}
/// Called when an outbound error occurs, i.e. failed to write to the
/// websocket stream.
fn outbound_error(&mut self, _error: ClientError) {}
}
/// The Relay WebSocket RPC client.
///
/// This provides the high-level access to all of the available RPC methods. For
/// a lower-level RPC stream see [`ClientStream`](crate::client::ClientStream).
#[derive(Debug, Clone)]
pub struct Client {
control_tx: UnboundedSender<ConnectionControl>,
}
impl Client {
/// Creates a new [`Client`] with the provided handler.
pub fn new<T>(handler: T) -> Self
where
T: ConnectionHandler,
{
let (control_tx, control_rx) = mpsc::unbounded_channel();
tokio::spawn(connection_event_loop(control_rx, handler));
Self { control_tx }
}
/// Publishes a message over the network on given topic.
pub fn publish(
&self,
topic: Topic,
message: impl Into<Arc<str>>,
tag: u32,
ttl: Duration,
prompt: bool,
) -> EmptyResponseFuture<Publish> {
let (request, response) = create_request(Publish {
topic,
message: message.into(),
ttl_secs: ttl.as_secs() as u32,
tag,
prompt,
});
self.request(request);
EmptyResponseFuture::new(response)
}
/// Subscribes on topic to receive messages. The request is resolved
/// optimistically as soon as the relay receives it.
pub fn subscribe(&self, topic: Topic) -> ResponseFuture<Subscribe> {
let (request, response) = create_request(Subscribe {
topic,
block: false,
});
self.request(request);
response
}
/// Subscribes on topic to receive messages. The request is resolved only
/// when fully processed by the relay.
/// Note: This function is experimental and will likely be removed in the
/// future.
pub fn subscribe_blocking(&self, topic: Topic) -> ResponseFuture<SubscribeBlocking> {
let (request, response) = create_request(SubscribeBlocking { topic });
self.request(request);
response
}
/// Unsubscribes from a topic.
pub fn unsubscribe(&self, topic: Topic) -> EmptyResponseFuture<Unsubscribe> {
let (request, response) = create_request(Unsubscribe { topic });
self.request(request);
EmptyResponseFuture::new(response)
}
/// Fetch mailbox messages for a specific topic.
pub fn fetch(&self, topic: Topic) -> ResponseFuture<FetchMessages> {
let (request, response) = create_request(FetchMessages { topic });
self.request(request);
response
}
/// Fetch mailbox messages for a specific topic. Returns a [`Stream`].
pub fn fetch_stream(&self, topics: impl Into<Vec<Topic>>) -> FetchMessageStream {
FetchMessageStream::new(self.clone(), topics.into())
}
/// Subscribes on multiple topics to receive messages. The request is
/// resolved optimistically as soon as the relay receives it.
pub fn batch_subscribe(&self, topics: impl Into<Vec<Topic>>) -> ResponseFuture<BatchSubscribe> {
let (request, response) = create_request(BatchSubscribe {
topics: topics.into(),
block: false,
});
self.request(request);
response
}
/// Subscribes on multiple topics to receive messages. The request is
/// resolved only when fully processed by the relay.
/// Note: This function is experimental and will likely be removed in the
/// future.
pub fn batch_subscribe_blocking(
&self,
topics: impl Into<Vec<Topic>>,
) -> impl Future<
Output = Result<
Vec<Result<SubscriptionId, Error<SubscriptionError>>>,
Error<SubscriptionError>,
>,
> {
let (request, response) = create_request(BatchSubscribeBlocking {
topics: topics.into(),
});
self.request(request);
async move {
Ok(response
.await?
.into_iter()
.map(crate::convert_subscription_result)
.collect())
}
}
/// Unsubscribes from multiple topics.
pub fn batch_unsubscribe(
&self,
subscriptions: impl Into<Vec<Unsubscribe>>,
) -> EmptyResponseFuture<BatchUnsubscribe> {
let (request, response) = create_request(BatchUnsubscribe {
subscriptions: subscriptions.into(),
});
self.request(request);
EmptyResponseFuture::new(response)
}
/// Fetch mailbox messages for multiple topics.
pub fn batch_fetch(&self, topics: impl Into<Vec<Topic>>) -> ResponseFuture<BatchFetchMessages> {
let (request, response) = create_request(BatchFetchMessages {
topics: topics.into(),
});
self.request(request);
response
}
/// Acknowledge receipt of messages from a subscribed client.
pub async fn batch_receive(
&self,
receipts: impl Into<Vec<Receipt>>,
) -> ResponseFuture<BatchReceiveMessages> {
let (request, response) = create_request(BatchReceiveMessages {
receipts: receipts.into(),
});
self.request(request);
response
}
/// Opens a connection to the Relay.
pub async fn connect(&self, opts: &ConnectionOptions) -> Result<(), ClientError> {
let (tx, rx) = oneshot::channel();
let request = opts.as_ws_request()?;
if self
.control_tx
.send(ConnectionControl::Connect { request, tx })
.is_ok()
{
rx.await.map_err(|_| ClientError::ChannelClosed)?
} else {
Err(ClientError::ChannelClosed)
}
}
/// Closes the Relay connection.
pub async fn disconnect(&self) -> Result<(), ClientError> {
let (tx, rx) = oneshot::channel();
if self
.control_tx
.send(ConnectionControl::Disconnect { tx })
.is_ok()
{
rx.await.map_err(|_| ClientError::ChannelClosed)?
} else {
Err(ClientError::ChannelClosed)
}
}
pub(crate) fn request(&self, request: OutboundRequest) {
if let Err(err) = self
.control_tx
.send(ConnectionControl::OutboundRequest(request))
{
let ConnectionControl::OutboundRequest(request) = err.0 else {
unreachable!();
};
request.tx.send(Err(ClientError::ChannelClosed)).ok();
}
}
}