11.8 KiB · text History 84bfe6e
//! Live updates: signed-in browsers hold one WebSocket (`/ws`, the htmx `ws`
//! extension) and are told when a topic they may see has new activity, so
//! the Latest lists on the page refetch themselves (assets/f/js/live.js).
//!
//! * **Events** are in-process: [`Hub::publish`] on a tokio broadcast
//!   channel, from the places a topic or post becomes visible (a new topic
//!   or reply that wasn't held, a hold or flag-hide dismissed, a held opening
//!   post moderated, a topic or post restored). The deployment is one
//!   replica; more would need Postgres `LISTEN/NOTIFY` to fan events out
//!   (see the README).
//! * **Visibility.** An event names a topic, nothing else. Each connection
//!   keeps its user and, at most every [`MIN_PUSH_GAP`], asks
//!   [`signal_for`] which of the topics it heard about that user can see
//!   *now*, with the same conditions the Latest list queries (the viewer's
//!   readable categories, not deleted, `Viewer::topic_condition` for held
//!   topics). Nothing visible, nothing sent. What's sent is a signal, not
//!   content: the categories touched, so the page knows which of its lists
//!   to refetch, as the user, through the ordinary routes.
//! * **Connections**: session cookie only (no bearer tokens, no anonymous
//!   sockets: 401), `Origin` must be `PUBLIC_URL`'s (403), at most
//!   [`PER_USER`] per user and [`GLOBAL`] in all (429). A ping every
//!   [`HEARTBEAT`] keeps proxies from idling it out; the session is re-read
//!   every [`RECHECK`], and a revoked or expired one closes the socket with
//!   1008 (which the htmx extension doesn't retry).
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use axum::extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade};
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
use tokio::sync::broadcast;
use tokio::time::Instant;
use tracing::debug;
use uuid::Uuid;

use crate::category_tree::CategoryTree;
use crate::entities::{topics, users};
use crate::AppState;

/// Connections per user (tabs).
pub const PER_USER: usize = 5;
/// Connections in all.
pub const GLOBAL: usize = 2000;
/// At most one push per connection this often.
pub const MIN_PUSH_GAP: Duration = Duration::from_secs(2);
/// Wait this long after the first event of a burst before pushing.
const SETTLE: Duration = Duration::from_millis(300);
pub const HEARTBEAT: Duration = Duration::from_secs(25);
pub const RECHECK: Duration = Duration::from_secs(60);
const CHANNEL: usize = 1024;

/// The in-process event bus and connection counts. One per process, in
/// `AppState`.
pub struct Hub {
    tx: broadcast::Sender<Uuid>,
    per_user: Mutex<HashMap<Uuid, usize>>,
    total: AtomicUsize,
}

impl Default for Hub {
    fn default() -> Self {
        Hub { tx: broadcast::channel(CHANNEL).0, per_user: Mutex::default(), total: AtomicUsize::new(0) }
    }
}

impl Hub {
    pub fn new() -> Arc<Hub> {
        Arc::new(Hub::default())
    }

    /// A topic has visible new activity. Cheap, and fine with nobody
    /// listening.
    pub fn publish(&self, topic: Uuid) {
        let _ = self.tx.send(topic);
    }

    pub fn subscribe(&self) -> broadcast::Receiver<Uuid> {
        self.tx.subscribe()
    }

    /// Room for one more connection for `user`?
    fn admit(self: &Arc<Self>, user: Uuid) -> Option<Slot> {
        let mut map = self.per_user.lock().unwrap();
        let n = map.entry(user).or_default();
        if *n >= PER_USER || self.total.load(Ordering::SeqCst) >= GLOBAL {
            return None;
        }
        *n += 1;
        self.total.fetch_add(1, Ordering::SeqCst);
        Some(Slot { hub: self.clone(), user })
    }

    /// Open connections.
    pub fn connections(&self) -> usize {
        self.total.load(Ordering::SeqCst)
    }
}

