Forum: live notices over WebSocket
A doorbell, not the data: the forum service tells a member's page that their menu counts, a thread or a conversation changed, and the page fetches the news over HTTP. Events go through Postgres NOTIFY so every instance hears them; pings keep the connection (and the online dot) alive; only the site's own origin may connect. The menu now refreshes its badges live, on every page change and when the page comes back to the front, and polls while there is no connection. Caddy sends /api/v1/forum/ws straight to the forum service; in development FORUM_WS_URL points at it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -30,7 +30,12 @@ struct User {
|
||||
|
||||
impl TestApp {
|
||||
fn new(pool: PgPool) -> Self {
|
||||
let state = AppState { db: pool.clone(), flood_secs: 0, base_url: "https://sorsfonalak.test".into() };
|
||||
let state = AppState {
|
||||
db: pool.clone(),
|
||||
flood_secs: 0,
|
||||
base_url: "https://sorsfonalak.test".into(),
|
||||
hub: crate::live::Hub::default(),
|
||||
};
|
||||
Self { router: routes::router(Arc::new(state)), pool }
|
||||
}
|
||||
|
||||
@@ -842,3 +847,68 @@ async fn instant_mails_and_unsubscribe(pool: PgPool) {
|
||||
let me = app.get("/v1/forum/me", Some(&anna)).await;
|
||||
assert_eq!(me["member"]["email"], json!({"replies": "off", "followed": "off", "messages": "off"}));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||
async fn live_doorbell_over_websocket(pool: PgPool) {
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
|
||||
let state = Arc::new(AppState {
|
||||
db: pool.clone(),
|
||||
flood_secs: 0,
|
||||
base_url: "https://sorsfonalak.test".into(),
|
||||
hub: crate::live::Hub::default(),
|
||||
});
|
||||
tokio::spawn(crate::live::listen(pool.clone(), state.hub.clone()));
|
||||
let router = routes::router(state.clone());
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let served = router.clone();
|
||||
tokio::spawn(async move { axum::serve(listener, served).await.unwrap() });
|
||||
let app = TestApp { router, pool };
|
||||
let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await;
|
||||
let bea = app.member("bea@example.com", "Holdfény", &["user"]).await;
|
||||
let thread = app.thread(&anna, "belso-utak", "Reggeli csend").await;
|
||||
// Give the database listener a moment to start.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
|
||||
let request = |token: &str, origin: Option<&str>| {
|
||||
let mut req = format!("ws://{addr}/v1/forum/ws").into_client_request().unwrap();
|
||||
req.headers_mut().insert("authorization", format!("Bearer {token}").parse().unwrap());
|
||||
if let Some(o) = origin {
|
||||
req.headers_mut().insert("origin", o.parse().unwrap());
|
||||
}
|
||||
req
|
||||
};
|
||||
// Another site may not open it with the visitor's credentials.
|
||||
let refused = tokio_tungstenite::connect_async(request(&anna.token, Some("https://evil.example"))).await;
|
||||
assert!(refused.is_err());
|
||||
let (mut ws, _) =
|
||||
tokio_tungstenite::connect_async(request(&anna.token, Some("https://sorsfonalak.test"))).await.unwrap();
|
||||
|
||||
// Bea replies in Anna's thread: Anna hears of the thread and of her menu.
|
||||
app.reply(&bea, thread, "Én hajnalban ülök le.", None).await;
|
||||
let mut heard = Vec::new();
|
||||
while heard.len() < 2 {
|
||||
let next = tokio::time::timeout(std::time::Duration::from_secs(5), futures_next(&mut ws)).await;
|
||||
match next {
|
||||
Ok(Some(text)) => heard.push(text),
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
assert_eq!(heard, vec![format!(r#"{{"id":{thread},"t":"thread"}}"#), r#"{"t":"nav"}"#.to_string()]);
|
||||
}
|
||||
|
||||
/// The next text message of a test WebSocket.
|
||||
async fn futures_next(
|
||||
ws: &mut tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>,
|
||||
) -> Option<String> {
|
||||
use futures_util::StreamExt;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
loop {
|
||||
match ws.next().await? {
|
||||
Ok(Message::Text(t)) => return Some(t.to_string()),
|
||||
Ok(_) => continue,
|
||||
Err(_) => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user