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
use futures::future;
use hyper::body::Sender;
use std::borrow::Cow;
#[derive(Debug, Default)]
pub struct Event {
    pub id: Option<Cow<'static, str>>,
    pub event: Option<Cow<'static, str>>,
    pub data: Cow<'static, str>,
}
impl Event {
    
    pub fn new<T: Into<Cow<'static, str>>>(data: T) -> Self {
        Event {
            id: None,
            event: None,
            data: data.into(),
        }
    }
    
    pub fn set_id<T: Into<Cow<'static, str>>>(mut self, id: T) -> Self {
        self.id = Some(id.into());
        self
    }
    
    
    pub fn set_event<T: Into<Cow<'static, str>>>(mut self, event: T) -> Self {
        self.event = Some(event.into());
        self
    }
    
    pub fn to_sse(&self) -> String {
        let mut sse = String::new();
        if let Some(id) = &self.id {
            sse.push_str(&format!("id: {}\n", id));
        }
        if let Some(event) = &self.event {
            sse.push_str(&format!("event: {}\n", event));
        }
        for line in self.data.lines() {
            sse.push_str(&format!("data: {}\n", line));
        }
        sse.push('\n');
        sse
    }
}
#[derive(Debug, Default)]
pub struct Server {
    clients: Vec<Sender>,
}
impl Server {
    
    pub fn new() -> Self {
        Server {
            clients: Vec::new(),
        }
    }
    
    pub fn add_client(&mut self, client: Sender) {
        self.clients.push(client);
    }
    
    
    pub async fn send_to_clients(&mut self, text: &str) {
        let mut sent =
            future::join_all(self.clients.iter_mut().map(|client| {
                async move { client.send_data(text.to_owned().into()).await.is_ok() }
            }))
            .await
            .into_iter();
        self.clients.retain(|_| sent.next().unwrap());
    }
    
    
    pub async fn send_heartbeat(&mut self) {
        self.send_to_clients(":\n\n").await
    }
}