socket_flow/
event.rs

1use crate::error::Error;
2use crate::message::Message;
3use crate::split::WSWriter;
4use futures::Stream;
5use rand::rngs::StdRng;
6use rand::{Rng, SeedableRng};
7use std::pin::Pin;
8use std::task::{Context, Poll};
9use tokio::sync::mpsc::Receiver;
10use uuid::Uuid;
11
12pub type ID = Uuid;
13
14// Used for generating a new UUID, every time a new client connects the server
15pub fn generate_new_uuid() -> Uuid {
16    let mut rng = StdRng::from_rng(&mut rand::rng());
17    let buf = rng.random::<[u8; 16]>();
18
19    Uuid::new_v8(buf)
20}
21
22// Base enum, used as the structure to represent every single event within
23// the websockets server, offering the end-user a practical way of spawning a server
24// and handling connections
25pub enum Event {
26    NewClient(ID, WSWriter),
27    NewMessage(ID, Message),
28    Disconnect(ID),
29    Error(ID, Error),
30}
31
32// This struct will be used for implementing Stream trait. Thus, the end-user
33// doesn't need to interact with the mpsc tokio channel directly
34pub struct EventStream {
35    receiver: Receiver<Event>,
36}
37
38impl EventStream {
39    pub fn new(receiver: Receiver<Event>) -> Self {
40        Self { receiver }
41    }
42}
43
44impl Stream for EventStream {
45    type Item = Event;
46
47    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
48        let this = self.get_mut();
49        Pin::new(&mut this.receiver).poll_recv(cx)
50    }
51}