/// A held connection slot, given back on drop.
struct Slot {
    hub: Arc<Hub>,
    user: Uuid,
}

impl Drop for Slot {
    fn drop(&mut self) {
        let mut map = self.hub.per_user.lock().unwrap();
        if let Some(n) = map.get_mut(&self.user) {
            *n = n.saturating_sub(1);
            if *n == 0 {
                map.remove(&self.user);
            }
        }
        self.hub.total.fetch_sub(1, Ordering::SeqCst);
    }
}

/// Whether `Origin` is `PUBLIC_URL`'s origin. Browsers always send it on a
/// WebSocket handshake; without it, it isn't a page of ours.
pub fn origin_ok(headers: &HeaderMap, public_url: &str) -> bool {
    let Some(origin) = headers.get("origin").and_then(|v| v.to_str().ok()) else { return false };
    match (url::Url::parse(origin), url::Url::parse(public_url)) {
        (Ok(a), Ok(b)) => a.origin() == b.origin(),
        _ => false,
    }
}

/// `GET /ws`.
pub async fn ws_handler(
    State(state): State<AppState>,
    headers: HeaderMap,
    upgrade: Result<WebSocketUpgrade, axum::extract::ws::rejection::WebSocketUpgradeRejection>,
) -> Response {
    let Some(token) = crate::middleware::session_token_from_headers(&headers) else {
        return StatusCode::UNAUTHORIZED.into_response();
    };
    let user = match crate::auth::validate_session(&state.db, &token).await {
        Ok(Some((user, _))) => user,
        Ok(None) => return StatusCode::UNAUTHORIZED.into_response(),
        Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
    };
    if !origin_ok(&headers, &state.config.public_url) {
        return StatusCode::FORBIDDEN.into_response();
    }
    let upgrade = match upgrade {
        Ok(u) => u,
        Err(e) => return e.into_response(),
    };
    let Some(slot) = state.live.admit(user.id) else {
        return StatusCode::TOO_MANY_REQUESTS.into_response();
    };
    upgrade.on_upgrade(move |socket| run(state, user, token, socket, slot))
}

async fn run(state: AppState, mut user: users::Model, token: String, mut socket: WebSocket, _slot: Slot) {
    debug!(user = %user.username, open = state.live.connections(), "live: connected");
    let mut events = state.live.subscribe();
    let mut pending: HashSet<Uuid> = HashSet::new();
    let mut flush_at: Option<Instant> = None;
    let mut last_push = Instant::now() - MIN_PUSH_GAP;
    let mut heartbeat = tokio::time::interval_at(Instant::now() + HEARTBEAT, HEARTBEAT);
    let mut recheck = tokio::time::interval_at(Instant::now() + RECHECK, RECHECK);
    let mut seq: u64 = 0;
    loop {
        let flush = async {
            match flush_at {
                Some(at) => tokio::time::sleep_until(at).await,
                None => std::future::pending().await,
            }
        };
        tokio::select! {
            msg = socket.recv() => match msg {
                Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
                // Pongs, and anything a client says: ignored.
                Some(Ok(_)) => {}
            },
            ev = events.recv() => match ev {
                Ok(topic) => {
                    pending.insert(topic);
                    if flush_at.is_none() {
                        flush_at = Some((Instant::now() + SETTLE).max(last_push + MIN_PUSH_GAP));
                    }
                }
                Err(broadcast::error::RecvError::Lagged(n)) => debug!(n, "live: lagged"),
                Err(broadcast::error::RecvError::Closed) => break,
            },
            _ = flush => {
                flush_at = None;
                last_push = Instant::now();
                let topics: Vec<Uuid> = pending.drain().collect();
                match signal_for(&state, &user, &topics).await {
                    Ok(Some(cats)) => {
                        seq += 1;
                        if socket.send(Message::Text(signal_html(&cats, seq).into())).await.is_err() {
                            break;
                        }
                    }
                    Ok(None) => {}
                    Err(e) => debug!(error = %e, "live: visibility check failed"),
                }
            },
            _ = heartbeat.tick() => {
                if socket.send(Message::Ping(Vec::new().into())).await.is_err() {
                    break;
                }
            },
            _ = recheck.tick() => {
                match crate::auth::validate_session(&state.db, &token).await {
                    Ok(Some((u, _))) => user = u,
                    Ok(None) => {
                        let _ = socket
                            .send(Message::Close(Some(CloseFrame { code: 1008, reason: "signed out".into() })))
                            .await;
                        break;
                    }
                    Err(_) => {}
                }
            },
        }
    }
    debug!(user = %user.username, "live: disconnected");
}

