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
|
use std::time::Duration;
use axum::response::sse::{self, KeepAlive};
use crate::{channel, message, user};
pub mod app;
mod broadcaster;
mod extract;
pub mod handlers;
pub mod repo;
mod sequence;
pub use self::{
broadcaster::Broadcaster,
sequence::{Instant, Sequence, Sequenced},
};
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
User(user::Event),
Channel(channel::Event),
Message(message::Event),
}
// Serialized representation is intended to look like the serialized representation of `Event`,
// above - though heartbeat events contain only a type field and none of the other event gubbins.
// They don't have to participate in sequence numbering, aren't generated from stored data, and
// generally Are Weird.
#[derive(serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Heartbeat {
Heartbeat,
}
impl Sequenced for Event {
fn instant(&self) -> Instant {
match self {
Self::User(event) => event.instant(),
Self::Channel(event) => event.instant(),
Self::Message(event) => event.instant(),
}
}
}
impl From<user::Event> for Event {
fn from(event: user::Event) -> Self {
Self::User(event)
}
}
impl From<channel::Event> for Event {
fn from(event: channel::Event) -> Self {
Self::Channel(event)
}
}
impl From<message::Event> for Event {
fn from(event: message::Event) -> Self {
Self::Message(event)
}
}
impl Heartbeat {
// The following values are a first-rough-guess attempt to balance noticing connection problems
// quickly with managing the (modest) costs of delivering and processing heartbeats. Feel
// encouraged to tune them if you have a better idea on how to set them!
// Advise clients to expect heartbeats this often
pub const TIMEOUT: Duration = Duration::from_secs(20);
// Actually send heartbeats this often; this is shorter to allow time for the heartbeat to
// arrive before the advised deadline.
pub const INTERVAL: Duration = Duration::from_secs(15);
}
impl TryFrom<Heartbeat> for sse::Event {
type Error = serde_json::Error;
fn try_from(heartbeat: Heartbeat) -> Result<sse::Event, Self::Error> {
let heartbeat = serde_json::to_string_pretty(&heartbeat)?;
let heartbeat = sse::Event::default().data(heartbeat);
Ok(heartbeat)
}
}
impl TryFrom<Heartbeat> for sse::KeepAlive {
type Error = <sse::Event as TryFrom<Heartbeat>>::Error;
fn try_from(heartbeat: Heartbeat) -> Result<sse::KeepAlive, Self::Error> {
let event = heartbeat.try_into()?;
let keep_alive = KeepAlive::new().interval(Heartbeat::INTERVAL).event(event);
Ok(keep_alive)
}
}
|