phyllo 0.3.0

Websocket-based client for Phoenix channels
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use crate::{
    channel::{
        ChannelBuilder, ChannelHandler, ChannelSocketMessage, ChannelStatus, SocketChannelMessage,
    },
    error::RegisterChannelError,
    message::Message,
};
use backoff::ExponentialBackoff;
use futures_util::{stream::SplitSink, SinkExt, StreamExt};
use serde::{de::DeserializeOwned, Serialize};
use std::{
    collections::{hash_map::Entry, HashMap},
    fmt::Debug,
    hash::Hash,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
    time::Duration,
};
use tokio::{
    net::TcpStream,
    select,
    sync::{
        broadcast,
        mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
        oneshot,
    },
    time,
};
use tokio_tungstenite::{
    connect_async_with_config,
    tungstenite::{self, protocol::WebSocketConfig},
    MaybeTlsStream, WebSocketStream,
};
use tracing::{info, instrument, warn};
use url::Url;

/// Handler half of a `Socket`.
#[derive(Debug, Clone)]
pub struct SocketHandler<T> {
    reference: Reference,
    handler_tx: UnboundedSender<HandlerSocketMessage<T>>,
}

impl<T> SocketHandler<T>
where
    T: Serialize + DeserializeOwned + Hash + Eq + Clone + Send + Sync + 'static + Debug,
{
    /// Register a new channel for the socket, returning a corresponding [`ChannelHandler`].
    ///
    /// To avoid a potential race condition where the join is established and a message is received before [`ChannelHandler::subscribe`](crate::channel::ChannelHandler::subscribe)
    /// returns [(`broadcast` channels only receives values sent after a `subscribe` call)](tokio::sync::broadcast), a ready-to-use [`broadcast::Receiver`] is included
    /// in the return.
    ///
    /// # Warnings
    /// [The topic `"phoenix"` is a protocol-reserved keyword.](crate::message::Message#warning)
    ///
    /// # Errors
    /// If the underlying `Socket` has been dropped, or if the given topic has already been registered, an error is returned.
    pub async fn channel<V, P, R>(
        &mut self,
        channel_builder: ChannelBuilder<T>,
    ) -> Result<
        (
            ChannelHandler<T, V, P, R>,
            broadcast::Receiver<Message<T, V, P, R>>,
        ),
        RegisterChannelError,
    >
    where
        V: Serialize + DeserializeOwned + Clone + Send + 'static + Debug,
        P: Serialize + DeserializeOwned + Clone + Send + 'static + Debug,
        R: Serialize + DeserializeOwned + Clone + Send + 'static + Debug,
    {
        let (tx, rx) = oneshot::channel();

        let _ = self.handler_tx.send(HandlerSocketMessage::Subscribe {
            topic: channel_builder.topic.clone(),
            callback: tx,
        });

        let (channel_socket, socket_channel) = rx
            .await
            .map_err(|_| RegisterChannelError::SocketDropped)?
            .ok_or(RegisterChannelError::DuplicateTopic)?;

        Ok(
            channel_builder.build::<V, P, R>(
                self.reference.clone(),
                socket_channel,
                channel_socket,
            ),
        )
    }

    /// Close the socket, dropping all queued messages. This function will work even if the underlying socket has already been closed by another `SocketHandler`.
    pub fn close(self) {
        let _ = self.handler_tx.send(HandlerSocketMessage::Close);
    }

    /// Returns whether the `Socket` half is still alive.
    pub async fn alive(&self) -> bool {
        !self.handler_tx.is_closed()
    }
}

/// A monotonically-increasing counter for tracking messages.
#[derive(Clone, Debug)]
pub struct Reference(Arc<AtomicU64>);

impl Reference {
    /// Constructs a new `Reference`.
    pub(crate) fn new() -> Self {
        Self(Arc::new(AtomicU64::new(0)))
    }

    /// Fetch the next value.
    pub fn next(&self) -> u64 {
        self.0.fetch_add(1, Ordering::Relaxed)
    }

    /// Reset the counter.
    pub(crate) fn reset(&self) {
        self.0.store(0, Ordering::Relaxed);
    }
}

impl Default for Reference {
    fn default() -> Self {
        Self::new()
    }
}

/// Callback for a topic subscription message sent from a `SocketHandler` to a `Socket`.
type HandlerSocketSubscribeCallback<T> = oneshot::Sender<
    Option<(
        UnboundedReceiver<SocketChannelMessage<T>>,
        UnboundedSender<ChannelSocketMessage<T>>,
    )>,
>;

/// A message sent from a `SocketHandler` to a `Socket`.
#[derive(Debug)]
enum HandlerSocketMessage<T> {
    /// Close the socket.
    Close,
    /// Create a subscription for the topic.
    Subscribe {
        topic: T,
        callback: HandlerSocketSubscribeCallback<T>,
    },
}