/// Of `topics`, the ones `user` can see now, by the Latest list's own
/// conditions, as the categories they're in (and those categories'
/// ancestors, whose pages list them too). `None`: nothing to tell.
pub async fn signal_for(
    state: &AppState,
    user: &users::Model,
    topic_ids: &[Uuid],
) -> Result<Option<BTreeSet<Uuid>>, sea_orm::DbErr> {
    if topic_ids.is_empty() {
        return Ok(None);
    }
    let tree = CategoryTree::load(state.db.as_ref()).await?;
    let vis = tree.visible_category_ids(crate::actions::viewer(user));
    if vis.is_empty() {
        return Ok(None);
    }
    // landing::latest_topics' filters, on just these topics.
    let seen = topics::Entity::find()
        .filter(topics::Column::Id.is_in(topic_ids.iter().copied()))
        .filter(topics::Column::CategoryId.is_in(vis.iter().copied()))
        .filter(topics::Column::DeletedAt.is_null())
        .filter(vis.viewer.topic_condition())
        .all(state.db.as_ref())
        .await?;
    let mut cats = BTreeSet::new();
    for t in &seen {
        cats.insert(t.category_id);
        cats.extend(tree.ancestors(t.category_id));
    }
    Ok((!cats.is_empty()).then_some(cats))
}

/// What the htmx `ws` extension swaps in (out of band) for live.js to read.
fn signal_html(cats: &BTreeSet<Uuid>, seq: u64) -> String {
    let cats: Vec<String> = cats.iter().map(Uuid::to_string).collect();
    format!(r#"<div id="live-signal" hx-swap-oob="true" data-seq="{seq}" data-categories="{}"></div>"#, cats.join(" "))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn origins_must_match_public_url() {
        let h = |o: &str| {
            let mut m = HeaderMap::new();
            m.insert("origin", o.parse().unwrap());
            m
        };
        assert!(origin_ok(&h("https://forum.example"), "https://forum.example"));
        assert!(origin_ok(&h("https://forum.example"), "https://forum.example/"));
        assert!(!origin_ok(&h("https://evil.example"), "https://forum.example"));
        assert!(!origin_ok(&h("http://forum.example"), "https://forum.example"));
        assert!(!origin_ok(&h("https://forum.example:8443"), "https://forum.example"));
        assert!(!origin_ok(&h("null"), "https://forum.example"));
        assert!(!origin_ok(&HeaderMap::new(), "https://forum.example"));
    }

    #[test]
    fn connections_are_capped_per_user_and_given_back() {
        let hub = Hub::new();
        let a = Uuid::now_v7();
        let slots: Vec<_> = (0..PER_USER).map(|_| hub.admit(a).expect("room")).collect();
        assert!(hub.admit(a).is_none(), "a sixth tab");
        let other = hub.admit(Uuid::now_v7());
        assert!(other.is_some(), "someone else");
        drop(slots);
        let again = hub.admit(a);
        assert!(again.is_some());
        assert_eq!(hub.connections(), 2);
        drop((other, again));
        assert_eq!(hub.connections(), 0);
    }

    #[test]
    fn the_signal_is_an_oob_swap_naming_only_categories() {
        let c = Uuid::now_v7();
        let html = signal_html(&BTreeSet::from([c]), 3);
        assert_eq!(html, format!(r#"<div id="live-signal" hx-swap-oob="true" data-seq="3" data-categories="{c}"></div>"#));
    }
}