flodgatt/src/response/event.rs

156 lines
5.1 KiB
Rust
Raw Normal View History

#[cfg(not(test))]
mod checked_event;
#[cfg(test)]
pub mod checked_event;
mod dynamic_event;
pub mod err;
pub use self::checked_event::CheckedEvent;
pub use self::dynamic_event::{DynEvent, EventKind};
use crate::Id;
use hashbrown::HashSet;
use serde::Serialize;
use std::convert::TryFrom;
use std::string::String;
use warp::sse::ServerSentEvent;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
TypeSafe(CheckedEvent),
Dynamic(DynEvent),
Stream events via a watch channel (#128) This squashed commit makes a fairly significant structural change to significantly reduce Flodgatt's CPU usage. Flodgatt connects to Redis in a single (green) thread, and then creates a new thread to handle each WebSocket/SSE connection. Previously, each thread was responsible for polling the Redis thread to determine whether it had a message relevant to the connected client. I initially selected this structure both because it was simple and because it minimized memory overhead – no messages are sent to a particular thread unless they are relevant to the client connected to the thread. However, I recently ran some load tests that show this approach to have unacceptable CPU costs when 300+ clients are simultaneously connected. Accordingly, Flodgatt now uses a different structure: the main Redis thread now announces each incoming message via a watch channel connected to every client thread, and each client thread filters out irrelevant messages. In theory, this could lead to slightly higher memory use, but tests I have run so far have not found a measurable increase. On the other hand, Flodgatt's CPU use is now an order of magnitude lower in tests I've run. This approach does run a (very slight) risk of dropping messages under extremely heavy load: because a watch channel only stores the most recent message transmitted, if Flodgatt adds a second message before the thread can read the first message, the first message will be overwritten and never transmitted. This seems unlikely to happen in practice, and we can avoid the issue entirely by changing to a broadcast channel when we upgrade to the most recent Tokio version (see #75).
2020-04-09 19:32:36 +02:00
Ping,
}
pub(crate) trait Payload {
fn language_unset(&self) -> bool;
fn language(&self) -> String;
fn involved_users(&self) -> HashSet<Id>;
fn author(&self) -> &Id;
fn sent_from(&self) -> &str;
}
impl Event {
pub(crate) fn to_json_string(&self) -> String {
if let Event::Ping = self {
"{}".to_string()
} else {
let event = &self.event_name();
let sendable_event = match self.payload() {
Some(payload) => SendableEvent::WithPayload { event, payload },
None => SendableEvent::NoPayload { event },
};
serde_json::to_string(&sendable_event).expect("Guaranteed: SendableEvent is Serialize")
}
}
pub(crate) fn to_warp_reply(&self) -> Option<(impl ServerSentEvent, impl ServerSentEvent)> {
if let Event::Ping = self {
None
} else {
Some((
warp::sse::event(self.event_name()),
warp::sse::data(self.payload().unwrap_or_else(String::new)),
))
}
}
pub(crate) fn update_payload(&self) -> Option<&checked_event::Status> {
if let Self::TypeSafe(CheckedEvent::Update { payload, .. }) = self {
Some(&payload)
} else {
None
}
}
pub(crate) fn dyn_update_payload(&self) -> Option<&dynamic_event::DynStatus> {
if let Self::Dynamic(DynEvent {
kind: EventKind::Update(s),
..
}) = self
{
Some(&s)
} else {
None
}
}
fn event_name(&self) -> String {
String::from(match self {
Self::TypeSafe(checked) => match checked {
CheckedEvent::Update { .. } => "update",
CheckedEvent::Notification { .. } => "notification",
CheckedEvent::Delete { .. } => "delete",
CheckedEvent::Announcement { .. } => "announcement",
CheckedEvent::AnnouncementReaction { .. } => "announcement.reaction",
CheckedEvent::AnnouncementDelete { .. } => "announcement.delete",
CheckedEvent::Conversation { .. } => "conversation",
CheckedEvent::FiltersChanged => "filters_changed",
},
Self::Dynamic(DynEvent {
kind: EventKind::Update(_),
..
}) => "update",
Self::Dynamic(DynEvent { event, .. }) => event,
Self::Ping => unreachable!(), // private method only called above
})
}
#[rustfmt::skip]
fn payload(&self) -> Option<String> {
use CheckedEvent::*;
match self {
Self::TypeSafe(checked) => match checked {
Update { payload, .. } => Some(escaped(payload)),
Notification { payload, .. } => Some(escaped(payload)),
Conversation { payload, .. } => Some(escaped(payload)),
Announcement { payload, .. } => Some(escaped(payload)),
AnnouncementReaction { payload, .. } => Some(escaped(payload)),
AnnouncementDelete { payload, .. } |
Delete { payload, .. } => Some(payload.clone()),
FiltersChanged => None,
},
Self::Dynamic(DynEvent { payload, .. }) => Some(payload.to_string()),
Self::Ping => unreachable!(), // private method only called above
}
}
}
impl TryFrom<String> for Event {
type Error = err::Event;
fn try_from(event_txt: String) -> Result<Event, Self::Error> {
Event::try_from(event_txt.as_str())
}
}
impl TryFrom<&str> for Event {
type Error = err::Event;
fn try_from(event_txt: &str) -> Result<Event, Self::Error> {
match serde_json::from_str(event_txt) {
Ok(checked_event) => Ok(Event::TypeSafe(checked_event)),
Err(e) => {
log::error!(
"Error safely parsing Redis input. Mastodon and Flodgatt do not \
strictly conform to the same version of Mastodon's API.\n{}\n\
Forwarding Redis payload without type checking it.",
e
);
let dyn_event: DynEvent = serde_json::from_str(&event_txt)?;
Ok(Event::Dynamic(dyn_event.set_update()?))
}
}
}
}
#[derive(Serialize, Debug, Clone)]
#[serde(untagged)]
enum SendableEvent<'a> {
WithPayload { event: &'a str, payload: String },
NoPayload { event: &'a str },
}
fn escaped<T: Serialize + std::fmt::Debug>(content: T) -> String {
serde_json::to_string(&content).expect("Guaranteed by Serialize trait bound")
}