type Sink = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, tungstenite::Message>;
// type Stream = SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>;
type TungsteniteWebSocketStream = WebSocketStream<MaybeTlsStream<TcpStream>>;

/// What the socket should do if an IO error is encountered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OnIoError {
    /// Close the socket connection permanently.
    Die,
    /// Retry according to the configured reconnection strategy.
    Retry,
}

/// Builder for a `Socket`.
#[derive(Debug, Clone)]
pub struct SocketBuilder {
    endpoint: Url,
    websocket_config: Option<WebSocketConfig>,
    heartbeat: Duration,
    reconnect: ExponentialBackoff,
    on_io_error: OnIoError,
}

impl SocketBuilder {
    /// Constructs a new `SocketBuilder`. `endpoint` is the endpoint to connect to; only `vsn=2.0.0` is supported.
    pub fn new(mut endpoint: Url) -> Self {
        endpoint.query_pairs_mut().append_pair("vsn", "2.0.0");

        Self {
            endpoint,
            websocket_config: None,
            heartbeat: Duration::from_millis(30000),
            reconnect: ExponentialBackoff::default(),
            on_io_error: OnIoError::Retry,
        }
    }

    /// Sets the endpoint to connect to. Only `vsn=2.0.0` is supported.
    pub fn endpoint(mut self, mut endpoint: Url) -> Self {
        endpoint.query_pairs_mut().append_pair("vsn", "2.0.0");

        self.endpoint = endpoint;
        self
    }

    /// Sets the configuration for the underlying `tungstenite` websocket.
    pub fn websocket_config(mut self, websocket_config: Option<WebSocketConfig>) -> Self {
        self.websocket_config = websocket_config;
        self
    }

    /// Sets the interval between heartbeat messages.
    pub fn heartbeat(mut self, heartbeat: Duration) -> Self {
        self.heartbeat = heartbeat;
        self
    }

    /// Sets the strategy for attempting reconnection using exponential backoff.
    pub fn reconnect(mut self, reconnect: ExponentialBackoff) -> Self {
        self.reconnect = reconnect;
        self
    }

    /// Sets how to handle an IO error.
    pub fn on_io_error(mut self, on_io_error: OnIoError) -> Self {
        self.on_io_error = on_io_error;
        self
    }

    /// Spawns the `Socket` and returns a corresponding `SocketHandler`.
    pub async fn build<T>(self) -> SocketHandler<T>
    where
        T: Serialize + DeserializeOwned + Eq + Clone + Hash + Send + Sync + 'static + Debug,
    {
        // Send, receiver for client -> server
        let (out_tx, out_rx) = unbounded_channel();

        // Send, receiver for handler -> socket
        let (handler_tx, handler_rx) = unbounded_channel();

        let subscriptions = HashMap::new();
        let reference = Reference::new();

        // Spawn task
        let socket: Socket<T> = Socket {
            handler_rx,
            out_tx,
            out_rx,
            subscriptions,
            reference: reference.clone(),
            endpoint: self.endpoint.clone(),
            websocket_config: self.websocket_config,
            heartbeat: self.heartbeat,
            reconnect: self.reconnect.clone(),
            on_io_error: self.on_io_error,
        };
        tokio::spawn(socket.run());

        SocketHandler {
            reference,
            handler_tx,
        }
    }
}

/// A socket for managing and receiving/sending Phoenix messages.
#[derive(Debug)]
struct Socket<T> {
    /// SocketHandler -> Socket
    handler_rx: UnboundedReceiver<HandlerSocketMessage<T>>,

    /// Tx for Channel -> Socket
    out_tx: UnboundedSender<ChannelSocketMessage<T>>,
    /// Rx for Channel -> Socket
    out_rx: UnboundedReceiver<ChannelSocketMessage<T>>,

    /// Mapping of channels to their channel senders
    subscriptions: HashMap<T, UnboundedSender<SocketChannelMessage<T>>>,

    /// Counter for heartbeat
    reference: Reference,

    endpoint: Url,
    websocket_config: Option<WebSocketConfig>,
    heartbeat: Duration,
    reconnect: ExponentialBackoff,
    on_io_error: OnIoError,
}

