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:
@@ -10,7 +10,7 @@ publish.workspace = true
|
||||
db.workspace = true
|
||||
service-kit.workspace = true
|
||||
anyhow.workspace = true
|
||||
axum.workspace = true
|
||||
axum = { workspace = true, features = ["ws"] }
|
||||
axum-extra.workspace = true
|
||||
deunicode.workspace = true
|
||||
serde.workspace = true
|
||||
@@ -18,11 +18,13 @@ serde_json.workspace = true
|
||||
sqlx.workspace = true
|
||||
thiserror.workspace = true
|
||||
time.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio = { workspace = true, features = ["time"] }
|
||||
tower-http.workspace = true
|
||||
tracing.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
tokio-tungstenite = "0.29"
|
||||
futures-util = { version = "0.3", default-features = false }
|
||||
http-body-util = "0.1"
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! Live notices over WebSocket: a doorbell, never the data. The server only
|
||||
//! says "something changed" (`{"t":"nav"}`: the menu's counts; `{"t":"thread",
|
||||
//! "id":…}`: a thread; `{"t":"conversation","id":…}`), and the page fetches the
|
||||
//! news over HTTP as before. A dropped connection loses nothing: the page asks
|
||||
//! again when it reconnects, and polls while it cannot.
|
||||
//!
|
||||
//! Events go through Postgres (`NOTIFY forum_events`), so every instance of the
|
||||
//! service hears every change, whichever instance it happened on; each one
|
||||
//! passes them to its own connections.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use sqlx::postgres::PgListener;
|
||||
use tokio::sync::broadcast;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::AppState;
|
||||
use crate::auth::Viewer;
|
||||
|
||||
pub const CHANNEL: &str = "forum_events";
|
||||
/// A ping this often keeps the connection open through proxies (Cloudflare
|
||||
/// closes one idle for 100 seconds), and refreshes the online dot.
|
||||
const PING: Duration = Duration::from_secs(30);
|
||||
/// Above this many recipients an event goes to everyone (NOTIFY payloads are small).
|
||||
const MAX_USERS: usize = 300;
|
||||
|
||||
/// What changed, and for whom.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Event {
|
||||
/// A thread got a post, an edit, a reaction or a removal (anyone viewing it refetches).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub thread: Option<i64>,
|
||||
/// A conversation changed (only its two members hear it, through `users`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub conversation: Option<i64>,
|
||||
/// Whose menu counts changed.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub users: Vec<Uuid>,
|
||||
/// Everyone's menu (too many recipients to list).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub everyone: bool,
|
||||
/// The moderators' menu (the open reports).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub moderators: bool,
|
||||
}
|
||||
|
||||
impl Event {
|
||||
pub fn for_users(mut self, users: Vec<Uuid>) -> Self {
|
||||
if users.len() > MAX_USERS {
|
||||
self.everyone = true;
|
||||
} else {
|
||||
self.users = users;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The messages one connection gets from this event.
|
||||
pub fn messages_for(&self, user: Uuid, moderator: bool) -> Vec<String> {
|
||||
let mine = self.everyone || self.users.contains(&user);
|
||||
let mut out = Vec::new();
|
||||
if let Some(id) = self.thread {
|
||||
out.push(json!({ "t": "thread", "id": id }).to_string());
|
||||
}
|
||||
if let (Some(id), true) = (self.conversation, self.users.contains(&user)) {
|
||||
out.push(json!({ "t": "conversation", "id": id }).to_string());
|
||||
}
|
||||
if mine || (self.moderators && moderator) {
|
||||
out.push(json!({ "t": "nav" }).to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The events of this instance, for its connections.
|
||||
#[derive(Clone)]
|
||||
pub struct Hub {
|
||||
tx: broadcast::Sender<Arc<Event>>,
|
||||
}
|
||||
|
||||
impl Default for Hub {
|
||||
fn default() -> Self {
|
||||
Self { tx: broadcast::channel(1024).0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Hub {
|
||||
pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
|
||||
self.tx.subscribe()
|
||||
}
|
||||
}
|
||||
|
||||
/// Announces a change to every instance. A failure is logged: the pages poll anyway.
|
||||
pub async fn emit(db: &PgPool, event: Event) {
|
||||
let payload = serde_json::to_string(&event).unwrap_or_default();
|
||||
if let Err(e) = sqlx::query("SELECT pg_notify($1, $2)").bind(CHANNEL).bind(&payload).execute(db).await {
|
||||
tracing::warn!(error = %e, "announcing a forum event");
|
||||
}
|
||||
}
|
||||
|
||||
/// Passes the database's events to this instance's connections, for good
|
||||
/// (it reconnects after a lost database connection).
|
||||
pub async fn listen(db: PgPool, hub: Hub) {
|
||||
loop {
|
||||
match PgListener::connect_with(&db).await {
|
||||
Ok(mut listener) => {
|
||||
if let Err(e) = listener.listen(CHANNEL).await {
|
||||
tracing::warn!(error = %e, "LISTEN forum_events failed");
|
||||
} else {
|
||||
loop {
|
||||
match listener.recv().await {
|
||||
Ok(note) => match serde_json::from_str::<Event>(note.payload()) {
|
||||
Ok(event) => {
|
||||
// No connection listening is fine.
|
||||
let _ = hub.tx.send(Arc::new(event));
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "unreadable forum event"),
|
||||
},
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "forum events: listener lost");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!(error = %e, "forum events: cannot listen"),
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the site itself may open a connection with the visitor's cookie
|
||||
/// (no cross-site WebSocket hijacking).
|
||||
fn origin_allowed(headers: &HeaderMap, base_url: &str) -> bool {
|
||||
match headers.get(header::ORIGIN).and_then(|o| o.to_str().ok()) {
|
||||
Some(origin) => origin.trim_end_matches('/') == base_url,
|
||||
// Not a browser (no Origin header): it brings its own token.
|
||||
None => headers.contains_key(header::AUTHORIZATION),
|
||||
}
|
||||
}
|
||||
|
||||
/// `GET /v1/forum/ws`: a member's live connection.
|
||||
pub async fn connect(
|
||||
State(state): State<Arc<AppState>>,
|
||||
viewer: Viewer,
|
||||
headers: HeaderMap,
|
||||
ws: WebSocketUpgrade,
|
||||
) -> Response {
|
||||
if !origin_allowed(&headers, &state.base_url) {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
let Some(member) = viewer.member.clone() else { return StatusCode::UNAUTHORIZED.into_response() };
|
||||
let moderator = viewer.is_moderator();
|
||||
let rx = state.hub.subscribe();
|
||||
let db = state.db.clone();
|
||||
ws.on_upgrade(move |socket| serve(socket, rx, db, member.user_id, moderator))
|
||||
}
|
||||
|
||||
async fn serve(
|
||||
mut socket: WebSocket,
|
||||
mut rx: broadcast::Receiver<Arc<Event>>,
|
||||
db: PgPool,
|
||||
user: Uuid,
|
||||
moderator: bool,
|
||||
) {
|
||||
let mut ping = tokio::time::interval(PING);
|
||||
ping.tick().await;
|
||||
loop {
|
||||
tokio::select! {
|
||||
event = rx.recv() => {
|
||||
let messages = match event {
|
||||
Ok(event) => event.messages_for(user, moderator),
|
||||
// Too slow to follow: just refresh everything.
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => vec![json!({ "t": "nav" }).to_string()],
|
||||
Err(broadcast::error::RecvError::Closed) => break,
|
||||
};
|
||||
for message in messages {
|
||||
if socket.send(Message::Text(message.into())).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = ping.tick() => {
|
||||
if socket.send(Message::Ping(Vec::new().into())).await.is_err() {
|
||||
return;
|
||||
}
|
||||
// Connected means present: the online dot.
|
||||
let _ = sqlx::query(
|
||||
"UPDATE forum.members SET last_seen_at = now() \
|
||||
WHERE user_id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '60 seconds')",
|
||||
)
|
||||
.bind(user)
|
||||
.execute(&db)
|
||||
.await;
|
||||
}
|
||||
incoming = socket.recv() => match incoming {
|
||||
// The page has nothing to say; pongs and the like are fine.
|
||||
Some(Ok(Message::Close(_))) | None | Some(Err(_)) => break,
|
||||
Some(Ok(_)) => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The followers of a thread other than `except` (whose menu counts change).
|
||||
pub async fn followers(db: &PgPool, thread: i64, except: Uuid) -> Vec<Uuid> {
|
||||
sqlx::query_scalar("SELECT user_id FROM forum.follows WHERE thread_id = $1 AND user_id <> $2")
|
||||
.bind(thread)
|
||||
.bind(except)
|
||||
.fetch_all(db)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn who_hears_what() {
|
||||
let (anna, bea) = (Uuid::now_v7(), Uuid::now_v7());
|
||||
let post = Event { thread: Some(7), ..Default::default() }.for_users(vec![anna]);
|
||||
assert_eq!(post.messages_for(anna, false), vec![r#"{"id":7,"t":"thread"}"#, r#"{"t":"nav"}"#]);
|
||||
assert_eq!(post.messages_for(bea, false), vec![r#"{"id":7,"t":"thread"}"#]);
|
||||
let message = Event { conversation: Some(3), ..Default::default() }.for_users(vec![bea]);
|
||||
assert!(message.messages_for(anna, true).is_empty(), "nobody else hears of a conversation");
|
||||
assert_eq!(message.messages_for(bea, false).len(), 2);
|
||||
let report = Event { moderators: true, ..Default::default() };
|
||||
assert!(report.messages_for(anna, false).is_empty());
|
||||
assert_eq!(report.messages_for(anna, true), vec![r#"{"t":"nav"}"#]);
|
||||
let many = Event::default().for_users((0..400).map(|_| Uuid::now_v7()).collect());
|
||||
assert!(many.everyone && many.users.is_empty());
|
||||
let round: Event = serde_json::from_str(&serde_json::to_string(&post).unwrap()).unwrap();
|
||||
assert_eq!(round, post);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
mod auth;
|
||||
mod error;
|
||||
mod live;
|
||||
mod mail;
|
||||
mod rank;
|
||||
mod routes;
|
||||
@@ -31,13 +32,16 @@ pub struct AppState {
|
||||
pub db: PgPool,
|
||||
/// Seconds a member waits between two posts (0 in the tests).
|
||||
pub flood_secs: i32,
|
||||
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`).
|
||||
/// The site's address, for the links in e-mails (`PUBLIC_BASE_URL`); also
|
||||
/// the only origin allowed to open a live connection.
|
||||
pub base_url: String,
|
||||
/// The live events of this instance (`live::listen` fills it).
|
||||
pub hub: live::Hub,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn new(db: PgPool, base_url: String) -> Self {
|
||||
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string() }
|
||||
Self { db, flood_secs: 5, base_url: base_url.trim_end_matches('/').to_string(), hub: live::Hub::default() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +56,9 @@ async fn main() -> anyhow::Result<()> {
|
||||
let pool = db::connect(&url).await.context("connecting to the database")?;
|
||||
db::migrate(&pool).await.context("running database migrations")?;
|
||||
let base_url = std::env::var("PUBLIC_BASE_URL").unwrap_or_else(|_| "http://localhost:3001".into());
|
||||
let app = routes::router(Arc::new(AppState::new(pool, base_url)));
|
||||
let state = Arc::new(AppState::new(pool, base_url));
|
||||
tokio::spawn(live::listen(state.db.clone(), state.hub.clone()));
|
||||
let app = routes::router(state);
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "listening");
|
||||
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
|
||||
|
||||
@@ -225,6 +225,11 @@ pub async fn request(
|
||||
};
|
||||
tx.commit().await?;
|
||||
crate::mail::after_message(&state, id, me.user_id, true, Some(&intro)).await;
|
||||
crate::live::emit(
|
||||
&state.db,
|
||||
crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![other]),
|
||||
)
|
||||
.await;
|
||||
Ok((StatusCode::CREATED, Json(json!({ "id": id }))))
|
||||
}
|
||||
|
||||
@@ -398,6 +403,8 @@ pub async fn respond(state: St, viewer: Viewer, path: IdPath, answer: &'static s
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me), me]);
|
||||
crate::live::emit(&state.db, event).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
@@ -463,6 +470,8 @@ pub async fn send(
|
||||
mark(&mut *tx, id, me, message_id).await?;
|
||||
tx.commit().await?;
|
||||
crate::mail::after_message(&state, id, me, false, None).await;
|
||||
let event = crate::live::Event { conversation: Some(id), ..Default::default() }.for_users(vec![c.other(me)]);
|
||||
crate::live::emit(&state.db, event).await;
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(json!({ "id": message_id, "mine": true, "body": body, "created_at": rfc3339(created_at) })),
|
||||
|
||||
@@ -66,6 +66,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/forum/nickname-check", get(members::nickname_check))
|
||||
.route("/v1/forum/presence", post(members::presence))
|
||||
.route("/v1/forum/unsubscribe", post(members::unsubscribe))
|
||||
.route("/v1/forum/ws", get(crate::live::connect))
|
||||
.route("/v1/forum/members/{nickname}", get(members::profile))
|
||||
.route("/v1/forum/members/{nickname}/ban", post(moderation::ban).delete(moderation::unban))
|
||||
.route("/v1/forum/mod/log", get(moderation::log))
|
||||
|
||||
@@ -18,6 +18,11 @@ use crate::error::{ApiError, ApiResult};
|
||||
use crate::rank::HELPED_POINTS;
|
||||
use crate::text;
|
||||
|
||||
/// Anyone viewing the thread refetches it (reactions, edits, removals).
|
||||
async fn announce(state: &crate::AppState, thread: i64) {
|
||||
crate::live::emit(&state.db, crate::live::Event { thread: Some(thread), ..Default::default() }).await;
|
||||
}
|
||||
|
||||
/// A post and its thread, both readable by the viewer.
|
||||
async fn load(db: &PgPool, viewer: &Viewer, id: i64) -> ApiResult<(PostRow, ThreadRow)> {
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
@@ -55,6 +60,7 @@ pub async fn edit(
|
||||
.bind(&body)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
@@ -120,6 +126,7 @@ pub async fn remove(
|
||||
}
|
||||
crate::mail::notify_reporters(&state, &reporters, "removed").await;
|
||||
}
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
@@ -224,6 +231,7 @@ pub async fn react(
|
||||
.await?;
|
||||
add_points(&mut tx, post.author_id, delta).await?;
|
||||
tx.commit().await?;
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
@@ -241,6 +249,7 @@ pub async fn unreact(State(state): St, viewer: Viewer, WithRejection(Path(id), _
|
||||
add_points(&mut tx, post.author_id, -points_of(&kind)).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
announce(&state, post.thread_id).await;
|
||||
Ok(Json(posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0)))
|
||||
}
|
||||
|
||||
@@ -293,6 +302,7 @@ async fn set_helped(
|
||||
add_points(&mut tx, post.author_id, if on { HELPED_POINTS } else { -HELPED_POINTS }).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
announce(&state, thread.id).await;
|
||||
let post: PostRow = sqlx::query_as(&format!("SELECT {POST_COLUMNS} FROM forum.posts WHERE id = $1"))
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
|
||||
@@ -97,6 +97,7 @@ pub async fn report_post(
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(post = id, kind = %req.kind, "post reported");
|
||||
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
|
||||
Ok((StatusCode::CREATED, received(&req.kind)))
|
||||
}
|
||||
|
||||
@@ -132,6 +133,7 @@ pub async fn report_message(
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
tracing::info!(message = id, kind = %req.kind, "message reported");
|
||||
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
|
||||
Ok((StatusCode::CREATED, received(&req.kind)))
|
||||
}
|
||||
|
||||
@@ -322,6 +324,7 @@ pub async fn handle(
|
||||
tx.commit().await?;
|
||||
let outcome = if status == "resolved" { "handled" } else { "no_violation" };
|
||||
crate::mail::notify_reporters(&state, &reporters, outcome).await;
|
||||
crate::live::emit(&state.db, crate::live::Event { moderators: true, ..Default::default() }).await;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
|
||||
@@ -421,6 +421,9 @@ pub async fn reply(
|
||||
after_post(&mut tx, member.user_id, id, post.id).await?;
|
||||
tx.commit().await?;
|
||||
crate::mail::after_reply(&state, id, post.id, member.user_id, post.parent_id, &body).await;
|
||||
let followers = crate::live::followers(&state.db, id, member.user_id).await;
|
||||
crate::live::emit(&state.db, crate::live::Event { thread: Some(id), ..Default::default() }.for_users(followers))
|
||||
.await;
|
||||
let post = posts_json(&state.db, &viewer, std::slice::from_ref(&post)).await?.remove(0);
|
||||
Ok((StatusCode::CREATED, Json(post)))
|
||||
}
|
||||
|
||||
@@ -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