use std::convert::Infallible;
use std::time::Duration;
use axum::http::{HeaderMap, HeaderValue, header};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use futures_util::{StreamExt, stream};
use serde::Serialize;
use serde_json::{Value, json};
use crate::{Bus, Error, Filter, Item, Position, Subscription};
pub fn last_event_id(headers: &HeaderMap) -> Option<Position> {
headers.get("last-event-id")?.to_str().ok()?.parse().ok()
}
#[derive(Debug, Clone, PartialEq)]
pub struct Options {
pub heartbeat: Duration,
pub max_lifetime: Option<Duration>,
pub retry: Option<Duration>,
}
impl Default for Options {
fn default() -> Self {
Options {
heartbeat: Duration::from_secs(25),
max_lifetime: Some(Duration::from_secs(600)),
retry: Some(Duration::from_secs(1)),
}
}
}
fn jittered(lifetime: Duration, spread: f64) -> Duration {
lifetime.mul_f64(0.9 + 0.2 * spread.clamp(0.0, 1.0))
}
fn spread() -> f64 {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or(0);
f64::from(nanos % 1_000_000) / 1_000_000.0
}
pub fn events(subscription: Subscription, options: Options) -> Response {
let deadline = options
.max_lifetime
.map(|l| tokio::time::Instant::now() + jittered(l, spread()));
let retry = options
.retry
.map(|r| Ok::<_, Infallible>(Event::default().retry(r)));
let messages = stream::unfold(Some(subscription), move |state| async move {
let mut sub = state?;
let next = match deadline {
Some(at) => tokio::time::timeout_at(at, sub.next()).await.ok()?,
None => sub.next().await,
};
match next {
Ok(Item::Message(m)) => {
let event = Event::default()
.event("message")
.id(m.position.to_string())
.data(json!({ "channel": m.channel, "data": m.data }).to_string());
Some((Ok::<_, Infallible>(event), Some(sub)))
}
Ok(Item::Gap) => Some((Ok(Event::default().event("gap").data("{}")), Some(sub))),
Err(e) => {
tracing::warn!("{e}");
None
}
}
});
let stream = stream::iter(retry).chain(messages);
let mut response = Sse::new(stream)
.keep_alive(KeepAlive::new().interval(options.heartbeat))
.into_response();
response
.headers_mut()
.insert("x-accel-buffering", HeaderValue::from_static("no"));
response
.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
response
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lifetimes_spread_within_ten_percent() {
let ten = Duration::from_secs(600);
assert_eq!(jittered(ten, 0.0), Duration::from_secs(540));
assert_eq!(jittered(ten, 0.5), Duration::from_secs(600));
assert!(jittered(ten, 0.999_999) < Duration::from_secs(660));
assert_eq!(jittered(ten, 7.0), Duration::from_secs(660));
let s = spread();
assert!((0.0..1.0).contains(&s));
}
}
#[derive(Debug, Serialize)]
pub struct Poll {
pub messages: Vec<Polled>,
pub position: String,
pub gap: bool,
}
#[derive(Debug, Serialize)]
pub struct Polled {
pub id: String,
pub channel: String,
pub data: Value,
}
pub async fn poll(
bus: &Bus,
from: Position,
filter: Filter,
wait: Duration,
) -> Result<Poll, Error> {
let mut sub = bus.subscribe(from, filter);
let mut out = Poll {
messages: Vec::new(),
position: from.to_string(),
gap: false,
};
let mut timeout = wait;
while let Ok(item) = tokio::time::timeout(timeout, sub.next()).await {
match item? {
Item::Message(m) => out.messages.push(Polled {
id: m.position.to_string(),
channel: m.channel,
data: m.data,
}),
Item::Gap => out.gap = true,
}
if !out.messages.is_empty() {
timeout = Duration::ZERO;
}
}
out.position = sub.position().to_string();
Ok(out)
}