impl<T> Socket<T>
where
    T: Serialize + DeserializeOwned + Clone + Eq + Hash + Send + 'static + Debug,
{
    /// Connect to the websocket with exponential backoff.
    #[instrument(skip(self), fields(endpoint = %self.endpoint))]
    async fn connect_with_backoff(&self) -> Result<TungsteniteWebSocketStream, tungstenite::Error> {
        backoff::future::retry(self.reconnect.clone(), || async {
            info!("attempting connection");
            Ok(
                connect_async_with_config(self.endpoint.clone(), self.websocket_config)
                    .await
                    .map_err(|e| {
                        warn!(error = ?e);
                        e
                    })?,
            )
        })
        .await
        .map(|(twss, _)| twss)
    }

    /// Runs the `Socket` task.
    pub async fn run(mut self) -> Result<(), tungstenite::Error> {
        let mut interval = {
            let mut i = time::interval(self.heartbeat);
            i.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
            i
        };

        'retry: loop {
            for (_, chan) in self.subscriptions.iter_mut() {
                let _ = chan.send(SocketChannelMessage::ChannelStatus(ChannelStatus::Rejoin));
            }
            self.reference.reset();

            // Connect to socket
            let (mut sink, mut stream) = self.connect_with_backoff().await.map(|ws| ws.split())?;
            info!("connected to websocket {}", self.endpoint);

            'conn: loop {
                if let Err(tungstenite::Error::Io(_)) = select! {
                    Some(v) = self.handler_rx.recv() => {
                        match v {
                            HandlerSocketMessage::Close => {
                                let _ = sink.close().await;
                                break 'retry;
                            },
                            HandlerSocketMessage::Subscribe { topic, callback } => {
                                let (in_tx, in_rx) = unbounded_channel();
                                let callback_value = match self.subscriptions.entry(topic.clone()) {
                                    Entry::Occupied(_) => {
                                        None
                                    },
                                    Entry::Vacant(e) => {
                                        e.insert(in_tx);
                                        Some((in_rx, self.out_tx.clone()))
                                    },
                                };
                                let _ = callback.send(callback_value);
                            },
                        }
                        Ok(())
                    },

                    // Heartbeat
                    _ = interval.tick() => Socket::<T>::send_hearbeat(self.reference.next(), &mut sink).await,

                    // Incoming message from channels
                    Some(v) = self.out_rx.recv() => self.from_channel(&mut sink, v).await,

                    // Incoming message from websocket
                    i = stream.next() => {
                        // If the stream is closed we can never receive any more messages. Break
                        match i {
                            Some(i) => {
                                match self.from_websocket(i).await {
                                    Ok(()) => Ok(()),
                                    Err(_) => break 'conn,
                                }
                            }
                            None => break 'conn,
                        }
                    },
                } {
                    match self.on_io_error {
                        OnIoError::Die => {
                            break 'retry;
                        }
                        OnIoError::Retry => {
                            break 'conn;
                        }
                    }
                };
            }
        }

        // Send close signal to all subscriptions
        for (topic, chan) in self.subscriptions.iter_mut() {
            info!(?topic, "close signal");
            let _ = chan.send(SocketChannelMessage::ChannelStatus(
                ChannelStatus::SocketClosed,
            ));
        }

        Ok(())
    }

    /// Sends a heartbeat message to the server.
    #[instrument(skip_all)]
    async fn send_hearbeat(reference: u64, sink: &mut Sink) -> Result<(), tungstenite::Error> {
        let heartbeat_message: tungstenite::Message =
            Message::heartbeat(reference).try_into().unwrap();

        info!(message = %heartbeat_message);

        sink.send(heartbeat_message).await
    }

    /// Handles an incoming message from a `Channel`.
    #[instrument(skip_all, fields(endpoint = %self.endpoint))]
    async fn from_channel(
        &mut self,
        sink: &mut Sink,
        message: ChannelSocketMessage<T>,
    ) -> Result<(), tungstenite::Error> {
        match message {
            ChannelSocketMessage::Message(message) => {
                info!(%message.content, "to websocket");
                let _ = message.callback.send(sink.send(message.content).await);
            }
            ChannelSocketMessage::TaskEnded(topic) => {
                info!(?topic, "removing task");
                self.subscriptions.remove(&topic);
            }
        }
        Ok(())
    }

    /// Handles an incoming message from the websocket.
    #[instrument(skip_all, fields(endpoint = %self.endpoint))]
    async fn from_websocket(
        &mut self,
        message: Result<tungstenite::Message, tungstenite::Error>,
    ) -> Result<(), tungstenite::Error> {
        match message {
            Ok(tungstenite::Message::Text(t)) => {
                info!(message = %t, "incoming");
                let _ = self.decode_and_relay(t).await;
                Ok(())
            }
            Err(e) => {
                warn!(error = ?e, "error received");
                Err(e)
            }
            _ => Ok(()),
        }
    }

    /// Transforms a websocket message into a `Message`, then relays it to the appropriate `Channel`.
    async fn decode_and_relay(&mut self, text: String) -> Result<(), serde_json::Error> {
        use serde_json::Value;

        // To determine which topic we should relay the raw tungstenite mesage to, we "ignore" V, P but deserialise for T.
        let message = serde_json::from_str::<Message<T, Value, Value, Value>>(&text)?;

        if let Some(chan) = self.subscriptions.get(&message.topic) {
            if let Err(e) = chan.send(SocketChannelMessage::Message(message)) {
                warn!(error = ?e, "failed to send message to channel");
            }
        }
        Ok(())
    }
}